sentinel-agent-sentinelsec 0.1.0

Pure Rust ModSecurity-compatible WAF agent for Sentinel - Full OWASP CRS support without C dependencies
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! Sentinel SentinelSec Agent Library
//!
//! A pure Rust ModSecurity-compatible WAF agent for Sentinel proxy.
//! Provides full OWASP Core Rule Set (CRS) support without any C dependencies.
//!
//! # Example
//!
//! ```ignore
//! use sentinel_agent_sentinelsec::{SentinelSecAgent, SentinelSecConfig};
//! use sentinel_agent_protocol::AgentServer;
//!
//! let config = SentinelSecConfig {
//!     rules_paths: vec!["/etc/modsecurity/crs/rules/*.conf".to_string()],
//!     ..Default::default()
//! };
//! let agent = SentinelSecAgent::new(config)?;
//! let server = AgentServer::new("sentinelsec", "/tmp/sentinelsec.sock", Box::new(agent));
//! server.run().await?;
//! ```

use anyhow::Result;
use base64::Engine;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

use sentinel_agent_protocol::{
    AgentHandler, AgentResponse, AuditMetadata, ConfigureEvent, HeaderOp, RequestBodyChunkEvent,
    RequestHeadersEvent, ResponseBodyChunkEvent, ResponseHeadersEvent,
};

use sentinel_modsec::ModSecurity;

/// SentinelSec configuration
#[derive(Debug, Clone)]
pub struct SentinelSecConfig {
    /// Paths to ModSecurity rule files (glob patterns supported)
    pub rules_paths: Vec<String>,
    /// Block mode (true) or detect-only mode (false)
    pub block_mode: bool,
    /// Paths to exclude from inspection
    pub exclude_paths: Vec<String>,
    /// Enable request body inspection
    pub body_inspection_enabled: bool,
    /// Maximum body size to inspect in bytes
    pub max_body_size: usize,
    /// Enable response body inspection
    pub response_inspection_enabled: bool,
}

impl Default for SentinelSecConfig {
    fn default() -> Self {
        Self {
            rules_paths: vec![],
            block_mode: true,
            exclude_paths: vec![],
            body_inspection_enabled: true,
            max_body_size: 1048576, // 1MB
            response_inspection_enabled: false,
        }
    }
}

/// JSON-serializable configuration for SentinelSec agent
///
/// Used for parsing configuration from the proxy's agent config.
/// Field names use kebab-case to match YAML/JSON config conventions.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct SentinelSecConfigJson {
    /// Paths to ModSecurity rule files (glob patterns supported)
    #[serde(default)]
    pub rules_paths: Vec<String>,
    /// Block mode (true) or detect-only mode (false)
    #[serde(default = "default_block_mode")]
    pub block_mode: bool,
    /// Paths to exclude from inspection
    #[serde(default)]
    pub exclude_paths: Vec<String>,
    /// Enable request body inspection
    #[serde(default = "default_body_inspection")]
    pub body_inspection_enabled: bool,
    /// Maximum body size to inspect in bytes
    #[serde(default = "default_max_body_size")]
    pub max_body_size: usize,
    /// Enable response body inspection
    #[serde(default)]
    pub response_inspection_enabled: bool,
}

fn default_block_mode() -> bool {
    true
}

fn default_body_inspection() -> bool {
    true
}

fn default_max_body_size() -> usize {
    1048576 // 1MB
}

impl From<SentinelSecConfigJson> for SentinelSecConfig {
    fn from(json: SentinelSecConfigJson) -> Self {
        Self {
            rules_paths: json.rules_paths,
            block_mode: json.block_mode,
            exclude_paths: json.exclude_paths,
            body_inspection_enabled: json.body_inspection_enabled,
            max_body_size: json.max_body_size,
            response_inspection_enabled: json.response_inspection_enabled,
        }
    }
}

/// Detection result from SentinelSec
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Detection {
    /// Rule ID that triggered the detection
    pub rule_id: String,
    /// Detection message
    pub message: String,
    /// Severity level
    pub severity: Option<String>,
}

