Skip to main content

gemini_adk_rs/live/
redaction.rs

1//! Transcript redaction — sensitive data never reaches the lanes.
2//!
3//! A voice caller will read card numbers, one-time passcodes, and account
4//! identifiers out loud, and speech recognition will faithfully transcribe
5//! them. Anything downstream of the transcript — callbacks, the transcript
6//! buffer, extraction, persistence snapshots, application logs — then holds
7//! that data unless it is removed first.
8//!
9//! A [`TranscriptRedactor`] installed on the session
10//! ([`LiveSessionBuilder::redaction`](super::builder::LiveSessionBuilder::redaction))
11//! is applied at the event router, *before* either lane sees the text: what
12//! the fast-lane callbacks receive, what the transcript buffer accumulates,
13//! what extractors read, and what a persistence backend stores are all the
14//! redacted form. There is deliberately no unredacted side channel.
15//!
16//! Two limits worth knowing:
17//!
18//! - **Streaming text deltas are not redacted.** A card number can straddle
19//!   delta boundaries where no single chunk matches anything. Deltas are a
20//!   text-mode display stream; voice deployments should treat transcripts
21//!   and [`TextComplete`](super::events::LiveEvent::TextComplete) (both
22//!   redacted) as the record.
23//! - **Redaction is pattern-based**, applied to each partial and final
24//!   transcript independently. It removes well-formed sensitive strings; it
25//!   is a complement to, not a replacement for, infrastructure-level data
26//!   loss prevention on stored audio.
27
28use regex::Regex;
29use std::sync::LazyLock;
30
31/// A card-number match is replaced by this, keeping the last four digits —
32/// enough for the conversation to stay coherent ("the card ending 1234")
33/// without retaining the number.
34fn card_replacement(last4: &str) -> String {
35    format!("[card ending {last4}]")
36}
37
38const NUMBER_REPLACEMENT: &str = "[redacted number]";
39
40/// Pattern-based transcript scrubber. Build one with the methods below and
41/// install it with
42/// [`LiveSessionBuilder::redaction`](super::builder::LiveSessionBuilder::redaction).
43///
44/// ```
45/// use gemini_adk_rs::live::redaction::TranscriptRedactor;
46///
47/// let redactor = TranscriptRedactor::new().card_numbers().long_digits(6);
48/// assert_eq!(
49///     redactor.redact("my card is 4111 1111 1111 1111 ok".into()),
50///     "my card is [card ending 1111] ok"
51/// );
52/// ```
53#[derive(Debug, Default)]
54pub struct TranscriptRedactor {
55    card_numbers: bool,
56    long_digits: Option<usize>,
57    custom: Vec<(Regex, String)>,
58}
59
60impl TranscriptRedactor {
61    /// A redactor with nothing enabled. Chain the methods below.
62    pub fn new() -> Self {
63        Self::default()
64    }
65
66    /// Redact payment-card numbers: runs of 13–19 digits (spaces and dashes
67    /// between groups allowed) that pass a Luhn check, replaced with
68    /// `[card ending NNNN]`. The Luhn check keeps ordinary long numbers —
69    /// tracking codes, reference IDs — from being eaten as cards.
70    pub fn card_numbers(mut self) -> Self {
71        self.card_numbers = true;
72        self
73    }
74
75    /// Redact any remaining run of `min` or more consecutive digits
76    /// (one-time passcodes, account numbers), replaced with
77    /// `[redacted number]`. Runs after the card pass, so a card keeps its
78    /// `[card ending NNNN]` form.
79    pub fn long_digits(mut self, min: usize) -> Self {
80        self.long_digits = Some(min);
81        self
82    }
83
84    /// Redact a custom pattern with a fixed replacement — national
85    /// identifiers, internal reference formats, whatever the deployment's
86    /// compliance regime names.
87    pub fn pattern(mut self, regex: Regex, replacement: impl Into<String>) -> Self {
88        self.custom.push((regex, replacement.into()));
89        self
90    }
91
92    /// Whether any rule is enabled. A no-op redactor is skipped entirely.
93    pub fn is_active(&self) -> bool {
94        self.card_numbers || self.long_digits.is_some() || !self.custom.is_empty()
95    }
96
97    /// Apply every enabled rule. Returns the input unchanged (no
98    /// reallocation) when nothing matches.
99    pub fn redact(&self, text: String) -> String {
100        let mut text = text;
101        if self.card_numbers {
102            text = redact_cards(&text);
103        }
104        if let Some(min) = self.long_digits {
105            text = redact_digit_runs(&text, min);
106        }
107        for (regex, replacement) in &self.custom {
108            if regex.is_match(&text) {
109                text = regex.replace_all(&text, replacement.as_str()).into_owned();
110            }
111        }
112        text
113    }
114}
115
116/// Candidate card spans: digit groups joined by optional single spaces or
117/// dashes. Verified by length and Luhn before replacement.
118static CARD_RE: LazyLock<Regex> = LazyLock::new(|| {
119    Regex::new(r"\d(?:[ -]?\d){11,18}").expect("CARD_RE literal is a valid regex")
120});
121
122/// Maximal digit runs. The caller keeps the runs of at least `min` digits, so
123/// the threshold never has to be compiled into a pattern (a large `min` would
124/// make `\d{min,}` fail to compile).
125static DIGIT_RUN_RE: LazyLock<Regex> =
126    LazyLock::new(|| Regex::new(r"\d+").expect("DIGIT_RUN_RE literal is a valid regex"));
127
128fn redact_cards(text: &str) -> String {
129    if !CARD_RE.is_match(text) {
130        return text.to_string();
131    }
132    CARD_RE
133        .replace_all(text, |caps: &regex::Captures<'_>| {
134            let raw = &caps[0];
135            let digits: String = raw.chars().filter(char::is_ascii_digit).collect();
136            if (13..=19).contains(&digits.len()) && luhn_valid(&digits) {
137                card_replacement(&digits[digits.len() - 4..])
138            } else {
139                raw.to_string()
140            }
141        })
142        .into_owned()
143}
144
145fn redact_digit_runs(text: &str, min: usize) -> String {
146    let mut out: Option<String> = None;
147    let mut copied = 0;
148    for m in DIGIT_RUN_RE.find_iter(text) {
149        if m.as_str().chars().count() < min {
150            continue;
151        }
152        let out = out.get_or_insert_with(|| String::with_capacity(text.len()));
153        out.push_str(&text[copied..m.start()]);
154        out.push_str(NUMBER_REPLACEMENT);
155        copied = m.end();
156    }
157    match out {
158        Some(mut out) => {
159            out.push_str(&text[copied..]);
160            out
161        }
162        None => text.to_string(),
163    }
164}
165
166/// The Luhn checksum every payment-card number satisfies (ISO/IEC 7812).
167fn luhn_valid(digits: &str) -> bool {
168    let mut sum = 0u32;
169    for (i, ch) in digits.chars().rev().enumerate() {
170        let Some(d) = ch.to_digit(10) else {
171            return false;
172        };
173        let d = if i % 2 == 1 {
174            let doubled = d * 2;
175            if doubled > 9 { doubled - 9 } else { doubled }
176        } else {
177            d
178        };
179        sum += d;
180    }
181    sum.is_multiple_of(10)
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn static_regex_literals_compile() {
190        // Forces each `LazyLock`: a bad literal fails here, not at runtime.
191        LazyLock::force(&CARD_RE);
192        LazyLock::force(&DIGIT_RUN_RE);
193    }
194
195    #[test]
196    fn an_unreachably_large_digit_threshold_redacts_nothing() {
197        // `\d{usize::MAX,}` cannot compile; the run-length comparison can.
198        let redactor = TranscriptRedactor::new().long_digits(usize::MAX);
199        assert_eq!(redactor.redact("code 123456789".into()), "code 123456789");
200    }
201
202    #[test]
203    fn digit_runs_shorter_than_the_threshold_are_kept() {
204        let redactor = TranscriptRedactor::new().long_digits(4);
205        assert_eq!(
206            redactor.redact("12 and 1234 and 12345".into()),
207            format!("12 and {NUMBER_REPLACEMENT} and {NUMBER_REPLACEMENT}")
208        );
209    }
210
211    fn full() -> TranscriptRedactor {
212        TranscriptRedactor::new().card_numbers().long_digits(6)
213    }
214
215    #[test]
216    fn redacts_a_spoken_card_number_keeping_last_four() {
217        assert_eq!(
218            full().redact("it's 4111 1111 1111 1111 thanks".into()),
219            "it's [card ending 1111] thanks"
220        );
221        // Dashed and unseparated forms too.
222        assert_eq!(
223            full().redact("4012-8888-8888-1881".into()),
224            "[card ending 1881]"
225        );
226        assert_eq!(
227            full().redact("378282246310005".into()),
228            "[card ending 0005]",
229            "15-digit card numbers are in range"
230        );
231    }
232
233    #[test]
234    fn luhn_failures_are_not_cards_but_still_hit_the_digit_rule() {
235        // 16 digits, wrong checksum: not a card, but still a long number.
236        assert_eq!(
237            full().redact("ref 4111111111111112".into()),
238            format!("ref {NUMBER_REPLACEMENT}")
239        );
240        // Without the digit rule it passes through untouched.
241        assert_eq!(
242            TranscriptRedactor::new()
243                .card_numbers()
244                .redact("ref 4111111111111112".into()),
245            "ref 4111111111111112"
246        );
247    }
248
249    #[test]
250    fn short_numbers_survive_otp_length_does_not() {
251        assert_eq!(
252            full().redact("table for 4 at 19:00".into()),
253            "table for 4 at 19:00"
254        );
255        assert_eq!(
256            full().redact("the code is 493028".into()),
257            format!("the code is {NUMBER_REPLACEMENT}")
258        );
259    }
260
261    #[test]
262    fn custom_patterns_apply() {
263        let redactor = TranscriptRedactor::new()
264            .pattern(Regex::new(r"[STFG]\d{7}[A-Z]").unwrap(), "[redacted id]");
265        assert_eq!(
266            redactor.redact("my id is S1234567D ok".into()),
267            "my id is [redacted id] ok"
268        );
269    }
270
271    #[test]
272    fn inactive_redactor_reports_itself() {
273        assert!(!TranscriptRedactor::new().is_active());
274        assert!(TranscriptRedactor::new().card_numbers().is_active());
275    }
276}