rustkernel_behavioral/types.rs
1//! Behavioral analytics types and data structures.
2
3use std::collections::HashMap;
4
5// ============================================================================
6// Event Types
7// ============================================================================
8
9/// A user event for behavioral analysis.
10#[derive(Debug, Clone)]
11pub struct UserEvent {
12 /// Event ID.
13 pub id: u64,
14 /// User ID.
15 pub user_id: u64,
16 /// Event type.
17 pub event_type: String,
18 /// Timestamp (Unix epoch seconds).
19 pub timestamp: u64,
20 /// Event attributes.
21 pub attributes: HashMap<String, EventValue>,
22 /// Session ID.
23 pub session_id: Option<u64>,
24 /// Device fingerprint.
25 pub device_id: Option<String>,
26 /// IP address.
27 pub ip_address: Option<String>,
28 /// Location (country code).
29 pub location: Option<String>,
30}
31
32/// Event attribute value.
33#[derive(Debug, Clone)]
34pub enum EventValue {
35 /// String value.
36 String(String),
37 /// Numeric value.
38 Number(f64),
39 /// Boolean value.
40 Bool(bool),
41 /// List of values.
42 List(Vec<EventValue>),
43}
44
45// ============================================================================
46// Profile Types
47// ============================================================================
48
49/// User behavioral profile.
50#[derive(Debug, Clone)]
51pub struct BehaviorProfile {
52 /// User ID.
53 pub user_id: u64,
54 /// Feature vector.
55 pub features: Vec<f64>,
56 /// Feature names.
57 pub feature_names: Vec<String>,
58 /// Profile creation time.
59 pub created_at: u64,
60 /// Last update time.
61 pub updated_at: u64,
62 /// Number of events used to build profile.
63 pub event_count: u64,
64}
65
66impl BehaviorProfile {
67 /// Create a new empty profile.
68 pub fn new(user_id: u64, feature_names: Vec<String>) -> Self {
69 let n = feature_names.len();
70 Self {
71 user_id,
72 features: vec![0.0; n],
73 feature_names,
74 created_at: 0,
75 updated_at: 0,
76 event_count: 0,
77 }
78 }
79
80 /// Get a feature by name.
81 pub fn get_feature(&self, name: &str) -> Option<f64> {
82 self.feature_names
83 .iter()
84 .position(|n| n == name)
85 .map(|i| self.features[i])
86 }
87}
88
89/// Profiling result.
90#[derive(Debug, Clone)]
91pub struct ProfilingResult {
92 /// User ID.
93 pub user_id: u64,
94 /// Extracted features.
95 pub features: Vec<(String, f64)>,
96 /// Profile stability score (0-1).
97 pub stability: f64,
98 /// Confidence in profile (0-1).
99 pub confidence: f64,
100}
101
102// ============================================================================
103// Anomaly Types
104// ============================================================================
105
106/// Anomaly detection result.
107#[derive(Debug, Clone)]
108pub struct AnomalyResult {
109 /// User ID.
110 pub user_id: u64,
111 /// Event ID that triggered anomaly.
112 pub event_id: u64,
113 /// Overall anomaly score (0-100).
114 pub anomaly_score: f64,
115 /// Is this an anomaly?
116 pub is_anomaly: bool,
117 /// Feature-level deviations.
118 pub deviations: Vec<FeatureDeviation>,
119 /// Anomaly type classification.
120 pub anomaly_type: Option<AnomalyType>,
121}
122
123/// Feature-level deviation.
124#[derive(Debug, Clone)]
125pub struct FeatureDeviation {
126 /// Feature name.
127 pub feature_name: String,
128 /// Expected value.
129 pub expected: f64,
130 /// Actual value.
131 pub actual: f64,
132 /// Z-score.
133 pub z_score: f64,
134 /// Contribution to anomaly score.
135 pub contribution: f64,
136}
137
138/// Type of detected anomaly.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum AnomalyType {
141 /// Time-based anomaly (unusual hours).
142 Temporal,
143 /// Location-based anomaly.
144 Geographic,
145 /// Device/access method anomaly.
146 Device,
147 /// Behavior pattern anomaly.
148 Behavioral,
149 /// Volume/frequency anomaly.
150 Velocity,
151 /// Multiple anomaly types.
152 Mixed,
153}
154
155// ============================================================================
156// Fraud Signature Types
157// ============================================================================
158
159/// A fraud signature pattern.
160#[derive(Debug, Clone)]
161pub struct FraudSignature {
162 /// Signature ID.
163 pub id: u32,
164 /// Signature name.
165 pub name: String,
166 /// Pattern to match.
167 pub pattern: SignaturePattern,
168 /// Severity (0-100).
169 pub severity: f64,
170 /// Whether signature is active.
171 pub active: bool,
172}
173
174/// Signature pattern definition.
175#[derive(Debug, Clone)]
176pub enum SignaturePattern {
177 /// Sequence of event types.
178 EventSequence(Vec<String>),
179 /// Event with specific attributes.
180 EventAttributes(String, HashMap<String, EventValue>),
181 /// Time-based pattern (events within time window).
182 TimeWindow {
183 /// Events that must occur within the window.
184 events: Vec<String>,
185 /// Time window in seconds.
186 window_secs: u64,
187 },
188 /// Count-based pattern.
189 CountThreshold {
190 /// Type of event to count.
191 event_type: String,
192 /// Minimum count threshold.
193 count: u32,
194 /// Time window in seconds.
195 window_secs: u64,
196 },
197 /// Regex pattern on event data.
198 Regex(String),
199}
200
201/// Signature match result.
202#[derive(Debug, Clone)]
203pub struct SignatureMatch {
204 /// Signature ID.
205 pub signature_id: u32,
206 /// Signature name.
207 pub signature_name: String,
208 /// Match score (0-100).
209 pub score: f64,
210 /// Matched event IDs.
211 pub matched_events: Vec<u64>,
212 /// Match details.
213 pub details: String,
214}
215
216// ============================================================================
217// Causal Graph Types
218// ============================================================================
219
220/// A causal graph node.
221#[derive(Debug, Clone)]
222pub struct CausalNode {
223 /// Node ID.
224 pub id: u64,
225 /// Event type this node represents.
226 pub event_type: String,
227 /// Node probability.
228 pub probability: f64,
229}
230
231/// A causal graph edge.
232#[derive(Debug, Clone)]
233pub struct CausalEdge {
234 /// Source node ID.
235 pub source: u64,
236 /// Target node ID.
237 pub target: u64,
238 /// Causal strength (0-1).
239 pub strength: f64,
240 /// Time lag (average seconds between events).
241 pub lag: f64,
242 /// Number of observations.
243 pub count: u64,
244}
245
246/// Causal graph construction result.
247#[derive(Debug, Clone)]
248pub struct CausalGraphResult {
249 /// Graph nodes.
250 pub nodes: Vec<CausalNode>,
251 /// Graph edges.
252 pub edges: Vec<CausalEdge>,
253 /// Root causes (nodes with high out-degree).
254 pub root_causes: Vec<u64>,
255 /// Effects (nodes with high in-degree).
256 pub effects: Vec<u64>,
257}
258
259// ============================================================================
260// Forensic Query Types
261// ============================================================================
262
263/// A forensic query definition.
264#[derive(Debug, Clone)]
265pub struct ForensicQuery {
266 /// Query ID.
267 pub id: u64,
268 /// Query type.
269 pub query_type: QueryType,
270 /// Time range start.
271 pub start_time: u64,
272 /// Time range end.
273 pub end_time: u64,
274 /// User filter.
275 pub user_ids: Option<Vec<u64>>,
276 /// Event type filter.
277 pub event_types: Option<Vec<String>>,
278 /// Custom filters.
279 pub filters: HashMap<String, String>,
280}
281
282/// Type of forensic query.
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub enum QueryType {
285 /// Search for specific pattern.
286 PatternSearch,
287 /// Timeline reconstruction.
288 Timeline,
289 /// User activity summary.
290 ActivitySummary,
291 /// Anomaly hunt.
292 AnomalyHunt,
293 /// Correlation analysis.
294 Correlation,
295}
296
297/// Forensic query result.
298#[derive(Debug, Clone)]
299pub struct ForensicResult {
300 /// Query ID.
301 pub query_id: u64,
302 /// Matched events.
303 pub events: Vec<u64>,
304 /// Match count.
305 pub total_matches: u64,
306 /// Summary statistics.
307 pub summary: HashMap<String, f64>,
308 /// Execution time (ms).
309 pub execution_time_ms: u64,
310}
311
312// ============================================================================
313// Event Correlation Types
314// ============================================================================
315
316/// Event correlation result.
317#[derive(Debug, Clone)]
318pub struct CorrelationResult {
319 /// Primary event ID.
320 pub event_id: u64,
321 /// Correlated events.
322 pub correlations: Vec<EventCorrelation>,
323 /// Correlation clusters.
324 pub clusters: Vec<CorrelationCluster>,
325}
326
327/// A single event correlation.
328#[derive(Debug, Clone)]
329pub struct EventCorrelation {
330 /// Correlated event ID.
331 pub correlated_event_id: u64,
332 /// Correlation score (0-1).
333 pub score: f64,
334 /// Correlation type.
335 pub correlation_type: CorrelationType,
336 /// Time difference (seconds).
337 pub time_diff: i64,
338}
339
340/// Type of correlation.
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
342pub enum CorrelationType {
343 /// Temporal proximity.
344 Temporal,
345 /// Same user.
346 User,
347 /// Same session.
348 Session,
349 /// Same device.
350 Device,
351 /// Same location.
352 Location,
353 /// Causal relationship.
354 Causal,
355}
356
357/// Cluster of correlated events.
358#[derive(Debug, Clone)]
359pub struct CorrelationCluster {
360 /// Cluster ID.
361 pub id: u64,
362 /// Event IDs in cluster.
363 pub event_ids: Vec<u64>,
364 /// Cluster coherence score.
365 pub coherence: f64,
366 /// Dominant correlation type.
367 pub dominant_type: CorrelationType,
368}