/// SentinelSec engine wrapper
pub struct SentinelSecEngine {
    modsec: ModSecurity,
    /// Agent configuration
    pub config: SentinelSecConfig,
}

impl SentinelSecEngine {
    /// Create a new SentinelSec engine with the given configuration
    pub fn new(config: SentinelSecConfig) -> Result<Self> {
        // Build rules string from all rule files
        let mut rules_content = String::new();

        // Always enable the rule engine
        rules_content.push_str("SecRuleEngine On\n");

        // Load rules from configured paths
        let mut loaded_count = 0;
        for path_pattern in &config.rules_paths {
            // Handle glob patterns
            let paths = glob::glob(path_pattern)
                .map_err(|e| anyhow::anyhow!("Invalid glob pattern '{}': {}", path_pattern, e))?;

            for entry in paths {
                match entry {
                    Ok(path) => {
                        if path.is_file() {
                            let content = fs::read_to_string(&path).map_err(|e| {
                                anyhow::anyhow!("Failed to read rule file {:?}: {}", path, e)
                            })?;
                            rules_content.push_str(&content);
                            rules_content.push('\n');
                            loaded_count += 1;
                            debug!(path = ?path, "Loaded rule file");
                        }
                    }
                    Err(e) => {
                        warn!(error = %e, "Error reading glob entry");
                    }
                }
            }
        }

        // Create the ModSecurity engine
        let modsec = if rules_content.trim().is_empty() || loaded_count == 0 {
            // No rules loaded, create with just SecRuleEngine On
            ModSecurity::from_string("SecRuleEngine On")
                .map_err(|e| anyhow::anyhow!("Failed to initialize SentinelSec engine: {}", e))?
        } else {
            ModSecurity::from_string(&rules_content)
                .map_err(|e| anyhow::anyhow!("Failed to parse rules: {}", e))?
        };

        info!(rules_files = loaded_count, rule_count = modsec.rule_count(), "SentinelSec engine initialized");

        Ok(Self { modsec, config })
    }

    /// Check if path should be excluded
    pub fn is_excluded(&self, path: &str) -> bool {
        self.config
            .exclude_paths
            .iter()
            .any(|p| path.starts_with(p))
    }
}

/// Body accumulator for tracking in-progress bodies
#[derive(Debug, Default)]
struct BodyAccumulator {
    data: Vec<u8>,
}

/// Pending transaction for body accumulation
struct PendingTransaction {
    body: BodyAccumulator,
    method: String,
    uri: String,
    headers: HashMap<String, Vec<String>>,
    #[allow(dead_code)]
    client_ip: String,
}

/// SentinelSec agent
pub struct SentinelSecAgent {
    engine: Arc<RwLock<SentinelSecEngine>>,
    pending_requests: Arc<RwLock<HashMap<String, PendingTransaction>>>,
}

impl SentinelSecAgent {
    /// Create a new SentinelSec agent with the given configuration
    pub fn new(config: SentinelSecConfig) -> Result<Self> {
        let engine = SentinelSecEngine::new(config)?;
        Ok(Self {
            engine: Arc::new(RwLock::new(engine)),
            pending_requests: Arc::new(RwLock::new(HashMap::new())),
        })
    }

    /// Reconfigure the agent with new settings
    ///
    /// This rebuilds the SentinelSec engine with the new configuration.
    /// In-flight requests using the old engine will complete normally.
    pub async fn reconfigure(&self, config: SentinelSecConfig) -> Result<()> {
        info!("Reconfiguring SentinelSec engine");
        let new_engine = SentinelSecEngine::new(config)?;
        let mut engine = self.engine.write().await;
        *engine = new_engine;
        // Clear pending requests since rules may have changed
        let mut pending = self.pending_requests.write().await;
        pending.clear();
        info!("SentinelSec engine reconfigured successfully");
        Ok(())
    }

