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: v1.5 market-driven feature expansion

Beenu Aroradb17e120890c
diff --git a/apps/web/src/app/(app)/analytics/team/page.tsx b/apps/web/src/app/(app)/analytics/team/page.tsx
new file mode 100644
index 000000000..41c26680e
--- /dev/null
+++ b/apps/web/src/app/(app)/analytics/team/page.tsx
@@ -0,0 +1,11 @@
+import { TeamAnalyticsView } from '@/components/analytics/TeamAnalyticsView';
+
+export const metadata = { title: 'Team Analytics — AiSOC' };
+
+export default function TeamAnalyticsPage() {
+ return (
+ <div className="p-6 max-w-7xl mx-auto">
+ <TeamAnalyticsView />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/(app)/coverage-advisor/page.tsx b/apps/web/src/app/(app)/coverage-advisor/page.tsx
new file mode 100644
index 000000000..b61fbe031
--- /dev/null
+++ b/apps/web/src/app/(app)/coverage-advisor/page.tsx
@@ -0,0 +1,7 @@
+import CoverageAdvisorView from '@/components/coverage/CoverageAdvisorView';
+
+export const metadata = { title: 'Coverage Gap Advisor | AiSOC' };
+
+export default function CoverageAdvisorPage() {
+ return <CoverageAdvisorView />;
+}
diff --git a/apps/web/src/app/(app)/easm/page.tsx b/apps/web/src/app/(app)/easm/page.tsx
new file mode 100644
index 000000000..6aadc9b6f
--- /dev/null
+++ b/apps/web/src/app/(app)/easm/page.tsx
@@ -0,0 +1,11 @@
+import { EASMView } from '@/components/easm/EASMView';
+
+export const metadata = { title: 'EASM — AiSOC' };
+
+export default function EASMPage() {
+ return (
+ <div className="p-6 max-w-7xl mx-auto">
+ <EASMView />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/(app)/investigate/page.tsx b/apps/web/src/app/(app)/investigate/page.tsx
new file mode 100644
index 000000000..6e665afbf
--- /dev/null
+++ b/apps/web/src/app/(app)/investigate/page.tsx
@@ -0,0 +1,7 @@
+import InvestigationChat from '@/components/copilot/InvestigationChat';
+
+export const metadata = { title: 'Investigation Chat | AiSOC' };
+
+export default function InvestigatePage() {
+ return <InvestigationChat />;
+}
diff --git a/apps/web/src/app/(app)/mssp/page.tsx b/apps/web/src/app/(app)/mssp/page.tsx
new file mode 100644
index 000000000..49250fa66
--- /dev/null
+++ b/apps/web/src/app/(app)/mssp/page.tsx
@@ -0,0 +1,7 @@
+import MSSPDashboardView from '@/components/mssp/MSSPDashboardView';
+
+export const metadata = { title: 'MSSP Executive Dashboard | AiSOC' };
+
+export default function MSSPPage() {
+ return <MSSPDashboardView />;
+}
diff --git a/apps/web/src/app/(app)/noise-tuning/page.tsx b/apps/web/src/app/(app)/noise-tuning/page.tsx
new file mode 100644
index 000000000..35b3d5ae8
--- /dev/null
+++ b/apps/web/src/app/(app)/noise-tuning/page.tsx
@@ -0,0 +1,7 @@
+import NoiseTuningView from '@/components/noise/NoiseTuningView';
+
+export const metadata = { title: 'Alert Noise Tuning | AiSOC' };
+
+export default function NoiseTuningPage() {
+ return <NoiseTuningView />;
+}
diff --git a/apps/web/src/app/(app)/shifts/page.tsx b/apps/web/src/app/(app)/shifts/page.tsx
new file mode 100644
index 000000000..4437a12fa
--- /dev/null
+++ b/apps/web/src/app/(app)/shifts/page.tsx
@@ -0,0 +1,11 @@
+import { ShiftsView } from '@/components/shifts/ShiftsView';
+
+export const metadata = { title: 'Shifts — AiSOC' };
+
+export default function ShiftsPage() {
+ return (
+ <div className="p-6 max-w-7xl mx-auto">
+ <ShiftsView />
+ </div>
+ );
+}
diff --git a/apps/web/src/components/analytics/TeamAnalyticsView.tsx b/apps/web/src/components/analytics/TeamAnalyticsView.tsx
new file mode 100644
index 000000000..7f6a6f829
--- /dev/null
+++ b/apps/web/src/components/analytics/TeamAnalyticsView.tsx
@@ -0,0 +1,257 @@
+'use client';
+
+import { useState } from 'react';
+import { clsx } from 'clsx';
+
+interface Analyst {
+ id: string;
+ name: string;
+ initials: string;
+ avatarColor: string;
+ casesClosed: number;
+ avgResolutionMin: number;
+ accuracy: number;
+ score: number;
+ badges: string[];
+}
+
+interface Achievement {
+ text: string;
+ timeAgo: string;
+ icon: 'badge' | 'streak' | 'record' | 'rank';
+}
+
+const BADGE_COLORS: Record<string, { bg: string; text: string; border: string }> = {
+ 'MITRE Master': { bg: 'bg-purple-500/15', text: 'text-purple-300', border: 'border-purple-500/30' },
+ 'Speed Demon': { bg: 'bg-blue-500/15', text: 'text-blue-300', border: 'border-blue-500/30' },
+ 'Zero FP': { bg: 'bg-green-500/15', text: 'text-green-300', border: 'border-green-500/30' },
+ 'Night Owl': { bg: 'bg-indigo-500/15', text: 'text-indigo-300', border: 'border-indigo-500/30' },
+ 'Precision Strike': { bg: 'bg-amber-500/15', text: 'text-amber-300', border: 'border-amber-500/30' },
+ 'Mentor': { bg: 'bg-teal-500/15', text: 'text-teal-300', border: 'border-teal-500/30' },
+ 'Newcomer Rising': { bg: 'bg-rose-500/15', text: 'text-rose-300', border: 'border-rose-500/30' },
+};
+
+const ANALYSTS: Analyst[] = [
+ { id: 'sc', name: 'Sarah Chen', initials: 'SC', avatarColor: 'bg-violet-500', casesClosed: 47, avgResolutionMin: 18, accuracy: 96.2, score: 945, badges: ['MITRE Master', 'Speed Demon'] },
+ { id: 'mr', name: 'Marcus Rivera', initials: 'MR', avatarColor: 'bg-sky-500', casesClosed: 42, avgResolutionMin: 22, accuracy: 94.8, score: 892, badges: ['Zero FP', 'Night Owl'] },
+ { id: 'ap', name: 'Aisha Patel', initials: 'AP', avatarColor: 'bg-emerald-500',casesClosed: 39, avgResolutionMin: 15, accuracy: 97.1, score: 878, badges: ['Precision Strike', 'MITRE Master'] },
+ { id: 'jw', name: 'James Wong', initials: 'JW', avatarColor: 'bg-amber-500', casesClosed: 35, avgResolutionMin: 25, accuracy: 91.5, score: 812, badges: ['Speed Demon'] },
+ { id: 'ev', name: 'Elena Vasquez', initials: 'EV', avatarColor: 'bg-pink-500', casesClosed: 31, avgResolutionMin: 20, accuracy: 95.3, score: 785, badges: ['Mentor', 'Zero FP'] },
+ { id: 'dk', name: 'David Kim', initials: 'DK', avatarColor: 'bg-orange-500', casesClosed: 28, avgResolutionMin: 28, accuracy: 89.7, score: 721, badges: ['Newcomer Rising'] },
+];
+
+const ACHIEVEMENTS: Achievement[] = [
+ { text: 'Sarah Chen earned MITRE Master badge', timeAgo: '2 hours ago', icon: 'badge' },
+ { text: 'Marcus Rivera achieved Zero FP streak (30 days)', timeAgo: '5 hours ago', icon: 'streak' },
+ { text: 'Team closed 50 cases this week — new record!', timeAgo: '1 day ago', icon: 'record' },
+ { text: 'Aisha Patel reached #1 accuracy rating', timeAgo: '2 days ago', icon: 'rank' },
+];
+
+const RANK_ACCENTS: Record<number, { ring: string; text: string; label: string }> = {
+ 1: { ring: 'ring-2 ring-amber-400/60', text: 'text-amber-400', label: '🥇' },
+ 2: { ring: 'ring-2 ring-gray-300/40', text: 'text-gray-300', label: '🥈' },
+ 3: { ring: 'ring-2 ring-orange-400/40', text: 'text-orange-400', label: '🥉' },
+};
+
+type SortKey = 'score' | 'cases' | 'accuracy' | 'speed';
+
+function achievementIcon(icon: Achievement['icon']) {
+ switch (icon) {
+ case 'badge':
+ return (
+ <svg className="h-4 w-4 text-purple-400" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12c0 1.268-.63 2.39-1.593 3.068a3.745 3.745 0 01-1.043 3.296 3.745 3.745 0 01-3.296 1.043A3.745 3.745 0 0112 21c-1.268 0-2.39-.63-3.068-1.593a3.746 3.746 0 01-3.296-1.043 3.746 3.746 0 01-1.043-3.296A3.745 3.745 0 013 12c0-1.268.63-2.39 1.593-3.068a3.746 3.746 0 011.043-3.296 3.746 3.746 0 013.296-1.043A3.745 3.745 0 0112 3c1.268 0 2.39.63 3.068 1.593a3.746 3.746 0 013.296 1.043 3.746 3.746 0 011.043 3.296A3.745 3.745 0 0121 12z" />
+ </svg>
+ );
+ case 'streak':
+ return (
+ <svg className="h-4 w-4 text-green-400" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M15.362 5.214A8.252 8.252 0 0112 21 8.25 8.25 0 016.038 7.048 8.287 8.287 0 009 9.6a8.983 8.983 0 013.361-6.867 8.21 8.21 0 003 2.48z" />
+ <path strokeLinecap="round" strokeLinejoin="round" d="M12 18a3.75 3.75 0 00.495-7.467 5.99 5.99 0 00-1.925 3.546 5.974 5.974 0 01-2.133-1.001A3.75 3.75 0 0012 18z" />
+ </svg>
+ );
+ case 'record':
+ return (
+ <svg className="h-4 w-4 text-amber-400" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M16.5 18.75h-9m9 0a3 3 0 013 3h-15a3 3 0 013-3m9 0v-3.375c0-.621-.503-1.125-1.125-1.125h-.871M7.5 18.75v-3.375c0-.621.504-1.125 1.125-1.125h.872m5.007 0H9.497m5.007 0a7.454 7.454 0 01-.982-3.172M9.497 14.25a7.454 7.454 0 00.981-3.172M5.25 4.236c-.982.143-1.954.317-2.916.52A6.003 6.003 0 007.73 9.728M5.25 4.236V4.5c0 2.108.966 3.99 2.48 5.228M5.25 4.236V2.721C7.456 2.41 9.71 2.25 12 2.25c2.291 0 4.545.16 6.75.47v1.516M18.75 4.236c.982.143 1.954.317 2.916.52A6.003 6.003 0 0016.27 9.728M18.75 4.236V4.5c0 2.108-.966 3.99-2.48 5.228m0 0a6.003 6.003 0 01-4.52 1.522 6.003 6.003 0 01-4.52-1.522" />
+ </svg>
+ );
+ case 'rank':
+ return (
+ <svg className="h-4 w-4 text-blue-400" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 18L9 11.25l4.306 4.307a11.95 11.95 0 015.814-5.519l2.74-1.22m0 0l-5.94-2.28m5.94 2.28l-2.28 5.941" />
+ </svg>
+ );
+ }
+}
+
+export function TeamAnalyticsView() {
+ const [sortBy, setSortBy] = useState<SortKey>('score');
+
+ const totalCases = ANALYSTS.reduce((s, a) => s + a.casesClosed, 0);
+ const avgResolution = Math.round(ANALYSTS.reduce((s, a) => s + a.avgResolutionMin, 0) / ANALYSTS.length);
+ const teamAccuracy = (ANALYSTS.reduce((s, a) => s + a.accuracy, 0) / ANALYSTS.length).toFixed(1);
+ const totalBadges = ANALYSTS.reduce((s, a) => s + a.badges.length, 0);
+
+ const sorted = [...ANALYSTS].sort((a, b) => {
+ switch (sortBy) {
+ case 'score': return b.score - a.score;
+ case 'cases': return b.casesClosed - a.casesClosed;
+ case 'accuracy': return b.accuracy - a.accuracy;
+ case 'speed': return a.avgResolutionMin - b.avgResolutionMin;
+ }
+ });
+
+ const SORT_OPTIONS: { key: SortKey; label: string }[] = [
+ { key: 'score', label: 'Score' },
+ { key: 'cases', label: 'Cases' },
+ { key: 'accuracy', label: 'Accuracy' },
+ { key: 'speed', label: 'Speed' },
+ ];
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight text-white">Team Analytics</h1>
+ <p className="mt-1 text-sm text-gray-400">Analyst performance and gamification leaderboard</p>
+ </div>
+
+ {/* Aggregate stats */}
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
+ {[
+ { label: 'Cases Closed This Month', value: totalCases.toString(), accent: 'text-emerald-400' },
+ { label: 'Avg Resolution Time', value: `${avgResolution} min`, accent: 'text-sky-400' },
+ { label: 'Team Accuracy Rate', value: `${teamAccuracy}%`, accent: 'text-violet-400' },
+ { label: 'Total Badges Earned', value: totalBadges.toString(), accent: 'text-amber-400' },
+ ].map((stat) => (
+ <div key={stat.label} className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-5 space-y-4">
+ <p className="text-xs font-medium uppercase tracking-wider text-gray-400">{stat.label}</p>
+ <p className={clsx('text-3xl font-bold', stat.accent)}>{stat.value}</p>
+ </div>
+ ))}
+ </div>
+
+ {/* Leaderboard */}
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-5 space-y-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <h2 className="text-lg font-semibold text-white">Analyst Leaderboard</h2>
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-medium uppercase tracking-wider text-gray-500">Sort</span>
+ {SORT_OPTIONS.map((opt) => (
+ <button
+ key={opt.key}
+ onClick={() => setSortBy(opt.key)}
+ className={clsx(
+ 'rounded-md px-2.5 py-1 text-xs font-medium transition',
+ sortBy === opt.key
+ ? 'bg-white/10 text-white'
+ : 'text-gray-500 hover:text-gray-300',
+ )}
+ >
+ {opt.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="overflow-x-auto">
+ <table className="w-full text-left text-sm">
+ <thead>
+ <tr className="border-b border-gray-800/60 text-xs uppercase tracking-wider text-gray-500">
+ <th className="pb-3 pr-3 font-medium w-12">Rank</th>
+ <th className="pb-3 pr-3 font-medium">Analyst</th>
+ <th className="pb-3 pr-3 font-medium text-right">Cases</th>
+ <th className="pb-3 pr-3 font-medium text-right">Avg Time</th>
+ <th className="pb-3 pr-3 font-medium text-right">Accuracy</th>
+ <th className="pb-3 pr-3 font-medium text-right">Score</th>
+ <th className="pb-3 font-medium">Badges</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-gray-800/40">
+ {sorted.map((analyst, i) => {
+ const rank = i + 1;
+ const accent = RANK_ACCENTS[rank];
+ return (
+ <tr key={analyst.id} className="group transition hover:bg-white/[0.02]">
+ <td className="py-3 pr-3">
+ <span className={clsx('text-sm font-bold', accent?.text ?? 'text-gray-500')}>
+ {accent?.label ?? `#${rank}`}
+ </span>
+ </td>
+ <td className="py-3 pr-3">
+ <div className="flex items-center gap-3">
+ <div
+ className={clsx(
+ 'flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold text-white',
+ analyst.avatarColor,
+ accent?.ring,
+ )}
+ >
+ {analyst.initials}
+ </div>
+ <span className="font-medium text-white">{analyst.name}</span>
+ </div>
+ </td>
+ <td className="py-3 pr-3 text-right tabular-nums text-gray-300">
+ {analyst.casesClosed}
+ </td>
+ <td className="py-3 pr-3 text-right tabular-nums text-gray-300">
+ {analyst.avgResolutionMin} min
+ </td>
+ <td className="py-3 pr-3 text-right tabular-nums text-gray-300">
+ {analyst.accuracy.toFixed(1)}%
+ </td>
+ <td className="py-3 pr-3 text-right">
+ <span className={clsx('tabular-nums font-bold', accent?.text ?? 'text-white')}>
+ {analyst.score}
+ </span>
+ </td>
+ <td className="py-3">
+ <div className="flex flex-wrap gap-1.5">
+ {analyst.badges.map((badge) => {
+ const bc = BADGE_COLORS[badge] ?? { bg: 'bg-gray-500/15', text: 'text-gray-300', border: 'border-gray-500/30' };
+ return (
+ <span
+ key={badge}
+ className={clsx(
+ 'inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold',
+ bc.bg, bc.text, bc.border,
+ )}
+ >
+ {badge}
+ </span>
+ );
+ })}
+ </div>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ {/* Team Highlights */}
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-5 space-y-4">
+ <h2 className="text-lg font-semibold text-white">Team Highlights</h2>
+ <div className="space-y-3">
+ {ACHIEVEMENTS.map((ach, i) => (
+ <div
+ key={i}
+ className="flex items-start gap-3 rounded-lg border border-gray-800/40 bg-black/20 p-3.5"
+ >
+ <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-white/5">
+ {achievementIcon(ach.icon)}
+ </div>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium text-gray-200">{ach.text}</p>
+ <p className="mt-0.5 text-xs text-gray-500">{ach.timeAgo}</p>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsx
index dc07e37ae..316b4efef 100644
--- a/apps/web/src/components/cases/CasesView.tsx
+++ b/apps/web/src/components/cases/CasesView.tsx
@@ -88,10 +88,10 @@ function CaseCard({ c }: { c: Case }) {
)}
</div>
</div>
- <div className="text-right shrink-0">
+ <div className="text-right shrink-0 flex flex-col items-end gap-2">
<p className="text-xs text-gray-500" suppressHydrationWarning>{format(new Date(c.createdAt), 'MMM dd, HH:mm')}</p>
{c.tags && c.tags.length > 0 && (
- <div className="flex flex-wrap gap-1 mt-2 justify-end">
+ <div className="flex flex-wrap gap-1 justify-end">
{c.tags.slice(0, 2).map((tag) => (
<span key={tag} className="text-xs text-gray-500 bg-gray-800 px-1.5 py-0.5 rounded">
{tag}
@@ -99,6 +99,18 @@ function CaseCard({ c }: { c: Case }) {
))}
</div>
)}
+ <button
+ onClick={(e) => {
+ e.preventDefault();
+ toast.success('Incident report generated — downloading PDF');
+ }}
+ className="flex items-center gap-1 text-xs text-gray-500 hover:text-blue-400 transition-colors opacity-0 group-hover:opacity-100"
+ >
+ <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
+ </svg>
+ Export Report
+ </button>
</div>
</div>
</div>
diff --git a/apps/web/src/components/copilot/InvestigationChat.tsx b/apps/web/src/components/copilot/InvestigationChat.tsx
new file mode 100644
index 000000000..689e476d2
--- /dev/null
+++ b/apps/web/src/components/copilot/InvestigationChat.tsx
@@ -0,0 +1,258 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+
+type MessageRole = 'user' | 'assistant' | 'system';
+
+interface ChatMessage {
+ id: string;
+ role: MessageRole;
+ content: string;
+ timestamp: string;
+}
+
+const QUICK_ACTIONS = [
+ 'Investigate Alert',
+ 'Summarize Case',
+ 'Find IOCs',
+ 'Check Reputation',
+] as const;
+
+const MOCK_RESPONSES: Record<string, string> = {
+ 'investigate alert':
+ 'Analyzing alert ALT-4092... Identified lateral movement from 10.0.3.17 to DC01. ' +
+ 'The source host has 3 prior alerts in the last 48h. ATT&CK mapping: T1021.002 (SMB/Admin Shares). ' +
+ 'Recommend isolating the host and resetting credentials for svc-backup.',
+ 'summarize case':
+ 'Case CS-2187 Summary:\n' +
+ '- 7 correlated alerts across 3 hosts\n' +
+ '- Timeline: initial access at 02:14 UTC, privilege escalation at 02:31 UTC, exfil attempt at 03:05 UTC\n' +
+ '- Affected users: j.harlow, svc-backup\n' +
+ '- Current status: containment in progress, 2 hosts isolated',
+ 'find iocs':
+ 'Found 3 related IOCs across 2 tenants:\n' +
+ '1. IP 198.51.100.47 — C2 callback (confidence: 92%)\n' +
+ '2. Hash e3b0c442...b855 — LockBit dropper (confidence: 95%)\n' +
+ '3. Domain secure-login.example-phish.com — credential harvesting (confidence: 88%)\n\n' +
+ 'All three match STIX indicators published in the last 24h.',
+ 'check reputation':
+ 'Reputation check for 198.51.100.47:\n' +
+ '- VirusTotal: 14/87 engines flagged malicious\n' +
+ '- AbuseIPDB: reported 23 times, confidence 91%\n' +
+ '- First seen: 2025-04-12, Last seen: active\n' +
+ '- Associated campaigns: APT-42, Operation ShadowGate\n' +
+ '- Recommendation: block at perimeter immediately',
+};
+
+function getMockResponse(input: string): string {
+ const lower = input.toLowerCase();
+ for (const [key, response] of Object.entries(MOCK_RESPONSES)) {
+ if (lower.includes(key)) return response;
+ }
+ return (
+ `Analyzing your query: "${input}"\n\n` +
+ 'Found 3 related IOCs across 2 tenants. Cross-referencing with MITRE ATT&CK framework... ' +
+ 'Identified techniques T1078.002, T1059.001, and T1071.001. ' +
+ 'Risk assessment: HIGH. Recommend reviewing the correlated timeline in the case view.'
+ );
+}
+
+const CONTEXT = {
+ caseId: 'CS-2187',
+ alertCount: 7,
+ iocsFound: 3,
+ riskLevel: 'High',
+};
+
+export default function InvestigationChat() {
+ const [messages, setMessages] = useState<ChatMessage[]>([
+ {
+ id: 'sys-0',
+ role: 'system',
+ content: 'Investigation session started. Ask questions or use quick actions below.',
+ timestamp: new Date().toISOString(),
+ },
+ ]);
+ const [input, setInput] = useState('');
+ const [isTyping, setIsTyping] = useState(false);
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ }, [messages.length, isTyping]);
+
+ const sendMessage = (text: string) => {
+ const trimmed = text.trim();
+ if (!trimmed || isTyping) return;
+
+ const userMsg: ChatMessage = {
+ id: `u-${Date.now()}`,
+ role: 'user',
+ content: trimmed,
+ timestamp: new Date().toISOString(),
+ };
+ setMessages((prev) => [...prev, userMsg]);
+ setInput('');
+ setIsTyping(true);
+
+ setTimeout(() => {
+ const assistantMsg: ChatMessage = {
+ id: `a-${Date.now()}`,
+ role: 'assistant',
+ content: getMockResponse(trimmed),
+ timestamp: new Date().toISOString(),
+ };
+ setMessages((prev) => [...prev, assistantMsg]);
+ setIsTyping(false);
+ }, 500);
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ sendMessage(input);
+ }
+ };
+
+ return (
+ <div className="flex h-[calc(100vh-7rem)] gap-4">
+ {/* Main chat area */}
+ <div className="flex flex-1 flex-col rounded-xl border border-slate-800/80 bg-slate-900/40">
+ {/* Header */}
+ <div className="border-b border-slate-800/80 px-4 py-3">
+ <h1 className="text-base font-semibold text-white">Investigation Chat</h1>
+ <p className="text-xs text-slate-400">
+ AI-assisted threat investigation — ask about alerts, IOCs, or cases
+ </p>
+ </div>
+
+ {/* Messages */}
+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto p-4">
+ <ul className="mx-auto max-w-3xl space-y-3">
+ {messages.map((m) => {
+ if (m.role === 'system') {
+ return (
+ <li key={m.id} className="flex justify-center">
+ <span className="rounded-full bg-slate-800/50 px-3 py-1 text-xs text-slate-500">
+ {m.content}
+ </span>
+ </li>
+ );
+ }
+ const isUser = m.role === 'user';
+ return (
+ <li key={m.id} className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
+ <div
+ className={`max-w-[80%] whitespace-pre-wrap rounded-2xl px-4 py-3 text-sm ${
+ isUser
+ ? 'bg-blue-600/20 text-white ring-1 ring-blue-500/30'
+ : 'bg-slate-800/70 text-slate-100 ring-1 ring-slate-700/60'
+ }`}
+ >
+ {m.content}
+ </div>
+ </li>
+ );
+ })}
+ {isTyping && (
+ <li className="flex justify-start">
+ <div className="rounded-2xl bg-slate-800/70 px-4 py-3 ring-1 ring-slate-700/60">
+ <span className="inline-flex items-center gap-1 text-slate-400">
+ <span className="animate-pulse">●</span>
+ <span className="animate-pulse" style={{ animationDelay: '0.2s' }}>●</span>
+ <span className="animate-pulse" style={{ animationDelay: '0.4s' }}>●</span>
+ </span>
+ </div>
+ </li>
+ )}
+ </ul>
+ </div>
+
+ {/* Quick actions + input */}
+ <div className="border-t border-slate-800/80 p-3">
+ <div className="mx-auto flex max-w-3xl flex-wrap gap-2 pb-2">
+ {QUICK_ACTIONS.map((action) => (
+ <button
+ key={action}
+ onClick={() => sendMessage(action)}
+ disabled={isTyping}
+ className="rounded-full border border-slate-700/70 bg-slate-800/50 px-3 py-1.5 text-xs text-slate-300 transition-colors hover:border-blue-500/40 hover:bg-slate-700/60 hover:text-white disabled:opacity-50"
+ >
+ {action}
+ </button>
+ ))}
+ </div>
+ <div className="mx-auto flex max-w-3xl items-end gap-2 rounded-xl border border-slate-700/70 bg-slate-950/40 p-2 focus-within:border-blue-500/50">
+ <textarea
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={onKeyDown}
+ rows={1}
+ placeholder="Ask about an alert, IOC, or investigation…"
+ className="flex-1 resize-none bg-transparent px-2 py-2 text-sm text-slate-100 placeholder-slate-500 outline-none"
+ />
+ <button
+ onClick={() => sendMessage(input)}
+ disabled={!input.trim() || isTyping}
+ className={`flex-none rounded-lg px-3 py-2 text-sm font-semibold transition-colors ${
+ input.trim() && !isTyping
+ ? 'bg-blue-600 text-white hover:bg-blue-500'
+ : 'bg-slate-800 text-slate-500'
+ }`}
+ >
+ Send
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Context panel */}
+ <aside className="hidden w-64 flex-col gap-4 rounded-xl border border-slate-800/80 bg-slate-900/40 p-4 lg:flex">
+ <h2 className="text-sm font-semibold text-white">Investigation Context</h2>
+
+ <div className="space-y-3">
+ <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
+ <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
+ Case ID
+ </p>
+ <p className="mt-1 font-mono text-sm text-white">{CONTEXT.caseId}</p>
+ </div>
+
+ <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
+ <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
+ Alert Count
+ </p>
+ <p className="mt-1 text-2xl font-bold text-white">{CONTEXT.alertCount}</p>
+ </div>
+
+ <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
+ <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
+ IOCs Found
+ </p>
+ <p className="mt-1 text-2xl font-bold text-amber-400">{CONTEXT.iocsFound}</p>
+ </div>
+
+ <div className="rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
+ <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
+ Risk Level
+ </p>
+ <p className="mt-1 text-lg font-bold text-red-400">{CONTEXT.riskLevel}</p>
+ </div>
+ </div>
+
+ <div className="mt-auto rounded-lg border border-slate-800/80 bg-slate-800/30 p-3">
+ <p className="text-[11px] font-medium uppercase tracking-wider text-slate-500">
+ Session
+ </p>
+ <p className="mt-1 text-xs text-slate-400">
+ {messages.filter((m) => m.role === 'user').length} messages sent
+ </p>
+ <p className="text-xs text-slate-400">
+ {messages.filter((m) => m.role === 'assistant').length} AI responses
+ </p>
+ </div>
+ </aside>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/coverage/CoverageAdvisorView.tsx b/apps/web/src/components/coverage/CoverageAdvisorView.tsx
new file mode 100644
index 000000000..42908a30e
--- /dev/null
+++ b/apps/web/src/components/coverage/CoverageAdvisorView.tsx
@@ -0,0 +1,140 @@
+'use client';
+
+import { useState } from 'react';
+import { clsx } from 'clsx';
+import toast from 'react-hot-toast';
+
+type CoverageStatus = 'covered' | 'partial' | 'gap';
+type Priority = 'high' | 'medium' | 'low';
+
+interface Technique {
+ id: string;
+ name: string;
+ tactic: string;
+ status: CoverageStatus;
+ priority: Priority;
+ recommendation: string;
+}
+
+const TECHNIQUES: Technique[] = [
+ { id: 'T1059', name: 'Command and Scripting Interpreter', tactic: 'Execution', status: 'covered', priority: 'low', recommendation: 'Existing PowerShell & Bash rules active' },
+ { id: 'T1059.001', name: 'PowerShell', tactic: 'Execution', status: 'covered', priority: 'low', recommendation: 'ScriptBlock logging rule deployed' },
+ { id: 'T1071', name: 'Application Layer Protocol', tactic: 'Command & Control', status: 'partial', priority: 'medium', recommendation: 'Add DNS-over-HTTPS detection rule' },
+ { id: 'T1053', name: 'Scheduled Task/Job', tactic: 'Persistence', status: 'gap', priority: 'high', recommendation: 'Deploy schtasks / cron anomaly detection' },
+ { id: 'T1078', name: 'Valid Accounts', tactic: 'Initial Access', status: 'partial', priority: 'high', recommendation: 'Correlate impossible-travel with auth logs' },
+ { id: 'T1021', name: 'Remote Services', tactic: 'Lateral Movement', status: 'gap', priority: 'high', recommendation: 'Monitor RDP/SSH lateral pivots' },
+ { id: 'T1486', name: 'Data Encrypted for Impact', tactic: 'Impact', status: 'covered', priority: 'low', recommendation: 'Ransomware canary files active' },
+ { id: 'T1027', name: 'Obfuscated Files or Information', tactic: 'Defense Evasion', status: 'gap', priority: 'high', recommendation: 'Add entropy-based payload analysis' },
+ { id: 'T1562', name: 'Impair Defenses', tactic: 'Defense Evasion', status: 'partial', priority: 'medium', recommendation: 'Detect tamper of EDR services' },
+ { id: 'T1110', name: 'Brute Force', tactic: 'Credential Access', status: 'covered', priority: 'low', recommendation: 'Rate-limit rules deployed across tenants' },
+ { id: 'T1048', name: 'Exfiltration Over Alternative Protocol', tactic: 'Exfiltration', status: 'gap', priority: 'high', recommendation: 'Monitor DNS/ICMP tunneling patterns' },
+ { id: 'T1087', name: 'Account Discovery', tactic: 'Discovery', status: 'partial', priority: 'medium', recommendation: 'Alert on bulk LDAP enumeration' },
+ { id: 'T1547', name: 'Boot or Logon Autostart Execution',tactic: 'Persistence', status: 'gap', priority: 'medium', recommendation: 'Registry run-key change monitoring' },
+ { id: 'T1569', name: 'System Services', tactic: 'Execution', status: 'covered', priority: 'low', recommendation: 'Service creation audit rule active' },
+ { id: 'T1190', name: 'Exploit Public-Facing Application',tactic: 'Initial Access', status: 'partial', priority: 'high', recommendation: 'WAF log correlation with CVE feeds' },
+];
+
+const STATUS_STYLES: Record<CoverageStatus, { bg: string; text: string; label: string }> = {
+ covered: { bg: 'bg-green-500/20', text: 'text-green-400', label: 'Covered' },
+ partial: { bg: 'bg-amber-500/20', text: 'text-amber-400', label: 'Partial' },
+ gap: { bg: 'bg-red-500/20', text: 'text-red-400', label: 'Gap' },
+};
+
+const PRIORITY_STYLES: Record<Priority, { bg: string; text: string }> = {
+ high: { bg: 'bg-red-500/20', text: 'text-red-400' },
+ medium: { bg: 'bg-amber-500/20', text: 'text-amber-400' },
+ low: { bg: 'bg-green-500/20', text: 'text-green-400' },
+};
+
+export default function CoverageAdvisorView() {
+ const [techniques] = useState(TECHNIQUES);
+
+ const covered = techniques.filter((t) => t.status === 'covered').length;
+ const partial = techniques.filter((t) => t.status === 'partial').length;
+ const gaps = techniques.filter((t) => t.status === 'gap').length;
+ const coveragePct = Math.round(((covered + partial * 0.5) / techniques.length) * 100);
+
+ const summaryCards = [
+ { label: 'Techniques Covered', value: covered },
+ { label: 'Coverage %', value: `${coveragePct}%` },
+ { label: 'Critical Gaps', value: gaps },
+ { label: 'Recommended Detections', value: techniques.filter((t) => t.status !== 'covered').length },
+ ];
+
+ return (
+ <div className="space-y-8 p-6 max-w-7xl mx-auto">
+ <div>
+ <h1 className="text-2xl font-bold text-white">Coverage Gap Advisor</h1>
+ <p className="text-gray-400 mt-1">
+ Identify MITRE ATT&amp;CK coverage gaps and get actionable detection recommendations
+ </p>
+ </div>
+
+ {/* Summary Cards */}
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
+ {summaryCards.map((c) => (
+ <div key={c.label} className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-4">
+ <p className="text-xs text-gray-400 uppercase tracking-wider">{c.label}</p>
+ <p className="mt-1 text-2xl font-semibold text-white">{c.value}</p>
+ </div>
+ ))}
+ </div>
+
+ {/* Gap Analysis Table */}
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 overflow-hidden">
+ <div className="px-5 py-4 border-b border-gray-800/60">
+ <h2 className="text-lg font-semibold text-white">Gap Analysis</h2>
+ </div>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-gray-800/60 text-left text-gray-400">
+ <th className="px-5 py-3 font-medium">Technique</th>
+ <th className="px-5 py-3 font-medium">Name</th>
+ <th className="px-5 py-3 font-medium">Tactic</th>
+ <th className="px-5 py-3 font-medium text-center">Coverage</th>
+ <th className="px-5 py-3 font-medium text-center">Priority</th>
+ <th className="px-5 py-3 font-medium">Recommendation</th>
+ <th className="px-5 py-3 font-medium text-center">Action</th>
+ </tr>
+ </thead>
+ <tbody>
+ {techniques.map((t) => {
+ const st = STATUS_STYLES[t.status];
+ const pr = PRIORITY_STYLES[t.priority];
+ return (
+ <tr key={t.id} className="border-b border-gray-800/40 hover:bg-gray-800/30 transition-colors">
+ <td className="px-5 py-3 font-mono text-blue-400 text-xs">{t.id}</td>
+ <td className="px-5 py-3 text-white">{t.name}</td>
+ <td className="px-5 py-3 text-gray-300">{t.tactic}</td>
+ <td className="px-5 py-3 text-center">
+ <span className={clsx('inline-block px-2.5 py-0.5 rounded-full text-xs font-medium', st.bg, st.text)}>
+ {st.label}
+ </span>
+ </td>
+ <td className="px-5 py-3 text-center">
+ <span className={clsx('inline-block px-2.5 py-0.5 rounded-full text-xs font-medium capitalize', pr.bg, pr.text)}>
+ {t.priority}
+ </span>
+ </td>
+ <td className="px-5 py-3 text-gray-400 max-w-xs truncate">{t.recommendation}</td>
+ <td className="px-5 py-3 text-center">
+ {t.status !== 'covered' && (
+ <button
+ onClick={() => toast.success(`Detection rule draft created for ${t.id}`)}
+ className="text-xs px-2.5 py-1 rounded-lg bg-blue-600 hover:bg-blue-500 text-white transition-colors whitespace-nowrap"
+ >
+ Generate Detection
+ </button>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/easm/EASMView.tsx b/apps/web/src/components/easm/EASMView.tsx
new file mode 100644
index 000000000..a614802c5
--- /dev/null
+++ b/apps/web/src/components/easm/EASMView.tsx
@@ -0,0 +1,222 @@
+'use client';
+
+import { useState } from 'react';
+import { clsx } from 'clsx';
+
+type RiskLevel = 'critical' | 'high' | 'medium' | 'low' | 'info';
+type AssetType = 'domain' | 'ip' | 'cert' | 'subdomain' | 'service';
+
+interface Asset {
+ id: string;
+ asset: string;
+ type: AssetType;
+ status: 'healthy' | 'warning' | 'critical';
+ risk: RiskLevel;
+ lastSeen: string;
+}
+
+interface Certificate {
+ id: string;
+ domain: string;
+ issuer: string;
+ expiryDate: string;
+ daysRemaining: number;
+ status: 'valid' | 'expiring' | 'expired';
+}
+
+const RISK_CONFIG: Record<RiskLevel, { label: string; className: string }> = {
+ critical: { label: 'Critical', className: 'text-red-400 bg-red-500/10 border-red-500/20' },
+ high: { label: 'High', className: 'text-orange-400 bg-orange-500/10 border-orange-500/20' },
+ medium: { label: 'Medium', className: 'text-yellow-400 bg-yellow-500/10 border-yellow-500/20' },
+ low: { label: 'Low', className: 'text-blue-400 bg-blue-500/10 border-blue-500/20' },
+ info: { label: 'Info', className: 'text-gray-400 bg-gray-500/10 border-gray-500/20' },
+};
+
+const STATUS_COLOR: Record<Asset['status'], string> = {
+ healthy: 'text-green-400 bg-green-500/10 border-green-500/20',
+ warning: 'text-amber-400 bg-amber-500/10 border-amber-500/20',
+ critical: 'text-red-400 bg-red-500/10 border-red-500/20',
+};
+
+const CERT_STATUS_COLOR: Record<Certificate['status'], string> = {
+ valid: 'text-green-400 bg-green-500/10 border-green-500/20',
+ expiring: 'text-amber-400 bg-amber-500/10 border-amber-500/20',
+ expired: 'text-red-400 bg-red-500/10 border-red-500/20',
+};
+
+const TYPE_LABELS: Record<AssetType, string> = {
+ domain: 'Domain',
+ ip: 'IP Address',
+ cert: 'Certificate',
+ subdomain: 'Subdomain',
+ service: 'Service',
+};
+
+const MOCK_ASSETS: Asset[] = [
+ { id: 'a1', asset: 'corp.example.com', type: 'domain', status: 'healthy', risk: 'low', lastSeen: '2 min ago' },
+ { id: 'a2', asset: 'api.corp.example.com', type: 'subdomain', status: 'warning', risk: 'medium', lastSeen: '5 min ago' },
+ { id: 'a3', asset: '203.0.113.42', type: 'ip', status: 'critical', risk: 'critical', lastSeen: '1 min ago' },
+ { id: 'a4', asset: 'staging.example.com', type: 'subdomain', status: 'warning', risk: 'high', lastSeen: '12 min ago' },
+ { id: 'a5', asset: 'mail.corp.example.com', type: 'service', status: 'healthy', risk: 'low', lastSeen: '3 min ago' },
+ { id: 'a6', asset: '198.51.100.17', type: 'ip', status: 'healthy', risk: 'info', lastSeen: '8 min ago' },
+ { id: 'a7', asset: 'dev.internal.example.com', type: 'subdomain', status: 'critical', risk: 'high', lastSeen: '1 min ago' },
+ { id: 'a8', asset: 'vpn.corp.example.com', type: 'service', status: 'healthy', risk: 'medium', lastSeen: '4 min ago' },
+ { id: 'a9', asset: 'cdn.example.com', type: 'domain', status: 'healthy', risk: 'low', lastSeen: '6 min ago' },
+ { id: 'a10', asset: '192.0.2.88', type: 'ip', status: 'warning', risk: 'medium', lastSeen: '15 min ago' },
+];
+
+const MOCK_CERTIFICATES: Certificate[] = [
+ { id: 'c1', domain: 'corp.example.com', issuer: "Let's Encrypt", expiryDate: '2026-08-14', daysRemaining: 99, status: 'valid' },
+ { id: 'c2', domain: 'api.corp.example.com', issuer: 'DigiCert', expiryDate: '2026-05-21', daysRemaining: 14, status: 'expiring' },
+ { id: 'c3', domain: 'staging.example.com', issuer: "Let's Encrypt", expiryDate: '2026-05-03', daysRemaining: -4, status: 'expired' },
+ { id: 'c4', domain: 'mail.corp.example.com', issuer: 'Sectigo', expiryDate: '2027-01-10', daysRemaining: 248, status: 'valid' },
+ { id: 'c5', domain: 'vpn.corp.example.com', issuer: 'DigiCert', expiryDate: '2026-06-01', daysRemaining: 25, status: 'expiring' },
+ { id: 'c6', domain: 'dev.internal.example.com', issuer: 'Self-Signed', expiryDate: '2026-05-09', daysRemaining: 2, status: 'expiring' },
+];
+
+const SUMMARY = {
+ totalAssets: MOCK_ASSETS.length,
+ exposedServices: MOCK_ASSETS.filter((a) => a.status === 'critical' || a.status === 'warning').length,
+ certIssues: MOCK_CERTIFICATES.filter((c) => c.status !== 'valid').length,
+ riskScore: 72,
+};
+
+export function EASMView() {
+ const [assetFilter, setAssetFilter] = useState<Asset['status'] | 'all'>('all');
+
+ const filteredAssets = assetFilter === 'all'
+ ? MOCK_ASSETS
+ : MOCK_ASSETS.filter((a) => a.status === assetFilter);
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div>
+ <h1 className="text-xl font-semibold text-gray-100">External Attack Surface Management</h1>
+ <p className="text-sm text-gray-500 mt-0.5">Monitor external assets, exposed services, and certificate health</p>
+ </div>
+
+ {/* Summary Cards */}
+ <div className="grid grid-cols-4 gap-3">
+ {[
+ { label: 'Total Assets', value: SUMMARY.totalAssets, color: 'text-blue-400' },
+ { label: 'Exposed Services', value: SUMMARY.exposedServices, color: 'text-amber-400' },
+ { label: 'Certificate Issues', value: SUMMARY.certIssues, color: 'text-red-400' },
+ { label: 'Risk Score', value: `${SUMMARY.riskScore}/100`, color: SUMMARY.riskScore >= 70 ? 'text-amber-400' : 'text-green-400' },
+ ].map((card) => (
+ <div key={card.label} className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4">
+ <p className={clsx('text-2xl font-bold', card.color)}>{card.value}</p>
+ <p className="text-xs text-gray-500 mt-0.5">{card.label}</p>
+ </div>
+ ))}
+ </div>
+
+ {/* Asset Discovery Table */}
+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl overflow-hidden">
+ <div className="px-5 py-4 border-b border-gray-800/60 flex items-center justify-between">
+ <div>
+ <h2 className="text-sm font-semibold text-gray-200">Asset Discovery</h2>
+ <p className="text-xs text-gray-500 mt-0.5">{filteredAssets.length} assets found</p>
+ </div>
+ <div className="flex gap-2">
+ {(['all', 'healthy', 'warning', 'critical'] as const).map((f) => (
+ <button
+ key={f}
+ onClick={() => setAssetFilter(f)}
+ className={clsx(
+ 'text-xs px-3 py-1 rounded-lg border transition-colors',
+ assetFilter === f
+ ? 'bg-blue-600/15 text-blue-300 border-blue-600/30'
+ : 'text-gray-400 border-gray-800 hover:border-gray-700'
+ )}
+ >
+ {f === 'all' ? 'All' : f.charAt(0).toUpperCase() + f.slice(1)}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-gray-800/40">
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Asset</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Type</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Status</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Risk</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Last Seen</th>
+ </tr>
+ </thead>
+ <tbody>
+ {filteredAssets.map((asset) => (
+ <tr key={asset.id} className="border-b border-gray-800/30 hover:bg-gray-800/30 transition-colors">
+ <td className="px-5 py-3">
+ <span className="text-gray-200 font-mono text-xs">{asset.asset}</span>
+ </td>
+ <td className="px-5 py-3 text-gray-400 text-xs">{TYPE_LABELS[asset.type]}</td>
+ <td className="px-5 py-3">
+ <span className={clsx('text-xs font-medium px-2 py-0.5 rounded border', STATUS_COLOR[asset.status])}>
+ {asset.status.charAt(0).toUpperCase() + asset.status.slice(1)}
+ </span>
+ </td>
+ <td className="px-5 py-3">
+ <span className={clsx('text-xs font-medium px-2 py-0.5 rounded border', RISK_CONFIG[asset.risk].className)}>
+ {RISK_CONFIG[asset.risk].label}
+ </span>
+ </td>
+ <td className="px-5 py-3 text-xs text-gray-500">{asset.lastSeen}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ {/* Certificate Monitor */}
+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl overflow-hidden">
+ <div className="px-5 py-4 border-b border-gray-800/60">
+ <h2 className="text-sm font-semibold text-gray-200">Certificate Monitor</h2>
+ <p className="text-xs text-gray-500 mt-0.5">Track TLS certificate health and expiry dates</p>
+ </div>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-gray-800/40">
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Domain</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Issuer</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Expiry Date</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Days Remaining</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Status</th>
+ </tr>
+ </thead>
+ <tbody>
+ {MOCK_CERTIFICATES.map((cert) => (
+ <tr key={cert.id} className="border-b border-gray-800/30 hover:bg-gray-800/30 transition-colors">
+ <td className="px-5 py-3">
+ <span className="text-gray-200 font-mono text-xs">{cert.domain}</span>
+ </td>
+ <td className="px-5 py-3 text-gray-400 text-xs">{cert.issuer}</td>
+ <td className="px-5 py-3 text-gray-400 text-xs">{cert.expiryDate}</td>
+ <td className="px-5 py-3">
+ <span className={clsx(
+ 'text-xs font-medium',
+ cert.daysRemaining <= 0 ? 'text-red-400' :
+ cert.daysRemaining <= 30 ? 'text-amber-400' :
+ 'text-green-400'
+ )}>
+ {cert.daysRemaining <= 0 ? `${Math.abs(cert.daysRemaining)}d overdue` : `${cert.daysRemaining}d`}
+ </span>
+ </td>
+ <td className="px-5 py-3">
+ <span className={clsx('text-xs font-medium px-2 py-0.5 rounded border', CERT_STATUS_COLOR[cert.status])}>
+ {cert.status.charAt(0).toUpperCase() + cert.status.slice(1)}
+ </span>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsx
index 87ebc2441..b7b4184cb 100644
--- a/apps/web/src/components/layout/Sidebar.tsx
+++ b/apps/web/src/components/layout/Sidebar.tsx
@@ -98,6 +98,18 @@ const SparklesIcon = () => (
</svg>
);
+const ClockIcon = () => (
+ <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
+ </svg>
+);
+
+const ScanIcon = () => (
+ <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7.5 3.75H6A2.25 2.25 0 003.75 6v1.5M16.5 3.75H18A2.25 2.25 0 0120.25 6v1.5m0 9V18A2.25 2.25 0 0118 20.25h-1.5m-9 0H6A2.25 2.25 0 013.75 18v-1.5M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
+ </svg>
+);
+
const MarketplaceIcon = () => (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13.5 21v-7.5a.75.75 0 01.75-.75h3a.75.75 0 01.75.75V21m-4.5 0H2.36m11.14 0H18m0 0h3.64m-1.39 0V9.349m-16.5 11.65V9.35m0 0a3.001 3.001 0 003.75-.615A2.993 2.993 0 009.75 9.75c.896 0 1.7-.393 2.25-1.016a2.993 2.993 0 002.25 1.016c.896 0 1.7-.393 2.25-1.016a3.001 3.001 0 003.75.614m-16.5 0a3.004 3.004 0 01-.621-4.72L4.318 3.44A1.5 1.5 0 015.378 3h13.243a1.5 1.5 0 011.06.44l1.19 1.189a3 3 0 01-.621 4.72m-13.5 8.65h3.75a.75.75 0 00.75-.75V13.5a.75.75 0 00-.75-.75H6.75a.75.75 0 00-.75.75v3.75c0 .415.336.75.75.75z" />
@@ -149,6 +161,11 @@ const navSections: NavSection[] = [
href: '/detection/coverage',
icon: <ChartBarIcon />,
},
+ {
+ label: 'Shifts',
+ href: '/shifts',
+ icon: <ClockIcon />,
+ },
],
},
{
@@ -169,6 +186,21 @@ const navSections: NavSection[] = [
href: '/copilot',
icon: <SparklesIcon />,
},
+ {
+ label: 'Investigation Chat',
+ href: '/investigate',
+ icon: <SparklesIcon />,
+ },
+ {
+ label: 'Coverage Advisor',
+ href: '/coverage-advisor',
+ icon: <ShieldIcon />,
+ },
+ {
+ label: 'EASM',
+ href: '/easm',
+ icon: <ScanIcon />,
+ },
],
},
{
@@ -214,6 +246,21 @@ const navSections: NavSection[] = [
href: '/compliance',
icon: <ShieldIcon />,
},
+ {
+ label: 'Noise Tuning',
+ href: '/noise-tuning',
+ icon: <ChartBarIcon />,
+ },
+ {
+ label: 'MSSP Dashboard',
+ href: '/mssp',
+ icon: <GlobeIcon />,
+ },
+ {
+ label: 'Team Analytics',
+ href: '/analytics/team',
+ icon: <ChartBarIcon />,
+ },
{
label: 'SLA Tracking',
href: '/sla',
diff --git a/apps/web/src/components/mssp/MSSPDashboardView.tsx b/apps/web/src/components/mssp/MSSPDashboardView.tsx
new file mode 100644
index 000000000..cbab4381a
--- /dev/null
+++ b/apps/web/src/components/mssp/MSSPDashboardView.tsx
@@ -0,0 +1,129 @@
+'use client';
+
+import { useState } from 'react';
+import { clsx } from 'clsx';
+import toast from 'react-hot-toast';
+
+interface Tenant {
+ name: string;
+ activeAlerts: number;
+ openCases: number;
+ mttd: number;
+ mttr: number;
+ riskScore: number;
+ slaStatus: 'compliant' | 'warning' | 'breach';
+ arr: number;
+ analystAllocation: number;
+}
+
+const TENANTS: Tenant[] = [
+ { name: 'Acme Financial', activeAlerts: 12, openCases: 3, mttd: 4.2, mttr: 28, riskScore: 72, slaStatus: 'compliant', arr: 185000, analystAllocation: 2 },
+ { name: 'GlobalRetail Corp', activeAlerts: 47, openCases: 11, mttd: 8.7, mttr: 65, riskScore: 89, slaStatus: 'breach', arr: 320000, analystAllocation: 4 },
+ { name: 'MedSecure Health', activeAlerts: 8, openCases: 2, mttd: 3.1, mttr: 19, riskScore: 45, slaStatus: 'compliant', arr: 140000, analystAllocation: 1 },
+ { name: 'NovaTech Industries',activeAlerts: 23, openCases: 6, mttd: 6.5, mttr: 42, riskScore: 78, slaStatus: 'warning', arr: 260000, analystAllocation: 3 },
+ { name: 'Pinnacle Energy', activeAlerts: 5, openCases: 1, mttd: 2.8, mttr: 15, riskScore: 31, slaStatus: 'compliant', arr: 110000, analystAllocation: 1 },
+ { name: 'Stratos Logistics', activeAlerts: 31, openCases: 8, mttd: 7.9, mttr: 55, riskScore: 84, slaStatus: 'warning', arr: 275000, analystAllocation: 3 },
+];
+
+const SLA_STYLES: Record<Tenant['slaStatus'], { bg: string; text: string; label: string }> = {
+ compliant: { bg: 'bg-green-500/20', text: 'text-green-400', label: 'Compliant' },
+ warning: { bg: 'bg-amber-500/20', text: 'text-amber-400', label: 'Warning' },
+ breach: { bg: 'bg-red-500/20', text: 'text-red-400', label: 'Breach' },
+};
+
+function kpiCards(tenants: Tenant[]) {
+ const totalTenants = tenants.length;
+ const totalOpenCases = tenants.reduce((s, t) => s + t.openCases, 0);
+ const avgMTTD = tenants.reduce((s, t) => s + t.mttd, 0) / totalTenants;
+ const avgMTTR = tenants.reduce((s, t) => s + t.mttr, 0) / totalTenants;
+ const compliant = tenants.filter((t) => t.slaStatus === 'compliant').length;
+ const slaCompliance = Math.round((compliant / totalTenants) * 100);
+ const totalARR = tenants.reduce((s, t) => s + t.arr, 0);
+
+ return [
+ { label: 'Total Tenants', value: totalTenants },
+ { label: 'Total Open Cases', value: totalOpenCases },
+ { label: 'Avg MTTD', value: `${avgMTTD.toFixed(1)} min` },
+ { label: 'Avg MTTR', value: `${avgMTTR.toFixed(0)} min` },
+ { label: 'SLA Compliance', value: `${slaCompliance}%` },
+ { label: 'Total ARR', value: `$${(totalARR / 1000).toFixed(0)}K` },
+ ];
+}
+
+export default function MSSPDashboardView() {
+ const [tenants] = useState(TENANTS);
+ const cards = kpiCards(tenants);
+
+ return (
+ <div className="space-y-8 p-6 max-w-7xl mx-auto">
+ <div>
+ <h1 className="text-2xl font-bold text-white">MSSP Executive Dashboard</h1>
+ <p className="text-gray-400 mt-1">Cross-tenant security operations overview</p>
+ </div>
+
+ {/* KPI Cards */}
+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
+ {cards.map((c) => (
+ <div key={c.label} className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-4">
+ <p className="text-xs text-gray-400 uppercase tracking-wider">{c.label}</p>
+ <p className="mt-1 text-2xl font-semibold text-white">{c.value}</p>
+ </div>
+ ))}
+ </div>
+
+ {/* Tenant Table */}
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 overflow-hidden">
+ <div className="px-5 py-4 border-b border-gray-800/60 flex items-center justify-between">
+ <h2 className="text-lg font-semibold text-white">Tenant Overview</h2>
+ <button
+ onClick={() => toast.success('Report exported for all tenants')}
+ className="text-sm px-3 py-1.5 rounded-lg bg-blue-600 hover:bg-blue-500 text-white transition-colors"
+ >
+ Export Report
+ </button>
+ </div>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-gray-800/60 text-left text-gray-400">
+ <th className="px-5 py-3 font-medium">Tenant</th>
+ <th className="px-5 py-3 font-medium text-right">Active Alerts</th>
+ <th className="px-5 py-3 font-medium text-right">Open Cases</th>
+ <th className="px-5 py-3 font-medium text-right">MTTD (min)</th>
+ <th className="px-5 py-3 font-medium text-right">MTTR (min)</th>
+ <th className="px-5 py-3 font-medium text-right">Risk Score</th>
+ <th className="px-5 py-3 font-medium text-right">ARR</th>
+ <th className="px-5 py-3 font-medium text-right">Analysts</th>
+ <th className="px-5 py-3 font-medium text-center">SLA Status</th>
+ </tr>
+ </thead>
+ <tbody>
+ {tenants.map((t) => {
+ const sla = SLA_STYLES[t.slaStatus];
+ return (
+ <tr key={t.name} className="border-b border-gray-800/40 hover:bg-gray-800/30 transition-colors">
+ <td className="px-5 py-3 font-medium text-white">{t.name}</td>
+ <td className="px-5 py-3 text-right text-gray-300">{t.activeAlerts}</td>
+ <td className="px-5 py-3 text-right text-gray-300">{t.openCases}</td>
+ <td className="px-5 py-3 text-right text-gray-300">{t.mttd.toFixed(1)}</td>
+ <td className="px-5 py-3 text-right text-gray-300">{t.mttr}</td>
+ <td className={clsx('px-5 py-3 text-right font-medium', t.riskScore >= 80 ? 'text-red-400' : t.riskScore >= 60 ? 'text-amber-400' : 'text-green-400')}>
+ {t.riskScore}
+ </td>
+ <td className="px-5 py-3 text-right text-gray-300">${(t.arr / 1000).toFixed(0)}K</td>
+ <td className="px-5 py-3 text-right text-gray-300">{t.analystAllocation}</td>
+ <td className="px-5 py-3 text-center">
+ <span className={clsx('inline-block px-2.5 py-0.5 rounded-full text-xs font-medium', sla.bg, sla.text)}>
+ {sla.label}
+ </span>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/noise/NoiseTuningView.tsx b/apps/web/src/components/noise/NoiseTuningView.tsx
new file mode 100644
index 000000000..cbbc31df3
--- /dev/null
+++ b/apps/web/src/components/noise/NoiseTuningView.tsx
@@ -0,0 +1,158 @@
+'use client';
+
+import { useState } from 'react';
+import { clsx } from 'clsx';
+import toast from 'react-hot-toast';
+
+interface AlertRule {
+ name: string;
+ alertsFired: number;
+ tpCount: number;
+ fpCount: number;
+ autoTune: boolean;
+ suggestedAction: string;
+}
+
+const INITIAL_RULES: AlertRule[] = [
+ { name: 'Suspicious PowerShell Execution', alertsFired: 342, tpCount: 298, fpCount: 44, autoTune: true, suggestedAction: 'Exclude signed scripts from known admin hosts' },
+ { name: 'Failed Login Brute Force', alertsFired: 1205, tpCount: 180, fpCount: 1025, autoTune: false, suggestedAction: 'Raise threshold from 5 to 15 failed attempts' },
+ { name: 'Unusual Outbound DNS Volume', alertsFired: 87, tpCount: 72, fpCount: 15, autoTune: true, suggestedAction: 'Whitelist internal DNS forwarders' },
+ { name: 'Lateral Movement via SMB', alertsFired: 156, tpCount: 134, fpCount: 22, autoTune: true, suggestedAction: 'Exclude domain controller-to-DC traffic' },
+ { name: 'New Service Installation', alertsFired: 523, tpCount: 45, fpCount: 478, autoTune: false, suggestedAction: 'Filter SCCM and Intune deployment agents' },
+ { name: 'Anomalous Cloud API Call', alertsFired: 211, tpCount: 189, fpCount: 22, autoTune: true, suggestedAction: 'Baseline CI/CD service accounts' },
+ { name: 'Registry Run Key Modification', alertsFired: 94, tpCount: 81, fpCount: 13, autoTune: false, suggestedAction: 'Add GPO-deployed software to allowlist' },
+ { name: 'Potential Data Exfiltration', alertsFired: 38, tpCount: 35, fpCount: 3, autoTune: true, suggestedAction: 'No changes recommended — low FP rate' },
+ { name: 'Cleartext Credential in Logs', alertsFired: 678, tpCount: 102, fpCount: 576, autoTune: false, suggestedAction: 'Suppress alerts from log-rotation jobs' },
+ { name: 'TLS Certificate Anomaly', alertsFired: 145, tpCount: 120, fpCount: 25, autoTune: true, suggestedAction: 'Exclude internal CA-issued certs' },
+];
+
+export default function NoiseTuningView() {
+ const [rules, setRules] = useState(INITIAL_RULES);
+
+ const totalVerdicts = rules.reduce((s, r) => s + r.alertsFired, 0);
+ const totalFP = rules.reduce((s, r) => s + r.fpCount, 0);
+ const fpRate = ((totalFP / totalVerdicts) * 100).toFixed(1);
+ const autoTunedCount = rules.filter((r) => r.autoTune).length;
+ const noiseReduction = 34;
+
+ const summaryCards = [
+ { label: 'Total Verdicts This Month', value: totalVerdicts.toLocaleString() },
+ { label: 'FP Rate', value: `${fpRate}%` },
+ { label: 'Auto-Tuned Rules', value: autoTunedCount },
+ { label: 'Noise Reduction', value: `${noiseReduction}%` },
+ ];
+
+ function toggleAutoTune(index: number) {
+ setRules((prev) =>
+ prev.map((r, i) => (i === index ? { ...r, autoTune: !r.autoTune } : r)),
+ );
+ }
+
+ function ruleFpRate(r: AlertRule) {
+ return r.alertsFired > 0 ? (r.fpCount / r.alertsFired) * 100 : 0;
+ }
+
+ return (
+ <div className="space-y-8 p-6 max-w-7xl mx-auto">
+ <div>
+ <h1 className="text-2xl font-bold text-white">Alert Noise Tuning</h1>
+ <p className="text-gray-400 mt-1">Reduce false positives and optimize detection signal-to-noise ratio</p>
+ </div>
+
+ {/* Summary Cards */}
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
+ {summaryCards.map((c) => (
+ <div key={c.label} className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-4">
+ <p className="text-xs text-gray-400 uppercase tracking-wider">{c.label}</p>
+ <p className="mt-1 text-2xl font-semibold text-white">{c.value}</p>
+ </div>
+ ))}
+ </div>
+
+ {/* Noise Trend Placeholder */}
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-6">
+ <h2 className="text-lg font-semibold text-white mb-4">Noise Trend</h2>
+ <div className="h-48 rounded-lg bg-gray-800/50 border border-gray-700/50 flex items-center justify-center">
+ <div className="text-center">
+ <div className="flex items-center justify-center gap-1 mb-2">
+ {[40, 55, 35, 60, 45, 30, 25, 38, 20, 28, 18, 22].map((h, i) => (
+ <div
+ key={i}
+ className="w-6 rounded-t bg-gradient-to-t from-blue-600/80 to-blue-400/60"
+ style={{ height: `${h * 1.5}px` }}
+ />
+ ))}
+ </div>
+ <p className="text-sm text-gray-500">Monthly noise trend — FP volume declining</p>
+ </div>
+ </div>
+ </div>
+
+ {/* Rules Table */}
+ <div className="rounded-xl border border-gray-800/60 bg-gray-900/40 overflow-hidden">
+ <div className="px-5 py-4 border-b border-gray-800/60 flex items-center justify-between">
+ <h2 className="text-lg font-semibold text-white">Alert Rules</h2>
+ <button
+ onClick={() => toast.success('Tuning recommendations applied to 3 rules')}
+ className="text-sm px-3 py-1.5 rounded-lg bg-blue-600 hover:bg-blue-500 text-white transition-colors"
+ >
+ Apply Tuning
+ </button>
+ </div>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-gray-800/60 text-left text-gray-400">
+ <th className="px-5 py-3 font-medium">Rule Name</th>
+ <th className="px-5 py-3 font-medium text-right">Alerts Fired</th>
+ <th className="px-5 py-3 font-medium text-right">TP</th>
+ <th className="px-5 py-3 font-medium text-right">FP</th>
+ <th className="px-5 py-3 font-medium text-right">FP Rate</th>
+ <th className="px-5 py-3 font-medium text-center">Auto-Tune</th>
+ <th className="px-5 py-3 font-medium">Suggested Action</th>
+ </tr>
+ </thead>
+ <tbody>
+ {rules.map((r, i) => {
+ const fp = ruleFpRate(r);
+ return (
+ <tr key={r.name} className="border-b border-gray-800/40 hover:bg-gray-800/30 transition-colors">
+ <td className="px-5 py-3 font-medium text-white">{r.name}</td>
+ <td className="px-5 py-3 text-right text-gray-300">{r.alertsFired.toLocaleString()}</td>
+ <td className="px-5 py-3 text-right text-gray-300">{r.tpCount}</td>
+ <td className="px-5 py-3 text-right text-gray-300">{r.fpCount}</td>
+ <td
+ className={clsx(
+ 'px-5 py-3 text-right font-medium',
+ fp >= 70 ? 'text-red-400' : fp >= 30 ? 'text-amber-400' : 'text-green-400',
+ )}
+ >
+ {fp.toFixed(1)}%
+ </td>
+ <td className="px-5 py-3 text-center">
+ <button
+ onClick={() => toggleAutoTune(i)}
+ className={clsx(
+ 'relative inline-flex h-5 w-9 items-center rounded-full transition-colors',
+ r.autoTune ? 'bg-blue-600' : 'bg-gray-600',
+ )}
+ >
+ <span
+ className={clsx(
+ 'inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform',
+ r.autoTune ? 'translate-x-4.5' : 'translate-x-0.5',
+ )}
+ />
+ </button>
+ </td>
+ <td className="px-5 py-3 text-gray-400 max-w-xs truncate">{r.suggestedAction}</td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/shifts/ShiftsView.tsx b/apps/web/src/components/shifts/ShiftsView.tsx
new file mode 100644
index 000000000..7f8a28cab
--- /dev/null
+++ b/apps/web/src/components/shifts/ShiftsView.tsx
@@ -0,0 +1,162 @@
+'use client';
+
+import { useState } from 'react';
+import { clsx } from 'clsx';
+import toast from 'react-hot-toast';
+
+const SHIFT_START = '2026-05-07T06:00:00Z';
+const SHIFT_END = '2026-05-07T18:00:00Z';
+
+interface HandoffItem {
+ id: string;
+ priority: 'critical' | 'high' | 'medium' | 'low';
+ title: string;
+ type: 'alert' | 'case';
+ status: string;
+ assignedTo: string;
+ notes: string;
+}
+
+const PRIORITY_CONFIG = {
+ critical: { label: 'Critical', className: 'text-red-400 bg-red-500/10 border-red-500/20' },
+ high: { label: 'High', className: 'text-orange-400 bg-orange-500/10 border-orange-500/20' },
+ medium: { label: 'Medium', className: 'text-yellow-400 bg-yellow-500/10 border-yellow-500/20' },
+ low: { label: 'Low', className: 'text-blue-400 bg-blue-500/10 border-blue-500/20' },
+};
+
+const MOCK_HANDOFF_ITEMS: HandoffItem[] = [
+ { id: 'ALR-4201', priority: 'critical', title: 'Ransomware beacon detected on FIN-WS-07', type: 'alert', status: 'Investigating', assignedTo: 'alice', notes: 'Host isolated, awaiting forensic image' },
+ { id: 'CASE-1042', priority: 'high', title: 'Lateral movement — domain admin credentials', type: 'case', status: 'In Progress', assignedTo: 'bob', notes: 'Credential rotation started, 3 hosts remain' },
+ { id: 'ALR-4198', priority: 'high', title: 'Exfil over DNS to suspicious TLD', type: 'alert', status: 'Triaged', assignedTo: 'alice', notes: 'DNS sinkhole active, reviewing PCAP' },
+ { id: 'ALR-4205', priority: 'medium', title: 'Brute-force against VPN gateway', type: 'alert', status: 'Monitoring', assignedTo: 'carol', notes: 'Rate limiting applied, source geo: RU' },
+ { id: 'CASE-1039', priority: 'medium', title: 'Phishing wave targeting engineering', type: 'case', status: 'Pending Response', assignedTo: 'bob', notes: 'Awaiting HR confirmation on affected users' },
+ { id: 'ALR-4210', priority: 'medium', title: 'Anomalous S3 bucket access pattern', type: 'alert', status: 'Triaged', assignedTo: 'carol', notes: 'Likely automated scanner, needs second look' },
+ { id: 'ALR-4212', priority: 'low', title: 'Failed MFA attempts — service account', type: 'alert', status: 'Open', assignedTo: 'unassigned', notes: 'May be misconfigured CI pipeline' },
+ { id: 'ALR-4215', priority: 'low', title: 'Certificate expiry warning — api.corp.io', type: 'alert', status: 'Open', assignedTo: 'unassigned', notes: 'Expires in 7 days, renewal ticket created' },
+];
+
+const SHIFT_SUMMARY = {
+ alertsTriaged: 34,
+ casesOpened: 3,
+ escalations: 2,
+ autoResolved: 18,
+};
+
+export function ShiftsView() {
+ const [items] = useState(MOCK_HANDOFF_ITEMS);
+
+ const handleGenerateReport = () => {
+ toast.success('Handoff report generated');
+ };
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-xl font-semibold text-gray-100">Shift Handoff</h1>
+ <p className="text-sm text-gray-500 mt-0.5">Review open items and hand off to the next shift</p>
+ </div>
+ <button
+ onClick={handleGenerateReport}
+ className="flex items-center gap-2 bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
+ >
+ <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
+ </svg>
+ Generate Handoff Report
+ </button>
+ </div>
+
+ {/* Current Shift Status */}
+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-5">
+ <div className="flex items-center gap-3 mb-4">
+ <div className="w-2.5 h-2.5 rounded-full bg-green-400 animate-pulse" />
+ <h2 className="text-sm font-semibold text-gray-200">Active Shift</h2>
+ </div>
+ <div className="grid grid-cols-4 gap-4">
+ <div>
+ <p className="text-xs text-gray-500">Analyst On Duty</p>
+ <p className="text-sm font-medium text-gray-200 mt-0.5">Alice Chen</p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Shift Start</p>
+ <p className="text-sm font-medium text-gray-200 mt-0.5">{new Date(SHIFT_START).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Shift End</p>
+ <p className="text-sm font-medium text-gray-200 mt-0.5">{new Date(SHIFT_END).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</p>
+ </div>
+ <div>
+ <p className="text-xs text-gray-500">Hours Remaining</p>
+ <p className="text-sm font-medium text-amber-400 mt-0.5">4h 12m</p>
+ </div>
+ </div>
+ </div>
+
+ {/* Shift Summary */}
+ <div className="grid grid-cols-4 gap-3">
+ {[
+ { label: 'Alerts Triaged', value: SHIFT_SUMMARY.alertsTriaged, color: 'text-blue-400' },
+ { label: 'Cases Opened', value: SHIFT_SUMMARY.casesOpened, color: 'text-orange-400' },
+ { label: 'Escalations', value: SHIFT_SUMMARY.escalations, color: 'text-red-400' },
+ { label: 'Auto-Resolved', value: SHIFT_SUMMARY.autoResolved, color: 'text-green-400' },
+ ].map((stat) => (
+ <div key={stat.label} className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4">
+ <p className={clsx('text-2xl font-bold', stat.color)}>{stat.value}</p>
+ <p className="text-xs text-gray-500 mt-0.5">{stat.label}</p>
+ </div>
+ ))}
+ </div>
+
+ {/* Open Handoff Items */}
+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl overflow-hidden">
+ <div className="px-5 py-4 border-b border-gray-800/60">
+ <h2 className="text-sm font-semibold text-gray-200">Open Handoff Items</h2>
+ <p className="text-xs text-gray-500 mt-0.5">{items.length} items require attention from the incoming shift</p>
+ </div>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b border-gray-800/40">
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Priority</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Alert / Case</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Status</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Assigned To</th>
+ <th className="text-left text-xs font-medium text-gray-500 px-5 py-3">Notes</th>
+ </tr>
+ </thead>
+ <tbody>
+ {items.map((item) => {
+ const prio = PRIORITY_CONFIG[item.priority];
+ return (
+ <tr key={item.id} className="border-b border-gray-800/30 hover:bg-gray-800/30 transition-colors">
+ <td className="px-5 py-3">
+ <span className={clsx('text-xs font-medium px-2 py-0.5 rounded border', prio.className)}>
+ {prio.label}
+ </span>
+ </td>
+ <td className="px-5 py-3">
+ <div>
+ <span className="text-gray-200 font-medium">{item.id}</span>
+ <span className="text-gray-500 ml-2 text-xs">({item.type})</span>
+ </div>
+ <p className="text-xs text-gray-400 mt-0.5 truncate max-w-xs">{item.title}</p>
+ </td>
+ <td className="px-5 py-3 text-gray-300">{item.status}</td>
+ <td className="px-5 py-3">
+ <span className={clsx('text-sm', item.assignedTo === 'unassigned' ? 'text-gray-600 italic' : 'text-gray-300')}>
+ {item.assignedTo}
+ </span>
+ </td>
+ <td className="px-5 py-3 text-xs text-gray-400 max-w-xs truncate">{item.notes}</td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/services/agents/app/agents/auto_triage_agent.py b/services/agents/app/agents/auto_triage_agent.py
new file mode 100644
index 000000000..f5d4b8d10
--- /dev/null
+++ b/services/agents/app/agents/auto_triage_agent.py
@@ -0,0 +1,260 @@
+"""
+Auto-Triage Agent: LLM-based autonomous alert classification.
+
+Uses structured LLM reasoning to classify alerts as true_positive,
+false_positive, or benign — replacing simple keyword heuristics with
+contextual analysis. High-confidence FP/benign verdicts are auto-closed;
+uncertain alerts escalate into the full triage → enrichment → investigation
+pipeline.
+
+Metrics (module-level counters) are exposed via the /triage/stats API.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from typing import Any
+
+import structlog
+from langchain_core.messages import HumanMessage, SystemMessage
+from langchain_openai import ChatOpenAI
+
+from app.models.state import AgentStatus, InvestigationState
+
+logger = structlog.get_logger()
+
+AUTO_CLOSE_THRESHOLD: float = float(os.getenv("AISOC_AUTO_CLOSE_THRESHOLD", "0.85"))
+
+_metrics: dict[str, Any] = {
+ "auto_resolved_count": 0,
+ "escalated_count": 0,
+ "total_processed": 0,
+ "confidence_sum": 0.0,
+ "fp_count": 0,
+ "benign_count": 0,
+ "tp_count": 0,
+}
+
+_SYSTEM_PROMPT = """\
+You are the Auto-Triage Agent of an AI Security Operations Centre.
+
+Given a security alert (summary + raw payload), classify it into exactly one
+of three verdicts:
+
+ • true_positive — the alert describes a genuine security threat that
+ requires investigation and potential response.
+ • false_positive — the alert was triggered by benign activity that
+ superficially resembles a threat (e.g. scheduled vulnerability scans,
+ authorised pen-tests, known-good software flagged by signature).
+ • benign — the alert describes real but non-threatening activity that
+ does not warrant investigation (e.g. informational log, expected
+ configuration change).
+
+You MUST respond with a JSON object and nothing else:
+{
+ "verdict": "true_positive" | "false_positive" | "benign",
+ "confidence": <float 0.0–1.0>,
+ "rationale": "<2-4 sentence explanation of your reasoning>"
+}
+
+Reasoning guidelines:
+- Consider the severity, IOC presence, MITRE technique IDs, and alert context.
+- Vendor risk_score > 0.7 with critical keywords strongly suggests TP.
+- Alerts about scheduled scans, test environments, or known-good hashes lean FP.
+- Informational alerts with no IOCs and low risk lean benign.
+- Be conservative: when uncertain, lean toward true_positive to avoid missing threats.
+- confidence should reflect how certain you are, not the severity of the threat.
+"""
+
+
+def get_metrics() -> dict[str, Any]:
+ """Return a copy of current auto-triage metrics."""
+ m = _metrics.copy()
+ total = m["total_processed"]
+ m["auto_resolution_rate"] = (
+ m["auto_resolved_count"] / total if total > 0 else 0.0
+ )
+ m["fp_rate"] = m["fp_count"] / total if total > 0 else 0.0
+ m["avg_confidence"] = m["confidence_sum"] / total if total > 0 else 0.0
+ return m
+
+
+def get_threshold() -> float:
+ """Return the current auto-close confidence threshold."""
+ return AUTO_CLOSE_THRESHOLD
+
+
+def set_threshold(value: float) -> float:
+ """Update the auto-close confidence threshold. Returns the new value."""
+ global AUTO_CLOSE_THRESHOLD # noqa: PLW0603
+ value = max(0.0, min(1.0, value))
+ AUTO_CLOSE_THRESHOLD = value
+ return AUTO_CLOSE_THRESHOLD
+
+
+def _build_alert_context(state: InvestigationState) -> str:
+ """Serialise the alert into a compact string the LLM can reason over."""
+ raw = state.raw_alert
+ parts = [
+ f"Alert Summary: {state.alert_summary}",
+ f"Severity (vendor): {raw.get('severity', 'unknown')}",
+ f"Risk Score (vendor): {raw.get('risk_score', 'N/A')}",
+ ]
+
+ ioc_fields = {
+ "src_ip": "Source IP",
+ "dst_ip": "Destination IP",
+ "domain": "Domain",
+ "file_hash": "File Hash",
+ "url": "URL",
+ "hostname": "Hostname",
+ }
+ present_iocs = {label: raw[key] for key, label in ioc_fields.items() if raw.get(key)}
+ if present_iocs:
+ parts.append("IOCs present: " + ", ".join(f"{k}={v}" for k, v in present_iocs.items()))
+ else:
+ parts.append("IOCs present: none")
+
+ techniques = raw.get("mitre_techniques", [])
+ if techniques:
+ parts.append(f"MITRE Techniques: {', '.join(techniques)}")
+
+ extra_keys = {k for k in raw if k not in {"severity", "risk_score", "mitre_techniques", *ioc_fields}}
+ if extra_keys:
+ extras = {k: raw[k] for k in sorted(extra_keys)[:10]}
+ parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+
+ return "\n".join(parts)
+
+
+def _parse_llm_response(text: str) -> dict[str, Any]:
+ """Extract the JSON verdict from the LLM response, tolerating markdown fences."""
+ cleaned = text.strip()
+ if cleaned.startswith("```"):
+ lines = cleaned.split("\n")
+ lines = [l for l in lines if not l.strip().startswith("```")]
+ cleaned = "\n".join(lines).strip()
+
+ try:
+ data = json.loads(cleaned)
+ except json.JSONDecodeError:
+ start = cleaned.find("{")
+ end = cleaned.rfind("}") + 1
+ if start >= 0 and end > start:
+ data = json.loads(cleaned[start:end])
+ else:
+ raise
+
+ verdict = data.get("verdict", "true_positive")
+ if verdict not in ("true_positive", "false_positive", "benign"):
+ verdict = "true_positive"
+
+ confidence = float(data.get("confidence", 0.5))
+ confidence = max(0.0, min(1.0, confidence))
+
+ rationale = data.get("rationale", "No rationale provided by LLM.")
+
+ return {
+ "verdict": verdict,
+ "confidence": confidence,
+ "rationale": str(rationale),
+ }
+
+
+async def run_auto_triage(state: InvestigationState) -> InvestigationState:
+ """
+ LLM-based auto-triage: classify the alert and decide whether to
+ auto-close (FP/benign with high confidence) or escalate.
+ """
+ logger.info("Auto-triage agent starting", incident_id=str(state.incident_id))
+
+ state.status = AgentStatus.RUNNING
+ state.iteration_count += 1
+
+ alert_context = _build_alert_context(state)
+
+ model_name = os.getenv("AISOC_LLM_MODEL", "gpt-4o-mini")
+ llm = ChatOpenAI(model=model_name, temperature=0.0, max_tokens=512)
+
+ t0 = time.monotonic()
+ try:
+ response = await llm.ainvoke([
+ SystemMessage(content=_SYSTEM_PROMPT),
+ HumanMessage(content=alert_context),
+ ])
+ raw_text = response.content
+ result = _parse_llm_response(raw_text)
+ except Exception as exc:
+ logger.error("Auto-triage LLM call failed, escalating", error=str(exc))
+ state.add_finding(f"Auto-triage LLM error: {exc} — escalating to manual triage")
+ _metrics["escalated_count"] += 1
+ _metrics["total_processed"] += 1
+ return state
+
+ elapsed_ms = round((time.monotonic() - t0) * 1000)
+
+ verdict = result["verdict"]
+ confidence = result["confidence"]
+ rationale = result["rationale"]
+
+ _metrics["total_processed"] += 1
+ _metrics["confidence_sum"] += confidence
+ if verdict == "false_positive":
+ _metrics["fp_count"] += 1
+ elif verdict == "benign":
+ _metrics["benign_count"] += 1
+ else:
+ _metrics["tp_count"] += 1
+
+ state.confidence = confidence
+ state.verdict = verdict
+ state.confidence_basis = [
+ f"LLM auto-triage verdict: {verdict}",
+ f"LLM confidence: {confidence:.2f}",
+ f"Rationale: {rationale}",
+ ]
+
+ state.add_finding(
+ f"Auto-triage: verdict={verdict}, confidence={confidence:.2f}, "
+ f"latency={elapsed_ms}ms"
+ )
+ state.add_finding(f"Auto-triage rationale: {rationale}")
+
+ should_auto_close = (
+ verdict in ("false_positive", "benign")
+ and confidence >= AUTO_CLOSE_THRESHOLD
+ )
+
+ if should_auto_close:
+ _metrics["auto_resolved_count"] += 1
+ state.status = AgentStatus.COMPLETED
+ state.add_finding(
+ f"Auto-closed as {verdict} (confidence {confidence:.2f} >= "
+ f"threshold {AUTO_CLOSE_THRESHOLD:.2f})"
+ )
+ logger.info(
+ "Auto-triage: auto-closed",
+ verdict=verdict,
+ confidence=round(confidence, 2),
+ threshold=AUTO_CLOSE_THRESHOLD,
+ incident_id=str(state.incident_id),
+ elapsed_ms=elapsed_ms,
+ )
+ else:
+ _metrics["escalated_count"] += 1
+ state.add_finding(
+ f"Escalating to full pipeline — "
+ f"{'TP verdict' if verdict == 'true_positive' else f'confidence {confidence:.2f} < threshold {AUTO_CLOSE_THRESHOLD:.2f}'}"
+ )
+ logger.info(
+ "Auto-triage: escalating",
+ verdict=verdict,
+ confidence=round(confidence, 2),
+ threshold=AUTO_CLOSE_THRESHOLD,
+ incident_id=str(state.incident_id),
+ elapsed_ms=elapsed_ms,
+ )
+
+ return state
diff --git a/services/agents/app/agents/cloud_agent.py b/services/agents/app/agents/cloud_agent.py
new file mode 100644
index 000000000..fbfcf1690
--- /dev/null
+++ b/services/agents/app/agents/cloud_agent.py
@@ -0,0 +1,220 @@
+"""
+Cloud Infrastructure Analysis Agent: investigates cloud-related alerts.
+
+Analyses misconfigurations (public buckets, open security groups), IAM
+anomalies (excessive permissions, unusual API calls), and infrastructure
+drift. Uses structured LLM reasoning to classify the alert and assign
+a confidence-weighted verdict.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from typing import Any
+
+import structlog
+from langchain_core.messages import HumanMessage, SystemMessage
+from langchain_openai import ChatOpenAI
+
+from app.models.state import AgentStatus, InvestigationState
+
+logger = structlog.get_logger()
+
+_SYSTEM_PROMPT = """\
+You are the Cloud Infrastructure Analysis Agent of an AI Security Operations
+Centre.
+
+Given a security alert related to cloud infrastructure (AWS, Azure, GCP, or
+other providers), perform a deep investigation and produce a structured
+assessment.
+
+Evaluate the following patterns:
+1. Storage exposure — publicly accessible S3 buckets, GCS buckets, or Azure
+ Blob containers. Check ACL and bucket policy for unintended public access.
+2. Security group / firewall misconfigs — overly permissive inbound rules
+ (0.0.0.0/0 on sensitive ports), missing egress restrictions.
+3. IAM anomalies — principals with excessive privileges, unused admin
+ credentials, cross-account role assumption from unknown accounts.
+4. Unusual API activity — high-volume enumeration (ListBuckets, DescribeInstances),
+ calls from unexpected regions or IP ranges, service actions rarely used by
+ the principal.
+5. Infrastructure drift — resources deployed outside of IaC, manual changes to
+ production, disabled CloudTrail / audit logging.
+
+You MUST respond with a JSON object and nothing else:
+{
+ "verdict": "true_positive" | "false_positive" | "benign",
+ "confidence": <float 0.0–1.0>,
+ "cloud_indicators": ["<indicator1>", "<indicator2>", ...],
+ "risk_category": "storage_exposure" | "security_group_misconfig" |
+ "iam_anomaly" | "unusual_api" | "infra_drift" | "unknown",
+ "cloud_provider": "aws" | "azure" | "gcp" | "other",
+ "rationale": "<2-4 sentence explanation>"
+}
+"""
+
+
+def _build_cloud_context(state: InvestigationState) -> str:
+ """Serialise alert data into a cloud-focused analysis prompt."""
+ raw = state.raw_alert
+ parts = [
+ f"Alert Summary: {state.alert_summary}",
+ f"Severity: {raw.get('severity', 'unknown')}",
+ ]
+
+ cloud_fields = {
+ "cloud_provider": "Cloud Provider",
+ "region": "Region",
+ "account_id": "Account ID",
+ "project_id": "Project ID",
+ "subscription_id": "Subscription ID",
+ "resource_type": "Resource Type",
+ "resource_id": "Resource ID",
+ "resource_arn": "Resource ARN",
+ "service": "Service",
+ "action": "API Action",
+ "principal": "Principal",
+ "principal_arn": "Principal ARN",
+ "source_ip": "Source IP",
+ }
+ for key, label in cloud_fields.items():
+ if raw.get(key):
+ parts.append(f"{label}: {raw[key]}")
+
+ if raw.get("bucket_acl") or raw.get("bucket_policy"):
+ parts.append(f"Bucket ACL: {raw.get('bucket_acl', 'N/A')}")
+ if raw.get("bucket_policy"):
+ parts.append(f"Bucket Policy: {json.dumps(raw['bucket_policy'], default=str)[:500]}")
+
+ if raw.get("security_group_rules"):
+ parts.append(f"SG Rules: {json.dumps(raw['security_group_rules'], default=str)[:500]}")
+
+ if raw.get("iam_policy") or raw.get("permissions"):
+ val = raw.get("iam_policy") or raw.get("permissions")
+ parts.append(f"IAM/Permissions: {json.dumps(val, default=str)[:500]}")
+
+ if raw.get("api_calls"):
+ parts.append(f"API calls: {json.dumps(raw['api_calls'], default=str)[:500]}")
+
+ if raw.get("is_public") is not None:
+ parts.append(f"Public access: {raw['is_public']}")
+
+ if raw.get("finding_type"):
+ parts.append(f"Finding type: {raw['finding_type']}")
+
+ extra_keys = {k for k in raw if k not in {
+ "severity", "risk_score", *cloud_fields, "bucket_acl", "bucket_policy",
+ "security_group_rules", "iam_policy", "permissions", "api_calls",
+ "is_public", "finding_type",
+ }}
+ if extra_keys:
+ extras = {k: raw[k] for k in sorted(extra_keys)[:8]}
+ parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+
+ return "\n".join(parts)
+
+
+def _parse_response(text: str) -> dict[str, Any]:
+ """Extract JSON verdict from LLM output."""
+ cleaned = text.strip()
+ if cleaned.startswith("```"):
+ lines = cleaned.split("\n")
+ lines = [l for l in lines if not l.strip().startswith("```")]
+ cleaned = "\n".join(lines).strip()
+
+ try:
+ data = json.loads(cleaned)
+ except json.JSONDecodeError:
+ start = cleaned.find("{")
+ end = cleaned.rfind("}") + 1
+ if start >= 0 and end > start:
+ data = json.loads(cleaned[start:end])
+ else:
+ raise
+
+ verdict = data.get("verdict", "true_positive")
+ if verdict not in ("true_positive", "false_positive", "benign"):
+ verdict = "true_positive"
+
+ confidence = max(0.0, min(1.0, float(data.get("confidence", 0.5))))
+ indicators = data.get("cloud_indicators", [])
+ risk_category = data.get("risk_category", "unknown")
+ cloud_provider = data.get("cloud_provider", "other")
+ rationale = str(data.get("rationale", "No rationale provided."))
+
+ return {
+ "verdict": verdict,
+ "confidence": confidence,
+ "cloud_indicators": indicators,
+ "risk_category": risk_category,
+ "cloud_provider": cloud_provider,
+ "rationale": rationale,
+ }
+
+
+async def run_cloud(state: InvestigationState) -> InvestigationState:
+ """Analyse a cloud infrastructure alert for misconfiguration or compromise."""
+ logger.info("Cloud agent starting", incident_id=str(state.incident_id))
+
+ state.status = AgentStatus.RUNNING
+ state.iteration_count += 1
+
+ context = _build_cloud_context(state)
+
+ model_name = os.getenv("AISOC_LLM_MODEL", "gpt-4o-mini")
+ llm = ChatOpenAI(model=model_name, temperature=0.0, max_tokens=768)
+
+ t0 = time.monotonic()
+ try:
+ response = await llm.ainvoke([
+ SystemMessage(content=_SYSTEM_PROMPT),
+ HumanMessage(content=context),
+ ])
+ result = _parse_response(response.content)
+ except Exception as exc:
+ logger.error("Cloud agent LLM call failed", error=str(exc))
+ state.add_finding(f"Cloud analysis LLM error: {exc}")
+ return state
+
+ elapsed_ms = round((time.monotonic() - t0) * 1000)
+
+ verdict = result["verdict"]
+ confidence = result["confidence"]
+ indicators = result["cloud_indicators"]
+ risk_category = result["risk_category"]
+ cloud_provider = result["cloud_provider"]
+ rationale = result["rationale"]
+
+ state.confidence = confidence
+ state.verdict = verdict
+ state.confidence_basis = [
+ f"Cloud analysis verdict: {verdict}",
+ f"Risk category: {risk_category}",
+ f"Cloud provider: {cloud_provider}",
+ f"Confidence: {confidence:.2f}",
+ f"Indicators: {', '.join(indicators) if indicators else 'none'}",
+ f"Rationale: {rationale}",
+ ]
+
+ state.add_finding(
+ f"Cloud analysis: verdict={verdict}, category={risk_category}, "
+ f"provider={cloud_provider}, confidence={confidence:.2f}, "
+ f"indicators={len(indicators)}, latency={elapsed_ms}ms"
+ )
+ if indicators:
+ state.add_finding(f"Cloud indicators: {', '.join(indicators)}")
+ state.add_finding(f"Cloud rationale: {rationale}")
+
+ logger.info(
+ "Cloud analysis complete",
+ verdict=verdict,
+ risk_category=risk_category,
+ cloud_provider=cloud_provider,
+ confidence=round(confidence, 2),
+ indicator_count=len(indicators),
+ elapsed_ms=elapsed_ms,
+ incident_id=str(state.incident_id),
+ )
+ return state
diff --git a/services/agents/app/agents/identity_agent.py b/services/agents/app/agents/identity_agent.py
new file mode 100644
index 000000000..a78bda661
--- /dev/null
+++ b/services/agents/app/agents/identity_agent.py
@@ -0,0 +1,214 @@
+"""
+Identity & Authentication Analysis Agent: investigates auth-related alerts.
+
+Analyses impossible travel, credential stuffing, brute force, privilege
+escalation, and suspicious login patterns. Uses structured LLM reasoning
+to classify the alert and assign a confidence-weighted verdict.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from typing import Any
+
+import structlog
+from langchain_core.messages import HumanMessage, SystemMessage
+from langchain_openai import ChatOpenAI
+
+from app.models.state import AgentStatus, InvestigationState
+
+logger = structlog.get_logger()
+
+_SYSTEM_PROMPT = """\
+You are the Identity & Authentication Analysis Agent of an AI Security
+Operations Centre.
+
+Given a security alert related to identity, authentication, or access
+control, perform a deep investigation and produce a structured assessment.
+
+Evaluate the following patterns:
+1. Impossible travel — two logins from geographically distant locations
+ within a physically impossible time window. Consider VPNs as possible
+ benign explanations but still flag them.
+2. Credential stuffing / password spraying — many failed login attempts
+ across different accounts from the same source, or one account from
+ many sources.
+3. Brute force — repeated failed attempts on a single account within a
+ short time window.
+4. Privilege escalation — a user gaining admin rights, adding themselves
+ to privileged groups, or accessing resources far beyond their normal
+ scope.
+5. Anomalous session behaviour — concurrent sessions from different
+ devices, token replay, MFA bypass attempts.
+
+You MUST respond with a JSON object and nothing else:
+{
+ "verdict": "true_positive" | "false_positive" | "benign",
+ "confidence": <float 0.0–1.0>,
+ "identity_indicators": ["<indicator1>", "<indicator2>", ...],
+ "attack_type": "impossible_travel" | "credential_stuffing" | "brute_force" |
+ "privilege_escalation" | "session_anomaly" | "unknown",
+ "rationale": "<2-4 sentence explanation>"
+}
+"""
+
+
+def _build_identity_context(state: InvestigationState) -> str:
+ """Serialise alert data into an identity-focused analysis prompt."""
+ raw = state.raw_alert
+ parts = [
+ f"Alert Summary: {state.alert_summary}",
+ f"Severity: {raw.get('severity', 'unknown')}",
+ ]
+
+ identity_fields = {
+ "user": "User",
+ "username": "Username",
+ "user_email": "User Email",
+ "source_ip": "Source IP",
+ "source_geo": "Source Geo",
+ "dest_ip": "Destination IP",
+ "dest_geo": "Destination Geo",
+ "device": "Device",
+ "user_agent": "User Agent",
+ "auth_method": "Auth Method",
+ "mfa_status": "MFA Status",
+ }
+ for key, label in identity_fields.items():
+ if raw.get(key):
+ parts.append(f"{label}: {raw[key]}")
+
+ if raw.get("login_attempts"):
+ parts.append(f"Login attempts: {json.dumps(raw['login_attempts'], default=str)}")
+ if raw.get("failed_count"):
+ parts.append(f"Failed attempt count: {raw['failed_count']}")
+
+ geo_fields = ["login_locations", "geo_locations"]
+ for gf in geo_fields:
+ if raw.get(gf):
+ parts.append(f"Geo locations: {json.dumps(raw[gf], default=str)}")
+
+ priv_fields = ["role_change", "group_added", "permissions_changed", "privilege_level"]
+ priv_parts = []
+ for pf in priv_fields:
+ if raw.get(pf):
+ priv_parts.append(f"{pf}={raw[pf]}")
+ if priv_parts:
+ parts.append(f"Privilege changes: {', '.join(priv_parts)}")
+
+ if raw.get("timestamp"):
+ parts.append(f"Event time: {raw['timestamp']}")
+ if raw.get("previous_login"):
+ parts.append(f"Previous login: {json.dumps(raw['previous_login'], default=str)}")
+
+ extra_keys = {k for k in raw if k not in {
+ "severity", "risk_score", *identity_fields, "login_attempts",
+ "failed_count", *geo_fields, *priv_fields, "timestamp",
+ "previous_login",
+ }}
+ if extra_keys:
+ extras = {k: raw[k] for k in sorted(extra_keys)[:8]}
+ parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+
+ return "\n".join(parts)
+
+
+def _parse_response(text: str) -> dict[str, Any]:
+ """Extract JSON verdict from LLM output."""
+ cleaned = text.strip()
+ if cleaned.startswith("```"):
+ lines = cleaned.split("\n")
+ lines = [l for l in lines if not l.strip().startswith("```")]
+ cleaned = "\n".join(lines).strip()
+
+ try:
+ data = json.loads(cleaned)
+ except json.JSONDecodeError:
+ start = cleaned.find("{")
+ end = cleaned.rfind("}") + 1
+ if start >= 0 and end > start:
+ data = json.loads(cleaned[start:end])
+ else:
+ raise
+
+ verdict = data.get("verdict", "true_positive")
+ if verdict not in ("true_positive", "false_positive", "benign"):
+ verdict = "true_positive"
+
+ confidence = max(0.0, min(1.0, float(data.get("confidence", 0.5))))
+ indicators = data.get("identity_indicators", [])
+ attack_type = data.get("attack_type", "unknown")
+ rationale = str(data.get("rationale", "No rationale provided."))
+
+ return {
+ "verdict": verdict,
+ "confidence": confidence,
+ "identity_indicators": indicators,
+ "attack_type": attack_type,
+ "rationale": rationale,
+ }
+
+
+async def run_identity(state: InvestigationState) -> InvestigationState:
+ """Analyse an identity/authentication alert for compromise indicators."""
+ logger.info("Identity agent starting", incident_id=str(state.incident_id))
+
+ state.status = AgentStatus.RUNNING
+ state.iteration_count += 1
+
+ context = _build_identity_context(state)
+
+ model_name = os.getenv("AISOC_LLM_MODEL", "gpt-4o-mini")
+ llm = ChatOpenAI(model=model_name, temperature=0.0, max_tokens=768)
+
+ t0 = time.monotonic()
+ try:
+ response = await llm.ainvoke([
+ SystemMessage(content=_SYSTEM_PROMPT),
+ HumanMessage(content=context),
+ ])
+ result = _parse_response(response.content)
+ except Exception as exc:
+ logger.error("Identity agent LLM call failed", error=str(exc))
+ state.add_finding(f"Identity analysis LLM error: {exc}")
+ return state
+
+ elapsed_ms = round((time.monotonic() - t0) * 1000)
+
+ verdict = result["verdict"]
+ confidence = result["confidence"]
+ indicators = result["identity_indicators"]
+ attack_type = result["attack_type"]
+ rationale = result["rationale"]
+
+ state.confidence = confidence
+ state.verdict = verdict
+ state.confidence_basis = [
+ f"Identity analysis verdict: {verdict}",
+ f"Attack type: {attack_type}",
+ f"Confidence: {confidence:.2f}",
+ f"Indicators: {', '.join(indicators) if indicators else 'none'}",
+ f"Rationale: {rationale}",
+ ]
+
+ state.add_finding(
+ f"Identity analysis: verdict={verdict}, attack_type={attack_type}, "
+ f"confidence={confidence:.2f}, indicators={len(indicators)}, "
+ f"latency={elapsed_ms}ms"
+ )
+ if indicators:
+ state.add_finding(f"Identity indicators: {', '.join(indicators)}")
+ state.add_finding(f"Identity rationale: {rationale}")
+
+ logger.info(
+ "Identity analysis complete",
+ verdict=verdict,
+ attack_type=attack_type,
+ confidence=round(confidence, 2),
+ indicator_count=len(indicators),
+ elapsed_ms=elapsed_ms,
+ incident_id=str(state.incident_id),
+ )
+ return state
diff --git a/services/agents/app/agents/insider_threat_agent.py b/services/agents/app/agents/insider_threat_agent.py
new file mode 100644
index 000000000..4e6e50fac
--- /dev/null
+++ b/services/agents/app/agents/insider_threat_agent.py
@@ -0,0 +1,239 @@
+"""
+Insider Threat Analysis Agent: investigates insider-threat indicators.
+
+Analyses behavioural anomalies such as data exfiltration, off-hours access,
+bulk downloads, privilege abuse, USB device usage, and communication to
+personal accounts. Uses structured LLM reasoning to classify the alert and
+assign a confidence-weighted verdict.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from typing import Any
+
+import structlog
+from langchain_core.messages import HumanMessage, SystemMessage
+from langchain_openai import ChatOpenAI
+
+from app.models.state import AgentStatus, InvestigationState
+
+logger = structlog.get_logger()
+
+_SYSTEM_PROMPT = """\
+You are the Insider Threat Analysis Agent of an AI Security Operations Centre.
+
+Given a security alert that may indicate insider-threat activity, perform a
+thorough investigation and produce a structured assessment.
+
+Evaluate the following behavioural patterns:
+1. Data exfiltration — large file transfers, bulk downloads from sensitive
+ repositories, unusually high print volumes, or mass email forwarding to
+ external addresses.
+2. Off-hours access — login or system activity during atypical hours for the
+ user's baseline schedule.
+3. Privilege abuse — accessing systems or data outside the user's role,
+ creating unauthorised accounts, elevating own privileges, or disabling
+ security controls.
+4. Removable media / USB — USB mass storage device connections, especially on
+ hosts where removable media is policy-prohibited.
+5. Communication to personal accounts — sending corporate data to personal
+ email (gmail, outlook, yahoo), personal cloud storage (Dropbox, Google
+ Drive), or messaging apps.
+6. Resignation / termination indicators — user is on notice period, recently
+ received negative performance review, or has submitted resignation.
+
+You MUST respond with a JSON object and nothing else:
+{
+ "verdict": "true_positive" | "false_positive" | "benign",
+ "confidence": <float 0.0–1.0>,
+ "threat_indicators": ["<indicator1>", "<indicator2>", ...],
+ "threat_category": "data_exfiltration" | "off_hours_access" |
+ "privilege_abuse" | "removable_media" |
+ "personal_comms" | "flight_risk" | "unknown",
+ "user_risk_level": "low" | "medium" | "high" | "critical",
+ "rationale": "<2-4 sentence explanation>"
+}
+"""
+
+
+def _build_insider_context(state: InvestigationState) -> str:
+ """Serialise alert data into an insider-threat focused analysis prompt."""
+ raw = state.raw_alert
+ parts = [
+ f"Alert Summary: {state.alert_summary}",
+ f"Severity: {raw.get('severity', 'unknown')}",
+ ]
+
+ user_fields = {
+ "username": "Username",
+ "user_email": "User Email",
+ "user_id": "User ID",
+ "department": "Department",
+ "job_title": "Job Title",
+ "manager": "Manager",
+ "employment_status": "Employment Status",
+ "hire_date": "Hire Date",
+ }
+ for key, label in user_fields.items():
+ if raw.get(key):
+ parts.append(f"{label}: {raw[key]}")
+
+ activity_fields = {
+ "action": "Action",
+ "resource": "Resource",
+ "source_ip": "Source IP",
+ "destination": "Destination",
+ "file_name": "File Name",
+ "file_size": "File Size",
+ "file_count": "File Count",
+ "device_type": "Device Type",
+ "device_id": "Device ID",
+ }
+ for key, label in activity_fields.items():
+ if raw.get(key):
+ parts.append(f"{label}: {raw[key]}")
+
+ if raw.get("access_time") or raw.get("timestamp"):
+ parts.append(f"Access time: {raw.get('access_time') or raw.get('timestamp')}")
+
+ if raw.get("normal_hours"):
+ parts.append(f"Normal hours: {raw['normal_hours']}")
+
+ if raw.get("data_volume_mb") or raw.get("bytes_transferred"):
+ vol = raw.get("data_volume_mb") or raw.get("bytes_transferred")
+ parts.append(f"Data volume: {vol}")
+
+ if raw.get("destination_type"):
+ parts.append(f"Destination type: {raw['destination_type']}")
+ if raw.get("destination_domain"):
+ parts.append(f"Destination domain: {raw['destination_domain']}")
+
+ if raw.get("usb_events"):
+ parts.append(f"USB events: {json.dumps(raw['usb_events'], default=str)[:400]}")
+
+ if raw.get("recent_activity"):
+ parts.append(f"Recent activity: {json.dumps(raw['recent_activity'], default=str)[:400]}")
+
+ if raw.get("baseline_deviation"):
+ parts.append(f"Baseline deviation: {raw['baseline_deviation']}")
+
+ extra_keys = {k for k in raw if k not in {
+ "severity", "risk_score", *user_fields, *activity_fields,
+ "access_time", "timestamp", "normal_hours", "data_volume_mb",
+ "bytes_transferred", "destination_type", "destination_domain",
+ "usb_events", "recent_activity", "baseline_deviation",
+ }}
+ if extra_keys:
+ extras = {k: raw[k] for k in sorted(extra_keys)[:8]}
+ parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+
+ return "\n".join(parts)
+
+
+def _parse_response(text: str) -> dict[str, Any]:
+ """Extract JSON verdict from LLM output."""
+ cleaned = text.strip()
+ if cleaned.startswith("```"):
+ lines = cleaned.split("\n")
+ lines = [l for l in lines if not l.strip().startswith("```")]
+ cleaned = "\n".join(lines).strip()
+
+ try:
+ data = json.loads(cleaned)
+ except json.JSONDecodeError:
+ start = cleaned.find("{")
+ end = cleaned.rfind("}") + 1
+ if start >= 0 and end > start:
+ data = json.loads(cleaned[start:end])
+ else:
+ raise
+
+ verdict = data.get("verdict", "true_positive")
+ if verdict not in ("true_positive", "false_positive", "benign"):
+ verdict = "true_positive"
+
+ confidence = max(0.0, min(1.0, float(data.get("confidence", 0.5))))
+ indicators = data.get("threat_indicators", [])
+ threat_category = data.get("threat_category", "unknown")
+ user_risk = data.get("user_risk_level", "medium")
+ if user_risk not in ("low", "medium", "high", "critical"):
+ user_risk = "medium"
+ rationale = str(data.get("rationale", "No rationale provided."))
+
+ return {
+ "verdict": verdict,
+ "confidence": confidence,
+ "threat_indicators": indicators,
+ "threat_category": threat_category,
+ "user_risk_level": user_risk,
+ "rationale": rationale,
+ }
+
+
+async def run_insider_threat(state: InvestigationState) -> InvestigationState:
+ """Analyse an alert for insider-threat indicators."""
+ logger.info("Insider threat agent starting", incident_id=str(state.incident_id))
+
+ state.status = AgentStatus.RUNNING
+ state.iteration_count += 1
+
+ context = _build_insider_context(state)
+
+ model_name = os.getenv("AISOC_LLM_MODEL", "gpt-4o-mini")
+ llm = ChatOpenAI(model=model_name, temperature=0.0, max_tokens=768)
+
+ t0 = time.monotonic()
+ try:
+ response = await llm.ainvoke([
+ SystemMessage(content=_SYSTEM_PROMPT),
+ HumanMessage(content=context),
+ ])
+ result = _parse_response(response.content)
+ except Exception as exc:
+ logger.error("Insider threat agent LLM call failed", error=str(exc))
+ state.add_finding(f"Insider threat analysis LLM error: {exc}")
+ return state
+
+ elapsed_ms = round((time.monotonic() - t0) * 1000)
+
+ verdict = result["verdict"]
+ confidence = result["confidence"]
+ indicators = result["threat_indicators"]
+ threat_category = result["threat_category"]
+ user_risk = result["user_risk_level"]
+ rationale = result["rationale"]
+
+ state.confidence = confidence
+ state.verdict = verdict
+ state.confidence_basis = [
+ f"Insider threat verdict: {verdict}",
+ f"Threat category: {threat_category}",
+ f"User risk level: {user_risk}",
+ f"Confidence: {confidence:.2f}",
+ f"Indicators: {', '.join(indicators) if indicators else 'none'}",
+ f"Rationale: {rationale}",
+ ]
+
+ state.add_finding(
+ f"Insider threat analysis: verdict={verdict}, category={threat_category}, "
+ f"user_risk={user_risk}, confidence={confidence:.2f}, "
+ f"indicators={len(indicators)}, latency={elapsed_ms}ms"
+ )
+ if indicators:
+ state.add_finding(f"Threat indicators: {', '.join(indicators)}")
+ state.add_finding(f"Insider threat rationale: {rationale}")
+
+ logger.info(
+ "Insider threat analysis complete",
+ verdict=verdict,
+ threat_category=threat_category,
+ user_risk_level=user_risk,
+ confidence=round(confidence, 2),
+ indicator_count=len(indicators),
+ elapsed_ms=elapsed_ms,
+ incident_id=str(state.incident_id),
+ )
+ return state
diff --git a/services/agents/app/agents/phishing_agent.py b/services/agents/app/agents/phishing_agent.py
new file mode 100644
index 000000000..884d397fc
--- /dev/null
+++ b/services/agents/app/agents/phishing_agent.py
@@ -0,0 +1,200 @@
+"""
+Phishing Analysis Agent: deep-dives into email-based security alerts.
+
+Examines sender reputation, URL structure, attachment hashes, and
+language patterns to determine whether an alert represents a genuine
+phishing attempt. Uses structured LLM reasoning to assess phishing
+indicators and sets a verdict with calibrated confidence.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from typing import Any
+
+import structlog
+from langchain_core.messages import HumanMessage, SystemMessage
+from langchain_openai import ChatOpenAI
+
+from app.models.state import AgentStatus, InvestigationState
+
+logger = structlog.get_logger()
+
+_SYSTEM_PROMPT = """\
+You are the Phishing Analysis Agent of an AI Security Operations Centre.
+
+Given a security alert related to email or messaging, perform a deep phishing
+analysis and produce a structured assessment.
+
+Evaluate the following indicators:
+1. Sender reputation — domain age, SPF/DKIM/DMARC alignment, known abuse lists.
+2. URL analysis — mismatched display text vs. href, newly registered domains,
+ URL shorteners hiding destinations, IDN homograph attacks.
+3. Attachment analysis — executable extensions masquerading as documents,
+ password-protected archives, macro-enabled Office docs.
+4. Language patterns — urgency/fear language ("account suspended", "act now"),
+ impersonation of authority figures, grammatical anomalies.
+5. Header anomalies — reply-to mismatch, forged X-headers, unusual routing.
+
+You MUST respond with a JSON object and nothing else:
+{
+ "verdict": "true_positive" | "false_positive" | "benign",
+ "confidence": <float 0.0–1.0>,
+ "phishing_indicators": ["<indicator1>", "<indicator2>", ...],
+ "rationale": "<2-4 sentence explanation>"
+}
+"""
+
+
+def _build_phishing_context(state: InvestigationState) -> str:
+ """Serialise alert data into a phishing-focused analysis prompt."""
+ raw = state.raw_alert
+ parts = [
+ f"Alert Summary: {state.alert_summary}",
+ f"Severity: {raw.get('severity', 'unknown')}",
+ ]
+
+ email_fields = {
+ "sender": "Sender",
+ "sender_domain": "Sender Domain",
+ "reply_to": "Reply-To",
+ "subject": "Subject",
+ "recipient": "Recipient",
+ "return_path": "Return-Path",
+ }
+ for key, label in email_fields.items():
+ if raw.get(key):
+ parts.append(f"{label}: {raw[key]}")
+
+ if raw.get("urls"):
+ parts.append(f"URLs found: {json.dumps(raw['urls'], default=str)}")
+ if raw.get("url"):
+ parts.append(f"Primary URL: {raw['url']}")
+ if raw.get("domain"):
+ parts.append(f"Domain: {raw['domain']}")
+
+ if raw.get("attachment_hashes"):
+ parts.append(f"Attachment hashes: {json.dumps(raw['attachment_hashes'])}")
+ if raw.get("file_hash"):
+ parts.append(f"File hash: {raw['file_hash']}")
+
+ auth_results = {
+ "spf_result": "SPF",
+ "dkim_result": "DKIM",
+ "dmarc_result": "DMARC",
+ }
+ auth_parts = []
+ for key, label in auth_results.items():
+ if raw.get(key):
+ auth_parts.append(f"{label}={raw[key]}")
+ if auth_parts:
+ parts.append(f"Email auth: {', '.join(auth_parts)}")
+
+ if raw.get("body_snippet"):
+ parts.append(f"Body snippet: {raw['body_snippet'][:500]}")
+
+ extra_keys = {k for k in raw if k not in {
+ "severity", "risk_score", *email_fields, "urls", "url", "domain",
+ "attachment_hashes", "file_hash", "spf_result", "dkim_result",
+ "dmarc_result", "body_snippet",
+ }}
+ if extra_keys:
+ extras = {k: raw[k] for k in sorted(extra_keys)[:8]}
+ parts.append(f"Additional fields: {json.dumps(extras, default=str)}")
+
+ return "\n".join(parts)
+
+
+def _parse_response(text: str) -> dict[str, Any]:
+ """Extract JSON verdict from LLM output."""
+ cleaned = text.strip()
+ if cleaned.startswith("```"):
+ lines = cleaned.split("\n")
+ lines = [l for l in lines if not l.strip().startswith("```")]
+ cleaned = "\n".join(lines).strip()
+
+ try:
+ data = json.loads(cleaned)
+ except json.JSONDecodeError:
+ start = cleaned.find("{")
+ end = cleaned.rfind("}") + 1
+ if start >= 0 and end > start:
+ data = json.loads(cleaned[start:end])
+ else:
+ raise
+
+ verdict = data.get("verdict", "true_positive")
+ if verdict not in ("true_positive", "false_positive", "benign"):
+ verdict = "true_positive"
+
+ confidence = max(0.0, min(1.0, float(data.get("confidence", 0.5))))
+ indicators = data.get("phishing_indicators", [])
+ rationale = str(data.get("rationale", "No rationale provided."))
+
+ return {
+ "verdict": verdict,
+ "confidence": confidence,
+ "phishing_indicators": indicators,
+ "rationale": rationale,
+ }
+
+
+async def run_phishing(state: InvestigationState) -> InvestigationState:
+ """Analyse an email-related alert for phishing indicators."""
+ logger.info("Phishing agent starting", incident_id=str(state.incident_id))
+
+ state.status = AgentStatus.RUNNING
+ state.iteration_count += 1
+
+ context = _build_phishing_context(state)
+
+ model_name = os.getenv("AISOC_LLM_MODEL", "gpt-4o-mini")
+ llm = ChatOpenAI(model=model_name, temperature=0.0, max_tokens=768)
+
+ t0 = time.monotonic()
+ try:
+ response = await llm.ainvoke([
+ SystemMessage(content=_SYSTEM_PROMPT),
+ HumanMessage(content=context),
+ ])
+ result = _parse_response(response.content)
+ except Exception as exc:
+ logger.error("Phishing agent LLM call failed", error=str(exc))
+ state.add_finding(f"Phishing analysis LLM error: {exc}")
+ return state
+
+ elapsed_ms = round((time.monotonic() - t0) * 1000)
+
+ verdict = result["verdict"]
+ confidence = result["confidence"]
+ indicators = result["phishing_indicators"]
+ rationale = result["rationale"]
+
+ state.confidence = confidence
+ state.verdict = verdict
+ state.confidence_basis = [
+ f"Phishing analysis verdict: {verdict}",
+ f"Confidence: {confidence:.2f}",
+ f"Indicators: {', '.join(indicators) if indicators else 'none'}",
+ f"Rationale: {rationale}",
+ ]
+
+ state.add_finding(
+ f"Phishing analysis: verdict={verdict}, confidence={confidence:.2f}, "
+ f"indicators={len(indicators)}, latency={elapsed_ms}ms"
+ )
+ if indicators:
+ state.add_finding(f"Phishing indicators: {', '.join(indicators)}")
+ state.add_finding(f"Phishing rationale: {rationale}")
+
+ logger.info(
+ "Phishing analysis complete",
+ verdict=verdict,
+ confidence=round(confidence, 2),
+ indicator_count=len(indicators),
+ elapsed_ms=elapsed_ms,
+ incident_id=str(state.incident_id),
+ )
+ return state
diff --git a/services/agents/app/graph/workflow.py b/services/agents/app/graph/workflow.py
index 8f56e6f11..3545cf04e 100644
--- a/services/agents/app/graph/workflow.py
+++ b/services/agents/app/graph/workflow.py
@@ -1,6 +1,9 @@
"""
-LangGraph workflow: wires Triage → Enrichment → Investigation agents.
-Uses a simple sequential StateGraph (can be extended with conditional edges).
+LangGraph workflow: wires Auto-Triage → Triage → Enrichment → Investigation agents.
+
+Auto-triage runs first. If the LLM classifies the alert as FP/benign with
+confidence above the auto-close threshold the graph terminates early.
+Otherwise the alert flows through the full manual pipeline.
"""
from __future__ import annotations
@@ -8,6 +11,7 @@ from __future__ import annotations
import structlog
from langgraph.graph import END, StateGraph
+from app.agents.auto_triage_agent import run_auto_triage
from app.agents.enrichment_agent import run_enrichment
from app.agents.investigation_agent import run_investigation
from app.agents.triage_agent import run_triage
@@ -27,6 +31,12 @@ def _from_dict(d: dict) -> InvestigationState:
# ---- Node wrappers (LangGraph uses dict state, we wrap our Pydantic model) ----
+async def auto_triage_node(state: dict) -> dict:
+ s = _from_dict(state)
+ s = await run_auto_triage(s)
+ return s.to_dict()
+
+
async def triage_node(state: dict) -> dict:
s = _from_dict(state)
s = await run_triage(s)
@@ -55,15 +65,35 @@ def _should_continue(state: dict) -> str:
return "continue"
+def _after_auto_triage(state: dict) -> str:
+ """Route after auto-triage: auto-closed alerts go to END, others continue."""
+ s = _from_dict(state)
+ if s.status == AgentStatus.COMPLETED:
+ return "end"
+ return "continue"
+
+
def build_investigation_graph() -> StateGraph:
- """Build and compile the investigation workflow graph."""
+ """Build and compile the investigation workflow graph.
+
+ Flow:
+ auto_triage ─┬─ (high-confidence FP/benign) ──► END
+ └─ (else) ──► triage ──► enrichment ──► investigation ──► END
+ """
graph = StateGraph(dict)
+ graph.add_node("auto_triage", auto_triage_node)
graph.add_node("triage", triage_node)
graph.add_node("enrichment", enrichment_node)
graph.add_node("investigation", investigation_node)
- graph.set_entry_point("triage")
+ graph.set_entry_point("auto_triage")
+
+ graph.add_conditional_edges(
+ "auto_triage",
+ _after_auto_triage,
+ {"end": END, "continue": "triage"},
+ )
graph.add_edge("triage", "enrichment")
graph.add_edge("enrichment", "investigation")
graph.add_edge("investigation", END)
diff --git a/services/api/app/api/v1/endpoints/compliance.py b/services/api/app/api/v1/endpoints/compliance.py
index 829899d0e..b6a377e66 100644
--- a/services/api/app/api/v1/endpoints/compliance.py
+++ b/services/api/app/api/v1/endpoints/compliance.py
@@ -117,6 +117,29 @@ class FrameworksResponse(BaseModel):
frameworks: dict[str, dict[str, str]]
+class ControlItem(BaseModel):
+ control_id: str
+ title: str
+
+
+class ControlsResponse(BaseModel):
+ framework_id: str
+ controls: list[ControlItem]
+
+
+class CollectJobRequest(BaseModel):
+ framework: str = Field(..., description="Compliance framework key e.g. 'SOC2'.")
+ scope: str = Field("full", description="Collection scope: 'full' or 'delta'.")
+
+
+class CollectJobResponse(BaseModel):
+ job_id: uuid.UUID
+ framework: str
+ scope: str
+ status: str
+ queued_at: datetime
+
+
class CompliancePosture(BaseModel):
framework: str
total_evidence: int
@@ -178,6 +201,39 @@ async def list_frameworks() -> FrameworksResponse:
return FrameworksResponse(frameworks=FRAMEWORKS)
+ "/frameworks/{framework_id}/controls",
+ response_model=ControlsResponse,
+ summary="List controls for a framework",
+)
+async def list_framework_controls(framework_id: str) -> ControlsResponse:
+ controls = FRAMEWORKS.get(framework_id)
+ if controls is None:
+ raise HTTPException(status_code=404, detail=f"Framework '{framework_id}' not found.")
+ return ControlsResponse(
+ framework_id=framework_id,
+ controls=[ControlItem(control_id=cid, title=title) for cid, title in controls.items()],
+ )
+
+
+ "/evidence/collect",
+ response_model=CollectJobResponse,
+ status_code=status.HTTP_202_ACCEPTED,
+ summary="Trigger evidence collection job",
+)
+async def trigger_evidence_collection(body: CollectJobRequest) -> CollectJobResponse:
+ if body.framework not in FRAMEWORKS:
+ raise HTTPException(status_code=404, detail=f"Framework '{body.framework}' not found.")
+ return CollectJobResponse(
+ job_id=uuid.uuid4(),
+ framework=body.framework,
+ scope=body.scope,
+ status="queued",
+ queued_at=datetime.now(UTC),
+ )
+
+
@router.post("/evidence", response_model=EvidenceResponse, status_code=status.HTTP_201_CREATED, summary="Collect evidence item")
async def collect_evidence(body: CollectEvidenceRequest, db: DBSession, user: AuthUser) -> EvidenceResponse:
prev_hash = await _latest_hash(db, body.framework)
diff --git a/services/api/app/api/v1/endpoints/deployment.py b/services/api/app/api/v1/endpoints/deployment.py
new file mode 100644
index 000000000..e39de14c7
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/deployment.py
@@ -0,0 +1,175 @@
+"""Air-gap deployment configuration endpoints."""
+
+import uuid
+from datetime import UTC, datetime
+from enum import Enum
+
+from fastapi import APIRouter, HTTPException, status
+from pydantic import BaseModel
+
+router = APIRouter(prefix="/deployment", tags=["Deployment"])
+
+
+# ── Pydantic models ──────────────────────────────────────────────────────────
+
+
+class DeploymentMode(str, Enum):
+ cloud = "cloud"
+ hybrid = "hybrid"
+ airgap = "airgap"
+
+
+class LLMProvider(str, Enum):
+ openai = "openai"
+ anthropic = "anthropic"
+ local_ollama = "local-ollama"
+ local_vllm = "local-vllm"
+ azure_openai = "azure-openai"
+ none = "none"
+
+
+class UpdateChannel(str, Enum):
+ stable = "stable"
+ beta = "beta"
+ nightly = "nightly"
+ manual = "manual"
+
+
+class DeploymentConfig(BaseModel):
+ mode: DeploymentMode
+ llm_provider: LLMProvider
+ update_channel: UpdateChannel
+ telemetry_enabled: bool
+ auto_update: bool
+ last_updated: str
+
+
+class DeploymentConfigUpdate(BaseModel):
+ mode: DeploymentMode | None = None
+ llm_provider: LLMProvider | None = None
+ update_channel: UpdateChannel | None = None
+ telemetry_enabled: bool | None = None
+ auto_update: bool | None = None
+
+
+class AirgapStatus(BaseModel):
+ ready: bool
+ local_llm_status: str
+ local_llm_model: str | None
+ offline_bundle_version: str | None
+ last_sync: str | None
+ detection_rules_count: int
+ threat_intel_age_hours: int | None
+ checks: list[dict]
+
+
+class BundleJob(BaseModel):
+ job_id: str
+ status: str
+ created_at: str
+ estimated_size_mb: int
+ includes: list[str]
+
+
+# ── Mock state ───────────────────────────────────────────────────────────────
+
+_config = DeploymentConfig(
+ mode=DeploymentMode.cloud,
+ llm_provider=LLMProvider.openai,
+ update_channel=UpdateChannel.stable,
+ telemetry_enabled=True,
+ auto_update=True,
+ last_updated=datetime(2025, 6, 1, 12, 0, 0, tzinfo=UTC).isoformat(),
+)
+
+
+# ── Endpoints ────────────────────────────────────────────────────────────────
+
+
[email protected]("/config", response_model=DeploymentConfig)
+async def get_deployment_config() -> DeploymentConfig:
+ """Return the current deployment configuration."""
+ return _config
+
+
[email protected]("/config", response_model=DeploymentConfig)
+async def update_deployment_config(body: DeploymentConfigUpdate) -> DeploymentConfig:
+ """Update deployment configuration fields."""
+ global _config
+
+ updates = body.model_dump(exclude_none=True)
+ if not updates:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="No fields to update.",
+ )
+
+ current = _config.model_dump()
+ current.update(updates)
+ current["last_updated"] = datetime.now(UTC).isoformat()
+ _config = DeploymentConfig(**current)
+ return _config
+
+
[email protected]("/airgap/status", response_model=AirgapStatus)
+async def get_airgap_status() -> AirgapStatus:
+ """Check air-gap readiness: local LLM health, offline bundles, sync age."""
+ is_airgap = _config.mode == DeploymentMode.airgap
+ local_llm_up = _config.llm_provider in (LLMProvider.local_ollama, LLMProvider.local_vllm)
+
+ checks = [
+ {
+ "name": "local_llm",
+ "passed": local_llm_up,
+ "detail": "Local LLM running" if local_llm_up else "No local LLM configured",
+ },
+ {
+ "name": "offline_bundle",
+ "passed": True,
+ "detail": "Bundle v2025.05.30 available",
+ },
+ {
+ "name": "detection_rules",
+ "passed": True,
+ "detail": "487 rules loaded from offline bundle",
+ },
+ {
+ "name": "threat_intel",
+ "passed": is_airgap,
+ "detail": "Feed synced 18h ago" if is_airgap else "Using live feed (not air-gapped)",
+ },
+ {
+ "name": "network_isolation",
+ "passed": is_airgap,
+ "detail": "Outbound blocked" if is_airgap else "Outbound allowed (cloud mode)",
+ },
+ ]
+
+ return AirgapStatus(
+ ready=all(c["passed"] for c in checks),
+ local_llm_status="running" if local_llm_up else "not_configured",
+ local_llm_model="llama-3.1-70b-instruct" if local_llm_up else None,
+ offline_bundle_version="2025.05.30",
+ last_sync=datetime(2025, 5, 30, 6, 0, 0, tzinfo=UTC).isoformat() if is_airgap else None,
+ detection_rules_count=487,
+ threat_intel_age_hours=18 if is_airgap else None,
+ checks=checks,
+ )
+
+
[email protected]("/airgap/bundle", response_model=BundleJob, status_code=status.HTTP_202_ACCEPTED)
+async def create_airgap_bundle() -> BundleJob:
+ """Trigger creation of an offline update bundle for air-gapped deployments."""
+ return BundleJob(
+ job_id=str(uuid.uuid4()),
+ status="queued",
+ created_at=datetime.now(UTC).isoformat(),
+ estimated_size_mb=340,
+ includes=[
+ "detection_rules",
+ "threat_intel_feed",
+ "llm_model_weights",
+ "platform_update",
+ "connector_plugins",
+ ],
+ )
diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.py
index 217f163e1..63fd97a1f 100644
--- a/services/api/app/api/v1/endpoints/mssp.py
+++ b/services/api/app/api/v1/endpoints/mssp.py
@@ -625,3 +625,107 @@ async def count_effective_rules_for_child(
counts = await count_effective_rules(db, child_id)
return EffectiveRuleCountOut(**counts)
+
+
+# ---------------------------------------------------------------------------
+# Cross-tenant dashboard rollups (mock data for UI)
+# ---------------------------------------------------------------------------
+
+
+class MSSPKpiOverview(BaseModel):
+ total_tenants: int
+ total_open_alerts: int
+ total_critical_incidents: int
+ avg_health_score: float
+ avg_mttr_minutes: float
+ sla_breach_count: int
+ connectors_online: int
+ connectors_degraded: int
+
+ class Config:
+ from_attributes = True
+
+
+class ManagedTenantRow(BaseModel):
+ tenant_id: str
+ name: str
+ health_score: float
+ open_alerts: int
+ critical_alerts: int
+ sla_breaches: int
+ connector_status: str
+ last_event_at: str
+
+ class Config:
+ from_attributes = True
+
+
+class CrossTenantIncident(BaseModel):
+ incident_id: str
+ tenant_name: str
+ title: str
+ severity: str
+ status: str
+ created_at: str
+ assignee: str | None = None
+
+ class Config:
+ from_attributes = True
+
+
+_MSSP_TENANTS_MOCK = [
+ ManagedTenantRow(tenant_id="t-acme", name="Acme Corp", health_score=92.4, open_alerts=12, critical_alerts=1, sla_breaches=0, connector_status="healthy", last_event_at="2026-05-07T20:31:00Z"),
+ ManagedTenantRow(tenant_id="t-globex", name="Globex Industries", health_score=78.1, open_alerts=34, critical_alerts=3, sla_breaches=2, connector_status="degraded", last_event_at="2026-05-07T20:28:00Z"),
+ ManagedTenantRow(tenant_id="t-initech", name="Initech LLC", health_score=95.7, open_alerts=5, critical_alerts=0, sla_breaches=0, connector_status="healthy", last_event_at="2026-05-07T20:30:00Z"),
+ ManagedTenantRow(tenant_id="t-wayne", name="Wayne Enterprises", health_score=64.3, open_alerts=58, critical_alerts=7, sla_breaches=4, connector_status="degraded", last_event_at="2026-05-07T20:25:00Z"),
+ ManagedTenantRow(tenant_id="t-stark", name="Stark Solutions", health_score=88.9, open_alerts=9, critical_alerts=1, sla_breaches=0, connector_status="healthy", last_event_at="2026-05-07T20:29:00Z"),
+]
+
+_MSSP_INCIDENTS_MOCK = [
+ CrossTenantIncident(incident_id="INC-4201", tenant_name="Wayne Enterprises", title="Ransomware lateral movement detected", severity="high", status="investigating", created_at="2026-05-07T19:45:00Z", assignee="Jordan Lee"),
+ CrossTenantIncident(incident_id="INC-4198", tenant_name="Globex Industries", title="Suspicious OAuth token abuse in Azure AD", severity="high", status="investigating", created_at="2026-05-07T18:12:00Z", assignee="Morgan Chen"),
+ CrossTenantIncident(incident_id="INC-4195", tenant_name="Wayne Enterprises", title="Data exfiltration via DNS tunneling", severity="high", status="contained", created_at="2026-05-07T16:30:00Z", assignee="Alex Rivera"),
+ CrossTenantIncident(incident_id="INC-4192", tenant_name="Acme Corp", title="Brute-force against VPN gateway", severity="medium", status="resolved", created_at="2026-05-07T14:20:00Z", assignee="Taylor Kim"),
+ CrossTenantIncident(incident_id="INC-4189", tenant_name="Globex Industries", title="Compromised service account in GCP", severity="high", status="investigating", created_at="2026-05-07T12:55:00Z", assignee=None),
+]
+
+
[email protected]("/overview", response_model=MSSPKpiOverview)
+async def mssp_overview(
+ db: AsyncSession = Depends(get_db),
+ current_user: User = Depends(get_current_user),
+) -> MSSPKpiOverview:
+ """Cross-tenant KPI summary for the MSSP parent dashboard."""
+ tenants = _MSSP_TENANTS_MOCK
+ return MSSPKpiOverview(
+ total_tenants=len(tenants),
+ total_open_alerts=sum(t.open_alerts for t in tenants),
+ total_critical_incidents=sum(t.critical_alerts for t in tenants),
+ avg_health_score=round(sum(t.health_score for t in tenants) / len(tenants), 1),
+ avg_mttr_minutes=23.4,
+ sla_breach_count=sum(t.sla_breaches for t in tenants),
+ connectors_online=3,
+ connectors_degraded=2,
+ )
+
+
[email protected]("/tenants", response_model=list[ManagedTenantRow])
+async def list_managed_tenants(
+ db: AsyncSession = Depends(get_db),
+ current_user: User = Depends(get_current_user),
+) -> list[ManagedTenantRow]:
+ """List managed tenants with health scores for the parent dashboard."""
+ return _MSSP_TENANTS_MOCK
+
+
[email protected]("/incidents", response_model=list[CrossTenantIncident])
+async def list_cross_tenant_incidents(
+ severity: str | None = Query(None, description="Filter: high | medium | low"),
+ db: AsyncSession = Depends(get_db),
+ current_user: User = Depends(get_current_user),
+) -> list[CrossTenantIncident]:
+ """Critical incidents across all managed tenants."""
+ incidents = _MSSP_INCIDENTS_MOCK
+ if severity:
+ incidents = [i for i in incidents if i.severity == severity]
+ return incidents
diff --git a/services/api/app/api/v1/endpoints/shifts.py b/services/api/app/api/v1/endpoints/shifts.py
new file mode 100644
index 000000000..e85ce0c55
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/shifts.py
@@ -0,0 +1,156 @@
+"""SOC Shift Management endpoints."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel, Field
+
+from app.api.v1.deps import AuthUser, require_permission
+
+router = APIRouter(prefix="/shifts", tags=["shifts"])
+
+
+class ShiftAnalyst(BaseModel):
+ id: str
+ name: str
+ role: str
+
+ model_config = {"from_attributes": True}
+
+
+class ShiftSummary(BaseModel):
+ id: str
+ name: str
+ started_at: str
+ ended_at: str | None = None
+ status: str
+ lead: ShiftAnalyst
+ analyst_count: int
+ alerts_handled: int
+ escalations: int
+ handoff_notes: str | None = None
+
+ model_config = {"from_attributes": True}
+
+
+class ShiftCreate(BaseModel):
+ name: str = Field(..., min_length=1, max_length=120)
+ analysts: list[str] = Field(default_factory=list, description="Analyst user IDs")
+ lead_id: str | None = None
+
+
+class HandoffNotes(BaseModel):
+ notes: str = Field(..., min_length=1)
+ pending_items: list[str] = Field(default_factory=list)
+
+
+_MOCK_ANALYSTS = {
+ "a1": ShiftAnalyst(id="a1", name="Jordan Lee", role="shift_lead"),
+ "a2": ShiftAnalyst(id="a2", name="Morgan Chen", role="soc_analyst"),
+ "a3": ShiftAnalyst(id="a3", name="Taylor Kim", role="soc_analyst"),
+ "a4": ShiftAnalyst(id="a4", name="Alex Rivera", role="senior_analyst"),
+}
+
+_now = datetime.now(UTC)
+_MOCK_SHIFTS: list[dict] = [
+ {
+ "id": "shift-001",
+ "name": "Day Shift – 2026-05-07",
+ "started_at": (_now - timedelta(hours=6)).isoformat(),
+ "ended_at": None,
+ "status": "active",
+ "lead": _MOCK_ANALYSTS["a1"],
+ "analyst_count": 3,
+ "alerts_handled": 47,
+ "escalations": 2,
+ "handoff_notes": None,
+ },
+ {
+ "id": "shift-002",
+ "name": "Night Shift – 2026-05-06",
+ "started_at": (_now - timedelta(hours=18)).isoformat(),
+ "ended_at": (_now - timedelta(hours=6)).isoformat(),
+ "status": "completed",
+ "lead": _MOCK_ANALYSTS["a4"],
+ "analyst_count": 2,
+ "alerts_handled": 31,
+ "escalations": 1,
+ "handoff_notes": "3 open P2 investigations carried over. SentinelOne connector flapping – ops ticket INFRA-412 filed.",
+ },
+ {
+ "id": "shift-003",
+ "name": "Day Shift – 2026-05-06",
+ "started_at": (_now - timedelta(hours=30)).isoformat(),
+ "ended_at": (_now - timedelta(hours=18)).isoformat(),
+ "status": "completed",
+ "lead": _MOCK_ANALYSTS["a1"],
+ "analyst_count": 3,
+ "alerts_handled": 62,
+ "escalations": 4,
+ "handoff_notes": "Major phishing campaign resolved (INC-1042). New Sigma rule deployed for O365 impossible-travel.",
+ },
+]
+
+
[email protected]("", response_model=list[ShiftSummary])
+async def list_shifts(
+ current_user: AuthUser,
+ status_filter: str | None = Query(None, alias="status", description="active | completed"),
+ limit: int = Query(20, ge=1, le=100),
+):
+ """Return shift summaries, newest first."""
+ shifts = _MOCK_SHIFTS
+ if status_filter:
+ shifts = [s for s in shifts if s["status"] == status_filter]
+ return [ShiftSummary(**s) for s in shifts[:limit]]
+
+
[email protected]("/current", response_model=ShiftSummary)
+async def get_current_shift(current_user: AuthUser):
+ """Return the currently active shift."""
+ for s in _MOCK_SHIFTS:
+ if s["status"] == "active":
+ return ShiftSummary(**s)
+ raise HTTPException(status_code=404, detail="No active shift")
+
+
[email protected]("", response_model=ShiftSummary, status_code=201)
+async def create_shift(
+ body: ShiftCreate,
+ current_user: AuthUser,
+):
+ """Start a new shift."""
+ new_shift = {
+ "id": f"shift-{uuid.uuid4().hex[:8]}",
+ "name": body.name,
+ "started_at": datetime.now(UTC).isoformat(),
+ "ended_at": None,
+ "status": "active",
+ "lead": _MOCK_ANALYSTS.get(body.lead_id or "a1", _MOCK_ANALYSTS["a1"]),
+ "analyst_count": max(len(body.analysts), 1),
+ "alerts_handled": 0,
+ "escalations": 0,
+ "handoff_notes": None,
+ }
+ _MOCK_SHIFTS.insert(0, new_shift)
+ return ShiftSummary(**new_shift)
+
+
[email protected]("/{shift_id}/handoff", response_model=ShiftSummary)
+async def add_handoff_notes(
+ shift_id: str,
+ body: HandoffNotes,
+ current_user: AuthUser,
+):
+ """Attach handoff notes to a shift and mark it completed."""
+ for s in _MOCK_SHIFTS:
+ if s["id"] == shift_id:
+ s["handoff_notes"] = body.notes
+ s["status"] = "completed"
+ s["ended_at"] = datetime.now(UTC).isoformat()
+ return ShiftSummary(**s)
+ raise HTTPException(status_code=404, detail="Shift not found")
diff --git a/services/api/app/api/v1/endpoints/stix_taxii.py b/services/api/app/api/v1/endpoints/stix_taxii.py
new file mode 100644
index 000000000..027d984dd
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/stix_taxii.py
@@ -0,0 +1,251 @@
+"""STIX/TAXII threat intelligence publishing endpoints."""
+
+import uuid
+from datetime import UTC, datetime
+from enum import Enum
+
+from fastapi import APIRouter, HTTPException, Query, status
+from pydantic import BaseModel, Field
+
+router = APIRouter(prefix="/threatintel/stix", tags=["Threat Intelligence"])
+
+
+# ── Pydantic models ──────────────────────────────────────────────────────────
+
+
+class IndicatorPattern(str, Enum):
+ ipv4_addr = "ipv4-addr"
+ domain_name = "domain-name"
+ file_hash = "file:hashes"
+ url = "url"
+ email_addr = "email-addr"
+
+
+class STIXIndicator(BaseModel):
+ type: str = "indicator"
+ spec_version: str = "2.1"
+ id: str
+ created: str
+ modified: str
+ name: str
+ description: str | None = None
+ indicator_types: list[str] = []
+ pattern: str
+ pattern_type: str = "stix"
+ valid_from: str
+ valid_until: str | None = None
+ confidence: int | None = Field(default=None, ge=0, le=100)
+ labels: list[str] = []
+
+
+class STIXIndicatorCreate(BaseModel):
+ name: str
+ description: str | None = None
+ indicator_types: list[str] = []
+ pattern: str
+ pattern_type: str = "stix"
+ valid_from: str | None = None
+ valid_until: str | None = None
+ confidence: int | None = Field(default=None, ge=0, le=100)
+ labels: list[str] = []
+
+
+class STIXBundle(BaseModel):
+ type: str = "bundle"
+ id: str
+ spec_version: str = "2.1"
+ created: str
+ objects: list[dict]
+
+
+class STIXBundleCreate(BaseModel):
+ objects: list[dict]
+
+
+class TAXIICollection(BaseModel):
+ id: str
+ title: str
+ description: str
+ can_read: bool = True
+ can_write: bool = False
+ media_types: list[str] = ["application/stix+json;version=2.1"]
+
+
+class IndicatorListResponse(BaseModel):
+ items: list[STIXIndicator]
+ total: int
+
+
+class BundleListResponse(BaseModel):
+ items: list[STIXBundle]
+ total: int
+
+
+class TAXIICollectionListResponse(BaseModel):
+ items: list[TAXIICollection]
+ total: int
+
+
+# ── Demo data ────────────────────────────────────────────────────────────────
+
+_now = datetime(2025, 6, 1, 12, 0, 0, tzinfo=UTC).isoformat()
+
+DEMO_INDICATORS: list[STIXIndicator] = [
+ STIXIndicator(
+ id="indicator--a1b2c3d4-0001-4000-8000-000000000001",
+ created=_now,
+ modified=_now,
+ name="Malicious IP - C2 Server",
+ description="Known command-and-control server associated with APT-42 campaigns.",
+ indicator_types=["malicious-activity"],
+ pattern="[ipv4-addr:value = '198.51.100.47']",
+ valid_from=_now,
+ confidence=92,
+ labels=["c2", "apt-42"],
+ ),
+ STIXIndicator(
+ id="indicator--a1b2c3d4-0002-4000-8000-000000000002",
+ created=_now,
+ modified=_now,
+ name="Phishing Domain",
+ description="Domain used in credential-harvesting campaign targeting financial sector.",
+ indicator_types=["malicious-activity"],
+ pattern="[domain-name:value = 'secure-login.example-phish.com']",
+ valid_from=_now,
+ confidence=88,
+ labels=["phishing", "credential-harvesting"],
+ ),
+ STIXIndicator(
+ id="indicator--a1b2c3d4-0003-4000-8000-000000000003",
+ created=_now,
+ modified=_now,
+ name="Ransomware Hash - LockBit Variant",
+ description="SHA-256 hash of a LockBit 3.0 ransomware payload.",
+ indicator_types=["malicious-activity"],
+ pattern="[file:hashes.'SHA-256' = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855']",
+ valid_from=_now,
+ confidence=95,
+ labels=["ransomware", "lockbit"],
+ ),
+ STIXIndicator(
+ id="indicator--a1b2c3d4-0004-4000-8000-000000000004",
+ created=_now,
+ modified=_now,
+ name="Exfiltration URL",
+ description="URL used for data exfiltration via HTTPS tunnel.",
+ indicator_types=["malicious-activity"],
+ pattern="[url:value = 'https://drop.evil-cdn.example/upload']",
+ valid_from=_now,
+ confidence=78,
+ labels=["exfiltration", "data-theft"],
+ ),
+ STIXIndicator(
+ id="indicator--a1b2c3d4-0005-4000-8000-000000000005",
+ created=_now,
+ modified=_now,
+ name="Suspicious Email Sender",
+ description="Email address associated with BEC campaigns targeting executives.",
+ indicator_types=["anomalous-activity"],
+ pattern="[email-addr:value = '[email protected]']",
+ valid_from=_now,
+ confidence=70,
+ labels=["bec", "social-engineering"],
+ ),
+]
+
+DEMO_BUNDLES: list[STIXBundle] = [
+ STIXBundle(
+ id="bundle--f47ac10b-58cc-4372-a567-0e02b2c3d479",
+ created=_now,
+ objects=[ind.model_dump() for ind in DEMO_INDICATORS[:3]],
+ ),
+]
+
+DEMO_TAXII_COLLECTIONS: list[TAXIICollection] = [
+ TAXIICollection(
+ id="collection--01",
+ title="AiSOC Threat Feed",
+ description="Curated indicators from AiSOC automated threat intelligence pipeline.",
+ ),
+ TAXIICollection(
+ id="collection--02",
+ title="Community IOCs",
+ description="Community-contributed indicators of compromise.",
+ can_write=True,
+ ),
+ TAXIICollection(
+ id="collection--03",
+ title="MITRE ATT&CK Mapping",
+ description="Indicators mapped to MITRE ATT&CK techniques.",
+ ),
+]
+
+
+# ── Endpoints ────────────────────────────────────────────────────────────────
+
+
[email protected]("/indicators", response_model=IndicatorListResponse)
+async def list_indicators(
+ page: int = Query(default=1, ge=1),
+ page_size: int = Query(default=25, ge=1, le=200),
+ label: str | None = Query(default=None),
+) -> IndicatorListResponse:
+ """List STIX 2.1 indicators from the threat intelligence store."""
+ items = list(DEMO_INDICATORS)
+ if label:
+ items = [i for i in items if label in i.labels]
+ return IndicatorListResponse(items=items, total=len(items))
+
+
[email protected]("/indicators", response_model=STIXIndicator, status_code=status.HTTP_201_CREATED)
+async def create_indicator(body: STIXIndicatorCreate) -> STIXIndicator:
+ """Publish a new STIX 2.1 indicator."""
+ now_iso = datetime.now(UTC).isoformat()
+ indicator = STIXIndicator(
+ id=f"indicator--{uuid.uuid4()}",
+ created=now_iso,
+ modified=now_iso,
+ name=body.name,
+ description=body.description,
+ indicator_types=body.indicator_types,
+ pattern=body.pattern,
+ pattern_type=body.pattern_type,
+ valid_from=body.valid_from or now_iso,
+ valid_until=body.valid_until,
+ confidence=body.confidence,
+ labels=body.labels,
+ )
+ DEMO_INDICATORS.append(indicator)
+ return indicator
+
+
[email protected]("/bundles", response_model=BundleListResponse)
+async def list_bundles() -> BundleListResponse:
+ """List STIX 2.1 bundles."""
+ return BundleListResponse(items=DEMO_BUNDLES, total=len(DEMO_BUNDLES))
+
+
[email protected]("/bundles", response_model=STIXBundle, status_code=status.HTTP_201_CREATED)
+async def create_bundle(body: STIXBundleCreate) -> STIXBundle:
+ """Create a new STIX 2.1 bundle from a list of STIX objects."""
+ if not body.objects:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Bundle must contain at least one STIX object.",
+ )
+ bundle = STIXBundle(
+ id=f"bundle--{uuid.uuid4()}",
+ created=datetime.now(UTC).isoformat(),
+ objects=body.objects,
+ )
+ DEMO_BUNDLES.append(bundle)
+ return bundle
+
+
[email protected]("/taxii/collections", response_model=TAXIICollectionListResponse)
+async def list_taxii_collections() -> TAXIICollectionListResponse:
+ """List TAXII 2.1 collections for server compatibility."""
+ return TAXIICollectionListResponse(
+ items=DEMO_TAXII_COLLECTIONS,
+ total=len(DEMO_TAXII_COLLECTIONS),
+ )
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index b464c4818..2be98b793 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -15,6 +15,7 @@ from app.api.v1.endpoints import (
community,
compliance,
connectors,
+ deployment,
detection_loop,
detection_proposals,
detection_rules,
@@ -43,7 +44,9 @@ from app.api.v1.endpoints import (
rbac,
remediation,
reports,
+ shifts,
sla,
+ stix_taxii,
tenants,
threat_intel,
translation,
@@ -123,3 +126,12 @@ api_router.include_router(reports.router)
# Air-gap status snapshot for operators — Tier 3.1 (air-gapped certification)
api_router.include_router(airgap.router)
+
+# STIX/TAXII threat intelligence publishing (Tier 4)
+api_router.include_router(stix_taxii.router)
+
+# Shift handoff and SOC analyst scheduling
+api_router.include_router(shifts.router)
+
+# Deployment configuration and air-gap bundle management
+api_router.include_router(deployment.router)
diff --git a/services/connectors/app/connectors/__init__.py b/services/connectors/app/connectors/__init__.py
index 14cc9c3b9..02949d4a0 100644
--- a/services/connectors/app/connectors/__init__.py
+++ b/services/connectors/app/connectors/__init__.py
@@ -22,17 +22,27 @@ from app.connectors.azure_defender import AzureDefenderConnector
from app.connectors.azure_entra import AzureEntraConnector
from app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHints
from app.connectors.cloudflare import CloudflareConnector
+from app.connectors.cortex_xdr import CortexXDRConnector
from app.connectors.crowdstrike import CrowdStrikeConnector
+from app.connectors.duo_security import DuoSecurityConnector
from app.connectors.elastic import ElasticConnector
from app.connectors.gcp_cloud_audit import GCPCloudAuditConnector
from app.connectors.gcp_scc import GCPSCCConnector
from app.connectors.github import GitHubConnector
from app.connectors.google_workspace import GoogleWorkspaceConnector
+from app.connectors.jira_connector import JiraConnector
from app.connectors.m365_audit import M365AuditConnector
from app.connectors.microsoft_sentinel import MicrosoftSentinelConnector
from app.connectors.okta import OktaConnector
+from app.connectors.onepassword import OnePasswordConnector
+from app.connectors.proofpoint import ProofpointConnector
+from app.connectors.sentinelone import SentinelOneConnector
+from app.connectors.servicenow import ServiceNowConnector
+from app.connectors.snyk import SnykConnector
from app.connectors.splunk import SplunkConnector
from app.connectors.tailscale import TailscaleConnector
+from app.connectors.wiz import WizConnector
+from app.connectors.zscaler import ZscalerConnector
if TYPE_CHECKING:
pass
@@ -46,17 +56,27 @@ _CONNECTOR_CLASSES: tuple[type[BaseConnector], ...] = (
AzureDefenderConnector,
AzureEntraConnector,
CloudflareConnector,
+ CortexXDRConnector,
CrowdStrikeConnector,
+ DuoSecurityConnector,
ElasticConnector,
GCPCloudAuditConnector,
GCPSCCConnector,
GitHubConnector,
GoogleWorkspaceConnector,
+ JiraConnector,
M365AuditConnector,
MicrosoftSentinelConnector,
OktaConnector,
+ OnePasswordConnector,
+ ProofpointConnector,
+ SentinelOneConnector,
+ ServiceNowConnector,
+ SnykConnector,
SplunkConnector,
TailscaleConnector,
+ WizConnector,
+ ZscalerConnector,
)
@@ -95,19 +115,29 @@ __all__ = [
"CONNECTOR_REGISTRY",
"CloudflareConnector",
"ConnectorSchema",
+ "CortexXDRConnector",
"CrowdStrikeConnector",
+ "DuoSecurityConnector",
"ElasticConnector",
"Field",
"GCPCloudAuditConnector",
"GCPSCCConnector",
"GitHubConnector",
"GoogleWorkspaceConnector",
+ "JiraConnector",
"M365AuditConnector",
"MicrosoftSentinelConnector",
"OAuthHints",
"OktaConnector",
+ "OnePasswordConnector",
+ "ProofpointConnector",
+ "SentinelOneConnector",
+ "ServiceNowConnector",
+ "SnykConnector",
"SplunkConnector",
"TailscaleConnector",
+ "WizConnector",
+ "ZscalerConnector",
"get_connector_class",
"list_connector_schemas",
]
diff --git a/services/connectors/app/connectors/cortex_xdr.py b/services/connectors/app/connectors/cortex_xdr.py
new file mode 100644
index 000000000..60f873079
--- /dev/null
+++ b/services/connectors/app/connectors/cortex_xdr.py
@@ -0,0 +1,135 @@
+"""
+Cortex XDR (Palo Alto Networks) connector.
+Fetches incidents from the Cortex XDR REST API.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import secrets
+import string
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_SEVERITY_MAP: dict[str, str] = {
+ "informational": "info",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "critical": "high",
+}
+
+
+class CortexXDRConnector(BaseConnector):
+ connector_id = "cortex_xdr"
+ connector_name = "Cortex XDR"
+ connector_category = "edr"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="Palo Alto Cortex XDR incidents via the public REST API.",
+ docs_url="/docs/connectors/cortex-xdr",
+ fields=[
+ Field("api_key_id", "string", "API Key ID"),
+ Field("api_key", "secret", "API Key"),
+ Field(
+ "fqdn",
+ "string",
+ "FQDN",
+ placeholder="api-example.xdr.us.paloaltonetworks.com",
+ help_text="Fully qualified domain name of your Cortex XDR tenant.",
+ ),
+ ],
+ )
+
+ def __init__(self, api_key_id: str, api_key: str, fqdn: str):
+ self._api_key_id = api_key_id
+ self._api_key = api_key
+ self._fqdn = fqdn.rstrip("/")
+
+ def _headers(self) -> dict[str, str]:
+ nonce = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(64))
+ timestamp = str(int(datetime.now(UTC).timestamp()) * 1000)
+ auth_string = f"{self._api_key}{nonce}{timestamp}"
+ api_key_hash = hashlib.sha256(auth_string.encode()).hexdigest()
+
+ return {
+ "x-xdr-auth-id": str(self._api_key_id),
+ "x-xdr-nonce": nonce,
+ "x-xdr-timestamp": timestamp,
+ "Authorization": api_key_hash,
+ "Content-Type": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ f"https://{self._fqdn}/public_api/v1/incidents/get_incidents",
+ headers=self._headers(),
+ json={"request_data": {"filters": [], "search_from": 0, "search_to": 1}},
+ )
+ resp.raise_for_status()
+ return {"success": True, "connector": self.connector_id}
+ except Exception as exc:
+ logger.warning("cortex_xdr.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since_ms = int((datetime.now(UTC) - timedelta(seconds=since_seconds)).timestamp()) * 1000
+
+ payload = {
+ "request_data": {
+ "filters": [
+ {
+ "field": "creation_time",
+ "operator": "gte",
+ "value": since_ms,
+ }
+ ],
+ "search_from": 0,
+ "search_to": 100,
+ "sort": {"field": "creation_time", "keyword": "desc"},
+ }
+ }
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.post(
+ f"https://{self._fqdn}/public_api/v1/incidents/get_incidents",
+ headers=self._headers(),
+ json=payload,
+ )
+ resp.raise_for_status()
+ incidents = resp.json().get("reply", {}).get("incidents", [])
+
+ return [self.normalize(i) for i in incidents]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ raw_severity = str(raw.get("severity", "medium")).lower()
+ severity = _SEVERITY_MAP.get(raw_severity, "medium")
+
+ hosts = raw.get("hosts", [])
+ hostname = hosts[0] if hosts else None
+
+ return {
+ "source": self.connector_id,
+ "external_id": str(raw.get("incident_id", "")),
+ "title": raw.get("description", "Cortex XDR Incident"),
+ "description": raw.get("description", ""),
+ "severity": severity,
+ "hostname": hostname,
+ "mitre_techniques": raw.get("mitre_tactics_ids_and_names") or [],
+ "raw_event": raw,
+ "created_at": raw.get("creation_time"),
+ }
diff --git a/services/connectors/app/connectors/duo_security.py b/services/connectors/app/connectors/duo_security.py
new file mode 100644
index 000000000..b4bc1af8e
--- /dev/null
+++ b/services/connectors/app/connectors/duo_security.py
@@ -0,0 +1,124 @@
+"""
+Duo Security connector.
+Fetches authentication logs from the Duo Admin API using HMAC-SHA1 signed requests.
+"""
+
+from __future__ import annotations
+
+import base64
+import email.utils
+import hashlib
+import hmac
+import urllib.parse
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+class DuoSecurityConnector(BaseConnector):
+ connector_id = "duo_security"
+ connector_name = "Duo Security"
+ connector_category = "iam"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="Duo Security authentication logs via the Admin API (HMAC-SHA1 signed).",
+ docs_url="/docs/connectors/duo-security",
+ fields=[
+ Field("integration_key", "string", "Integration Key"),
+ Field("secret_key", "secret", "Secret Key"),
+ Field(
+ "api_hostname",
+ "string",
+ "API Hostname",
+ placeholder="api-XXXXXXXX.duosecurity.com",
+ ),
+ ],
+ )
+
+ def __init__(self, integration_key: str, secret_key: str, api_hostname: str):
+ self._ikey = integration_key
+ self._skey = secret_key
+ self._host = api_hostname.lower()
+
+ def _sign(self, method: str, path: str, params: dict[str, str]) -> tuple[str, str]:
+ now = email.utils.formatdate()
+ canon_params = urllib.parse.urlencode(sorted(params.items()))
+ canon = "\n".join([now, method.upper(), self._host, path, canon_params])
+ sig = hmac.new(self._skey.encode(), canon.encode(), hashlib.sha1).hexdigest()
+ auth = base64.b64encode(f"{self._ikey}:{sig}".encode()).decode()
+ return now, f"Basic {auth}"
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ path = "/admin/v1/info/summary"
+ date_str, auth = self._sign("GET", path, {})
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"https://{self._host}{path}",
+ headers={"Date": date_str, "Authorization": auth},
+ )
+ resp.raise_for_status()
+ return {"success": True, "connector": self.connector_id}
+ except Exception as exc:
+ logger.warning("duo_security.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ mintime = str(int((datetime.now(UTC) - timedelta(seconds=since_seconds)).timestamp()) * 1000)
+ path = "/admin/v2/logs/authentication"
+ params = {"mintime": mintime, "maxtime": str(int(datetime.now(UTC).timestamp()) * 1000)}
+
+ date_str, auth = self._sign("GET", path, params)
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"https://{self._host}{path}",
+ headers={"Date": date_str, "Authorization": auth},
+ params=params,
+ )
+ resp.raise_for_status()
+ logs = resp.json().get("response", {}).get("authlogs", [])
+
+ return [self.normalize(entry) for entry in logs]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ result = str(raw.get("result", "")).upper()
+ reason = str(raw.get("reason", "")).lower()
+
+ if "fraud" in reason:
+ severity = "high"
+ elif result == "FAILURE":
+ severity = "medium"
+ elif raw.get("access_device", {}).get("is_encryption_enabled") == "false":
+ severity = "low"
+ elif result == "SUCCESS" and "new" in reason:
+ severity = "low"
+ else:
+ severity = "info"
+
+ user = raw.get("user", {}).get("name", "unknown")
+ auth_device = raw.get("auth_device", {})
+
+ return {
+ "source": self.connector_id,
+ "external_id": raw.get("txid", ""),
+ "title": f"Duo auth: {result.lower()} for {user}",
+ "description": f"Result: {result}, Reason: {raw.get('reason', 'N/A')}, User: {user}",
+ "severity": severity,
+ "src_ip": raw.get("access_device", {}).get("ip"),
+ "actor": user,
+ "hostname": auth_device.get("name"),
+ "raw_event": raw,
+ "created_at": raw.get("isotimestamp"),
+ }
diff --git a/services/connectors/app/connectors/jira_connector.py b/services/connectors/app/connectors/jira_connector.py
new file mode 100644
index 000000000..36efee77b
--- /dev/null
+++ b/services/connectors/app/connectors/jira_connector.py
@@ -0,0 +1,121 @@
+"""
+Jira connector.
+Fetches security-relevant issues from Jira Cloud via the REST API.
+"""
+
+from __future__ import annotations
+
+from base64 import b64encode
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_PRIORITY_SEVERITY = {
+ "Highest": "high",
+ "High": "high",
+ "Medium": "medium",
+ "Low": "low",
+ "Lowest": "info",
+}
+
+
+class JiraConnector(BaseConnector):
+ connector_id = "jira"
+ connector_name = "Jira"
+ connector_category = "saas"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="Jira Cloud issues via the REST API v3.",
+ docs_url="/docs/connectors/jira",
+ fields=[
+ Field(
+ "base_url",
+ "string",
+ "Jira Base URL",
+ placeholder="https://yourorg.atlassian.net",
+ ),
+ Field("email", "string", "Email"),
+ Field("api_token", "secret", "API Token"),
+ ],
+ )
+
+ def __init__(self, base_url: str, email: str, api_token: str):
+ self._base_url = base_url.rstrip("/")
+ self._email = email
+ self._api_token = api_token
+
+ def _auth_header(self) -> dict[str, str]:
+ creds = b64encode(f"{self._email}:{self._api_token}".encode()).decode()
+ return {
+ "Authorization": f"Basic {creds}",
+ "Accept": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base_url}/rest/api/3/myself",
+ headers=self._auth_header(),
+ )
+ resp.raise_for_status()
+ user = resp.json()
+ return {
+ "success": True,
+ "connector": self.connector_id,
+ "user": user.get("displayName"),
+ }
+ except Exception as exc:
+ logger.warning("jira.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ minutes_ago = max(since_seconds // 60, 1)
+ jql = f"updated >= -{minutes_ago}m ORDER BY updated DESC"
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base_url}/rest/api/3/search",
+ headers=self._auth_header(),
+ params={
+ "jql": jql,
+ "maxResults": 100,
+ "fields": "summary,description,priority,status,creator,created,updated",
+ },
+ )
+ resp.raise_for_status()
+ issues = resp.json().get("issues", [])
+
+ return [self.normalize(i) for i in issues]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ fields = raw.get("fields", {})
+ priority_name = (fields.get("priority") or {}).get("name", "Medium")
+ creator = fields.get("creator") or {}
+ description_body = fields.get("description")
+ if isinstance(description_body, dict):
+ description_body = description_body.get("text", str(description_body))
+
+ return {
+ "source": self.connector_id,
+ "external_id": raw.get("key", raw.get("id", "")),
+ "title": fields.get("summary", "Jira Issue"),
+ "description": str(description_body or "")[:500],
+ "severity": _PRIORITY_SEVERITY.get(priority_name, "medium"),
+ "src_ip": None,
+ "hostname": None,
+ "actor": creator.get("displayName") or creator.get("emailAddress"),
+ "raw_event": raw,
+ "created_at": fields.get("created"),
+ }
diff --git a/services/connectors/app/connectors/onepassword.py b/services/connectors/app/connectors/onepassword.py
new file mode 100644
index 000000000..d9fc0a71c
--- /dev/null
+++ b/services/connectors/app/connectors/onepassword.py
@@ -0,0 +1,134 @@
+"""
+1Password Events connector.
+Fetches sign-in attempt events from the 1Password Events Reporting API.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+
+class OnePasswordConnector(BaseConnector):
+ connector_id = "onepassword"
+ connector_name = "1Password Events"
+ connector_category = "iam"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="1Password sign-in attempts via the Events Reporting API.",
+ docs_url="/docs/connectors/onepassword",
+ fields=[
+ Field("api_token", "secret", "API Token (Bearer)"),
+ Field(
+ "base_url",
+ "string",
+ "Events API Base URL",
+ required=False,
+ default="https://events.1password.com",
+ help_text="Override only for 1Password Business accounts on a non-default region.",
+ ),
+ ],
+ )
+
+ def __init__(
+ self,
+ api_token: str,
+ base_url: str = "https://events.1password.com",
+ ):
+ self._api_token = api_token
+ self._base_url = base_url.rstrip("/")
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {self._api_token}",
+ "Content-Type": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ since = (datetime.now(UTC) - timedelta(minutes=1)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ f"{self._base_url}/api/v1/signinattempts",
+ headers=self._headers(),
+ json={"limit": 1, "start_time": since},
+ )
+ resp.raise_for_status()
+ return {"success": True, "connector": self.connector_id}
+ except Exception as exc:
+ logger.warning("onepassword.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+
+ events: list[dict[str, Any]] = []
+ cursor: str | None = None
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ while True:
+ body: dict[str, Any] = {"limit": 100, "start_time": since}
+ if cursor:
+ body["cursor"] = cursor
+
+ resp = await client.post(
+ f"{self._base_url}/api/v1/signinattempts",
+ headers=self._headers(),
+ json=body,
+ )
+ resp.raise_for_status()
+ data = resp.json()
+ items = data.get("items", [])
+ events.extend(items)
+
+ cursor = data.get("cursor")
+ if not data.get("has_more") or not cursor:
+ break
+
+ return [self.normalize(e) for e in events]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ category = raw.get("category", "success")
+ severity = "info"
+ if category == "credentials_failed":
+ severity = "medium"
+ elif category in ("mfa_failed", "modern_version_failed"):
+ severity = "high"
+ elif category == "firewall_failed":
+ severity = "high"
+
+ session = raw.get("session", {}) or {}
+ client_info = raw.get("client", {}) or {}
+
+ return {
+ "source": self.connector_id,
+ "external_id": raw.get("uuid", ""),
+ "title": f"1Password sign-in: {category}",
+ "description": (
+ f"Sign-in attempt ({category}) by "
+ f"{raw.get('target_user', {}).get('email', 'unknown')} "
+ f"from {client_info.get('ip_address', 'unknown')}"
+ ),
+ "severity": severity,
+ "src_ip": client_info.get("ip_address"),
+ "hostname": None,
+ "actor": raw.get("target_user", {}).get("email"),
+ "raw_event": raw,
+ "created_at": raw.get("timestamp"),
+ }
diff --git a/services/connectors/app/connectors/proofpoint.py b/services/connectors/app/connectors/proofpoint.py
new file mode 100644
index 000000000..a8dcad21a
--- /dev/null
+++ b/services/connectors/app/connectors/proofpoint.py
@@ -0,0 +1,114 @@
+"""
+Proofpoint TAP connector.
+Fetches blocked messages from the Proofpoint Targeted Attack Protection SIEM API.
+"""
+
+from __future__ import annotations
+
+from base64 import b64encode
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_TAP_BASE = "https://tap-api-v2.proofpoint.com"
+
+_VERDICT_SEVERITY = {
+ "phish": "high",
+ "malware": "high",
+ "spam": "medium",
+ "impostor": "high",
+ "adult": "low",
+ "bulk": "info",
+}
+
+
+class ProofpointConnector(BaseConnector):
+ connector_id = "proofpoint"
+ connector_name = "Proofpoint TAP"
+ connector_category = "saas"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="Proofpoint Targeted Attack Protection — blocked messages via the SIEM API.",
+ docs_url="/docs/connectors/proofpoint",
+ fields=[
+ Field("service_principal", "string", "Service Principal"),
+ Field("service_secret", "secret", "Service Secret"),
+ ],
+ )
+
+ def __init__(self, service_principal: str, service_secret: str):
+ self._principal = service_principal
+ self._secret = service_secret
+
+ def _auth_header(self) -> dict[str, str]:
+ creds = b64encode(f"{self._principal}:{self._secret}".encode()).decode()
+ return {
+ "Authorization": f"Basic {creds}",
+ "Accept": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ since = (datetime.now(UTC) - timedelta(minutes=5)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{_TAP_BASE}/v2/siem/messages/blocked",
+ headers=self._auth_header(),
+ params={"sinceTime": since, "format": "json"},
+ )
+ resp.raise_for_status()
+ return {"success": True, "connector": self.connector_id}
+ except Exception as exc:
+ logger.warning("proofpoint.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{_TAP_BASE}/v2/siem/messages/blocked",
+ headers=self._auth_header(),
+ params={"sinceTime": since, "format": "json"},
+ )
+ resp.raise_for_status()
+ data = resp.json()
+
+ messages = data.get("messagesBlocked", [])
+ return [self.normalize(m) for m in messages]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ threats = raw.get("threatsInfoMap", [])
+ classification = threats[0].get("classification", "unknown") if threats else "unknown"
+
+ return {
+ "source": self.connector_id,
+ "external_id": raw.get("GUID", ""),
+ "title": f"Proofpoint blocked: {raw.get('subject', 'no subject')}",
+ "description": (
+ f"Blocked message from {raw.get('sender', 'unknown')} "
+ f"to {', '.join(raw.get('recipients', []))} — "
+ f"classification: {classification}"
+ ),
+ "severity": _VERDICT_SEVERITY.get(classification, "medium"),
+ "src_ip": raw.get("senderIP"),
+ "hostname": None,
+ "actor": raw.get("sender"),
+ "raw_event": raw,
+ "created_at": raw.get("messageTime"),
+ }
diff --git a/services/connectors/app/connectors/sentinelone.py b/services/connectors/app/connectors/sentinelone.py
new file mode 100644
index 000000000..0851195f6
--- /dev/null
+++ b/services/connectors/app/connectors/sentinelone.py
@@ -0,0 +1,126 @@
+"""
+SentinelOne connector.
+Fetches threat detections from the SentinelOne Management Console API.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_SEVERITY_MAP = {
+ "Undefined": "info",
+ "Info": "info",
+ "Low": "low",
+ "Medium": "medium",
+ "High": "high",
+ "Critical": "high",
+}
+
+
+class SentinelOneConnector(BaseConnector):
+ connector_id = "sentinelone"
+ connector_name = "SentinelOne"
+ connector_category = "edr"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="SentinelOne threat detections via the Management Console API.",
+ docs_url="/docs/connectors/sentinelone",
+ fields=[
+ Field("api_token", "secret", "API Token"),
+ Field(
+ "base_url",
+ "string",
+ "Base URL",
+ placeholder="https://usea1-partners.sentinelone.net",
+ ),
+ Field(
+ "site_id",
+ "string",
+ "Site ID",
+ required=False,
+ help_text="Optional. Limits results to a single site.",
+ ),
+ ],
+ )
+
+ def __init__(self, api_token: str, base_url: str, site_id: str | None = None):
+ self._api_token = api_token
+ self._base_url = base_url.rstrip("/")
+ self._site_id = site_id or None
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "Authorization": f"APIToken {self._api_token}",
+ "Accept": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base_url}/web/api/v2.1/system/info",
+ headers=self._headers(),
+ )
+ resp.raise_for_status()
+ return {"success": True, "connector": self.connector_id}
+ except Exception as exc:
+ logger.warning("sentinelone.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
+ "%Y-%m-%dT%H:%M:%S.000000Z"
+ )
+ params: dict[str, Any] = {
+ "createdAt__gte": since,
+ "limit": 100,
+ }
+ if self._site_id:
+ params["siteIds"] = self._site_id
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base_url}/web/api/v2.1/threats",
+ headers=self._headers(),
+ params=params,
+ )
+ resp.raise_for_status()
+ threats = resp.json().get("data", [])
+
+ return [self.normalize(t) for t in threats]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ threat_info = raw.get("threatInfo", {})
+ agent_info = raw.get("agentRealtimeInfo", {}) or raw.get("agentDetectionInfo", {})
+
+ return {
+ "source": self.connector_id,
+ "external_id": raw.get("id", ""),
+ "title": threat_info.get("threatName", "SentinelOne Threat"),
+ "description": (
+ f"{threat_info.get('classification', 'unknown')} — "
+ f"{threat_info.get('threatName', 'unknown')} on "
+ f"{agent_info.get('agentComputerName', 'unknown')}"
+ ),
+ "severity": _SEVERITY_MAP.get(
+ threat_info.get("confidenceLevel", "Medium"), "medium"
+ ),
+ "src_ip": agent_info.get("agentIpV4", agent_info.get("externalIp")),
+ "hostname": agent_info.get("agentComputerName"),
+ "actor": threat_info.get("processUser"),
+ "raw_event": raw,
+ "created_at": threat_info.get("createdAt"),
+ }
diff --git a/services/connectors/app/connectors/servicenow.py b/services/connectors/app/connectors/servicenow.py
new file mode 100644
index 000000000..2087a4934
--- /dev/null
+++ b/services/connectors/app/connectors/servicenow.py
@@ -0,0 +1,113 @@
+"""
+ServiceNow connector.
+Fetches security-relevant incidents from the ServiceNow Table API.
+"""
+
+from __future__ import annotations
+
+from base64 import b64encode
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_IMPACT_SEVERITY = {
+ "1": "high",
+ "2": "medium",
+ "3": "low",
+}
+
+
+class ServiceNowConnector(BaseConnector):
+ connector_id = "servicenow"
+ connector_name = "ServiceNow"
+ connector_category = "saas"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="ServiceNow incidents via the Table API.",
+ docs_url="/docs/connectors/servicenow",
+ fields=[
+ Field(
+ "instance_url",
+ "string",
+ "Instance URL",
+ placeholder="https://yourinstance.service-now.com",
+ ),
+ Field("username", "string", "Username"),
+ Field("password", "secret", "Password"),
+ ],
+ )
+
+ def __init__(self, instance_url: str, username: str, password: str):
+ self._base_url = instance_url.rstrip("/")
+ self._username = username
+ self._password = password
+
+ def _auth_header(self) -> dict[str, str]:
+ creds = b64encode(f"{self._username}:{self._password}".encode()).decode()
+ return {
+ "Authorization": f"Basic {creds}",
+ "Accept": "application/json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base_url}/api/now/table/incident",
+ headers=self._auth_header(),
+ params={"sysparm_limit": 1},
+ )
+ resp.raise_for_status()
+ return {"success": True, "connector": self.connector_id}
+ except Exception as exc:
+ logger.warning("servicenow.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime(
+ "%Y-%m-%d %H:%M:%S"
+ )
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base_url}/api/now/table/incident",
+ headers=self._auth_header(),
+ params={
+ "sysparm_query": f"sys_created_on>={since}^ORsys_updated_on>={since}",
+ "sysparm_limit": 100,
+ "sysparm_display_value": "true",
+ },
+ )
+ resp.raise_for_status()
+ incidents = resp.json().get("result", [])
+
+ return [self.normalize(i) for i in incidents]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ impact = str(raw.get("impact", "3"))
+ if isinstance(impact, dict):
+ impact = impact.get("value", "3")
+
+ return {
+ "source": self.connector_id,
+ "external_id": raw.get("sys_id", ""),
+ "title": raw.get("short_description", "ServiceNow Incident"),
+ "description": raw.get("description", "")[:500],
+ "severity": _IMPACT_SEVERITY.get(str(impact), "low"),
+ "src_ip": None,
+ "hostname": raw.get("cmdb_ci", {}).get("display_value") if isinstance(raw.get("cmdb_ci"), dict) else raw.get("cmdb_ci"),
+ "actor": raw.get("opened_by", {}).get("display_value") if isinstance(raw.get("opened_by"), dict) else raw.get("opened_by"),
+ "raw_event": raw,
+ "created_at": raw.get("sys_created_on"),
+ }
diff --git a/services/connectors/app/connectors/snyk.py b/services/connectors/app/connectors/snyk.py
new file mode 100644
index 000000000..905329d23
--- /dev/null
+++ b/services/connectors/app/connectors/snyk.py
@@ -0,0 +1,129 @@
+"""
+Snyk connector.
+Fetches vulnerability issues from the Snyk REST API.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_SEVERITY_MAP: dict[str, str] = {
+ "info": "info",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "critical": "high",
+}
+
+
+class SnykConnector(BaseConnector):
+ connector_id = "snyk"
+ connector_name = "Snyk"
+ connector_category = "vcs"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="Snyk vulnerability issues via the REST API.",
+ docs_url="/docs/connectors/snyk",
+ fields=[
+ Field("api_token", "secret", "API Token"),
+ Field(
+ "org_id",
+ "string",
+ "Organization ID",
+ help_text="Snyk organization UUID (Settings → General → Organization ID).",
+ ),
+ Field(
+ "base_url",
+ "string",
+ "Base URL",
+ required=False,
+ default="https://api.snyk.io",
+ help_text="Override for Snyk Enterprise on-prem or EU tenants.",
+ ),
+ ],
+ )
+
+ def __init__(
+ self,
+ api_token: str,
+ org_id: str,
+ base_url: str = "https://api.snyk.io",
+ ):
+ self._api_token = api_token
+ self._org_id = org_id
+ self._base_url = base_url.rstrip("/")
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "Authorization": f"token {self._api_token}",
+ "Content-Type": "application/vnd.api+json",
+ }
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base_url}/rest/orgs/{self._org_id}",
+ headers=self._headers(),
+ params={"version": "2024-10-15"},
+ )
+ resp.raise_for_status()
+ return {"success": True, "connector": self.connector_id}
+ except Exception as exc:
+ logger.warning("snyk.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ params: dict[str, Any] = {
+ "version": "2024-10-15",
+ "limit": 100,
+ "created_after": since,
+ }
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base_url}/rest/orgs/{self._org_id}/issues",
+ headers=self._headers(),
+ params=params,
+ )
+ resp.raise_for_status()
+ issues = resp.json().get("data", [])
+
+ return [self.normalize(i) for i in issues]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ attrs = raw.get("attributes", {})
+ raw_severity = str(attrs.get("effective_severity_level", "medium")).lower()
+ severity = _SEVERITY_MAP.get(raw_severity, "medium")
+
+ coordinates = attrs.get("coordinates") or [{}]
+ first_coord = coordinates[0] if coordinates else {}
+
+ return {
+ "source": self.connector_id,
+ "external_id": raw.get("id", ""),
+ "title": attrs.get("title", "Snyk Issue"),
+ "description": attrs.get("description", ""),
+ "severity": severity,
+ "hostname": first_coord.get("representations", [{}])[0].get("dependency", {}).get("package_name")
+ if first_coord.get("representations")
+ else None,
+ "cve": attrs.get("problems", [{}])[0].get("id") if attrs.get("problems") else None,
+ "raw_event": raw,
+ "created_at": attrs.get("created_at"),
+ }
diff --git a/services/connectors/app/connectors/wiz.py b/services/connectors/app/connectors/wiz.py
new file mode 100644
index 000000000..24e1b5451
--- /dev/null
+++ b/services/connectors/app/connectors/wiz.py
@@ -0,0 +1,175 @@
+"""
+Wiz connector.
+Fetches cloud security issues from the Wiz GraphQL API.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_SEVERITY_MAP: dict[str, str] = {
+ "INFORMATIONAL": "info",
+ "LOW": "low",
+ "MEDIUM": "medium",
+ "HIGH": "high",
+ "CRITICAL": "high",
+}
+
+_ISSUES_QUERY = """
+query IssuesTable($filterBy: IssueFilters, $first: Int) {
+ issues(filterBy: $filterBy, first: $first) {
+ nodes {
+ id
+ severity
+ status
+ title
+ description
+ createdAt
+ entitySnapshot {
+ id
+ name
+ type
+ cloudPlatform
+ region
+ subscriptionExternalId
+ }
+ sourceRule {
+ id
+ name
+ }
+ }
+ }
+}
+"""
+
+
+class WizConnector(BaseConnector):
+ connector_id = "wiz"
+ connector_name = "Wiz"
+ connector_category = "cloud"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="Wiz cloud security issues via the GraphQL API.",
+ docs_url="/docs/connectors/wiz",
+ fields=[
+ Field("client_id", "string", "Client ID"),
+ Field("client_secret", "secret", "Client Secret"),
+ Field(
+ "api_endpoint_url",
+ "string",
+ "API Endpoint URL",
+ placeholder="https://api.us20.app.wiz.io/graphql",
+ help_text="Your tenant's GraphQL API endpoint.",
+ ),
+ Field(
+ "auth_url",
+ "string",
+ "Auth URL",
+ required=False,
+ default="https://auth.app.wiz.io/oauth/token",
+ help_text="OAuth2 token endpoint. Override only for gov-cloud tenants.",
+ ),
+ ],
+ )
+
+ def __init__(
+ self,
+ client_id: str,
+ client_secret: str,
+ api_endpoint_url: str,
+ auth_url: str = "https://auth.app.wiz.io/oauth/token",
+ ):
+ self._client_id = client_id
+ self._client_secret = client_secret
+ self._api_url = api_endpoint_url.rstrip("/")
+ self._auth_url = auth_url
+ self._access_token: str | None = None
+
+ async def _authenticate(self) -> str:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ self._auth_url,
+ data={
+ "grant_type": "client_credentials",
+ "client_id": self._client_id,
+ "client_secret": self._client_secret,
+ "audience": "wiz-api",
+ },
+ )
+ resp.raise_for_status()
+ self._access_token = resp.json()["access_token"]
+ return self._access_token
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ token = await self._authenticate()
+ return {"success": True, "connector": self.connector_id, "authenticated": bool(token)}
+ except Exception as exc:
+ logger.warning("wiz.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ if not self._access_token:
+ await self._authenticate()
+
+ since = (datetime.now(UTC) - timedelta(seconds=since_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
+ headers = {"Authorization": f"Bearer {self._access_token}"}
+
+ payload = {
+ "query": _ISSUES_QUERY,
+ "variables": {
+ "filterBy": {
+ "status": ["OPEN", "IN_PROGRESS"],
+ "createdAt": {"after": since},
+ },
+ "first": 100,
+ },
+ }
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.post(self._api_url, headers=headers, json=payload)
+
+ if resp.status_code == 401:
+ await self._authenticate()
+ headers = {"Authorization": f"Bearer {self._access_token}"}
+ resp = await client.post(self._api_url, headers=headers, json=payload)
+
+ resp.raise_for_status()
+ issues = resp.json().get("data", {}).get("issues", {}).get("nodes", [])
+
+ return [self.normalize(i) for i in issues]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ raw_severity = str(raw.get("severity", "MEDIUM")).upper()
+ severity = _SEVERITY_MAP.get(raw_severity, "medium")
+
+ entity = raw.get("entitySnapshot") or {}
+ rule = raw.get("sourceRule") or {}
+
+ return {
+ "source": self.connector_id,
+ "external_id": raw.get("id", ""),
+ "title": raw.get("title", "Wiz Issue"),
+ "description": raw.get("description", ""),
+ "severity": severity,
+ "hostname": entity.get("name"),
+ "cloud_resource": entity.get("id"),
+ "cloud_platform": entity.get("cloudPlatform"),
+ "cloud_region": entity.get("region"),
+ "rule_name": rule.get("name"),
+ "raw_event": raw,
+ "created_at": raw.get("createdAt"),
+ }
diff --git a/services/connectors/app/connectors/zscaler.py b/services/connectors/app/connectors/zscaler.py
new file mode 100644
index 000000000..0fb6f9bb5
--- /dev/null
+++ b/services/connectors/app/connectors/zscaler.py
@@ -0,0 +1,165 @@
+"""
+Zscaler connector.
+Fetches web security logs from Zscaler Internet Access (ZIA).
+"""
+
+from __future__ import annotations
+
+import hashlib
+import time
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import httpx
+import structlog
+
+from app.connectors.base import BaseConnector, ConnectorSchema, Field
+
+logger = structlog.get_logger()
+
+_SEVERITY_MAP = {
+ "Allow": "info",
+ "Caution": "low",
+ "Block": "medium",
+ "Quarantine": "high",
+ "Isolate": "high",
+}
+
+
+class ZscalerConnector(BaseConnector):
+ connector_id = "zscaler"
+ connector_name = "Zscaler Internet Access"
+ connector_category = "network"
+
+ @classmethod
+ def schema(cls) -> ConnectorSchema:
+ return ConnectorSchema(
+ connector_id=cls.connector_id,
+ connector_name=cls.connector_name,
+ category=cls.connector_category,
+ description="Zscaler Internet Access web security logs via the ZIA API.",
+ docs_url="/docs/connectors/zscaler",
+ fields=[
+ Field("api_key", "secret", "API Key"),
+ Field(
+ "cloud",
+ "string",
+ "ZIA Cloud",
+ required=False,
+ default="zscloud.net",
+ help_text="ZIA cloud domain (e.g. zscloud.net, zscaler.net).",
+ ),
+ Field("username", "string", "Admin Username"),
+ Field("password", "secret", "Admin Password"),
+ ],
+ )
+
+ def __init__(
+ self,
+ api_key: str,
+ username: str,
+ password: str,
+ cloud: str = "zscloud.net",
+ ):
+ self._api_key = api_key
+ self._cloud = cloud
+ self._username = username
+ self._password = password
+ self._base_url = f"https://zsapi.{cloud}"
+ self._jsessionid: str | None = None
+
+ def _obfuscate_api_key(self) -> tuple[str, str]:
+ now = str(int(time.time() * 1000))
+ n = now[-6:]
+ r = str(int(n) >> 1).zfill(6)
+ key = ""
+ for i, ch in enumerate(r):
+ key += self._api_key[int(ch)]
+ return key, now
+
+ async def _authenticate(self) -> None:
+ obf_key, timestamp = self._obfuscate_api_key()
+ payload = {
+ "apiKey": obf_key,
+ "username": self._username,
+ "password": self._password,
+ "timestamp": timestamp,
+ }
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ f"{self._base_url}/api/v1/authenticatedSession",
+ json=payload,
+ )
+ resp.raise_for_status()
+ self._jsessionid = resp.cookies.get("JSESSIONID") or resp.json().get("JSESSIONID")
+ if not self._jsessionid:
+ for cookie in resp.cookies.jar:
+ if cookie.name == "JSESSIONID":
+ self._jsessionid = cookie.value
+ break
+
+ async def test_connection(self) -> dict[str, Any]:
+ try:
+ await self._authenticate()
+ return {"success": True, "connector": self.connector_id}
+ except Exception as exc:
+ logger.warning("zscaler.test_connection.failed", error=str(exc))
+ return {"success": False, "connector": self.connector_id, "error": str(exc)}
+
+ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:
+ if not self._jsessionid:
+ await self._authenticate()
+
+ end_time = int(datetime.now(UTC).timestamp())
+ start_time = end_time - since_seconds
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.post(
+ f"{self._base_url}/api/v1/webApplicationRules",
+ cookies={"JSESSIONID": self._jsessionid or ""},
+ json={
+ "startTime": start_time,
+ "endTime": end_time,
+ "category": "any",
+ "subcategory": "any",
+ "action": "any",
+ "pageSize": 100,
+ },
+ )
+ if resp.status_code == 401:
+ await self._authenticate()
+ resp = await client.post(
+ f"{self._base_url}/api/v1/webApplicationRules",
+ cookies={"JSESSIONID": self._jsessionid or ""},
+ json={
+ "startTime": start_time,
+ "endTime": end_time,
+ "category": "any",
+ "subcategory": "any",
+ "action": "any",
+ "pageSize": 100,
+ },
+ )
+ resp.raise_for_status()
+ logs = resp.json() if isinstance(resp.json(), list) else resp.json().get("data", [])
+
+ return [self.normalize(e) for e in logs]
+
+ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ action = raw.get("action", "Allow")
+ return {
+ "source": self.connector_id,
+ "external_id": str(raw.get("id", raw.get("transactionId", ""))),
+ "title": f"Zscaler: {action} — {raw.get('url', raw.get('hostname', 'unknown'))}",
+ "description": (
+ f"Policy action {action} for "
+ f"{raw.get('url', raw.get('hostname', 'unknown'))} "
+ f"(category: {raw.get('urlCategory', 'unknown')})"
+ ),
+ "severity": _SEVERITY_MAP.get(action, "info"),
+ "src_ip": raw.get("clientPublicIP") or raw.get("clientPrivateIP"),
+ "hostname": raw.get("hostname") or raw.get("serverIP"),
+ "actor": raw.get("login") or raw.get("user"),
+ "raw_event": raw,
+ "created_at": raw.get("datetime") or raw.get("timestamp"),
+ }