feat(aria): Phase 2 — precursor sequence detection engine
CD - Develop / build-and-deploy (push) Failing after 11m45s

Adds multi-phase attack sequence detection to ARIA. After each event is
ingested, SequenceDetectionService queries events within a 15-minute window
for the same device and fires a PrecursorSequenceAlert when jackpotting
(PHYSICAL_ACCESS + malware phase) or skimming (PHYSICAL_ACCESS + card reader
tamper/USB) patterns are detected. Confidence is scored 0–1 based on phases
and severity. Detected sequences are published to hiveops.aria.sequences Kafka
topic. Adds REST API (GET /sequences, GET /{id}/events, POST /{id}/resolve) and
enables the Precursor Alerts view in the SPA with filter sidebar, confidence
bar, and event detail slide panel.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-15 14:25:35 -04:00
parent fe9a252dcd
commit aa9f8a10ef
12 changed files with 1026 additions and 12 deletions
+11 -6
View File
@@ -2,6 +2,7 @@
import Dashboard from './components/Dashboard.svelte';
import ThreatEvents from './components/ThreatEvents.svelte';
import IocManagement from './components/IocManagement.svelte';
import PrecursorAlerts from './components/PrecursorAlerts.svelte';
import Toast from './components/common/Toast.svelte';
import { onMount } from 'svelte';
import { authApi } from './lib/api';
@@ -18,7 +19,7 @@
localStorage.setItem('ariaSidebarCollapsed', String(sidebarCollapsed));
}
type View = 'dashboard' | 'events' | 'ioc';
type View = 'dashboard' | 'events' | 'ioc' | 'sequences';
let currentView: View = 'dashboard';
let eventsInitialSeverity: ThreatSeverity | '' = '';
@@ -31,6 +32,7 @@
if (e.detail.view === 'events-critical') navigate('events', 'CRITICAL');
else if (e.detail.view === 'events-high') navigate('events', 'HIGH');
else if (e.detail.view === 'ioc') navigate('ioc');
else if (e.detail.view === 'sequences') navigate('sequences');
}
onMount(() => {
@@ -84,17 +86,18 @@
</button>
</div>
{#if !sidebarCollapsed}
<div class="nav-section-header">Phase 23</div>
{/if}
<div class="nav-group">
<button class="nav-btn nav-disabled" disabled title="Precursor Alerts (Phase 2)">
<button class="nav-btn" class:active={currentView === 'sequences'}
on:click={() => navigate('sequences')} title="Precursor Alerts">
<span class="nav-icon">🔔</span>
{#if !sidebarCollapsed}<span>Precursor Alerts</span>{/if}
</button>
</div>
{#if !sidebarCollapsed}
<div class="nav-section-header">Phase 3</div>
{/if}
<div class="nav-group">
<button class="nav-btn nav-disabled" disabled title="Device Posture (Phase 3)">
<span class="nav-icon">🔒</span>
@@ -125,6 +128,8 @@
<ThreatEvents initialSeverity={eventsInitialSeverity} />
{:else if currentView === 'ioc'}
<IocManagement />
{:else if currentView === 'sequences'}
<PrecursorAlerts />
{/if}
</main>
</div>
+9 -1
View File
@@ -58,6 +58,13 @@
<div class="stat-label">Active IOCs</div>
<div class="stat-hint">Manage IOCs →</div>
</button>
<button class="stat-card clickable seq" on:click={() => dispatch('navigate', { view: 'sequences' })}>
<div class="stat-icon seq-icon">🔔</div>
<div class="stat-value seq-val">{(stats.activeSequenceCount ?? 0).toLocaleString()}</div>
<div class="stat-label">Active Sequences</div>
<div class="stat-hint">View alerts →</div>
</button>
</div>
<div class="section-title">Phase Coverage</div>
@@ -99,7 +106,7 @@
.stat-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(5, 1fr);
gap: 16px;
margin-bottom: 32px;
}
@@ -134,6 +141,7 @@
.critical-val { color: #dc2626; }
.high-val { color: #d97706; }
.ioc-val { color: #2563eb; }
.seq-val { color: #7c3aed; }
.section-title {
font-size: 0.78rem;
@@ -0,0 +1,660 @@
<script lang="ts">
import { onMount } from 'svelte';
import { ariaApi, type PrecursorSequenceAlert, type SequenceType, type ThreatEvent } from '../lib/api';
import { addToast } from '../lib/stores';
let alerts: PrecursorSequenceAlert[] = [];
let totalElements = 0;
let totalPages = 0;
let currentPage = 0;
const pageSize = 25;
let loading = true;
let resolving: number | null = null;
// Filters
let filterStatus: 'active' | 'resolved' | 'all' = 'active';
let filterType: SequenceType | '' = '';
let filterDevice = '';
let deviceSearchTimer: ReturnType<typeof setTimeout>;
// Detail panel
let panelOpen = false;
let panelAlert: PrecursorSequenceAlert | null = null;
let panelEvents: ThreatEvent[] = [];
let panelLoading = false;
async function load(page = 0) {
loading = true;
try {
const params: Record<string, any> = { page, size: pageSize };
if (filterStatus === 'active') params.resolved = false;
if (filterType) params.sequenceType = filterType;
if (filterDevice.trim()) params.deviceAgentId = filterDevice.trim();
const res = await ariaApi.getSequences(params);
alerts = res.data.content;
totalElements = res.data.page.totalElements;
totalPages = res.data.page.totalPages;
currentPage = res.data.page.number;
} catch {
addToast('error', 'Load Failed', 'Could not load sequence alerts');
} finally {
loading = false;
}
}
async function openPanel(alert: PrecursorSequenceAlert) {
panelAlert = alert;
panelOpen = true;
panelEvents = [];
panelLoading = true;
try {
const res = await ariaApi.getSequenceEvents(alert.id);
panelEvents = res.data;
} catch {
addToast('error', 'Load Failed', 'Could not load sequence events');
} finally {
panelLoading = false;
}
}
async function resolve(alert: PrecursorSequenceAlert) {
resolving = alert.id;
try {
const res = await ariaApi.resolveSequence(alert.id);
alerts = alerts.map(a => a.id === alert.id ? res.data : a);
if (panelAlert?.id === alert.id) panelAlert = res.data;
addToast('success', 'Resolved', `Sequence alert #${alert.id} marked as resolved`);
if (filterStatus === 'active') await load(currentPage);
} catch {
addToast('error', 'Error', 'Could not resolve alert');
} finally {
resolving = null;
}
}
function onDeviceInput() {
clearTimeout(deviceSearchTimer);
deviceSearchTimer = setTimeout(() => load(0), 350);
}
function onFilterChange() { load(0); }
function formatDate(iso: string) {
return new Date(iso).toLocaleString('en-US', {
month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
});
}
function confidencePct(c: number) {
return Math.round(c * 100) + '%';
}
onMount(() => load(0));
</script>
<div class="page-wrap">
<div class="header">
<div class="header-text">
<h1>Precursor Alerts</h1>
<p>Multi-phase attack sequence detection — jackpotting and skimming precursors</p>
</div>
<div class="header-count">
{#if !loading}
<span class="total-badge">{totalElements} alert{totalElements !== 1 ? 's' : ''}</span>
{/if}
</div>
</div>
<div class="toolbar">
<div class="toolbar-left">
<div class="filter-group">
<label class="filter-label">Status</label>
<select class="filter-select" bind:value={filterStatus} on:change={onFilterChange}>
<option value="active">Active</option>
<option value="all">All</option>
<option value="resolved">Resolved</option>
</select>
</div>
<div class="filter-group">
<label class="filter-label">Type</label>
<select class="filter-select" bind:value={filterType} on:change={onFilterChange}>
<option value="">All Types</option>
<option value="JACKPOTTING">Jackpotting</option>
<option value="SKIMMING">Skimming</option>
<option value="UNKNOWN">Unknown</option>
</select>
</div>
<div class="filter-group">
<label class="filter-label">Device</label>
<input
class="filter-input"
type="text"
placeholder="Device ID…"
bind:value={filterDevice}
on:input={onDeviceInput}
/>
</div>
</div>
<button class="btn btn-secondary btn-sm" on:click={() => load(currentPage)}>
Refresh
</button>
</div>
{#if loading}
<div class="loading-row">Loading…</div>
{:else if alerts.length === 0}
<div class="empty-state">
<div class="empty-icon">🔔</div>
<div class="empty-title">No {filterStatus === 'active' ? 'active ' : ''}sequence alerts</div>
<div class="empty-sub">ARIA will generate alerts when multi-phase attack precursors are detected</div>
</div>
{:else}
<div class="table-wrapper">
<table>
<thead>
<tr>
<th>Type</th>
<th>Device</th>
<th>Phases Detected</th>
<th>Confidence</th>
<th>Triggered</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{#each alerts as alert (alert.id)}
<tr>
<td>
<span class="seq-badge seq-{alert.sequenceType.toLowerCase()}">
{alert.sequenceType === 'JACKPOTTING' ? '💰' : alert.sequenceType === 'SKIMMING' ? '💳' : '❓'}
{alert.sequenceType}
</span>
</td>
<td class="device-cell">{alert.deviceAgentId ?? '—'}</td>
<td>
<div class="phases">
{#each (alert.phasesDetected ?? []) as phase}
<span class="phase-chip">{phase.replace('_', ' ')}</span>
{/each}
</div>
</td>
<td>
<div class="confidence-wrap">
<div class="confidence-bar">
<div class="confidence-fill conf-{confidenceClass(alert.confidence)}"
style="width: {confidencePct(alert.confidence)}"></div>
</div>
<span class="confidence-text">{confidencePct(alert.confidence)}</span>
</div>
</td>
<td class="date-cell">{formatDate(alert.triggeredAt)}</td>
<td>
{#if alert.resolvedAt}
<span class="status-chip resolved">Resolved</span>
{:else}
<span class="status-chip active">Active</span>
{/if}
</td>
<td>
<div class="actions">
<button class="btn btn-secondary btn-sm" on:click={() => openPanel(alert)}>
Events
</button>
{#if !alert.resolvedAt}
<button
class="btn btn-primary btn-sm"
disabled={resolving === alert.id}
on:click={() => resolve(alert)}
>
{resolving === alert.id ? '…' : 'Resolve'}
</button>
{/if}
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
{#if totalPages > 1}
<div class="pagination">
<button class="btn btn-secondary btn-sm" disabled={currentPage === 0}
on:click={() => load(currentPage - 1)}>← Prev</button>
<span class="page-info">Page {currentPage + 1} of {totalPages}</span>
<button class="btn btn-secondary btn-sm" disabled={currentPage >= totalPages - 1}
on:click={() => load(currentPage + 1)}>Next →</button>
</div>
{/if}
{/if}
</div>
{#if panelOpen && panelAlert}
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div class="overlay" on:click={() => { panelOpen = false; panelAlert = null; }}></div>
<div class="panel">
<div class="panel-header">
<div>
<h2 class="panel-title">Sequence #{panelAlert.id}</h2>
<p class="panel-sub">{panelAlert.sequenceType} — {panelAlert.deviceAgentId ?? 'Unknown device'}</p>
</div>
<button class="close-btn" on:click={() => { panelOpen = false; panelAlert = null; }}>✕</button>
</div>
<div class="panel-meta">
<div class="meta-row">
<span class="meta-label">Confidence</span>
<span class="meta-val">{confidencePct(panelAlert.confidence)}</span>
</div>
<div class="meta-row">
<span class="meta-label">Triggered</span>
<span class="meta-val">{formatDate(panelAlert.triggeredAt)}</span>
</div>
{#if panelAlert.resolvedAt}
<div class="meta-row">
<span class="meta-label">Resolved by</span>
<span class="meta-val">{panelAlert.resolvedBy}</span>
</div>
{/if}
<div class="meta-row">
<span class="meta-label">Phases</span>
<div class="phases">
{#each (panelAlert.phasesDetected ?? []) as p}
<span class="phase-chip">{p.replace('_', ' ')}</span>
{/each}
</div>
</div>
</div>
<div class="panel-section-title">Events in Sequence</div>
{#if panelLoading}
<div class="panel-loading">Loading events…</div>
{:else if panelEvents.length === 0}
<div class="panel-loading">No events tagged to this sequence yet</div>
{:else}
<div class="panel-events">
{#each panelEvents as ev (ev.id)}
<div class="event-row">
<span class="sev-dot sev-{ev.severity.toLowerCase()}"></span>
<div class="event-body">
<div class="event-signal">{ev.signalKey}</div>
<div class="event-meta">{ev.attackPhase?.replace('_',' ') ?? '—'} · {formatDate(ev.detectedAt)}</div>
</div>
<span class="sev-label sev-text-{ev.severity.toLowerCase()}">{ev.severity}</span>
</div>
{/each}
</div>
{/if}
{#if !panelAlert.resolvedAt}
<div class="panel-footer">
<button
class="btn btn-primary"
disabled={resolving === panelAlert.id}
on:click={() => panelAlert && resolve(panelAlert)}
>
{resolving === panelAlert?.id ? 'Resolving…' : 'Mark Resolved'}
</button>
</div>
{/if}
</div>
{/if}
<script lang="ts" context="module">
function confidenceClass(c: number): string {
if (c >= 0.8) return 'high';
if (c >= 0.5) return 'med';
return 'low';
}
</script>
<style>
.page-wrap {
padding: 24px;
height: 100%;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0;
}
.header-count { display: flex; align-items: center; }
.total-badge {
background: rgba(255,255,255,0.15);
color: white;
padding: 4px 12px;
border-radius: 20px;
font-size: 0.82rem;
font-weight: 600;
}
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.toolbar-left {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.filter-group {
display: flex;
align-items: center;
gap: 6px;
}
.filter-label {
font-size: 0.8rem;
color: #6b7280;
white-space: nowrap;
}
.filter-select, .filter-input {
padding: 6px 10px;
border: 1px solid #e2e8f0;
border-radius: 6px;
font-size: 0.85rem;
background: white;
color: #1f2937;
outline: none;
}
.filter-input { width: 160px; }
.filter-select:focus, .filter-input:focus { border-color: #2563eb; }
.loading-row {
padding: 2rem;
text-align: center;
color: #6b7280;
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 4rem 2rem;
gap: 12px;
}
.empty-icon { font-size: 2.5rem; }
.empty-title { font-size: 1.1rem; font-weight: 600; color: #374151; }
.empty-sub { font-size: 0.85rem; color: #9ca3af; text-align: center; }
.table-wrapper {
background: white;
border: 1px solid #e5e7eb;
border-radius: 10px;
overflow: hidden;
margin-bottom: 16px;
}
table { width: 100%; border-collapse: collapse; }
thead tr { background: #f9fafb; }
th {
padding: 10px 14px;
font-size: 0.78rem;
font-weight: 700;
color: #374151;
text-align: left;
text-transform: uppercase;
letter-spacing: 0.4px;
border-bottom: 1px solid #e5e7eb;
white-space: nowrap;
}
td {
padding: 10px 14px;
font-size: 0.88rem;
color: #1f2937;
border-bottom: 1px solid #f3f4f6;
vertical-align: middle;
}
tbody tr:last-child td { border-bottom: none; }
tbody tr:hover td { background: #eff6ff; }
.device-cell { font-family: monospace; font-size: 0.82rem; color: #374151; }
.date-cell { white-space: nowrap; color: #6b7280; font-size: 0.82rem; }
.seq-badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 10px;
border-radius: 20px;
font-size: 0.78rem;
font-weight: 700;
white-space: nowrap;
}
.seq-jackpotting { background: #fef2f2; color: #dc2626; }
.seq-skimming { background: #fff7ed; color: #d97706; }
.seq-unknown { background: #f3f4f6; color: #6b7280; }
.phases { display: flex; flex-wrap: wrap; gap: 4px; }
.phase-chip {
background: #e0e7ff;
color: #3730a3;
padding: 2px 7px;
border-radius: 10px;
font-size: 0.7rem;
font-weight: 600;
white-space: nowrap;
text-transform: uppercase;
letter-spacing: 0.2px;
}
.confidence-wrap {
display: flex;
align-items: center;
gap: 8px;
}
.confidence-bar {
width: 60px;
height: 6px;
background: #e5e7eb;
border-radius: 3px;
overflow: hidden;
flex-shrink: 0;
}
.confidence-fill { height: 100%; border-radius: 3px; transition: width 0.3s; }
.confidence-fill.conf-high { background: #dc2626; }
.confidence-fill.conf-med { background: #d97706; }
.confidence-fill.conf-low { background: #16a34a; }
.confidence-text { font-size: 0.8rem; color: #374151; font-weight: 600; }
.status-chip {
display: inline-block;
padding: 3px 10px;
border-radius: 20px;
font-size: 0.75rem;
font-weight: 600;
}
.status-chip.active { background: #fee2e2; color: #dc2626; }
.status-chip.resolved { background: #dcfce7; color: #16a34a; }
.actions { display: flex; gap: 6px; align-items: center; }
.pagination {
display: flex;
align-items: center;
gap: 12px;
justify-content: center;
padding: 8px 0;
}
.page-info { font-size: 0.82rem; color: #6b7280; }
/* Panel */
.overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.35);
z-index: 100;
}
.panel {
position: fixed;
top: 0;
right: 0;
width: 520px;
height: 100vh;
background: white;
box-shadow: -4px 0 24px rgba(0,0,0,0.15);
z-index: 101;
display: flex;
flex-direction: column;
overflow: hidden;
}
.panel-header {
padding: 20px 20px 16px;
border-bottom: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
align-items: flex-start;
flex-shrink: 0;
}
.panel-title { margin: 0 0 4px; font-size: 1.1rem; font-weight: 700; color: #111827; }
.panel-sub { margin: 0; font-size: 0.82rem; color: #6b7280; font-family: monospace; }
.close-btn {
background: none;
border: none;
font-size: 1.1rem;
cursor: pointer;
color: #9ca3af;
padding: 4px;
line-height: 1;
}
.close-btn:hover { color: #374151; }
.panel-meta {
padding: 16px 20px;
border-bottom: 1px solid #e5e7eb;
display: flex;
flex-direction: column;
gap: 10px;
flex-shrink: 0;
}
.meta-row { display: flex; align-items: flex-start; gap: 12px; }
.meta-label { font-size: 0.78rem; font-weight: 600; color: #6b7280; width: 90px; flex-shrink: 0; padding-top: 2px; }
.meta-val { font-size: 0.88rem; color: #111827; }
.panel-section-title {
padding: 12px 20px 8px;
font-size: 0.72rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #9ca3af;
flex-shrink: 0;
}
.panel-loading {
padding: 24px 20px;
font-size: 0.88rem;
color: #9ca3af;
text-align: center;
}
.panel-events {
flex: 1;
overflow-y: auto;
padding: 0 20px 16px;
display: flex;
flex-direction: column;
gap: 6px;
}
.event-row {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 10px 12px;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 7px;
}
.sev-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
margin-top: 5px;
}
.sev-dot.sev-critical { background: #dc2626; }
.sev-dot.sev-high { background: #d97706; }
.sev-dot.sev-medium { background: #ca8a04; }
.sev-dot.sev-low { background: #16a34a; }
.sev-dot.sev-info { background: #6b7280; }
.event-body { flex: 1; min-width: 0; }
.event-signal { font-size: 0.88rem; font-weight: 600; color: #111827; font-family: monospace; }
.event-meta { font-size: 0.75rem; color: #9ca3af; margin-top: 2px; }
.sev-label { font-size: 0.72rem; font-weight: 700; padding-top: 2px; }
.sev-text-critical { color: #dc2626; }
.sev-text-high { color: #d97706; }
.sev-text-medium { color: #ca8a04; }
.sev-text-low { color: #16a34a; }
.sev-text-info { color: #6b7280; }
.panel-footer {
padding: 16px 20px;
border-top: 1px solid #e5e7eb;
flex-shrink: 0;
}
/* Dark mode */
:global(.dark-mode) .filter-select,
:global(.dark-mode) .filter-input {
background: #1e293b;
border-color: #334155;
color: #e2e8f0;
}
:global(.dark-mode) .filter-label { color: #9ca3af; }
:global(.dark-mode) .table-wrapper { background: #1f2937; border-color: #374151; }
:global(.dark-mode) thead tr { background: #111827; }
:global(.dark-mode) th { color: #9ca3af; border-color: #374151; }
:global(.dark-mode) td { color: #e5e7eb; border-color: #374151; }
:global(.dark-mode) tbody tr:hover td { background: #1e3a5f; }
:global(.dark-mode) .device-cell { color: #9ca3af; }
:global(.dark-mode) .date-cell { color: #6b7280; }
:global(.dark-mode) .confidence-bar { background: #374151; }
:global(.dark-mode) .confidence-text { color: #e2e8f0; }
:global(.dark-mode) .phase-chip { background: #1e3a8a; color: #a5b4fc; }
:global(.dark-mode) .empty-title { color: #e2e8f0; }
:global(.dark-mode) .empty-sub { color: #6b7280; }
:global(.dark-mode) .panel { background: #1f2937; }
:global(.dark-mode) .panel-header { border-color: #374151; }
:global(.dark-mode) .panel-title { color: #f1f5f9; }
:global(.dark-mode) .panel-sub { color: #9ca3af; }
:global(.dark-mode) .panel-meta { border-color: #374151; }
:global(.dark-mode) .meta-val { color: #e2e8f0; }
:global(.dark-mode) .event-row { background: #111827; border-color: #374151; }
:global(.dark-mode) .event-signal { color: #e2e8f0; }
:global(.dark-mode) .panel-footer { border-color: #374151; }
:global(.dark-mode) .seq-jackpotting { background: #450a0a; color: #fca5a5; }
:global(.dark-mode) .seq-skimming { background: #431407; color: #fdba74; }
:global(.dark-mode) .seq-unknown { background: #1e293b; color: #94a3b8; }
:global(.dark-mode) .status-chip.active { background: #450a0a; color: #fca5a5; }
:global(.dark-mode) .status-chip.resolved { background: #052e16; color: #86efac; }
</style>
+27
View File
@@ -59,11 +59,29 @@ export interface ThreatEvent {
institutionKey?: string;
}
export type SequenceType = 'JACKPOTTING' | 'SKIMMING' | 'UNKNOWN';
export interface AriaStats {
totalEvents: number;
criticalCount: number;
highCount: number;
activeIocCount: number;
activeSequenceCount: number;
}
export interface PrecursorSequenceAlert {
id: number;
deviceId?: number;
deviceAgentId?: string;
sequenceType: SequenceType;
phasesDetected?: string[];
confidence: number;
triggeredAt: string;
autoResponseTaken: string;
resolvedAt?: string;
resolvedBy?: string;
institutionKey?: string;
sequenceId: string;
}
export interface PageResponse<T> {
@@ -104,4 +122,13 @@ export const ariaApi = {
deactivateIoc: (id: number) =>
api.delete(`/api/aria/ioc/${id}`),
getSequences: (params?: { resolved?: boolean; sequenceType?: SequenceType; deviceAgentId?: string; page?: number; size?: number }) =>
api.get<PageResponse<PrecursorSequenceAlert>>('/api/aria/sequences', { params }),
getSequenceEvents: (id: number) =>
api.get<ThreatEvent[]>(`/api/aria/sequences/${id}/events`),
resolveSequence: (id: number) =>
api.post<PrecursorSequenceAlert>(`/api/aria/sequences/${id}/resolve`),
};
@@ -0,0 +1,80 @@
package com.hiveops.aria.controller;
import com.hiveops.aria.entity.PrecursorSequenceAlert;
import com.hiveops.aria.entity.ThreatEvent;
import com.hiveops.aria.repository.PrecursorSequenceAlertRepository;
import com.hiveops.aria.repository.ThreatEventRepository;
import com.hiveops.aria.security.AriaPrincipal;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.util.List;
@RestController
@RequestMapping("/api/aria/sequences")
@RequiredArgsConstructor
public class PrecursorSequenceAlertController {
private final PrecursorSequenceAlertRepository alertRepository;
private final ThreatEventRepository eventRepository;
@GetMapping
@PreAuthorize("hasAnyRole('MSP_ADMIN','BCOS_ADMIN')")
public Page<PrecursorSequenceAlert> getSequences(
@RequestParam(required = false) Boolean resolved,
@RequestParam(required = false) PrecursorSequenceAlert.SequenceType sequenceType,
@RequestParam(required = false) String deviceAgentId,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "25") int size) {
Pageable pageable = PageRequest.of(page, size, Sort.by("triggeredAt").descending());
if (deviceAgentId != null && !deviceAgentId.isBlank()) {
return alertRepository.findByDeviceAgentIdOrderByTriggeredAtDesc(deviceAgentId, pageable);
}
if (Boolean.FALSE.equals(resolved)) {
if (sequenceType != null) {
return alertRepository.findBySequenceTypeAndResolvedAtIsNullOrderByTriggeredAtDesc(sequenceType, pageable);
}
return alertRepository.findByResolvedAtIsNullOrderByTriggeredAtDesc(pageable);
}
if (sequenceType != null) {
return alertRepository.findBySequenceTypeOrderByTriggeredAtDesc(sequenceType, pageable);
}
return alertRepository.findAllByOrderByTriggeredAtDesc(pageable);
}
@GetMapping("/{id}/events")
@PreAuthorize("hasAnyRole('MSP_ADMIN','BCOS_ADMIN')")
public ResponseEntity<List<ThreatEvent>> getSequenceEvents(@PathVariable Long id) {
return alertRepository.findById(id)
.map(alert -> ResponseEntity.ok(eventRepository.findBySequenceId(alert.getSequenceId())))
.orElse(ResponseEntity.notFound().build());
}
@PostMapping("/{id}/resolve")
@PreAuthorize("hasAnyRole('MSP_ADMIN','BCOS_ADMIN')")
public ResponseEntity<PrecursorSequenceAlert> resolve(
@PathVariable Long id,
@AuthenticationPrincipal AriaPrincipal principal) {
return alertRepository.findById(id)
.map(alert -> {
if (alert.getResolvedAt() != null) {
return ResponseEntity.ok(alert);
}
alert.setResolvedAt(Instant.now());
alert.setResolvedBy(principal != null ? principal.getEmail() : "unknown");
return ResponseEntity.ok(alertRepository.save(alert));
})
.orElse(ResponseEntity.notFound().build());
}
}
@@ -1,6 +1,7 @@
package com.hiveops.aria.controller;
import com.hiveops.aria.entity.ThreatEvent;
import com.hiveops.aria.repository.PrecursorSequenceAlertRepository;
import com.hiveops.aria.repository.ThreatEventRepository;
import com.hiveops.aria.repository.ThreatIocRepository;
import lombok.RequiredArgsConstructor;
@@ -22,6 +23,7 @@ public class ThreatEventController {
private final ThreatEventRepository eventRepository;
private final ThreatIocRepository iocRepository;
private final PrecursorSequenceAlertRepository sequenceAlertRepository;
@GetMapping("/events")
@PreAuthorize("hasAnyRole('MSP_ADMIN','BCOS_ADMIN')")
@@ -57,11 +59,14 @@ public class ThreatEventController {
PageRequest.of(0, Integer.MAX_VALUE)).getTotalElements();
long activeIocs = iocRepository.findByActiveTrue().size();
long activeSequences = sequenceAlertRepository.countByResolvedAtIsNull();
return ResponseEntity.ok(Map.of(
"totalEvents", totalEvents,
"criticalCount", critical24h,
"highCount", high24h,
"activeIocCount", activeIocs
"totalEvents", totalEvents,
"criticalCount", critical24h,
"highCount", high24h,
"activeIocCount", activeIocs,
"activeSequenceCount", activeSequences
));
}
}
@@ -8,10 +8,16 @@ import org.springframework.kafka.config.TopicBuilder;
@Configuration
public class AriaKafkaConfig {
public static final String TOPIC_THREATS = "hiveops.aria.threats";
public static final String TOPIC_THREATS = "hiveops.aria.threats";
public static final String TOPIC_SEQUENCES = "hiveops.aria.sequences";
@Bean
public NewTopic ariaThreatsTopic() {
return TopicBuilder.name(TOPIC_THREATS).partitions(1).replicas(1).build();
}
@Bean
public NewTopic ariaSequencesTopic() {
return TopicBuilder.name(TOPIC_SEQUENCES).partitions(1).replicas(1).build();
}
}
@@ -0,0 +1,26 @@
package com.hiveops.aria.kafka;
import lombok.*;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.UUID;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AriaSequenceEvent {
private UUID alertId;
private UUID sequenceId;
private Long deviceId;
private String deviceAgentId;
private String institutionKey;
private String sequenceType;
private String[] phasesDetected;
private BigDecimal confidence;
private Instant triggeredAt;
private String sourceService;
}
@@ -0,0 +1,27 @@
package com.hiveops.aria.kafka;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
@Slf4j
public class AriaSequenceProducer {
private final KafkaTemplate<String, Object> kafkaTemplate;
public void publishSequenceAlert(AriaSequenceEvent event) {
kafkaTemplate.send(AriaKafkaConfig.TOPIC_SEQUENCES, event.getDeviceAgentId(), event)
.whenComplete((result, ex) -> {
if (ex != null) {
log.error("Failed to publish sequence alert for device {}: {}",
event.getDeviceAgentId(), ex.getMessage());
} else {
log.debug("Sequence alert published for device {}, type={}",
event.getDeviceAgentId(), event.getSequenceType());
}
});
}
}
@@ -14,4 +14,14 @@ public interface PrecursorSequenceAlertRepository extends JpaRepository<Precurso
Page<PrecursorSequenceAlert> findByDeviceAgentIdOrderByTriggeredAtDesc(String deviceAgentId, Pageable pageable);
Page<PrecursorSequenceAlert> findAllByOrderByTriggeredAtDesc(Pageable pageable);
boolean existsByDeviceAgentIdAndResolvedAtIsNull(String deviceAgentId);
long countByResolvedAtIsNull();
Page<PrecursorSequenceAlert> findBySequenceTypeOrderByTriggeredAtDesc(
PrecursorSequenceAlert.SequenceType sequenceType, Pageable pageable);
Page<PrecursorSequenceAlert> findBySequenceTypeAndResolvedAtIsNullOrderByTriggeredAtDesc(
PrecursorSequenceAlert.SequenceType sequenceType, Pageable pageable);
}
@@ -0,0 +1,153 @@
package com.hiveops.aria.service;
import com.hiveops.aria.entity.PrecursorSequenceAlert;
import com.hiveops.aria.entity.ThreatEvent;
import com.hiveops.aria.entity.ThreatEvent.AttackPhase;
import com.hiveops.aria.entity.ThreatEvent.ThreatSeverity;
import com.hiveops.aria.kafka.AriaSequenceEvent;
import com.hiveops.aria.kafka.AriaSequenceProducer;
import com.hiveops.aria.repository.PrecursorSequenceAlertRepository;
import com.hiveops.aria.repository.ThreatEventRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class SequenceDetectionService {
private final ThreatEventRepository eventRepository;
private final PrecursorSequenceAlertRepository alertRepository;
private final AriaSequenceProducer sequenceProducer;
@Value("${aria.sequence.window.minutes:15}")
private int windowMinutes;
public void detectAndAlert(ThreatEvent triggerEvent) {
if (triggerEvent.getDeviceAgentId() == null) return;
String deviceAgentId = triggerEvent.getDeviceAgentId();
Instant since = Instant.now().minus(windowMinutes, ChronoUnit.MINUTES);
// JPA flushes before this query, so the trigger event is included
List<ThreatEvent> recentEvents = eventRepository
.findByDeviceAgentIdAndDetectedAtAfterOrderByDetectedAtAsc(deviceAgentId, since);
if (recentEvents.size() < 2) return;
Set<AttackPhase> phases = recentEvents.stream()
.map(ThreatEvent::getAttackPhase)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
DetectionResult detection = detectSequenceType(recentEvents, phases);
if (detection == null) return;
if (alertRepository.existsByDeviceAgentIdAndResolvedAtIsNull(deviceAgentId)) {
log.debug("Sequence already active for device {}, skipping duplicate", deviceAgentId);
return;
}
UUID sequenceId = UUID.randomUUID();
recentEvents.forEach(e -> e.setSequenceId(sequenceId));
eventRepository.saveAll(recentEvents);
String[] phasesArr = phases.stream().map(Enum::name).toArray(String[]::new);
PrecursorSequenceAlert alert = PrecursorSequenceAlert.builder()
.deviceId(triggerEvent.getDeviceId())
.deviceAgentId(deviceAgentId)
.sequenceType(detection.type())
.phasesDetected(phasesArr)
.confidence(detection.confidence())
.institutionKey(triggerEvent.getInstitutionKey())
.sequenceId(sequenceId)
.build();
alertRepository.save(alert);
log.warn("ARIA SEQUENCE ALERT: type={} device={} phases={} confidence={}",
detection.type(), deviceAgentId, Arrays.toString(phasesArr), detection.confidence());
publishToKafka(alert);
}
private DetectionResult detectSequenceType(List<ThreatEvent> events, Set<AttackPhase> phases) {
if (!phases.contains(AttackPhase.PHYSICAL_ACCESS)) return null;
boolean hasStaging = phases.contains(AttackPhase.MALWARE_STAGING);
boolean hasExecution = phases.contains(AttackPhase.MALWARE_EXECUTION);
if (hasStaging || hasExecution) {
return new DetectionResult(
PrecursorSequenceAlert.SequenceType.JACKPOTTING,
calculateJackpottingConfidence(events, phases));
}
boolean hasSkimmingSignal = events.stream().anyMatch(e ->
"CARD_READER_TAMPER".equals(e.getSignalKey()) || "USB_INSERTION".equals(e.getSignalKey()));
if (hasSkimmingSignal) {
return new DetectionResult(
PrecursorSequenceAlert.SequenceType.SKIMMING,
calculateSkimmingConfidence(events));
}
return null;
}
private BigDecimal calculateJackpottingConfidence(List<ThreatEvent> events, Set<AttackPhase> phases) {
double score = 0.0;
if (phases.contains(AttackPhase.PHYSICAL_ACCESS)) score += 0.25;
if (phases.contains(AttackPhase.MALWARE_STAGING)) score += 0.30;
if (phases.contains(AttackPhase.MALWARE_EXECUTION)) score += 0.25;
if (phases.contains(AttackPhase.PERSISTENCE)) score += 0.10;
if (phases.contains(AttackPhase.CLEANUP)) score += 0.05;
if (hasCritical(events)) score += 0.10;
if (hasIocMatch(events)) score += 0.05;
return BigDecimal.valueOf(Math.min(1.0, score)).setScale(3, RoundingMode.HALF_UP);
}
private BigDecimal calculateSkimmingConfidence(List<ThreatEvent> events) {
double score = 0.35;
if (events.stream().anyMatch(e -> "CARD_READER_TAMPER".equals(e.getSignalKey()))) score += 0.40;
if (events.stream().anyMatch(e -> "USB_INSERTION".equals(e.getSignalKey()))) score += 0.20;
if (hasCritical(events)) score += 0.05;
return BigDecimal.valueOf(Math.min(1.0, score)).setScale(3, RoundingMode.HALF_UP);
}
private boolean hasCritical(List<ThreatEvent> events) {
return events.stream().anyMatch(e -> e.getSeverity() == ThreatSeverity.CRITICAL);
}
private boolean hasIocMatch(List<ThreatEvent> events) {
return events.stream().anyMatch(e -> e.getMatchedIoc() != null);
}
private void publishToKafka(PrecursorSequenceAlert alert) {
AriaSequenceEvent event = AriaSequenceEvent.builder()
.alertId(UUID.randomUUID())
.sequenceId(alert.getSequenceId())
.deviceId(alert.getDeviceId())
.deviceAgentId(alert.getDeviceAgentId())
.institutionKey(alert.getInstitutionKey())
.sequenceType(alert.getSequenceType().name())
.phasesDetected(alert.getPhasesDetected())
.confidence(alert.getConfidence())
.triggeredAt(alert.getTriggeredAt())
.sourceService("hiveops-aria")
.build();
sequenceProducer.publishSequenceAlert(event);
}
private record DetectionResult(PrecursorSequenceAlert.SequenceType type, BigDecimal confidence) {}
}
@@ -22,6 +22,7 @@ public class ThreatEventIngestionService {
private final ThreatEventRepository eventRepository;
private final ThreatEventClassifier classifier;
private final AriaThreatProducer producer;
private final SequenceDetectionService sequenceDetectionService;
@Transactional
public void ingest(ThreatEventIngestionRequest request) {
@@ -67,6 +68,12 @@ public class ThreatEventIngestionService {
if (shouldPublish(result.severity())) {
publishToKafka(event, result);
}
try {
sequenceDetectionService.detectAndAlert(event);
} catch (Exception e) {
log.error("Sequence detection failed for device {}: {}", request.getDeviceAgentId(), e.getMessage(), e);
}
}
private boolean shouldPublish(ThreatEvent.ThreatSeverity severity) {