floe-core 0.4.5

Core library for Floe, a YAML-driven technical ingestion tool.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::collections::HashMap;

use polars::prelude::*;
use sha2::{Digest, Sha256};

use crate::config::{extract_first_n, extract_last_n, PiiColumnConfig, PiiConfig, PiiStrategy};
use crate::FloeResult;

/// Apply PII masking to all configured columns.
///
/// `schema_to_runtime` maps schema column names to post-rename runtime names
/// (e.g. `"Credit Card"` → `"credit_card"` when normalize_columns is active).
/// Only entries where the names differ are present; columns whose schema name
/// already equals the runtime name need no entry.
pub fn apply_pii_masking(
    df: &mut DataFrame,
    pii: &PiiConfig,
    schema_to_runtime: &HashMap<String, String>,
) -> FloeResult<()> {
    for col_cfg in &pii.columns {
        apply_pii_column(df, col_cfg, schema_to_runtime)?;
    }
    Ok(())
}

fn apply_pii_column(
    df: &mut DataFrame,
    col_cfg: &PiiColumnConfig,
    schema_to_runtime: &HashMap<String, String>,
) -> FloeResult<()> {
    let declared_name = col_cfg.name.as_str();
    // When normalize_columns is active the schema column name may differ from
    // the runtime name in the DataFrame (e.g. "Credit Card" → "credit_card").
    // schema_to_runtime maps schema names to their post-rename runtime names.
    let runtime_name = schema_to_runtime
        .get(declared_name)
        .map(|s| s.as_str())
        .unwrap_or(declared_name);

    // If column was removed by a prior `drop` or doesn't exist, skip silently.
    if df.column(runtime_name).is_err() {
        return Ok(());
    }

    match col_cfg.strategy {
        PiiStrategy::Hash => {
            let col = df.column(runtime_name)?;
            let new_series = hash_column(col, runtime_name)?;
            df.with_column(new_series).map_err(|e| {
                Box::new(crate::errors::RunError(format!(
                    "PII hash: failed to replace column {runtime_name}: {e}"
                ))) as Box<dyn std::error::Error + Send + Sync>
            })?;
        }
        PiiStrategy::Drop => {
            df.drop_in_place(runtime_name).map_err(|e| {
                Box::new(crate::errors::RunError(format!(
                    "PII drop: failed to drop column {runtime_name}: {e}"
                ))) as Box<dyn std::error::Error + Send + Sync>
            })?;
        }
        PiiStrategy::Nullify => {
            let col = df.column(runtime_name)?;
            let len = col.len();
            let dtype = col.dtype().clone();
            let null_series = Series::full_null(runtime_name.into(), len, &dtype);
            df.with_column(null_series).map_err(|e| {
                Box::new(crate::errors::RunError(format!(
                    "PII nullify: failed to replace column {runtime_name}: {e}"
                ))) as Box<dyn std::error::Error + Send + Sync>
            })?;
        }
        PiiStrategy::Redact => {
            let redact_value = col_cfg.redact_value.as_deref().unwrap_or("[REDACTED]");
            let col = df.column(runtime_name)?;
            let new_series = redact_column(col, runtime_name, redact_value)?;
            df.with_column(new_series).map_err(|e| {
                Box::new(crate::errors::RunError(format!(
                    "PII redact: failed to replace column {runtime_name}: {e}"
                ))) as Box<dyn std::error::Error + Send + Sync>
            })?;
        }
        PiiStrategy::Mask => {
            let pattern = col_cfg.mask_pattern.as_deref().unwrap_or("");
            let first_n = extract_first_n(pattern);
            let last_n = extract_last_n(pattern);
            let col = df.column(runtime_name)?;
            let new_series = mask_column(col, runtime_name, pattern, first_n, last_n)?;
            df.with_column(new_series).map_err(|e| {
                Box::new(crate::errors::RunError(format!(
                    "PII mask: failed to replace column {runtime_name}: {e}"
                ))) as Box<dyn std::error::Error + Send + Sync>
            })?;
        }
        PiiStrategy::Tokenize => {
            // Rejected at config validation; never reached at runtime.
        }
    }
    Ok(())
}

