Skip to main content

bulwark_security/security/
inspector_header_size.rs

1use crate::request::context::RequestContext;
2use crate::security::inspector::{Inspector, InspectorFinding};
3use crate::security::FindingSeverity;
4use crate::BulwarkError;
5
6/// InspectorHeaderSize
7///
8/// Mengecek total ukuran header request.
9/// Fokus: mencegah abuse header yang terlalu besar.
10pub struct InspectorHeaderSize {
11    /// Batas aman (byte)
12    soft_limit: usize,
13    /// Batas keras (byte)
14    hard_limit: usize,
15}
16
17impl InspectorHeaderSize {
18    /// Membuat inspector dengan dua threshold:
19    /// - soft_limit  -> Medium (log)
20    /// - hard_limit  -> High (block)
21    pub fn new(soft_limit: usize, hard_limit: usize) -> Self {
22        Self {
23            soft_limit,
24            hard_limit,
25        }
26    }
27
28    /// Hitung total ukuran header (nama + nilai)
29    fn calculate_total_size(ctx: &RequestContext) -> usize {
30        ctx.headers.iter().map(|(k, v)| k.len() + v.len()).sum()
31    }
32}
33
34impl Inspector for InspectorHeaderSize {
35    fn inspect(&self, ctx: &RequestContext) -> Result<Option<InspectorFinding>, BulwarkError> {
36        let total_size = Self::calculate_total_size(ctx);
37
38        // HARD LIMIT → High severity (Block)
39        if total_size > self.hard_limit {
40            return Ok(Some(InspectorFinding::new(
41                "inspector_header_size",
42                FindingSeverity::High,
43                format!(
44                    "header size {} bytes exceeds hard limit {}",
45                    total_size, self.hard_limit
46                ),
47            )));
48        }
49
50        // SOFT LIMIT → Medium severity (Log)
51        if total_size > self.soft_limit {
52            return Ok(Some(InspectorFinding::new(
53                "inspector_header_size",
54                FindingSeverity::Medium,
55                format!(
56                    "header size {} bytes exceeds soft limit {}",
57                    total_size, self.soft_limit
58                ),
59            )));
60        }
61
62        // Aman
63        Ok(None)
64    }
65}