    /// Process a complete request through SentinelSec
    async fn process_request(
        &self,
        correlation_id: &str,
        method: &str,
        uri: &str,
        headers: &HashMap<String, Vec<String>>,
        body: Option<&[u8]>,
    ) -> Result<Option<(u16, String, Vec<String>)>> {
        let engine = self.engine.read().await;

        // Create a new transaction
        let mut tx = engine.modsec.new_transaction();

        // Process URI
        tx.process_uri(uri, method, "HTTP/1.1")
            .map_err(|e| anyhow::anyhow!("process_uri failed: {}", e))?;

        // Add headers
        for (name, values) in headers {
            for value in values {
                tx.add_request_header(name, value)
                    .map_err(|e| anyhow::anyhow!("add_request_header failed: {}", e))?;
            }
        }

        // Process request headers (phase 1)
        tx.process_request_headers()
            .map_err(|e| anyhow::anyhow!("process_request_headers failed: {}", e))?;

        // Check for intervention after headers
        if let Some(intervention) = tx.intervention() {
            let status = intervention.status;
            if status != 0 && status != 200 {
                debug!(
                    correlation_id = correlation_id,
                    status = status,
                    "SentinelSec intervention (headers)"
                );
                let rule_ids = tx.matched_rules().iter().map(|s| s.to_string()).collect();
                return Ok(Some((status, "Blocked by SentinelSec".to_string(), rule_ids)));
            }
        }

        // Process body if provided (phase 2)
        if let Some(body_data) = body {
            if !body_data.is_empty() {
                tx.append_request_body(body_data)
                    .map_err(|e| anyhow::anyhow!("append_request_body failed: {}", e))?;
                tx.process_request_body()
                    .map_err(|e| anyhow::anyhow!("process_request_body failed: {}", e))?;

                // Check for intervention after body
                if let Some(intervention) = tx.intervention() {
                    let status = intervention.status;
                    if status != 0 && status != 200 {
                        debug!(
                            correlation_id = correlation_id,
                            status = status,
                            "SentinelSec intervention (body)"
                        );
                        let rule_ids = tx.matched_rules().iter().map(|s| s.to_string()).collect();
                        return Ok(Some((status, "Blocked by SentinelSec".to_string(), rule_ids)));
                    }
                }
            }
        }

        Ok(None)
    }
}

#[async_trait::async_trait]
impl AgentHandler for SentinelSecAgent {
    async fn on_configure(&self, event: ConfigureEvent) -> AgentResponse {
        debug!(agent_id = %event.agent_id, "Received configure event");

        // Parse the JSON config into SentinelSecConfigJson
        let config_json: SentinelSecConfigJson = match serde_json::from_value(event.config) {
            Ok(config) => config,
            Err(e) => {
                warn!(error = %e, "Failed to parse SentinelSec configuration");
                // Return allow but log the error - agent can still work with existing config
                return AgentResponse::default_allow();
            }
        };

        // Convert to internal config and reconfigure the engine
        let config: SentinelSecConfig = config_json.into();
        if let Err(e) = self.reconfigure(config).await {
            warn!(error = %e, "Failed to reconfigure SentinelSec engine");
            // Return allow but log the error
            return AgentResponse::default_allow();
        }

        info!(agent_id = %event.agent_id, "SentinelSec agent configured successfully");
        AgentResponse::default_allow()
    }

