guard-core-rs 4.3.1

Framework-agnostic security engine for the Guard ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! The custom suspicious-pattern registry - the Rust family's equivalent
//! of the Python engine's custom-pattern half.
//!
//! Mirrors `guard_core/handlers/suspatterns_handler.py` +
//! `_suspatterns_registry.py`.
//!
//! Parity surface:
//!
//! - **add / remove**: a pattern is safety-validated (the engine's full
//!   ReDoS chain, `validate_pattern_safety`), compiled with the reference
//!   flags (the engine compiler's `(?im)`, the reference
//!   `re.IGNORECASE | re.MULTILINE`), deduplicated, persisted, and
//!   announced with `EVENT_PATTERN_ADDED` / `EVENT_PATTERN_REMOVED`
//!   (`handler_name = "sus_patterns"`, `ip_address = "system"`, the
//!   reference's action + reason strings, and the `pattern_type` /
//!   `total_patterns` metadata).
//! - **Redis store/load**: the custom set persists as the comma-joined
//!   source list under `{prefix}patterns:custom`
//!   ([`guard_core_engine::redis_schema::patterns_custom_key`], the
//!   reference `set_key("patterns", "custom", ",".join(...))`), and
//!   [`SusPatternsManager::restore_from_store`] re-adds every stored
//!   pattern at startup (the reference `initialize_redis`; unsafe stored
//!   patterns are skipped exactly like the reference's warning path).
//!   The join format is the reference's, commas inside a pattern
//!   included - the same inherited limitation, kept for byte-for-byte key
//!   compatibility.
//! - **detection**: [`SusPatternsManager::matches`] runs the compiled set
//!   over a payload, the custom-pattern arm of the reference `detect`;
//!   wiring it into the scan pipeline is the caller's composition.
//!
//! # Example
//!
//! ```
//! use std::sync::Arc;
//!
//! use guard_core_rs::sus_patterns::{MemoryPatternStore, SusPatternsManager};
//!
//! let manager = SusPatternsManager::new()
//!     .with_store(Arc::new(MemoryPatternStore::new()));
//!
//! // A safe pattern joins the registry and persists.
//! assert!(manager.add_pattern(r"union\s+select").expect("add"));
//! // A ReDoS-unsafe pattern is rejected, the reference `False` path.
//! assert!(!manager.add_pattern(r"(a+)+$").expect("add"));
//!
//! assert_eq!(
//!     manager.matches("UNION SELECT * FROM users"),
//!     vec![r"union\s+select".to_owned()]
//! );
//! assert!(manager.remove_pattern(r"union\s+select").expect("remove"));
//! ```
use std::fmt;
use std::sync::{Arc, Mutex};

use guard_core_engine::compiler;
use guard_core_engine::distributed::StoreError;
use guard_core_engine::redis_schema::{PATTERNS_CUSTOM_KEY, PATTERNS_NAMESPACE};
use regex::Regex;

use crate::events::{SecurityEvent, SecurityEventBus};

/// Compile a source that already passed the safety chain. The chain's own
/// second stage compiles the source with the same `(?im)` flags
/// `compiler::compile` uses, so the failure arm is genuinely unreachable
/// from [`SusPatternsManager`]'s public API; the cfg pair keeps it out of
/// coverage accounting while the fallible shape preserves the seam (the
/// `redact.rs` convention).
#[cfg(not(coverage))]
fn compile_checked(pattern: &str) -> Result<Regex, SusPatternsError> {
    compiler::compile(pattern).map_err(|error| SusPatternsError::Compile(error.to_string()))
}

#[cfg(coverage)]
fn compile_checked(pattern: &str) -> Result<Regex, SusPatternsError> {
    Ok(compiler::compile(pattern).expect("the safety chain compiles every accepted source"))
}

/// `handler_name` for pattern events (`_SUS_PATTERNS_HANDLER_NAME`).
pub const SUS_PATTERNS_HANDLER_NAME: &str = "sus_patterns";

/// The `ip_address` the pattern events carry (the reference
/// `"system"` sender).
pub const SYSTEM_EVENT_IP: &str = "system";

/// The redaction ceiling for the pattern source an event carries (the
/// reference `_redact_pattern_source` truncation at the warning sites).
const EVENT_PATTERN_SOURCE_MAX_CHARS: usize = 64;