fn to_string_chunked(col: &Column, col_name: &str) -> FloeResult<StringChunked> {
    let str_col = col.cast(&DataType::String).map_err(|e| {
        Box::new(crate::errors::RunError(format!(
            "PII: failed to cast column {col_name} to string: {e}"
        ))) as Box<dyn std::error::Error + Send + Sync>
    })?;
    let series = str_col.as_materialized_series().clone();
    let ca = series.str().map_err(|e| {
        Box::new(crate::errors::RunError(format!(
            "PII: failed to access string chunked array for column {col_name}: {e}"
        ))) as Box<dyn std::error::Error + Send + Sync>
    })?;
    Ok(ca.clone())
}

fn hash_column(col: &Column, col_name: &str) -> FloeResult<Series> {
    let ca = to_string_chunked(col, col_name)?;
    let hashed: StringChunked = ca.apply(|opt| {
        opt.map(|v| {
            let mut hasher = Sha256::new();
            hasher.update(v.as_bytes());
            hex::encode(hasher.finalize()).into()
        })
    });
    let mut s = hashed.into_series();
    s.rename(col_name.into());
    Ok(s)
}

fn redact_column(col: &Column, col_name: &str, redact_value: &str) -> FloeResult<Series> {
    let ca = to_string_chunked(col, col_name)?;
    let redacted: StringChunked = ca.apply(|opt| opt.map(|_| redact_value.into()));
    let mut s = redacted.into_series();
    s.rename(col_name.into());
    Ok(s)
}

fn mask_column(
    col: &Column,
    col_name: &str,
    pattern: &str,
    first_n: Option<usize>,
    last_n: Option<usize>,
) -> FloeResult<Series> {
    let ca = to_string_chunked(col, col_name)?;
    let masked: StringChunked =
        ca.apply(|opt| opt.map(|v| apply_mask(v, pattern, first_n, last_n).into()));
    let mut s = masked.into_series();
    s.rename(col_name.into());
    Ok(s)
}