    async fn on_request_headers(&self, event: RequestHeadersEvent) -> AgentResponse {
        let path = &event.uri;
        let correlation_id = &event.metadata.correlation_id;

        // Check exclusions
        {
            let engine = self.engine.read().await;
            if engine.is_excluded(path) {
                debug!(path = path, "Path excluded from SentinelSec");
                return AgentResponse::default_allow();
            }
        }

        // Always process headers immediately (phase 1)
        // This detects attacks in URI, query string, and headers
        match self
            .process_request(
                correlation_id,
                &event.method,
                &event.uri,
                &event.headers,
                None,
            )
            .await
        {
            Ok(Some((status, message, rule_ids))) => {
                let engine = self.engine.read().await;
                if engine.config.block_mode {
                    info!(
                        correlation_id = correlation_id,
                        status = status,
                        rules = ?rule_ids,
                        "Request blocked by SentinelSec"
                    );
                    let rule_id = rule_ids.first().cloned().unwrap_or_default();
                    AgentResponse::block(status, Some("Forbidden".to_string()))
                        .add_response_header(HeaderOp::Set {
                            name: "X-WAF-Blocked".to_string(),
                            value: "true".to_string(),
                        })
                        .add_response_header(HeaderOp::Set {
                            name: "X-WAF-Rule".to_string(),
                            value: rule_id,
                        })
                        .add_response_header(HeaderOp::Set {
                            name: "X-WAF-Message".to_string(),
                            value: message.clone(),
                        })
                        .with_audit(AuditMetadata {
                            tags: vec!["sentinelsec".to_string(), "blocked".to_string()],
                            rule_ids,
                            reason_codes: vec![message],
                            ..Default::default()
                        })
                } else {
                    info!(
                        correlation_id = correlation_id,
                        rules = ?rule_ids,
                        "SentinelSec detection (detect-only mode)"
                    );
                    AgentResponse::default_allow()
                        .add_request_header(HeaderOp::Set {
                            name: "X-WAF-Detected".to_string(),
                            value: message.clone(),
                        })
                        .with_audit(AuditMetadata {
                            tags: vec!["sentinelsec".to_string(), "detected".to_string()],
                            rule_ids,
                            reason_codes: vec![message],
                            ..Default::default()
                        })
                }
            }
            Ok(None) => {
                // Headers passed - if body inspection enabled, store for body processing
                let engine = self.engine.read().await;
                if engine.config.body_inspection_enabled {
                    let mut pending = self.pending_requests.write().await;
                    pending.insert(
                        correlation_id.clone(),
                        PendingTransaction {
                            body: BodyAccumulator::default(),
                            method: event.method.clone(),
                            uri: event.uri.clone(),
                            headers: event.headers.clone(),
                            client_ip: event.metadata.client_ip.clone(),
                        },
                    );
                }
                AgentResponse::default_allow()
            }
            Err(e) => {
                warn!(error = %e, "SentinelSec processing error");
                AgentResponse::default_allow()
            }
        }
    }

    async fn on_response_headers(&self, _event: ResponseHeadersEvent) -> AgentResponse {
        AgentResponse::default_allow()
    }

    async fn on_request_body_chunk(&self, event: RequestBodyChunkEvent) -> AgentResponse {
        let correlation_id = &event.correlation_id;

        // Check if we have a pending request
        let pending_exists = {
            let pending = self.pending_requests.read().await;
            pending.contains_key(correlation_id)
        };

        if !pending_exists {
            // No pending request - body inspection might be disabled
            return AgentResponse::default_allow();
        }

        // Decode base64 chunk
        let chunk = match base64::engine::general_purpose::STANDARD.decode(&event.data) {
            Ok(data) => data,
            Err(e) => {
                warn!(error = %e, "Failed to decode body chunk");
                return AgentResponse::default_allow();
            }
        };

        // Accumulate chunk
        let should_process = {
            let mut pending = self.pending_requests.write().await;
            if let Some(tx) = pending.get_mut(correlation_id) {
                let engine = self.engine.read().await;

                // Check size limit
                if tx.body.data.len() + chunk.len() > engine.config.max_body_size {
                    debug!(
                        correlation_id = correlation_id,
                        "Body exceeds max size, skipping inspection"
                    );
                    pending.remove(correlation_id);
                    return AgentResponse::default_allow();
                }

                tx.body.data.extend(chunk);
                event.is_last
            } else {
                false
            }
        };

        // If this is the last chunk, process the complete request
        if should_process {
            let pending_tx = {
                let mut pending = self.pending_requests.write().await;
                pending.remove(correlation_id)
            };

            if let Some(tx) = pending_tx {
                match self
                    .process_request(
                        correlation_id,
                        &tx.method,
                        &tx.uri,
                        &tx.headers,
                        Some(&tx.body.data),
                    )
                    .await
                {
                    Ok(Some((status, message, rule_ids))) => {
                        let engine = self.engine.read().await;
                        if engine.config.block_mode {
                            info!(
                                correlation_id = correlation_id,
                                status = status,
                                rules = ?rule_ids,
                                "Request blocked by SentinelSec (body inspection)"
                            );
                            let rule_id = rule_ids.first().cloned().unwrap_or_default();
                            return AgentResponse::block(status, Some("Forbidden".to_string()))
                                .add_response_header(HeaderOp::Set {
                                    name: "X-WAF-Blocked".to_string(),
                                    value: "true".to_string(),
                                })
                                .add_response_header(HeaderOp::Set {
                                    name: "X-WAF-Rule".to_string(),
                                    value: rule_id,
                                })
                                .add_response_header(HeaderOp::Set {
                                    name: "X-WAF-Message".to_string(),
                                    value: message.clone(),
                                })
                                .with_audit(AuditMetadata {
                                    tags: vec![
                                        "sentinelsec".to_string(),
                                        "blocked".to_string(),
                                        "body".to_string(),
                                    ],
                                    rule_ids,
                                    reason_codes: vec![message],
                                    ..Default::default()
                                });
                        } else {
                            info!(
                                correlation_id = correlation_id,
                                rules = ?rule_ids,
                                "SentinelSec detection in body (detect-only mode)"
                            );
                            return AgentResponse::default_allow()
                                .add_request_header(HeaderOp::Set {
                                    name: "X-WAF-Detected".to_string(),
                                    value: message.clone(),
                                })
                                .with_audit(AuditMetadata {
                                    tags: vec![
                                        "sentinelsec".to_string(),
                                        "detected".to_string(),
                                        "body".to_string(),
                                    ],
                                    rule_ids,
                                    reason_codes: vec![message],
                                    ..Default::default()
                                });
                        }
                    }
                    Ok(None) => {}
                    Err(e) => {
                        warn!(error = %e, "SentinelSec body processing error");
                    }
                }
            }
        }

        AgentResponse::default_allow()
    }