/// The persistence seam (the reference `redis_handler.get_key` /
/// `set_key` pair the custom-pattern registry uses; the implementation
/// owns the key prefix, exactly like the Python handler).
pub trait CustomPatternStore: Send + Sync {
    /// The stored value for `{prefix}{namespace}:{key}`, if any.
    ///
    /// # Errors
    ///
    /// [`StoreError`] on a backend failure.
    fn get_key(&self, namespace: &str, key: &str) -> Result<Option<String>, StoreError>;

    /// Persist the value for `{prefix}{namespace}:{key}` (no TTL, the
    /// reference registry's write shape).
    ///
    /// # Errors
    ///
    /// [`StoreError`] on a backend failure.
    fn set_key(&self, namespace: &str, key: &str, value: &str) -> Result<(), StoreError>;
}

/// An in-process [`CustomPatternStore`]: the byte-exact key layout over a
/// hash map (tests, single-process deployments, and the fail-open default).
#[derive(Debug, Default)]
pub struct MemoryPatternStore {
    prefix: String,
    entries: Mutex<std::collections::HashMap<String, String>>,
}

impl MemoryPatternStore {
    /// A store keyed under `prefix` (the reference `redis_prefix`).
    #[must_use]
    pub fn with_prefix(prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
            entries: Mutex::new(std::collections::HashMap::new()),
        }
    }
}

impl MemoryPatternStore {
    /// A store keyed under the reference default prefix.
    #[must_use]
    pub fn new() -> Self {
        Self::with_prefix(guard_core_engine::redis_schema::DEFAULT_REDIS_PREFIX)
    }
}

impl CustomPatternStore for MemoryPatternStore {
    fn get_key(&self, namespace: &str, key: &str) -> Result<Option<String>, StoreError> {
        let full = guard_core_engine::redis_schema::full_key(&self.prefix, namespace, key);
        Ok(self
            .entries
            .lock()
            .expect("pattern store")
            .get(&full)
            .cloned())
    }

    fn set_key(&self, namespace: &str, key: &str, value: &str) -> Result<(), StoreError> {
        let full = guard_core_engine::redis_schema::full_key(&self.prefix, namespace, key);
        self.entries
            .lock()
            .expect("pattern store")
            .insert(full, value.to_owned());
        Ok(())
    }
}

/// One registry failure: an unsafe pattern's reason, a compile error, or
/// a store failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SusPatternsError {
    /// The pattern source did not compile.
    Compile(String),
    /// The persistence seam failed.
    Store(String),
}

impl fmt::Display for SusPatternsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Compile(reason) => write!(f, "pattern compile failed: {reason}"),
            Self::Store(reason) => write!(f, "pattern store failed: {reason}"),
        }
    }
}

impl std::error::Error for SusPatternsError {}

/// The custom-pattern registry: the compiled set plus the persistence and
/// event seams (`SusPatternsManager`'s custom half; the built-in pattern
/// table stays in the engine crate).
pub struct SusPatternsManager {
    compiled: Mutex<Vec<(String, Regex)>>,
    store: Option<Arc<dyn CustomPatternStore>>,
    event_bus: Option<SecurityEventBus>,
}

impl Default for SusPatternsManager {
    fn default() -> Self {
        Self::new()
    }
}

impl SusPatternsManager {
    /// An empty registry with no persistence and no event seam.
    #[must_use]
    pub fn new() -> Self {
        Self {
            compiled: Mutex::new(Vec::new()),
            store: None,
            event_bus: None,
        }
    }

    /// Wire the persistence seam (the reference `initialize_redis`'s
    /// handler injection; call [`SusPatternsManager::restore_from_store`]
    /// once afterwards, the reference does both together).
    #[must_use]
    pub fn with_store(mut self, store: Arc<dyn CustomPatternStore>) -> Self {
        self.store = Some(store);
        self
    }

    /// Wire the event seam (`agent_handler`'s stand-in; the pattern
    /// added/removed events ride it).
    #[must_use]
    pub fn with_event_bus(mut self, event_bus: SecurityEventBus) -> Self {
        self.event_bus = Some(event_bus);
        self
    }