fn apply_mask(value: &str, pattern: &str, first_n: Option<usize>, last_n: Option<usize>) -> String {
    let fn_val = first_n.unwrap_or(0);
    let ln_val = last_n.unwrap_or(0);

    // Count Unicode scalar values, not bytes, to avoid splitting multi-byte chars.
    let char_count = value.chars().count();

    // Clamp revealed chars so they never overlap; suffix takes priority.
    // Never return the raw value unchanged — always apply the pattern's literal mask chars.
    let actual_ln = ln_val.min(char_count);
    let actual_fn = fn_val.min(char_count.saturating_sub(actual_ln));

    let prefix: String = value.chars().take(actual_fn).collect();
    let suffix: String = value.chars().skip(char_count - actual_ln).collect();

    let mut result = pattern.to_string();
    if fn_val > 0 {
        result = result.replace(&format!("{{first{fn_val}}}"), &prefix);
    }
    if ln_val > 0 {
        result = result.replace(&format!("{{last{ln_val}}}"), &suffix);
    }
    result
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use polars::prelude::*;

    use super::apply_pii_masking;
    use crate::config::{PiiColumnConfig, PiiConfig, PiiStrategy};

    fn str_series(name: &str, values: &[Option<&str>]) -> Column {
        Series::new(name.into(), values).into()
    }

    fn single_col_df(name: &str, values: &[Option<&str>]) -> DataFrame {
        DataFrame::new(vec![str_series(name, values)]).unwrap()
    }

    fn simple_pii(name: &str, strategy: PiiStrategy) -> PiiConfig {
        PiiConfig {
            columns: vec![PiiColumnConfig {
                name: name.to_string(),
                strategy,
                mask_pattern: None,
                redact_value: None,
            }],
        }
    }

    fn get_str(df: &DataFrame, col: &str, row: usize) -> Option<String> {
        df.column(col)
            .unwrap()
            .str()
            .unwrap()
            .get(row)
            .map(|s| s.to_string())
    }

    // --- hash ---

    #[test]
    fn hash_produces_64_char_hex() {
        let mut df = single_col_df("email", &[Some("a@b.com")]);
        apply_pii_masking(
            &mut df,
            &simple_pii("email", PiiStrategy::Hash),
            &HashMap::new(),
        )
        .unwrap();
        let v = get_str(&df, "email", 0).unwrap();
        assert_eq!(v.len(), 64, "SHA-256 hex output must be 64 chars");
        assert!(v.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn hash_on_empty_string_produces_sha256() {
        let mut df = single_col_df("email", &[Some("")]);
        apply_pii_masking(
            &mut df,
            &simple_pii("email", PiiStrategy::Hash),
            &HashMap::new(),
        )
        .unwrap();
        // SHA-256("") = e3b0c44298fc1c149afbf4c8996fb924...
        let v = get_str(&df, "email", 0).unwrap();
        assert_eq!(v.len(), 64);
        assert!(v.starts_with("e3b0c442"));
    }

    #[test]
    fn hash_preserves_null() {
        let mut df = single_col_df("email", &[Some("a@b.com"), None]);
        apply_pii_masking(
            &mut df,
            &simple_pii("email", PiiStrategy::Hash),
            &HashMap::new(),
        )
        .unwrap();
        assert!(
            get_str(&df, "email", 1).is_none(),
            "null must stay null after hash"
        );
    }

    // --- redact ---

    #[test]
    fn redact_replaces_with_default_placeholder() {
        let mut df = single_col_df("cc", &[Some("1234-5678-9012-3456")]);
        apply_pii_masking(
            &mut df,
            &simple_pii("cc", PiiStrategy::Redact),
            &HashMap::new(),
        )
        .unwrap();
        assert_eq!(get_str(&df, "cc", 0).unwrap(), "[REDACTED]");
    }

    #[test]
    fn redact_uses_custom_value() {
        let mut df = single_col_df("cc", &[Some("secret")]);
        let pii = PiiConfig {
            columns: vec![PiiColumnConfig {
                name: "cc".to_string(),
                strategy: PiiStrategy::Redact,
                mask_pattern: None,
                redact_value: Some("[PII]".to_string()),
            }],
        };
        apply_pii_masking(&mut df, &pii, &HashMap::new()).unwrap();
        assert_eq!(get_str(&df, "cc", 0).unwrap(), "[PII]");
    }

    #[test]
    fn redact_on_empty_string_replaces_with_placeholder() {
        let mut df = single_col_df("cc", &[Some("")]);
        apply_pii_masking(
            &mut df,
            &simple_pii("cc", PiiStrategy::Redact),
            &HashMap::new(),
        )
        .unwrap();
        assert_eq!(get_str(&df, "cc", 0).unwrap(), "[REDACTED]");
    }

    #[test]
    fn redact_preserves_null() {
        let mut df = single_col_df("cc", &[Some("val"), None]);
        apply_pii_masking(
            &mut df,
            &simple_pii("cc", PiiStrategy::Redact),
            &HashMap::new(),
        )
        .unwrap();
        assert!(
            get_str(&df, "cc", 1).is_none(),
            "null must stay null after redact"
        );
    }

    // --- nullify ---

    #[test]
    fn nullify_replaces_all_values_with_null() {
        let mut df = single_col_df("field", &[Some("a"), Some("b"), None]);
        apply_pii_masking(
            &mut df,
            &simple_pii("field", PiiStrategy::Nullify),
            &HashMap::new(),
        )
        .unwrap();
        let col = df.column("field").unwrap();
        assert!(col.get(0).unwrap().is_null());
        assert!(col.get(1).unwrap().is_null());
        assert!(col.get(2).unwrap().is_null());
    }

    // --- drop ---

    #[test]
    fn drop_removes_column_from_dataframe() {
        let mut df = DataFrame::new(vec![
            str_series("keep", &[Some("x")]),
            str_series("pii_col", &[Some("secret")]),
        ])
        .unwrap();
        apply_pii_masking(
            &mut df,
            &simple_pii("pii_col", PiiStrategy::Drop),
            &HashMap::new(),
        )
        .unwrap();
        assert!(
            df.column("pii_col").is_err(),
            "dropped column must not exist"
        );
        assert!(
            df.column("keep").is_ok(),
            "unrelated column must be untouched"
        );
    }

    // --- mask ---

    #[test]
    fn mask_applies_last4_pattern() {
        let mut df = single_col_df("cc", &[Some("1234567890123456")]);
        let pii = PiiConfig {
            columns: vec![PiiColumnConfig {
                name: "cc".to_string(),
                strategy: PiiStrategy::Mask,
                mask_pattern: Some("****{last4}".to_string()),
                redact_value: None,
            }],
        };
        apply_pii_masking(&mut df, &pii, &HashMap::new()).unwrap();
        assert_eq!(get_str(&df, "cc", 0).unwrap(), "****3456");
    }

    #[test]
    fn mask_on_empty_string_keeps_mask_literal() {
        let mut df = single_col_df("cc", &[Some("")]);
        let pii = PiiConfig {
            columns: vec![PiiColumnConfig {
                name: "cc".to_string(),
                strategy: PiiStrategy::Mask,
                mask_pattern: Some("****{last4}".to_string()),
                redact_value: None,
            }],
        };
        apply_pii_masking(&mut df, &pii, &HashMap::new()).unwrap();
        // empty string → no suffix to reveal → {last4} replaced with "" → "****"
        assert_eq!(get_str(&df, "cc", 0).unwrap(), "****");
    }

    #[test]
    fn mask_preserves_null() {
        let mut df = single_col_df("cc", &[Some("1234567890"), None]);
        let pii = PiiConfig {
            columns: vec![PiiColumnConfig {
                name: "cc".to_string(),
                strategy: PiiStrategy::Mask,
                mask_pattern: Some("****{last4}".to_string()),
                redact_value: None,
            }],
        };
        apply_pii_masking(&mut df, &pii, &HashMap::new()).unwrap();
        assert!(
            get_str(&df, "cc", 1).is_none(),
            "null must stay null after mask"
        );
    }

    // --- normalize_columns rename path ---

    #[test]
    fn masking_resolves_schema_to_runtime_name() {
        // Schema declares "Credit Card"; normalize_columns renames it to "credit_card" at runtime.
        let mut df = DataFrame::new(vec![str_series("credit_card", &[Some("secret")])]).unwrap();
        let mut mapping = HashMap::new();
        mapping.insert("Credit Card".to_string(), "credit_card".to_string());
        let pii = PiiConfig {
            columns: vec![PiiColumnConfig {
                name: "Credit Card".to_string(),
                strategy: PiiStrategy::Redact,
                mask_pattern: None,
                redact_value: None,
            }],
        };
        apply_pii_masking(&mut df, &pii, &mapping).unwrap();
        assert_eq!(get_str(&df, "credit_card", 0).unwrap(), "[REDACTED]");
    }

    // --- missing column ---

    #[test]
    fn missing_column_is_skipped_without_error() {
        let mut df = single_col_df("other", &[Some("value")]);
        // "email" is not in the DataFrame (e.g. mismatch=ignore dropped it).
        apply_pii_masking(
            &mut df,
            &simple_pii("email", PiiStrategy::Hash),
            &HashMap::new(),
        )
        .unwrap();
        // Other columns must be untouched.
        assert_eq!(get_str(&df, "other", 0).unwrap(), "value");
    }
}