Skip to main content

vac_sidecar/
security.rs

1//! Security hardening utilities for Phase 4.7
2//! 
3//! This module provides:
4//! - Memory protection (mlock, zeroization)
5//! - Input validation
6//! - Rate limiting
7
8use zeroize::{Zeroize, ZeroizeOnDrop};
9
10/// Secure string that zeroizes on drop
11#[derive(Clone, Zeroize, ZeroizeOnDrop)]
12pub struct SecureString(String);
13
14impl SecureString {
15    pub fn new(s: String) -> Self {
16        Self(s)
17    }
18    
19    pub fn as_str(&self) -> &str {
20        &self.0
21    }
22    
23    pub fn as_bytes(&self) -> &[u8] {
24        self.0.as_bytes()
25    }
26}
27
28impl From<String> for SecureString {
29    fn from(s: String) -> Self {
30        Self::new(s)
31    }
32}
33
34impl From<SecureString> for String {
35    fn from(s: SecureString) -> Self {
36        s.as_str().to_owned()
37    }
38}
39
40/// Attempt to lock memory pages to prevent swapping to disk
41/// 
42/// This is a best-effort operation. On some systems (e.g., Windows),
43/// this may not be fully supported. Errors are logged but don't fail startup.
44pub fn mlock_memory(ptr: *const u8, len: usize) -> Result<(), String> {
45    #[cfg(unix)]
46    {
47        use std::ffi::c_void;
48        use std::io;
49        let result = unsafe {
50            libc::mlock(ptr as *const c_void, len)
51        };
52        if result == 0 {
53            Ok(())
54        } else {
55            let err = io::Error::last_os_error();
56            Err(format!("mlock failed: {}", err))
57        }
58    }
59    
60    #[cfg(not(unix))]
61    {
62        let _ = (ptr, len);
63        // Windows and other platforms: mlock not available
64        // This is acceptable - zeroization is still effective
65        Ok(())
66    }
67}
68
69/// Attempt to unlock memory pages
70pub fn munlock_memory(ptr: *const u8, len: usize) -> Result<(), String> {
71    #[cfg(unix)]
72    {
73        use std::ffi::c_void;
74        use std::io;
75        let result = unsafe {
76            libc::munlock(ptr as *const c_void, len)
77        };
78        if result == 0 {
79            Ok(())
80        } else {
81            let err = io::Error::last_os_error();
82            Err(format!("munlock failed: {}", err))
83        }
84    }
85    
86    #[cfg(not(unix))]
87    {
88        let _ = (ptr, len);
89        Ok(())
90    }
91}
92
93/// Lock a string's memory to prevent swapping
94/// 
95/// This is best-effort and logs warnings on failure.
96pub fn lock_string_memory(s: &str) {
97    if let Err(e) = mlock_memory(s.as_ptr(), s.len()) {
98        tracing::warn!("Failed to lock string memory (non-fatal): {}", e);
99    }
100}
101
102/// Validate correlation ID format (must be valid UUID v4)
103pub fn validate_correlation_id(cid: &str) -> bool {
104    uuid::Uuid::parse_str(cid).is_ok()
105}
106
107/// Validate HTTP header name
108/// 
109/// Header names must be ASCII and not contain control characters.
110pub fn validate_header_name(name: &str) -> bool {
111    if name.is_empty() || name.len() > 256 {
112        return false;
113    }
114    name.chars().all(|c| c.is_ascii() && !c.is_control())
115}
116
117/// Validate HTTP header value
118/// 
119/// Header values must be valid UTF-8 and not exceed reasonable length.
120pub fn validate_header_value(value: &str) -> bool {
121    if value.len() > 8192 {
122        // 8KB limit per header value (RFC 7230 recommends 4KB, we allow 8KB)
123        return false;
124    }
125    // Check for control characters (except tab, which is allowed in header values)
126    value.chars().all(|c| !c.is_control() || c == '\t')
127}
128
129/// Maximum request body size (10MB)
130pub const MAX_REQUEST_BODY_SIZE: usize = 10 * 1024 * 1024;
131
132/// Validate request body size
133pub fn validate_body_size(size: usize) -> bool {
134    size <= MAX_REQUEST_BODY_SIZE
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    
141    #[test]
142    fn test_validate_correlation_id() {
143        assert!(validate_correlation_id("550e8400-e29b-41d4-a716-446655440000"));
144        assert!(!validate_correlation_id("not-a-uuid"));
145        assert!(!validate_correlation_id(""));
146    }
147    
148    #[test]
149    fn test_validate_header_name() {
150        assert!(validate_header_name("Authorization"));
151        assert!(validate_header_name("X-Correlation-ID"));
152        assert!(!validate_header_name(""));
153        assert!(!validate_header_name(&"a".repeat(257))); // Too long
154        assert!(!validate_header_name("Header\nName")); // Control char
155    }
156    
157    #[test]
158    fn test_validate_header_value() {
159        assert!(validate_header_value("Bearer token123"));
160        assert!(validate_header_value(&"a".repeat(8192))); // Max size
161        assert!(!validate_header_value(&"a".repeat(8193))); // Too large
162        assert!(!validate_header_value("Value\nwith\nnewlines")); // Control chars
163    }
164    
165    #[test]
166    fn test_validate_body_size() {
167        assert!(validate_body_size(MAX_REQUEST_BODY_SIZE));
168        assert!(validate_body_size(1024));
169        assert!(!validate_body_size(MAX_REQUEST_BODY_SIZE + 1));
170    }
171    
172    #[test]
173    fn test_secure_string() {
174        let s = SecureString::new("secret".to_string());
175        assert_eq!(s.as_str(), "secret");
176        // Drop should zeroize
177        drop(s);
178    }
179}