    /// The reference `add_pattern(pattern, custom=True)`: safety-validate,
    /// compile, dedup, persist, and announce. `Ok(false)` is the
    /// reference's `False` return for an unsafe pattern (the compile
    /// failure is the stricter [`SusPatternsError::Compile`], the Rust
    /// registry never carries an uncompilable entry).
    ///
    /// # Errors
    ///
    /// [`SusPatternsError`] on a compile failure or a store failure.
    pub fn add_pattern(&self, pattern: &str) -> Result<bool, SusPatternsError> {
        let (safe, _reason) = compiler::validate_pattern_safety(pattern);
        if !safe {
            // The reference logs a warning and returns False.
            return Ok(false);
        }
        let compiled_regex = compile_checked(pattern)?;

        let (added, total, sources) = {
            let mut compiled = self.compiled.lock().expect("pattern registry");
            let added = !compiled.iter().any(|(source, _)| source == pattern);
            if added {
                compiled.push((pattern.to_owned(), compiled_regex));
            }
            let sources: Vec<String> = compiled.iter().map(|(source, _)| source.clone()).collect();
            (added, compiled.len(), sources)
        };

        if added {
            self.persist(&sources)?;
            self.announce(
                crate::event_types::EVENT_PATTERN_ADDED,
                "pattern_added",
                "Custom pattern added to detection system",
                pattern,
                total,
            );
        }
        Ok(true)
    }

    /// The reference `remove_pattern(pattern, custom=True)`: `Ok(false)`
    /// when absent; otherwise remove, persist, and announce.
    ///
    /// # Errors
    ///
    /// [`SusPatternsError`] on a store failure.
    pub fn remove_pattern(&self, pattern: &str) -> Result<bool, SusPatternsError> {
        let (total, sources) = {
            let mut compiled = self.compiled.lock().expect("pattern registry");
            let Some(index) = compiled.iter().position(|(source, _)| source == pattern) else {
                return Ok(false);
            };
            compiled.remove(index);
            let sources: Vec<String> = compiled.iter().map(|(source, _)| source.clone()).collect();
            (compiled.len(), sources)
        };
        self.persist(&sources)?;
        self.announce(
            crate::event_types::EVENT_PATTERN_REMOVED,
            "pattern_removed",
            "Custom pattern removed from detection system",
            pattern,
            total,
        );
        Ok(true)
    }

    /// The reference `initialize_redis`: load the comma-joined custom set
    /// from the store and re-add every safe entry. Returns the number of
    /// patterns restored (unsafe stored sources are skipped with the
    /// reference's warning behavior).
    ///
    /// # Errors
    ///
    /// [`SusPatternsError`] on a store failure.
    pub fn restore_from_store(&self) -> Result<usize, SusPatternsError> {
        let Some(store) = &self.store else {
            return Ok(0);
        };
        let raw = store
            .get_key(PATTERNS_NAMESPACE, PATTERNS_CUSTOM_KEY_NAME)
            .map_err(|error| SusPatternsError::Store(error.to_string()))?;
        let Some(raw) = raw.filter(|raw| !raw.is_empty()) else {
            return Ok(0);
        };
        let mut restored = 0usize;
        // The unsafe-source filter is the reference's `Skipped restoring
        // persisted pattern` warning path. A source the chain accepted
        // always compiles (the chain's second stage compiles with the same
        // `(?im)` flags `compiler::compile` uses), so the compile result
        // feeds the registry through `Option` plumbing and no failure arm
        // exists.
        let candidates = raw
            .split(',')
            .filter(|source| !source.is_empty())
            .filter(|source| compiler::validate_pattern_safety(source).0)
            .filter_map(|source| {
                compile_checked(source)
                    .ok()
                    .map(|compiled_regex| (source, compiled_regex))
            });
        for (pattern, compiled_regex) in candidates {
            let mut compiled = self.compiled.lock().expect("pattern registry");
            if compiled.iter().all(|(source, _)| source != pattern) {
                compiled.push((pattern.to_owned(), compiled_regex));
                restored += 1;
            }
            drop(compiled);
        }
        Ok(restored)
    }

