Skip to main content

sql_splitter/redactor/strategy/
hash.rs

1//! Hash strategy - one-way SHA256 hash.
2
3use super::{RedactValue, Strategy, StrategyKind};
4use sha2::{Digest, Sha256};
5
6/// Strategy that hashes values with SHA256
7#[derive(Debug, Clone)]
8pub struct HashStrategy {
9    /// Whether to preserve email domain
10    preserve_domain: bool,
11}
12
13impl HashStrategy {
14    pub fn new(preserve_domain: bool) -> Self {
15        Self { preserve_domain }
16    }
17
18    /// Hash a string value
19    fn hash_value(&self, value: &str) -> String {
20        if self.preserve_domain {
21            // Email: preserve domain
22            if let Some((local, domain)) = value.rsplit_once('@') {
23                let mut result = String::with_capacity(8 + 1 + domain.len());
24                Self::write_hash_prefix(local, 8, &mut result);
25                result.push('@');
26                result.push_str(domain);
27                return result;
28            }
29        }
30
31        // Regular hash: take first 16 chars of hex
32        let mut result = String::with_capacity(16);
33        Self::write_hash_prefix(value, 16, &mut result);
34        result
35    }
36
37    /// Hash `value` and append the requested leading hexadecimal digits.
38    ///
39    /// Redaction only exposes 8 or 16 hex digits. Encoding all 64 digits and
40    /// then slicing them allocates and writes bytes that the caller discards.
41    fn write_hash_prefix(value: &str, digits: usize, output: &mut String) {
42        const HEX: &[u8; 16] = b"0123456789abcdef";
43
44        let mut hasher = Sha256::new();
45        hasher.update(value.as_bytes());
46        let digest = hasher.finalize();
47        let initial_len = output.len();
48
49        for byte in digest.iter().take(digits.div_ceil(2)) {
50            output.push(HEX[(byte >> 4) as usize] as char);
51            if output.len() - initial_len == digits {
52                break;
53            }
54            output.push(HEX[(byte & 0x0f) as usize] as char);
55        }
56    }
57}
58
59impl Strategy for HashStrategy {
60    fn apply(&self, value: &RedactValue, _rng: &mut dyn rand::Rng) -> RedactValue {
61        match value {
62            RedactValue::Null => RedactValue::Null,
63            RedactValue::String(s) => RedactValue::String(self.hash_value(s)),
64            RedactValue::Integer(i) => RedactValue::String(self.hash_value(&i.to_string())),
65            RedactValue::Bytes(b) => {
66                let s = String::from_utf8_lossy(b);
67                RedactValue::String(self.hash_value(&s))
68            }
69        }
70    }
71
72    fn kind(&self) -> StrategyKind {
73        StrategyKind::Hash {
74            preserve_domain: self.preserve_domain,
75        }
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use rand::SeedableRng;
83
84    #[test]
85    fn test_hash_strategy() {
86        let strategy = HashStrategy::new(false);
87        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
88
89        let result = strategy.apply(&RedactValue::String("secret".to_string()), &mut rng);
90        match result {
91            RedactValue::String(s) => {
92                assert_eq!(s, "2bb80d537b1da3e3");
93                // Hash is deterministic
94                let result2 = strategy.apply(&RedactValue::String("secret".to_string()), &mut rng);
95                match result2 {
96                    RedactValue::String(s2) => assert_eq!(s, s2),
97                    _ => panic!("Expected String"),
98                }
99            }
100            _ => panic!("Expected String"),
101        }
102    }
103
104    #[test]
105    fn test_hash_preserve_domain() {
106        let strategy = HashStrategy::new(true);
107        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
108
109        let result = strategy.apply(
110            &RedactValue::String("john.doe@example.com".to_string()),
111            &mut rng,
112        );
113        match result {
114            RedactValue::String(s) => {
115                assert_eq!(s, "30f69670@example.com");
116            }
117            _ => panic!("Expected String"),
118        }
119    }
120
121    #[test]
122    fn test_hash_deterministic() {
123        let strategy = HashStrategy::new(false);
124        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
125
126        // Same input = same output (for referential integrity)
127        let result1 = strategy.apply(
128            &RedactValue::String("test@example.com".to_string()),
129            &mut rng,
130        );
131        let result2 = strategy.apply(
132            &RedactValue::String("test@example.com".to_string()),
133            &mut rng,
134        );
135
136        match (result1, result2) {
137            (RedactValue::String(s1), RedactValue::String(s2)) => assert_eq!(s1, s2),
138            _ => panic!("Expected Strings"),
139        }
140    }
141
142    #[test]
143    fn test_hash_null() {
144        let strategy = HashStrategy::new(false);
145        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
146
147        let result = strategy.apply(&RedactValue::Null, &mut rng);
148        assert!(matches!(result, RedactValue::Null));
149    }
150}