    async fn on_response_body_chunk(&self, event: ResponseBodyChunkEvent) -> AgentResponse {
        // Response body inspection not yet implemented
        let _ = event;
        AgentResponse::default_allow()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = SentinelSecConfig::default();
        assert!(config.rules_paths.is_empty());
        assert!(config.block_mode);
        assert!(config.body_inspection_enabled);
        assert!(!config.response_inspection_enabled);
        assert_eq!(config.max_body_size, 1048576);
    }

    #[test]
    fn test_engine_initialization() {
        let config = SentinelSecConfig::default();
        let engine = SentinelSecEngine::new(config);
        assert!(engine.is_ok());
    }

    #[test]
    fn test_engine_with_inline_rule() {
        // Test with a simple inline rule
        let config = SentinelSecConfig::default();
        let engine = SentinelSecEngine::new(config).unwrap();

        // Verify engine is working
        let mut tx = engine.modsec.new_transaction();
        tx.process_uri("/test", "GET", "HTTP/1.1").unwrap();
        tx.process_request_headers().unwrap();

        // Should not block clean requests
        assert!(tx.intervention().is_none());
    }

    #[test]
    fn test_path_exclusion() {
        let config = SentinelSecConfig {
            exclude_paths: vec!["/health".to_string(), "/metrics".to_string()],
            ..Default::default()
        };
        let engine = SentinelSecEngine::new(config).unwrap();

        assert!(engine.is_excluded("/health"));
        assert!(engine.is_excluded("/health/live"));
        assert!(engine.is_excluded("/metrics"));
        assert!(!engine.is_excluded("/api/users"));
    }

