Skip to main content

sql_splitter/redactor/
mod.rs

1//! Redactor module for anonymizing sensitive data in SQL dumps.
2//!
3//! This module provides:
4//! - YAML configuration parsing for redaction rules
5//! - Column pattern matching with glob support
6//! - Multiple redaction strategies (null, constant, hash, mask, shuffle, fake, skip)
7//! - Streaming redaction of INSERT and COPY statements
8//! - Config auto-generation from schema analysis
9
10mod config;
11mod config_generator;
12mod matcher;
13mod rewriter;
14pub mod strategy;
15
16pub use config::RedactConfig;
17#[allow(unused_imports)] // Public API re-exports used by external consumers
18pub use config::{RedactConfigBuilder, RedactYamlConfig, Rule};
19pub use config_generator::generate_config;
20pub use matcher::ColumnMatcher;
21pub use rewriter::ValueRewriter;
22pub use strategy::StrategyKind;
23
24use crate::parser::postgres_copy::parse_copy_columns;
25use crate::parser::{Parser, SqlDialect, StatementType};
26use crate::schema::Schema;
27use ahash::AHashMap;
28use schemars::JsonSchema;
29use std::fs::File;
30use std::io::{BufWriter, Write};
31use std::path::Path;
32
33/// Statistics from redaction operation
34#[derive(Debug, Default, serde::Serialize, JsonSchema)]
35pub struct RedactStats {
36    /// Number of tables processed
37    pub tables_processed: usize,
38    /// Number of rows redacted
39    pub rows_redacted: u64,
40    /// Number of columns redacted
41    pub columns_redacted: u64,
42    /// Per-table statistics
43    pub table_stats: Vec<TableRedactStats>,
44    /// Warning messages
45    pub warnings: Vec<String>,
46}
47
48/// Per-table redaction statistics
49#[derive(Debug, Clone, serde::Serialize, JsonSchema)]
50pub struct TableRedactStats {
51    pub name: String,
52    pub rows_processed: u64,
53    pub columns_redacted: u64,
54}
55
56/// Main redactor struct
57pub struct Redactor {
58    config: RedactConfig,
59    schema: Schema,
60    matcher: ColumnMatcher,
61    rewriter: ValueRewriter,
62    stats: RedactStats,
63    /// Pending COPY header for PostgreSQL (header comes before data block)
64    pending_copy: Option<PendingCopy>,
65}
66
67/// Pending COPY statement awaiting data block
68struct PendingCopy {
69    header: Vec<u8>,
70    table_name: String,
71    columns: Vec<String>,
72}
73
74impl Redactor {
75    /// Create a new Redactor with the given configuration
76    pub fn new(config: RedactConfig) -> anyhow::Result<Self> {
77        // Build schema from input file (Pass 1)
78        let schema = Self::build_schema(&config.input, config.dialect)?;
79
80        // Build column matcher from config rules
81        let matcher = ColumnMatcher::from_config(&config)?;
82
83        // Create value rewriter with seed for reproducibility
84        let rewriter = ValueRewriter::new(config.seed, config.dialect, config.locale.clone());
85
86        Ok(Self {
87            config,
88            schema,
89            matcher,
90            rewriter,
91            stats: RedactStats::default(),
92            pending_copy: None,
93        })
94    }
95
96    /// Build schema from input file
97    fn build_schema(input: &Path, dialect: SqlDialect) -> anyhow::Result<Schema> {
98        Schema::from_sql_file(input, dialect, None)
99    }
100
101    /// Run the redaction process
102    pub fn run(&mut self) -> anyhow::Result<RedactStats> {
103        if self.config.dry_run {
104            return self.dry_run();
105        }
106
107        // Open output (buffered in both cases; bare stdout would issue a
108        // write syscall per statement when piped)
109        let output: Box<dyn Write> = if let Some(ref path) = self.config.output {
110            Box::new(BufWriter::new(File::create(path)?))
111        } else {
112            Box::new(BufWriter::new(std::io::stdout()))
113        };
114
115        self.process_file(output)?;
116
117        Ok(std::mem::take(&mut self.stats))
118    }
119
120    /// Dry run - analyze without writing
121    fn dry_run(&mut self) -> anyhow::Result<RedactStats> {
122        let reader = crate::splitter::open_input(&self.config.input)?;
123        let mut parser = Parser::with_dialect(reader, 64 * 1024, self.config.dialect);
124
125        let mut tables_seen: AHashMap<String, u64> = AHashMap::new();
126
127        while let Some(stmt) = parser.read_statement()? {
128            let (stmt_type, table_name) =
129                Parser::<&[u8]>::parse_statement_with_dialect(&stmt, self.config.dialect);
130
131            if !table_name.is_empty()
132                && (stmt_type == StatementType::Insert || stmt_type == StatementType::Copy)
133            {
134                *tables_seen.entry(table_name).or_insert(0) += 1;
135            }
136        }
137
138        // Build stats from dry run
139        for (name, count) in tables_seen {
140            if let Some(table) = self.schema.get_table(&name) {
141                let columns_matched = self.matcher.count_matches(&name, table);
142                if columns_matched > 0 {
143                    self.stats.tables_processed += 1;
144                    self.stats.rows_redacted += count;
145                    self.stats.columns_redacted += columns_matched as u64 * count;
146                    self.stats.table_stats.push(TableRedactStats {
147                        name,
148                        rows_processed: count,
149                        columns_redacted: columns_matched as u64,
150                    });
151                }
152            }
153        }
154
155        Ok(std::mem::take(&mut self.stats))
156    }
157
158    /// Process the file and write redacted output
159    fn process_file(&mut self, mut output: Box<dyn Write>) -> anyhow::Result<()> {
160        let reader = crate::splitter::open_input(&self.config.input)?;
161        let mut parser = Parser::with_dialect(reader, 64 * 1024, self.config.dialect);
162
163        while let Some(stmt) = parser.read_statement()? {
164            let (stmt_type, table_name) =
165                Parser::<&[u8]>::parse_statement_with_dialect(&stmt, self.config.dialect);
166
167            let redacted = match stmt_type {
168                StatementType::Insert if !table_name.is_empty() => {
169                    self.redact_insert(&stmt, &table_name)?
170                }
171                StatementType::Copy if !table_name.is_empty() => {
172                    // PostgreSQL COPY: store header, wait for data block
173                    if self.config.dialect == SqlDialect::Postgres {
174                        let header_str = String::from_utf8_lossy(&stmt);
175                        let columns = parse_copy_columns(&header_str);
176                        self.pending_copy = Some(PendingCopy {
177                            header: stmt.clone(),
178                            table_name: table_name.clone(),
179                            columns,
180                        });
181                        // Don't output yet - wait for data block
182                        continue;
183                    }
184                    self.redact_copy(&stmt, &table_name)?
185                }
186                StatementType::Unknown
187                    if self.config.dialect == SqlDialect::Postgres
188                        && self.pending_copy.is_some()
189                        && (stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n")) =>
190                {
191                    // This is the COPY data block
192                    self.redact_copy_data(&stmt)?
193                }
194                _ => {
195                    // If we have a pending COPY that wasn't followed by a data block,
196                    // output it as-is
197                    if let Some(pending) = self.pending_copy.take() {
198                        output.write_all(&pending.header)?;
199                    }
200                    stmt
201                }
202            };
203
204            output.write_all(&redacted)?;
205        }
206
207        // Handle any remaining pending COPY header at EOF
208        if let Some(pending) = self.pending_copy.take() {
209            output.write_all(&pending.header)?;
210        }
211
212        output.flush()?;
213        Ok(())
214    }
215
216    /// Record per-run and per-table counters after a statement was redacted
217    fn record_stats(&mut self, table_name: &str, rows_redacted: u64, cols_redacted: u64) {
218        if rows_redacted == 0 {
219            return;
220        }
221
222        self.stats.rows_redacted += rows_redacted;
223        self.stats.columns_redacted += cols_redacted;
224
225        // Find or create table stats entry
226        if let Some(ts) = self
227            .stats
228            .table_stats
229            .iter_mut()
230            .find(|t| t.name == table_name)
231        {
232            ts.rows_processed += rows_redacted;
233            ts.columns_redacted += cols_redacted;
234        } else {
235            self.stats.tables_processed += 1;
236            self.stats.table_stats.push(TableRedactStats {
237                name: table_name.to_string(),
238                rows_processed: rows_redacted,
239                columns_redacted: cols_redacted,
240            });
241        }
242    }
243
244    /// Redact an INSERT statement
245    fn redact_insert(&mut self, stmt: &[u8], table_name: &str) -> anyhow::Result<Vec<u8>> {
246        // Skip if table should be excluded
247        if self.should_skip_table(table_name) {
248            return Ok(stmt.to_vec());
249        }
250
251        // Get table schema
252        let Some(table) = self.schema.get_table(table_name) else {
253            self.stats.warnings.push(format!(
254                "No schema for table '{}', passing through unchanged",
255                table_name
256            ));
257            return Ok(stmt.to_vec());
258        };
259
260        // Get strategies for each column
261        let strategies = self.matcher.get_strategies(table_name, table);
262
263        // If no columns need redaction, pass through
264        if strategies.iter().all(|s| matches!(s, StrategyKind::Skip)) {
265            return Ok(stmt.to_vec());
266        }
267
268        // Rewrite the INSERT statement with redacted values
269        let (redacted, rows_redacted, cols_redacted) =
270            self.rewriter
271                .rewrite_insert(stmt, table_name, table, &strategies)?;
272
273        self.record_stats(table_name, rows_redacted, cols_redacted);
274
275        Ok(redacted)
276    }
277
278    /// Redact a COPY statement (PostgreSQL)
279    fn redact_copy(&mut self, stmt: &[u8], table_name: &str) -> anyhow::Result<Vec<u8>> {
280        // Skip if table should be excluded
281        if self.should_skip_table(table_name) {
282            return Ok(stmt.to_vec());
283        }
284
285        // Get table schema
286        let Some(table) = self.schema.get_table(table_name) else {
287            self.stats.warnings.push(format!(
288                "No schema for table '{}', passing through unchanged",
289                table_name
290            ));
291            return Ok(stmt.to_vec());
292        };
293
294        // Get strategies for each column
295        let strategies = self.matcher.get_strategies(table_name, table);
296
297        // If no columns need redaction, pass through
298        if strategies.iter().all(|s| matches!(s, StrategyKind::Skip)) {
299            return Ok(stmt.to_vec());
300        }
301
302        // Rewrite the COPY statement with redacted values
303        let (redacted, rows_redacted, cols_redacted) =
304            self.rewriter
305                .rewrite_copy(stmt, table_name, table, &strategies)?;
306
307        self.record_stats(table_name, rows_redacted, cols_redacted);
308
309        Ok(redacted)
310    }
311
312    /// Redact a PostgreSQL COPY data block (comes after the header)
313    fn redact_copy_data(&mut self, data_block: &[u8]) -> anyhow::Result<Vec<u8>> {
314        let pending = self
315            .pending_copy
316            .take()
317            .ok_or_else(|| anyhow::anyhow!("COPY data block without pending header"))?;
318
319        let table_name = &pending.table_name;
320
321        // Skip if table should be excluded
322        if self.should_skip_table(table_name) {
323            // Output header + data unchanged
324            let mut result = pending.header;
325            result.extend_from_slice(data_block);
326            return Ok(result);
327        }
328
329        // Get table schema
330        let Some(table) = self.schema.get_table(table_name) else {
331            self.stats.warnings.push(format!(
332                "No schema for table '{}', passing through unchanged",
333                table_name
334            ));
335            let mut result = pending.header;
336            result.extend_from_slice(data_block);
337            return Ok(result);
338        };
339
340        // Get strategies for each column
341        let strategies = self.matcher.get_strategies(table_name, table);
342
343        // If no columns need redaction, pass through
344        if strategies.iter().all(|s| matches!(s, StrategyKind::Skip)) {
345            let mut result = pending.header;
346            result.extend_from_slice(data_block);
347            return Ok(result);
348        }
349
350        // Rewrite the COPY data block with redacted values
351        let (redacted_data, rows_redacted, cols_redacted) =
352            self.rewriter
353                .rewrite_copy_data(data_block, table, &strategies, &pending.columns)?;
354
355        self.record_stats(&pending.table_name, rows_redacted, cols_redacted);
356
357        // Combine header + redacted data
358        // The header typically doesn't end with newline, so add one
359        let mut result = pending.header;
360        if !result.ends_with(b"\n") {
361            result.push(b'\n');
362        }
363        result.extend_from_slice(&redacted_data);
364        Ok(result)
365    }
366
367    /// Check if a table should be skipped
368    fn should_skip_table(&self, name: &str) -> bool {
369        // Check exclude list
370        if self
371            .config
372            .exclude
373            .iter()
374            .any(|e| e.eq_ignore_ascii_case(name))
375        {
376            return true;
377        }
378
379        // Check include list (if specified)
380        if let Some(ref tables) = self.config.tables_filter {
381            if !tables.iter().any(|t| t.eq_ignore_ascii_case(name)) {
382                return true;
383            }
384        }
385
386        false
387    }
388}