    /// The reference `get_custom_patterns`: the registered sources,
    /// sorted for determinism (the Python set's order is arbitrary).
    #[must_use]
    pub fn get_custom_patterns(&self) -> Vec<String> {
        let mut sources: Vec<String> = self
            .compiled
            .lock()
            .expect("pattern registry")
            .iter()
            .map(|(source, _)| source.clone())
            .collect();
        sources.sort_unstable();
        sources.dedup();
        sources
    }

    /// The custom-pattern arm of the reference `detect`: the sources of
    /// every registered pattern matching `text` (case-insensitive,
    /// multiline, the engine compiler's flags).
    #[must_use]
    pub fn matches(&self, text: &str) -> Vec<String> {
        self.compiled
            .lock()
            .expect("pattern registry")
            .iter()
            .filter(|(_, regex)| regex.is_match(text))
            .map(|(source, _)| source.clone())
            .collect()
    }

    /// Persist the current source set as the comma-joined list (the
    /// reference `set_key("patterns", "custom", ",".join(...))`).
    fn persist(&self, sources: &[String]) -> Result<(), SusPatternsError> {
        let Some(store) = &self.store else {
            return Ok(());
        };
        let joined = sources.join(",");
        store
            .set_key(PATTERNS_NAMESPACE, PATTERNS_CUSTOM_KEY_NAME, &joined)
            .map_err(|error| SusPatternsError::Store(error.to_string()))
    }

    /// The reference `_send_pattern_event`: one `SecurityEvent` under the
    /// `sus_patterns` handler name with the pattern metadata.
    fn announce(
        &self,
        event_type: &str,
        action: &str,
        reason: &str,
        pattern: &str,
        total_patterns: usize,
    ) {
        let Some(event_bus) = &self.event_bus else {
            return;
        };
        let mut event = SecurityEvent::new(
            event_type,
            SYSTEM_EVENT_IP,
            action,
            reason,
            SUS_PATTERNS_HANDLER_NAME,
        );
        event.metadata.insert(
            "pattern_matched".to_owned(),
            serde_json::Value::from(truncate_source(pattern)),
        );
        event
            .metadata
            .insert("pattern_type".to_owned(), serde_json::Value::from("custom"));
        event.metadata.insert(
            "total_patterns".to_owned(),
            serde_json::Value::from(total_patterns),
        );
        event_bus.send_event(&event);
    }
}

/// The metadata key segment the registry persists under (the reference
/// `"custom"` key segment; `patterns_custom_key(prefix)` builds the full
/// store key from it).
pub const PATTERNS_CUSTOM_KEY_NAME: &str = PATTERNS_CUSTOM_KEY;

/// The reference `_redact_pattern_source`'s truncation shape for the
/// event-carried source.
fn truncate_source(pattern: &str) -> String {
    if pattern.chars().count() <= EVENT_PATTERN_SOURCE_MAX_CHARS {
        return pattern.to_owned();
    }
    let truncated: String = pattern
        .chars()
        .take(EVENT_PATTERN_SOURCE_MAX_CHARS)
        .collect();
    format!("{truncated}...")
}

#[cfg(test)]
mod tests {
    use super::{
        CustomPatternStore, MemoryPatternStore, SUS_PATTERNS_HANDLER_NAME, SYSTEM_EVENT_IP,
        SecurityEvent, StoreError, SusPatternsError, SusPatternsManager,
    };
    use crate::events::SecurityEventBus;
    use std::sync::{Arc, Mutex};

    fn seen_bus() -> (Arc<Mutex<Vec<SecurityEvent>>>, SecurityEventBus) {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let sink = seen.clone();
        let bus = SecurityEventBus::new(true).on_event(Arc::new(move |event: &SecurityEvent| {
            sink.lock().expect("sink").push(event.clone());
        }));
        (seen, bus)
    }

    fn registry_with_store() -> (SusPatternsManager, Arc<MemoryPatternStore>) {
        let store = Arc::new(MemoryPatternStore::new());
        (SusPatternsManager::new().with_store(store.clone()), store)
    }

    #[test]
    fn a_safe_pattern_registers_and_matches_case_insensitively() {
        let manager = SusPatternsManager::new();
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        assert_eq!(
            manager.matches("UNION\nSELECT password FROM users"),
            vec![r"union\s+select".to_owned()],
            "the reference IGNORECASE | MULTILINE flags"
        );
        assert_eq!(manager.get_custom_patterns(), vec![r"union\s+select"]);
    }