    #[test]
    fn test_sql_injection_blocked() {
        // Create a ModSecurity engine with a SQL injection detection rule
        let rules = r#"
            SecRuleEngine On
            SecRule ARGS "@detectSQLi" "id:942100,phase:2,deny,status:403,msg:'SQL Injection Attack Detected'"
            SecRule QUERY_STRING "@detectSQLi" "id:942101,phase:1,deny,status:403,msg:'SQL Injection in Query String'"
            SecRule REQUEST_URI "@contains union select" "id:942102,phase:1,deny,status:403,msg:'UNION SELECT detected'"
        "#;

        let modsec = sentinel_modsec::ModSecurity::from_string(rules).unwrap();

        // Test 1: Classic SQL injection in query string
        let mut tx = modsec.new_transaction();
        tx.process_uri("/api/users?id=1' OR '1'='1", "GET", "HTTP/1.1").unwrap();
        tx.process_request_headers().unwrap();

        let intervention = tx.intervention();
        assert!(
            intervention.is_some(),
            "Expected SQL injection to be blocked: 1' OR '1'='1"
        );
        if let Some(i) = intervention {
            assert_eq!(i.status, 403);
            println!("Blocked with status {}: {:?}", i.status, i.rule_ids);
        }

        // Test 2: UNION-based SQL injection
        let mut tx2 = modsec.new_transaction();
        tx2.process_uri("/api/users?id=1 union select * from users--", "GET", "HTTP/1.1").unwrap();
        tx2.process_request_headers().unwrap();

        let intervention2 = tx2.intervention();
        assert!(
            intervention2.is_some(),
            "Expected UNION SELECT injection to be blocked"
        );

        // Test 3: Clean request should pass
        let mut tx3 = modsec.new_transaction();
        tx3.process_uri("/api/users?id=123", "GET", "HTTP/1.1").unwrap();
        tx3.process_request_headers().unwrap();

        assert!(
            tx3.intervention().is_none(),
            "Clean request should not be blocked"
        );
    }

    #[test]
    fn test_xss_blocked() {
        // Create a ModSecurity engine with XSS detection rule
        let rules = r#"
            SecRuleEngine On
            SecRule ARGS "@detectXSS" "id:941100,phase:2,deny,status:403,msg:'XSS Attack Detected'"
            SecRule QUERY_STRING "@detectXSS" "id:941101,phase:1,deny,status:403,msg:'XSS in Query String'"
            SecRule REQUEST_URI "@contains <script" "id:941102,phase:1,deny,status:403,msg:'Script tag detected'"
        "#;

        let modsec = sentinel_modsec::ModSecurity::from_string(rules).unwrap();

        // Test 1: Script tag injection
        let mut tx = modsec.new_transaction();
        tx.process_uri("/search?q=<script>alert(1)</script>", "GET", "HTTP/1.1").unwrap();
        tx.process_request_headers().unwrap();

        let intervention = tx.intervention();
        assert!(
            intervention.is_some(),
            "Expected XSS to be blocked: <script>alert(1)</script>"
        );
        if let Some(i) = intervention {
            assert_eq!(i.status, 403);
            println!("XSS blocked with status {}: {:?}", i.status, i.rule_ids);
        }

        // Test 2: Event handler injection
        let mut tx2 = modsec.new_transaction();
        tx2.process_uri("/search?q=<img src=x onerror=alert(1)>", "GET", "HTTP/1.1").unwrap();
        tx2.process_request_headers().unwrap();

        let intervention2 = tx2.intervention();
        assert!(
            intervention2.is_some(),
            "Expected event handler XSS to be blocked"
        );

        // Test 3: Clean request should pass
        let mut tx3 = modsec.new_transaction();
        tx3.process_uri("/search?q=hello+world", "GET", "HTTP/1.1").unwrap();
        tx3.process_request_headers().unwrap();

        assert!(
            tx3.intervention().is_none(),
            "Clean request should not be blocked"
        );
    }

    #[test]
    fn test_request_body_sql_injection() {
        // Test SQL injection in POST body
        let rules = r#"
            SecRuleEngine On
            SecRequestBodyAccess On
            SecRule ARGS "@detectSQLi" "id:942200,phase:2,deny,status:403,msg:'SQL Injection in Body'"
        "#;

        let modsec = sentinel_modsec::ModSecurity::from_string(rules).unwrap();

        let mut tx = modsec.new_transaction();
        tx.process_uri("/api/login", "POST", "HTTP/1.1").unwrap();
        tx.add_request_header("Content-Type", "application/x-www-form-urlencoded").unwrap();
        tx.process_request_headers().unwrap();

        // Add malicious body
        let body = b"username=admin&password=' OR '1'='1";
        tx.append_request_body(body).unwrap();
        tx.process_request_body().unwrap();

        let intervention = tx.intervention();
        assert!(
            intervention.is_some(),
            "Expected SQL injection in POST body to be blocked"
        );
        if let Some(i) = intervention {
            assert_eq!(i.status, 403);
            println!("Body SQLi blocked: {:?}", i.rule_ids);
        }
    }
}