1use crate::parser::SqlDialect;
7use crate::redactor::config::RedactConfig;
8use crate::redactor::StrategyKind;
9use std::fs::File;
10use std::io::Write;
11
12#[derive(Debug)]
14pub struct ColumnAnalysis {
15 pub table: String,
16 pub column: String,
17 #[allow(dead_code)]
18 pub column_type: String,
19 pub suggested_strategy: Option<StrategyKind>,
20 pub confidence: Confidence,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq)]
25pub enum Confidence {
26 High,
27 Medium,
28 Low,
29 None,
30}
31
32impl Confidence {
33 fn as_comment(&self) -> &'static str {
34 match self {
35 Confidence::High => "",
36 Confidence::Medium => " # Medium confidence",
37 Confidence::Low => " # Low confidence - review",
38 Confidence::None => "",
39 }
40 }
41}
42
43pub fn generate_config(config: &RedactConfig) -> anyhow::Result<()> {
45 let analyses = analyze_for_config(&config.input, config.dialect)?;
46
47 let output_path = config.output.clone().unwrap_or_else(|| {
49 let mut path = config.input.clone();
50 path.set_extension("redact.yaml");
51 path
52 });
53
54 generate_config_yaml(&analyses, &output_path)?;
55
56 eprintln!("Generated config: {:?}", output_path);
57 eprintln!(
58 "Found {} columns with potential PII",
59 analyses
60 .iter()
61 .filter(|a| a.suggested_strategy.is_some())
62 .count()
63 );
64
65 Ok(())
66}
67
68fn analyze_for_config(
70 input: &std::path::Path,
71 dialect: SqlDialect,
72) -> anyhow::Result<Vec<ColumnAnalysis>> {
73 let schema = crate::schema::Schema::from_sql_file(input, dialect, None)?;
75
76 let mut analyses = Vec::new();
78 for table in schema.iter() {
79 for col in &table.columns {
80 let (strategy, confidence) = detect_pii(&col.name, &format!("{:?}", col.col_type));
81 analyses.push(ColumnAnalysis {
82 table: table.name.clone(),
83 column: col.name.clone(),
84 column_type: format!("{:?}", col.col_type),
85 suggested_strategy: strategy,
86 confidence,
87 });
88 }
89 }
90
91 Ok(analyses)
92}
93
94fn detect_pii(column_name: &str, _column_type: &str) -> (Option<StrategyKind>, Confidence) {
96 let name = column_name.to_lowercase();
97
98 if name.contains("email") {
100 return (
101 Some(StrategyKind::Hash {
102 preserve_domain: true,
103 }),
104 Confidence::High,
105 );
106 }
107 if name.contains("password") || name.contains("passwd") {
108 return (
109 Some(StrategyKind::Constant {
110 value: "$2b$10$REDACTED".to_string(),
111 }),
112 Confidence::High,
113 );
114 }
115 if name.contains("ssn") || name.contains("social_security") {
116 return (Some(StrategyKind::Null), Confidence::High);
117 }
118 if name.contains("tax_id") || name == "tin" {
119 return (Some(StrategyKind::Null), Confidence::High);
120 }
121 if name.contains("credit_card") || name.starts_with("cc_") {
122 return (
123 Some(StrategyKind::Mask {
124 pattern: "****-****-****-XXXX".to_string(),
125 }),
126 Confidence::High,
127 );
128 }
129
130 if name.contains("phone") || name.contains("mobile") || name.contains("cell") {
132 return (
133 Some(StrategyKind::Fake {
134 generator: "phone".to_string(),
135 }),
136 Confidence::Medium,
137 );
138 }
139 if name == "first_name" || name == "fname" {
140 return (
141 Some(StrategyKind::Fake {
142 generator: "first_name".to_string(),
143 }),
144 Confidence::High,
145 );
146 }
147 if name == "last_name" || name == "lname" || name.contains("surname") {
148 return (
149 Some(StrategyKind::Fake {
150 generator: "last_name".to_string(),
151 }),
152 Confidence::High,
153 );
154 }
155 if (name.contains("name") && !name.contains("username") && name != "name")
156 || name == "full_name"
157 {
158 return (
159 Some(StrategyKind::Fake {
160 generator: "name".to_string(),
161 }),
162 Confidence::Medium,
163 );
164 }
165 if name.contains("address") || name.contains("street") {
166 return (
167 Some(StrategyKind::Fake {
168 generator: "address".to_string(),
169 }),
170 Confidence::Medium,
171 );
172 }
173 if name == "city" {
174 return (
175 Some(StrategyKind::Fake {
176 generator: "city".to_string(),
177 }),
178 Confidence::Medium,
179 );
180 }
181 if name.contains("zip") || name.contains("postal") {
182 return (
183 Some(StrategyKind::Fake {
184 generator: "zip".to_string(),
185 }),
186 Confidence::Medium,
187 );
188 }
189 if name.contains("ip_address") || name == "ip_addr" || name == "ip" {
190 return (
191 Some(StrategyKind::Fake {
192 generator: "ip".to_string(),
193 }),
194 Confidence::Medium,
195 );
196 }
197 if name.contains("birth") || name == "dob" || name.contains("date_of_birth") {
198 return (
199 Some(StrategyKind::Fake {
200 generator: "date".to_string(),
201 }),
202 Confidence::Medium,
203 );
204 }
205
206 if name.contains("company") || name.contains("organization") {
208 return (
209 Some(StrategyKind::Fake {
210 generator: "company".to_string(),
211 }),
212 Confidence::Low,
213 );
214 }
215
216 (None, Confidence::None)
217}
218
219fn generate_config_yaml(
221 analyses: &[ColumnAnalysis],
222 output: &std::path::Path,
223) -> anyhow::Result<()> {
224 let mut yaml = String::new();
225
226 yaml.push_str("# sql-splitter redact configuration\n");
228 yaml.push_str("# Generated by: sql-splitter redact <input> --generate-config\n");
229 yaml.push_str("#\n");
230 yaml.push_str("# Review and modify this file before running redaction.\n");
231 yaml.push_str("# See: https://github.com/helgesverre/sql-splitter#redact-config\n");
232 yaml.push('\n');
233
234 yaml.push_str("# Random seed for reproducible redaction (optional)\n");
236 yaml.push_str("# seed: 12345\n\n");
237
238 yaml.push_str("# Locale for fake data generation\n");
240 yaml.push_str("# Supported: en, de_de, fr_fr, zh_cn, zh_tw, ja_jp, pt_br, ar_sa\n");
241 yaml.push_str("locale: en\n\n");
242
243 yaml.push_str("# Default strategy for columns not matching any rule\n");
245 yaml.push_str("defaults:\n");
246 yaml.push_str(" strategy: skip\n\n");
247
248 yaml.push_str("# Redaction rules (processed in order, first match wins)\n");
250 yaml.push_str("rules:\n");
251
252 let mut by_table: std::collections::BTreeMap<&str, Vec<&ColumnAnalysis>> =
254 std::collections::BTreeMap::new();
255 for analysis in analyses {
256 by_table.entry(&analysis.table).or_default().push(analysis);
257 }
258
259 for (table, columns) in by_table {
260 yaml.push_str(&format!("\n # --- Table: {} ---\n", table));
261
262 for col in columns {
263 if let Some(ref strategy) = col.suggested_strategy {
264 let confidence_note = col.confidence.as_comment();
265
266 yaml.push_str(&format!(" - column: \"{}.{}\"\n", table, col.column));
267
268 match strategy {
269 StrategyKind::Null => {
270 yaml.push_str(" strategy: null\n");
271 }
272 StrategyKind::Constant { value } => {
273 yaml.push_str(" strategy: constant\n");
274 yaml.push_str(&format!(" value: \"{}\"\n", value));
275 }
276 StrategyKind::Hash { preserve_domain } => {
277 yaml.push_str(" strategy: hash\n");
278 if *preserve_domain {
279 yaml.push_str(" preserve_domain: true\n");
280 }
281 }
282 StrategyKind::Mask { pattern } => {
283 yaml.push_str(" strategy: mask\n");
284 yaml.push_str(&format!(" pattern: \"{}\"\n", pattern));
285 }
286 StrategyKind::Fake { generator } => {
287 yaml.push_str(" strategy: fake\n");
288 yaml.push_str(&format!(" generator: {}\n", generator));
289 }
290 StrategyKind::Shuffle => {
291 yaml.push_str(" strategy: shuffle\n");
292 }
293 StrategyKind::Skip => {
294 yaml.push_str(" strategy: skip\n");
295 }
296 }
297
298 if !confidence_note.is_empty() {
299 yaml.push_str(&format!(" {}\n", confidence_note.trim()));
300 }
301 } else {
302 yaml.push_str(&format!(
304 " # - column: \"{}.{}\" # No PII detected\n",
305 table, col.column
306 ));
307 yaml.push_str(" # strategy: skip\n");
308 }
309 }
310 }
311
312 yaml.push_str("\n# Tables to skip entirely (no redaction applied)\n");
314 yaml.push_str("skip_tables:\n");
315 yaml.push_str(" # - schema_migrations\n");
316 yaml.push_str(" # - ar_internal_metadata\n");
317
318 let mut file = File::create(output)?;
320 file.write_all(yaml.as_bytes())?;
321
322 Ok(())
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn test_detect_email() {
331 let (strategy, confidence) = detect_pii("email", "Text");
332 assert!(matches!(strategy, Some(StrategyKind::Hash { .. })));
333 assert_eq!(confidence, Confidence::High);
334
335 let (strategy, _) = detect_pii("user_email", "Text");
336 assert!(matches!(strategy, Some(StrategyKind::Hash { .. })));
337 }
338
339 #[test]
340 fn test_detect_password() {
341 let (strategy, confidence) = detect_pii("password", "Text");
342 assert!(matches!(strategy, Some(StrategyKind::Constant { .. })));
343 assert_eq!(confidence, Confidence::High);
344 }
345
346 #[test]
347 fn test_detect_ssn() {
348 let (strategy, confidence) = detect_pii("ssn", "Text");
349 assert!(matches!(strategy, Some(StrategyKind::Null)));
350 assert_eq!(confidence, Confidence::High);
351 }
352
353 #[test]
354 fn test_detect_phone() {
355 let (strategy, confidence) = detect_pii("phone_number", "Text");
356 assert!(matches!(strategy, Some(StrategyKind::Fake { .. })));
357 assert_eq!(confidence, Confidence::Medium);
358 }
359
360 #[test]
361 fn test_detect_no_pii() {
362 let (strategy, confidence) = detect_pii("id", "Int");
363 assert!(strategy.is_none());
364 assert_eq!(confidence, Confidence::None);
365
366 let (strategy, _) = detect_pii("created_at", "DateTime");
367 assert!(strategy.is_none());
368 }
369}