Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions crates/tinymemory-api/src/safety/detector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@ fn level_from_score(score: u32) -> RiskLevel {
pub fn scan(content: &str) -> PiiScanResult {
// BTreeMap keeps the output deterministic (categories emitted in enum
// order) without a separate sort pass.
let mut counts: BTreeMap<PiiCategory, usize> = BTreeMap::new();
//
// Spans rather than a running count: two rules in one category can match
// the same value (`+1 415-555-0100` is both a US-format and an
// international phone number), and a count is of identifiers, not of
// rules, so overlapping spans are folded into one before they are counted.
let mut spans: BTreeMap<PiiCategory, Vec<(usize, usize)>> = BTreeMap::new();

for rule in rules() {
for m in rule.regex.find_iter(content) {
Expand All @@ -51,13 +56,20 @@ pub fn scan(content: &str) -> PiiScanResult {
{
continue;
}
*counts.entry(rule.category).or_default() += 1;
spans
.entry(rule.category)
.or_default()
.push((m.start(), m.end()));
}
}

if counts.is_empty() {
if spans.is_empty() {
return PiiScanResult::default();
}
let counts: BTreeMap<PiiCategory, usize> = spans
.into_iter()
.map(|(category, spans)| (category, distinct_spans(spans)))
.collect();

let distinct = counts.len() as u32;
let mut score: u32 = counts.keys().map(|c| c.weight()).sum();
Expand Down Expand Up @@ -85,6 +97,22 @@ pub fn scan(content: &str) -> PiiScanResult {
}
}

/// The number of distinct values among `spans`: byte ranges that overlap are
/// one value seen by more than one rule, ranges that merely touch or stand
/// apart are separate values. The same value written twice is two.
fn distinct_spans(mut spans: Vec<(usize, usize)>) -> usize {
spans.sort_unstable();
let mut count = 0;
let mut covered_to = 0;
for (start, end) in spans {
if count == 0 || start >= covered_to {
count += 1;
}
covered_to = covered_to.max(end);
}
count
}

/// Replacement for every value [`redact_identifiers`] removes.
pub const REDACTED_IDENTIFIER: &str = "[redacted]";

Expand Down
13 changes: 13 additions & 0 deletions crates/tinymemory-api/src/safety/detector_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,16 @@ fn level_thresholds_are_monotonic() {
assert_eq!(level_from_score(45), RiskLevel::High);
assert_eq!(level_from_score(1000), RiskLevel::High);
}

#[test]
fn distinct_spans_folds_overlaps_and_keeps_separate_values() {
assert_eq!(distinct_spans(vec![]), 0);
assert_eq!(distinct_spans(vec![(5, 20)]), 1);
// Two rules over one value, one of them a sub-span of the other.
assert_eq!(distinct_spans(vec![(6, 20), (5, 20)]), 1);
// Partial overlap is still one value.
assert_eq!(distinct_spans(vec![(0, 10), (8, 15)]), 1);
// Touching and separate ranges are distinct values.
assert_eq!(distinct_spans(vec![(0, 10), (10, 20)]), 2);
assert_eq!(distinct_spans(vec![(30, 40), (0, 10), (12, 20)]), 3);
}
37 changes: 37 additions & 0 deletions crates/tinymemory-api/src/safety/mod_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,43 @@ fn phone_shaped_ssn_not_double_counted_as_ssn() {
assert!(!r.has_category(PiiCategory::NationalId));
}

fn count_of(r: &PiiScanResult, category: PiiCategory) -> usize {
r.hits
.iter()
.find(|hit| hit.category == category)
.map_or(0, |hit| hit.count)
}

#[test]
fn a_value_matched_by_two_rules_counts_once() {
// `+1 415-555-0100` is both a US-format and an international phone
// number. It is one identifier, so it is one hit.
let r = scan("call +1 415-555-0100");
assert_eq!(count_of(&r, PiiCategory::PhoneNumber), 1, "{r:?}");
assert_eq!(r.level, RiskLevel::Low);
}

#[test]
fn distinct_values_in_one_category_each_count() {
let r = scan("+1 415-555-0100, 415-555-0199 or +44 20 7946 0958");
assert_eq!(count_of(&r, PiiCategory::PhoneNumber), 3, "{r:?}");
// The same value written twice is two occurrences.
let r = scan("415-555-0100 then again 415-555-0100");
assert_eq!(count_of(&r, PiiCategory::PhoneNumber), 2, "{r:?}");
}

#[test]
fn a_doubly_matched_value_is_redacted_whole() {
assert_eq!(
redact_identifiers("call +1 415-555-0100 now"),
"call [redacted] now"
);
assert_eq!(
redact_identifiers("call +1 415.555.1234 now"),
"call [redacted] now"
);
}

// ---------------------------------------------------------------------------
// Risk-level escalation
// ---------------------------------------------------------------------------
Expand Down
7 changes: 5 additions & 2 deletions crates/tinymemory-api/src/safety/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,13 @@ fn build_rules() -> Vec<Rule> {
None,
),
// US-style phone number (3-3-4 groups, requires a separator so it
// doesn't swallow arbitrary 10-digit numbers).
// doesn't swallow arbitrary 10-digit numbers). A leading `+1` is part
// of the number: `\b` cannot sit between a space and the `+`, so the
// alternation lets the match start on the `+` itself and redaction
// takes the whole value rather than leaving a stray `+` behind.
pattern_rule(
PiiCategory::PhoneNumber,
r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b",
r"(?:\+|\b)(?:1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b",
None,
),
// Legacy international phone-like pattern. Its repetition counts
Expand Down
Loading