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