Skip to main content

sql_splitter/redactor/strategy/
mod.rs

1//! Redaction strategies for anonymizing data.
2//!
3//! Each strategy implements a different approach to redacting values:
4//! - `null`: Replace with NULL
5//! - `constant`: Replace with a fixed value
6//! - `hash`: One-way hash (deterministic)
7//! - `mask`: Partial masking with pattern
8//! - `shuffle`: Redistribute values within column
9//! - `fake`: Generate realistic fake data
10//! - `skip`: No redaction (passthrough)
11
12mod constant;
13mod fake;
14mod hash;
15mod mask;
16mod null;
17mod shuffle;
18mod skip;
19
20pub use constant::ConstantStrategy;
21pub use fake::FakeStrategy;
22pub use hash::HashStrategy;
23pub use mask::MaskStrategy;
24pub use null::NullStrategy;
25#[allow(unused_imports)] // Public API re-export
26pub use shuffle::ShuffleStrategy;
27#[allow(unused_imports)] // Public API re-export
28pub use skip::SkipStrategy;
29
30use serde::{Deserialize, Serialize};
31
32/// Redaction strategy kind with associated configuration
33#[derive(Debug, Clone, Default, Serialize, Deserialize)]
34#[serde(tag = "strategy", rename_all = "snake_case")]
35pub enum StrategyKind {
36    /// Replace value with NULL
37    Null,
38
39    /// Replace with a constant value
40    Constant {
41        /// The constant value to use
42        value: String,
43    },
44
45    /// One-way hash (SHA256)
46    Hash {
47        /// Preserve email domain (user@domain.com → hash@domain.com)
48        #[serde(default)]
49        preserve_domain: bool,
50    },
51
52    /// Partial masking with pattern
53    Mask {
54        /// Pattern: * = asterisk, X = keep, # = random digit
55        pattern: String,
56    },
57
58    /// Shuffle values within the column
59    Shuffle,
60
61    /// Generate fake data
62    Fake {
63        /// Generator name: email, name, phone, address, etc.
64        generator: String,
65    },
66
67    /// No redaction (passthrough)
68    #[default]
69    Skip,
70}
71
72impl StrategyKind {
73    /// Validate the strategy configuration
74    pub fn validate(&self) -> anyhow::Result<()> {
75        match self {
76            StrategyKind::Null => Ok(()),
77            StrategyKind::Constant { value } => {
78                if value.is_empty() {
79                    anyhow::bail!("Constant strategy requires a non-empty value");
80                }
81                Ok(())
82            }
83            StrategyKind::Hash { .. } => Ok(()),
84            StrategyKind::Mask { pattern } => {
85                if pattern.is_empty() {
86                    anyhow::bail!("Mask strategy requires a non-empty pattern");
87                }
88                // Validate pattern characters
89                for c in pattern.chars() {
90                    if !matches!(c, '*' | 'X' | '#' | '-' | ' ' | '.' | '@' | '(' | ')') {
91                        // Allow common separator chars
92                    }
93                }
94                Ok(())
95            }
96            StrategyKind::Shuffle => anyhow::bail!(
97                "The shuffle redaction strategy is not supported because it requires a two-pass rewrite"
98            ),
99            StrategyKind::Fake { generator } => {
100                if !is_valid_generator(generator) {
101                    anyhow::bail!("Unknown fake generator: {}. Use: email, name, first_name, last_name, phone, address, city, zip, company, ip, uuid, date, etc.", generator);
102                }
103                Ok(())
104            }
105            StrategyKind::Skip => Ok(()),
106        }
107    }
108}
109
110/// Check if a fake generator name is valid
111fn is_valid_generator(name: &str) -> bool {
112    matches!(
113        name.to_lowercase().as_str(),
114        "email"
115            | "safe_email"
116            | "name"
117            | "first_name"
118            | "last_name"
119            | "full_name"
120            | "phone"
121            | "phone_number"
122            | "address"
123            | "street_address"
124            | "city"
125            | "state"
126            | "zip"
127            | "zip_code"
128            | "postal_code"
129            | "country"
130            | "company"
131            | "company_name"
132            | "job_title"
133            | "username"
134            | "user_name"
135            | "url"
136            | "ip"
137            | "ip_address"
138            | "ipv4"
139            | "ipv6"
140            | "uuid"
141            | "date"
142            | "date_time"
143            | "datetime"
144            | "time"
145            | "credit_card"
146            | "iban"
147            | "lorem"
148            | "paragraph"
149            | "sentence"
150            | "word"
151            | "ssn"
152    )
153}
154
155#[cfg(test)]
156mod tests {
157    use super::StrategyKind;
158
159    #[test]
160    fn shuffle_is_rejected_until_two_pass_rewriting_is_available() {
161        let error = StrategyKind::Shuffle
162            .validate()
163            .expect_err("shuffle must not silently preserve source values");
164
165        assert_eq!(
166            error.to_string(),
167            "The shuffle redaction strategy is not supported because it requires a two-pass rewrite"
168        );
169    }
170}
171
172/// Value representation for redaction
173#[derive(Debug, Clone)]
174pub enum RedactValue {
175    /// NULL value
176    Null,
177    /// String value (may contain SQL escaping)
178    String(String),
179    /// Integer value
180    Integer(i64),
181    /// Raw bytes (for binary data)
182    Bytes(Vec<u8>),
183}
184
185impl RedactValue {
186    /// Check if this is a NULL value
187    pub fn is_null(&self) -> bool {
188        matches!(self, RedactValue::Null)
189    }
190
191    /// Get as string, or None if NULL
192    pub fn as_str(&self) -> Option<&str> {
193        match self {
194            RedactValue::String(s) => Some(s),
195            _ => None,
196        }
197    }
198}
199
200/// Trait for redaction strategies
201pub trait Strategy: Send + Sync {
202    /// Apply the strategy to redact a value
203    fn apply(&self, value: &RedactValue, rng: &mut dyn rand::Rng) -> RedactValue;
204
205    /// Get the strategy kind
206    fn kind(&self) -> StrategyKind;
207}