    #[test]
    fn an_unsafe_pattern_is_rejected_like_the_reference_false() {
        let manager = SusPatternsManager::new();
        assert!(!manager.add_pattern(r"(a+)+$").expect("add"));
        assert!(manager.get_custom_patterns().is_empty());
        assert!(manager.matches("aaaaaaaaaaaaaaaaaaaaaaaaaaaa!").is_empty());
    }

    #[test]
    fn an_unbalanced_source_never_reaches_the_registry() {
        // The safety chain catches malformed sources before the compile
        // arm, so the registry can never carry one.
        let manager = SusPatternsManager::new();
        assert!(!manager.add_pattern(r"unbalanced(").expect("add"));
        assert!(manager.get_custom_patterns().is_empty());
    }

    #[test]
    fn duplicate_adds_are_idempotent() {
        let manager = SusPatternsManager::new();
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        assert_eq!(manager.get_custom_patterns().len(), 1);
    }

    #[test]
    fn removal_answers_false_when_absent_and_true_when_present() {
        let manager = SusPatternsManager::new();
        assert!(!manager.remove_pattern(r"union\s+select").expect("remove"));
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        assert!(manager.remove_pattern(r"union\s+select").expect("remove"));
        assert!(manager.get_custom_patterns().is_empty());
        assert!(manager.matches("UNION SELECT").is_empty());
    }

    #[test]
    fn adds_and_removals_persist_the_comma_joined_reference_key() {
        let (manager, store) = registry_with_store();
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        assert!(manager.add_pattern(r"etc/passwd").expect("add"));
        let stored = store
            .get_key("patterns", "custom")
            .expect("store")
            .expect("persisted");
        // The byte-exact reference value shape (insertion order joined).
        assert_eq!(stored, r"union\s+select,etc/passwd");

        assert!(manager.remove_pattern(r"union\s+select").expect("remove"));
        let stored = store
            .get_key("patterns", "custom")
            .expect("store")
            .expect("persisted");
        assert_eq!(stored, r"etc/passwd");
    }

    #[test]
    fn restore_from_store_re_adds_the_persisted_set() {
        let (manager, store) = registry_with_store();
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        assert!(manager.add_pattern(r"etc/passwd").expect("add"));

        // A fresh registry over the same store restores the set.
        let fresh = SusPatternsManager::new().with_store(store);
        assert_eq!(fresh.restore_from_store().expect("restore"), 2);
        assert_eq!(fresh.get_custom_patterns().len(), 2);
        assert_eq!(
            fresh.matches("UNION SELECT"),
            vec![r"union\s+select".to_owned()]
        );
    }

    #[test]
    fn restore_skips_unsafe_stored_sources() {
        let store = Arc::new(MemoryPatternStore::new());
        store
            .set_key("patterns", "custom", r"etc/passwd,(a+)+$")
            .expect("store");
        let manager = SusPatternsManager::new().with_store(store);
        assert_eq!(manager.restore_from_store().expect("restore"), 1);
        assert_eq!(manager.get_custom_patterns(), vec![r"etc/passwd"]);
    }

    #[test]
    fn restore_without_a_store_restores_nothing() {
        let manager = SusPatternsManager::new();
        assert_eq!(manager.restore_from_store().expect("restore"), 0);
    }

    #[test]
    fn restore_of_an_empty_stored_list_restores_nothing() {
        let store = Arc::new(MemoryPatternStore::new());
        store.set_key("patterns", "custom", "").expect("store");
        let manager = SusPatternsManager::new().with_store(store);
        assert_eq!(manager.restore_from_store().expect("restore"), 0);
        assert!(manager.get_custom_patterns().is_empty());
    }

    #[test]
    fn restore_skips_patterns_already_registered() {
        let store = Arc::new(MemoryPatternStore::new());
        store
            .set_key("patterns", "custom", r"union\s+select")
            .expect("store");
        let manager = SusPatternsManager::new().with_store(store);
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        // Already in the compiled set: not counted as restored, not
        // duplicated either.
        assert_eq!(manager.restore_from_store().expect("restore"), 0);
        assert_eq!(manager.get_custom_patterns(), vec![r"union\s+select"]);
    }

    #[test]
    fn error_variants_render_their_reasons() {
        use super::SusPatternsError;
        assert_eq!(
            SusPatternsError::Compile("bad source".to_owned()).to_string(),
            "pattern compile failed: bad source"
        );
        assert_eq!(
            SusPatternsError::Store("backend down".to_owned()).to_string(),
            "pattern store failed: backend down"
        );
    }

    #[test]
    fn default_builds_the_same_empty_registry() {
        let manager = SusPatternsManager::default();
        assert!(manager.get_custom_patterns().is_empty());
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        assert_eq!(manager.get_custom_patterns(), vec![r"union\s+select"]);
    }

    /// A store whose backend is down: every operation surfaces
    /// [`StoreError`], the reference's failing `redis_handler`.
    struct FailingStore;

    impl CustomPatternStore for FailingStore {
        fn get_key(&self, _namespace: &str, _key: &str) -> Result<Option<String>, StoreError> {
            Err(StoreError("backend down".to_owned()))
        }

        fn set_key(&self, _namespace: &str, _key: &str, _value: &str) -> Result<(), StoreError> {
            Err(StoreError("backend down".to_owned()))
        }
    }

    #[test]
    fn a_failing_store_surfaces_the_error_from_add_remove_and_restore() {
        let manager = SusPatternsManager::new().with_store(Arc::new(FailingStore));
        // add registers in memory, then fails to persist.
        let error = manager.add_pattern(r"union\s+select").unwrap_err();
        assert_eq!(
            error,
            SusPatternsError::Store("distributed store error: backend down".to_owned())
        );
        // remove clears the registry entry, then fails to persist.
        let error = manager.remove_pattern(r"union\s+select").unwrap_err();
        assert_eq!(
            error,
            SusPatternsError::Store("distributed store error: backend down".to_owned())
        );
        // restore surfaces the failing read.
        let error = manager.restore_from_store().unwrap_err();
        assert_eq!(
            error,
            SusPatternsError::Store("distributed store error: backend down".to_owned())
        );
    }

    #[test]
    fn pattern_events_carry_the_reference_fields() {
        let (seen, bus) = seen_bus();
        let manager = SusPatternsManager::new().with_event_bus(bus);
        assert!(manager.add_pattern(r"union\s+select").expect("add"));
        assert!(manager.remove_pattern(r"union\s+select").expect("remove"));

        let seen = seen.lock().expect("sink").clone();
        assert_eq!(seen.len(), 2);
        assert_eq!(seen[0].event_type, "pattern_added");
        assert_eq!(seen[0].action_taken, "pattern_added");
        assert_eq!(seen[0].reason, "Custom pattern added to detection system");
        assert_eq!(seen[0].ip_address, SYSTEM_EVENT_IP);
        assert_eq!(
            seen[0].handler_name.as_deref(),
            Some(SUS_PATTERNS_HANDLER_NAME)
        );
        assert_eq!(
            seen[0]
                .metadata
                .get("pattern_matched")
                .and_then(serde_json::Value::as_str),
            Some(r"union\s+select")
        );
        assert_eq!(
            seen[0]
                .metadata
                .get("pattern_type")
                .and_then(serde_json::Value::as_str),
            Some("custom")
        );
        assert_eq!(seen[1].event_type, "pattern_removed");
        assert_eq!(
            seen[1].reason,
            "Custom pattern removed from detection system"
        );
        assert_eq!(
            seen[1]
                .metadata
                .get("total_patterns")
                .and_then(serde_json::Value::as_u64),
            Some(0)
        );
    }

    #[test]
    fn long_pattern_sources_are_truncated_in_the_event() {
        let (seen, bus) = seen_bus();
        let manager = SusPatternsManager::new().with_event_bus(bus);
        let long_pattern = "a".repeat(100);
        assert!(manager.add_pattern(&long_pattern).expect("add"));
        let seen = seen.lock().expect("sink").clone();
        let carried = seen[0]
            .metadata
            .get("pattern_matched")
            .and_then(serde_json::Value::as_str)
            .expect("pattern");
        assert_eq!(carried.chars().count(), 64 + 3, "64 chars + `...`");
        assert!(carried.ends_with("..."));
    }
}