diff --git a/Cargo.lock b/Cargo.lock index ae79bc9b..0f6db30f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1779,7 +1779,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.3", + "socket2 0.5.10", "system-configuration", "tokio", "tower-service", @@ -2731,7 +2731,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2 0.6.3", + "socket2 0.5.10", "thiserror 2.0.18", "tokio", "tracing", @@ -2769,7 +2769,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.3", + "socket2 0.5.10", "tracing", "windows-sys 0.60.2", ] @@ -3538,6 +3538,19 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "serde_yaml_ng" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" +dependencies = [ + "indexmap 2.13.0", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serdect" version = "0.2.0" @@ -4082,6 +4095,7 @@ dependencies = [ "tokio", "tracing", "tw-crypto", + "tw-guard", "url", "utoipa", "uuid", @@ -4121,6 +4135,7 @@ dependencies = [ "tokio-stream", "tracing", "tw-dialect", + "tw-guard", "tw-types", "tw-upstream", "tw-wire", @@ -4200,6 +4215,7 @@ dependencies = [ "tracing-subscriber", "tw-crypto", "tw-dialect", + "tw-guard", "tw-types", "url", "utoipa", @@ -4659,8 +4675,8 @@ dependencies = [ [[package]] name = "tw-crypto" -version = "0.35.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.35.0#f7590fa074c1fd068f6ac5156588a98a87d5b032" +version = "0.37.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.37.0#62b818634a660cbce419e26d45e3d8e9f792ccd9" dependencies = [ "aes-gcm", "anyhow", @@ -4672,17 +4688,40 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.35.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.35.0#f7590fa074c1fd068f6ac5156588a98a87d5b032" +version = "0.37.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.37.0#62b818634a660cbce419e26d45e3d8e9f792ccd9" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "tw-guard" +version = "0.37.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.37.0#62b818634a660cbce419e26d45e3d8e9f792ccd9" dependencies = [ + "base64 0.22.1", + "regex", "serde", "serde_json", + "serde_yaml_ng", + "thiserror 2.0.18", + "tw-dialect", + "tw-secret", +] + +[[package]] +name = "tw-secret" +version = "0.37.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.37.0#62b818634a660cbce419e26d45e3d8e9f792ccd9" +dependencies = [ + "thiserror 2.0.18", ] [[package]] name = "tw-types" -version = "0.35.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.35.0#f7590fa074c1fd068f6ac5156588a98a87d5b032" +version = "0.37.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.37.0#62b818634a660cbce419e26d45e3d8e9f792ccd9" dependencies = [ "serde", "serde_json", @@ -4691,8 +4730,8 @@ dependencies = [ [[package]] name = "tw-upstream" -version = "0.35.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.35.0#f7590fa074c1fd068f6ac5156588a98a87d5b032" +version = "0.37.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.37.0#62b818634a660cbce419e26d45e3d8e9f792ccd9" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -4705,8 +4744,8 @@ dependencies = [ [[package]] name = "tw-wire" -version = "0.35.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.35.0#f7590fa074c1fd068f6ac5156588a98a87d5b032" +version = "0.37.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.37.0#62b818634a660cbce419e26d45e3d8e9f792ccd9" dependencies = [ "bytes", "chrono", @@ -4771,6 +4810,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + [[package]] name = "untrusted" version = "0.9.0" @@ -5110,7 +5155,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 95365430..0b7bb0d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,11 +47,12 @@ strip = "symbols" # One copy, not two. Code that lives in core is used from core directly, # never re-exported through a local shim — the envelope layout in # tw-crypto already drifted by 61 lines once, while two copies existed. -tw-crypto = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.35.0" } -tw-dialect = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.35.0" } -tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.35.0" } -tw-upstream = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.35.0" } -tw-wire = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.35.0" } +tw-crypto = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.37.0" } +tw-dialect = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.37.0" } +tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.37.0" } +tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.37.0" } +tw-upstream = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.37.0" } +tw-wire = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.37.0" } # Web framework axum = { version = "0.8", features = ["macros", "ws"] } @@ -141,3 +142,4 @@ think-watch-common = { path = "crates/common" } think-watch-auth = { path = "crates/auth" } think-watch-gateway = { path = "crates/gateway" } think-watch-mcp-gateway = { path = "crates/mcp-gateway" } + diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index dbf21a3e..d0fe4b2e 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -4,6 +4,7 @@ version.workspace = true edition.workspace = true [dependencies] +tw-guard = { workspace = true } tw-crypto = { workspace = true } axum = { workspace = true } sqlx = { workspace = true } diff --git a/crates/common/src/pii.rs b/crates/common/src/pii.rs index 325308fd..8a18f92f 100644 --- a/crates/common/src/pii.rs +++ b/crates/common/src/pii.rs @@ -1,153 +1,113 @@ -//! Cross-crate PII redaction primitive. +//! PII patterns, and the at-rest redactor. //! -//! Lives in `common` (not `gateway`) so the mcp-gateway crate can -//! use it without inverting the dep graph. The gateway crate's -//! `pii_redactor::PiiRedactor` keeps its request-level redaction -//! API (which walks the decoded request from `tw-dialect`) and -//! delegates blob redaction to this module's -//! [`BlobRedactor`]. +//! The patterns live in `security.pii_redactor_patterns`. Two surfaces use +//! them, and both must see the same set — a pattern added in the admin UI +//! that one surface skips is a leak nobody notices: //! -//! ## Why blob vs message redaction is split +//! * **In flight** (gateway only): PII in the caller's request is swapped +//! for placeholders (`{{EMAIL_1}}`) before it goes upstream, and put back +//! in the response for this caller. `gateway::pii_redactor` owns that. +//! * **At rest** (both gateways): request and response bodies, tool +//! arguments and tool results are written to the audit log. The row is +//! write-only, so matches become `{{REDACTED_}}` and nothing is +//! kept to restore them. That is [`BlobRedactor`]. //! -//! Two distinct use cases: -//! -//! * **In-flight redaction** (gateway only): the user's request goes -//! upstream with PII replaced by placeholders (`{{EMAIL_1}}`), -//! and the upstream response is restored back to the original PII -//! for THIS caller. Needs a per-request restoration context. -//! `gateway::pii_redactor::PiiRedactor::redact_messages` owns -//! this. -//! -//! * **At-rest redaction**: the audit pipeline serializes -//! `request_body` / `response_body` / `tool_arguments` / -//! `tool_result` and writes them into ClickHouse. The audit row -//! is WRITE-ONLY (the user's response was already restored from -//! the in-flight context); no restoration needed. Pure substring -//! replacement with a `{{REDACTED_}}` marker is sufficient. -//! This is what [`BlobRedactor`] does. -//! -//! Both halves load the same pattern set from -//! `security.pii_redactor_patterns` so a rule added via the admin -//! UI applies to BOTH redaction surfaces consistently. +//! Matching is thinkwatch-core's (`tw-guard`), the same engine the desktop +//! gateway redacts with; the patterns are ours. + +use std::sync::Arc; -use regex::Regex; use serde::{Deserialize, Serialize}; +use tw_guard::redact::rules::RuleSet; -/// Pattern config as persisted in `system_settings`. Mirrors the -/// gateway-side shape exactly because both crates deserialize from -/// the same JSON value. The `placeholder_prefix` field is unused -/// by `BlobRedactor` (placeholders are write-only, no per-match -/// salt needed) but kept on the struct so config edits don't have -/// to fork into two schemas. +/// A pattern as persisted in `system_settings`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PiiPatternConfig { pub name: String, pub regex: String, + /// The label in the placeholder: `EMAIL` in `{{EMAIL_1}}`. pub placeholder_prefix: String, } -#[derive(Clone)] -struct CompiledPattern { - name: String, - regex: Regex, +/// The rule set for these patterns: one rule per pattern, labelled with +/// its prefix. +/// +/// A pattern that does not compile is skipped, loudly — the save-time +/// validator should have refused it, and one bad row should not take all +/// redaction offline. +pub fn rules(configs: &[PiiPatternConfig]) -> RuleSet { + configs.iter().fold(RuleSet::none(), |set, c| { + match set + .clone() + .with_labeled(&c.name, &c.regex, Some(&c.placeholder_prefix)) + { + Ok(next) => next, + Err(e) => { + tracing::error!( + pattern = %c.name, + error = %e, + "Invalid PII regex — pattern is DISABLED for redaction" + ); + metrics::counter!("pii_pattern_invalid_total", "pattern" => c.name.clone()) + .increment(1); + set + } + } + }) +} + +/// Replace every match in `input` with `{{REDACTED_}}`. +/// Nothing is kept to restore them: the result is write-only audit data. +pub fn redact_blob(rules: &RuleSet, input: &str) -> String { + if rules.is_empty() { + return input.to_string(); + } + let hits = tw_guard::redact::rules::scan_text(input, rules); + let mut out = input.to_string(); + for h in hits.iter().rev() { + out.replace_range( + h.bytes.clone(), + &format!("{{{{REDACTED_{}}}}}", h.rule.id()), + ); + } + out } -/// Stateless, thread-safe blob redactor. Construct once at startup -/// (or hot-swap when the operator edits patterns), wrap in -/// `Arc>` for cheap reads on the hot path. `redact_blob` -/// is `O(N · M)` worst case where N is pattern count and M is body -/// length — same as the gateway's in-flight redactor. -#[derive(Clone, Default)] +/// The at-rest redactor, for a caller that holds no in-flight redactor +/// (the MCP gateway). Hot-swapped with the patterns. +#[derive(Clone)] pub struct BlobRedactor { - patterns: Vec, + rules: Arc, +} + +impl Default for BlobRedactor { + fn default() -> Self { + Self { + rules: Arc::new(RuleSet::none()), + } + } } impl std::fmt::Debug for BlobRedactor { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("BlobRedactor") - .field("pattern_count", &self.patterns.len()) - .finish() + f.debug_struct("BlobRedactor").finish_non_exhaustive() } } impl BlobRedactor { - /// Build a redactor from the same config shape the gateway uses. - /// Invalid regexes are skipped with a loud `tracing::error!` and - /// a metric increment — same fail-soft posture as - /// `gateway::pii_redactor::PiiRedactor::from_config` because an - /// operator save-time validator should have rejected the bad - /// pattern before it reached us, and an unparseable rule - /// shouldn't keep ALL redaction offline. pub fn from_configs(configs: &[PiiPatternConfig]) -> Self { - let patterns = configs - .iter() - .filter_map(|c| match crate::regex_util::compile_bounded(&c.regex) { - Ok(regex) => Some(CompiledPattern { - name: c.name.clone(), - regex, - }), - Err(e) => { - tracing::error!( - pattern = %c.name, - error = %e, - "Invalid PII regex — pattern is DISABLED for blob redaction" - ); - metrics::counter!( - "blob_redactor_pattern_invalid_total", - "pattern" => c.name.clone(), - ) - .increment(1); - None - } - }) - .collect(); - Self { patterns } + Self { + rules: Arc::new(rules(configs)), + } } - /// `true` when there are no compiled patterns — callers can - /// skip the redact pass entirely (avoids the per-message - /// `.to_string()` copy). + /// No patterns: callers can skip the pass (and its copy) entirely. pub fn is_empty(&self) -> bool { - self.patterns.is_empty() + self.rules.is_empty() } - /// Apply all configured patterns to an arbitrary serialized blob. - /// Result has matched substrings replaced by - /// `{{REDACTED_}}` markers. Overlapping matches are - /// resolved deterministically (longest-match-wins on tie) so - /// re-running the redactor on the same input is idempotent. pub fn redact_blob(&self, input: &str) -> String { - if self.patterns.is_empty() { - return input.to_string(); - } - // Gather all matches first so overlapping patterns get a - // deterministic non-overlapping resolution. - let mut all_matches: Vec<(usize, usize, usize)> = Vec::new(); - for (pattern_idx, pattern) in self.patterns.iter().enumerate() { - for m in pattern.regex.find_iter(input) { - all_matches.push((m.start(), m.end(), pattern_idx)); - } - } - if all_matches.is_empty() { - return input.to_string(); - } - // Sort earliest-start first, longest-match-wins on tie. - all_matches.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| (b.1 - b.0).cmp(&(a.1 - a.0)))); - let mut filtered: Vec<(usize, usize, usize)> = Vec::new(); - for m in &all_matches { - if filtered.iter().all(|f| m.0 >= f.1 || m.1 <= f.0) { - filtered.push(*m); - } - } - // Reverse so replace_range from-end-first keeps earlier - // indices valid. - filtered.sort_by_key(|b| std::cmp::Reverse(b.0)); - let mut result = input.to_string(); - for (start, end, pattern_idx) in filtered { - let replacement = format!("{{{{REDACTED_{}}}}}", self.patterns[pattern_idx].name); - result.replace_range(start..end, &replacement); - } - result + redact_blob(&self.rules, input) } } diff --git a/crates/gateway/Cargo.toml b/crates/gateway/Cargo.toml index 2c7567f0..6e5fad2a 100644 --- a/crates/gateway/Cargo.toml +++ b/crates/gateway/Cargo.toml @@ -4,6 +4,7 @@ version.workspace = true edition.workspace = true [dependencies] +tw-guard = { workspace = true } tw-types = { workspace = true } tw-dialect = { workspace = true } tw-upstream = { workspace = true, features = ["bedrock"] } diff --git a/crates/gateway/src/pii_redactor.rs b/crates/gateway/src/pii_redactor.rs index 99e1b60a..1513f15a 100644 --- a/crates/gateway/src/pii_redactor.rs +++ b/crates/gateway/src/pii_redactor.rs @@ -1,235 +1,55 @@ -use regex::Regex; -use std::collections::HashMap; -use std::sync::LazyLock; - -/// Serializable PII pattern for storage in system_settings. -#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] -pub struct PiiPatternConfig { - pub name: String, - pub regex: String, - pub placeholder_prefix: String, -} - -/// Detects and replaces PII in user messages before sending to upstream LLMs, -/// then restores original values in the response. -#[derive(Clone)] -pub struct PiiRedactor { - patterns: Vec, -} - -#[derive(Clone)] -struct PiiPattern { - name: String, - regex: Regex, - placeholder_prefix: String, -} - -/// Holds the mapping from placeholders back to original PII values. -pub struct RedactionContext { - /// Maps placeholder (e.g. `{{EMAIL_1}}`) to original value. - pub replacements: HashMap, -} +//! In-flight PII redaction: swap the caller's PII for placeholders before +//! the request goes upstream, and put it back in what comes back. +//! +//! The patterns, and the engine that matches and restores them, are shared +//! (see `think_watch_common::pii`); this file is the part only an +//! in-flight redactor needs — which parts of a request to look at, and +//! how the values found there reach the request actually sent. + +use serde_json::Value; +use think_watch_common::pii::PiiPatternConfig; +use tw_guard::redact::replace::{Ledger, Scheme}; +use tw_guard::redact::rules::RuleSet; + +/// `{{EMAIL_1}}`. The label tells the model what used to be there, so it +/// can still answer sensibly; a pattern without one would read `{{PII_1}}`. +pub const SCHEME: Scheme = Scheme { + open: "{{", + close: "}}", + label: "PII", +}; /// Keys that carry base64 in a request. Replacement never enters them: a /// digit run landing inside an encoded image is unlikely, but where it /// happens the thing changed is the image, not the PII. const BASE64_CARRIERS: &[&str] = &["data", "bytes"]; -impl RedactionContext { - /// Carry the found PII onto a **raw** request. - /// - /// A request forwarded in its own format never goes through the - /// decoded form — that is how `cache_control` and everything else - /// the decoded form does not model survive. But PII is found on the - /// decoded form, where the structure is known, so the - /// value → placeholder mapping has to be carried back onto the raw - /// JSON. - /// - /// **On the parsed `Value`, not the bytes**: a client may send `@` as - /// `\u0040`, and the bytes would not contain the value at all. - /// - /// Longer values first, so `a@x.com` does not eat part of `aa@x.com`. - /// - /// A value that also appears in the system prompt is replaced there - /// too — which only happens when the caller also wrote it. - pub fn apply_to(&self, value: &mut serde_json::Value) { - if self.replacements.is_empty() { - return; - } - let mut pairs: Vec<(&str, &str)> = self - .replacements - .iter() - .map(|(ph, orig)| (orig.as_str(), ph.as_str())) - .collect(); - pairs.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(b.0))); - walk_strings(value, &mut |s| { - for (orig, ph) in &pairs { - if s.contains(orig) { - *s = s.replace(orig, ph); - } - } - }); - } - - /// Paint the original values back into a whole response's bytes. - /// - /// A whole response has its placeholders intact, so this works on the - /// bytes. Each original is JSON-escaped first — one containing a quote, - /// put back as-is, would break the document. A stream cannot be done - /// this way: a placeholder split across two frames is not contiguous in - /// the byte stream (see [`PiiStreamRestorer`]). - pub fn restore_bytes(&self, body: &[u8]) -> Vec { - if self.replacements.is_empty() { - return body.to_vec(); - } - let mut text = String::from_utf8_lossy(body).into_owned(); - for (ph, orig) in &self.replacements { - if text.contains(ph.as_str()) { - let escaped = serde_json::to_string(orig).unwrap_or_default(); - // Drop the quotes `to_string` added; keep the escaping. - let inner = &escaped[1..escaped.len().saturating_sub(1)]; - text = text.replace(ph.as_str(), inner); - } - } - text.into_bytes() - } -} - -fn walk_strings(v: &mut serde_json::Value, f: &mut impl FnMut(&mut String)) { - match v { - serde_json::Value::String(s) => f(s), - serde_json::Value::Array(items) => items.iter_mut().for_each(|i| walk_strings(i, f)), - serde_json::Value::Object(map) => { - for (k, child) in map.iter_mut() { - if !BASE64_CARRIERS.contains(&k.as_str()) { - walk_strings(child, f); - } - } - } - _ => {} - } -} - -impl Default for PiiRedactor { - fn default() -> Self { - Self::new() - } +/// Detects PII in the caller's text and swaps it for placeholders. +#[derive(Clone)] +pub struct PiiRedactor { + rules: RuleSet, } impl PiiRedactor { - /// Create a PII redactor from a list of pattern configs (from DynamicConfig). - /// - /// Each pattern is compiled through - /// `think_watch_common::regex_util::compile_bounded` so an operator - /// who saves a pathological pattern can't DOS the redactor — - /// every gateway request would otherwise pay seconds of regex - /// engine work per inbound message. pub fn from_config(configs: &[PiiPatternConfig]) -> Self { - let patterns = configs - .iter() - .filter_map( - |c| match think_watch_common::regex_util::compile_bounded(&c.regex) { - Ok(regex) => Some(PiiPattern { - name: c.name.clone(), - regex, - placeholder_prefix: c.placeholder_prefix.clone(), - }), - Err(e) => { - // Save-time validation in admin/settings should prevent - // invalid patterns from ever reaching us. If one shows - // up here it means the DB row was hand-edited or the - // validator drifted — either way, surface loudly so - // operators don't think PII redaction is on when it - // silently isn't. - tracing::error!( - pattern = %c.name, - error = %e, - "Invalid PII regex — pattern is DISABLED for redaction" - ); - metrics::counter!( - "gateway_pii_pattern_invalid_total", - "pattern" => c.name.clone(), - ) - .increment(1); - None - } - }, - ) - .collect(); - Self { patterns } - } - - pub fn new() -> Self { - // Static compiled regexes — compiled once, reused across all - // PiiRedactor instances and requests. - static RE_EMAIL: LazyLock = LazyLock::new(|| { - Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}").unwrap() - }); - static RE_ID_CARD_CN: LazyLock = - LazyLock::new(|| Regex::new(r"\b\d{17}[\dXx]\b").unwrap()); - static RE_CREDIT_CARD: LazyLock = - LazyLock::new(|| Regex::new(r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b").unwrap()); - static RE_PHONE_CN: LazyLock = LazyLock::new(|| Regex::new(r"1[3-9]\d{9}").unwrap()); - static RE_PHONE_US: LazyLock = - LazyLock::new(|| Regex::new(r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b").unwrap()); - static RE_IPV4: LazyLock = - LazyLock::new(|| Regex::new(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b").unwrap()); - - // Order matters: longer/more specific patterns must come before shorter ones - // to prevent partial matches (e.g. phone patterns matching inside credit cards). - let patterns = vec![ - PiiPattern { - name: "email".into(), - regex: RE_EMAIL.clone(), - placeholder_prefix: "EMAIL".into(), - }, - PiiPattern { - name: "id_card_cn".into(), - regex: RE_ID_CARD_CN.clone(), - placeholder_prefix: "ID".into(), - }, - PiiPattern { - name: "credit_card".into(), - regex: RE_CREDIT_CARD.clone(), - placeholder_prefix: "CARD".into(), - }, - PiiPattern { - name: "phone_cn".into(), - regex: RE_PHONE_CN.clone(), - placeholder_prefix: "PHONE".into(), - }, - PiiPattern { - name: "phone_us".into(), - regex: RE_PHONE_US.clone(), - placeholder_prefix: "PHONE".into(), - }, - PiiPattern { - name: "ipv4".into(), - regex: RE_IPV4.clone(), - placeholder_prefix: "IP".into(), - }, - ]; - - Self { patterns } + Self { + rules: think_watch_common::pii::rules(configs), + } } /// Redact one piece of text. For the admin "try these patterns" /// endpoint, and anything else that holds plain text rather than a /// request. - pub fn redact_str(&self, text: &str) -> (String, RedactionContext) { - let mut counters = HashMap::new(); - let mut replacements = HashMap::new(); - let out = self.redact_text(text, &mut counters, &mut replacements, "text"); - (out, RedactionContext { replacements }) + pub fn redact_str(&self, text: &str) -> (String, Ledger) { + let r = tw_guard::redact::replace::redact_text(text, &self.rules, Ledger::new(SCHEME)); + (r.text, r.ledger) } /// Redact the caller's text in a decoded request. /// - /// The decoded form's structure is known, which the earlier version — - /// guessing at a `serde_json::Value` for a string or a `text` field — - /// never had: it missed text nested in Anthropic `tool_result` blocks, - /// the array form of `system`, and Responses parts whose text field is - /// not called `text`. + /// The decoded form's structure is known: text nested in a tool + /// result, the array form of `system`, a Responses part whose text + /// field is not called `text` — all of them are just parts here. /// /// Only user messages are redacted; assistant turns pass through. /// @@ -237,316 +57,111 @@ impl PiiRedactor { /// the operator, not typed by the caller; redacting an address or IP /// in it rewrites the operator's instructions, and such values there /// are configuration, not user PII. - pub fn redact_request(&self, request: &mut tw_dialect::ir::Request) -> RedactionContext { + pub fn redact_request(&self, request: &mut tw_dialect::ir::Request) -> Ledger { use tw_dialect::ir::Role; - let mut counters: HashMap = HashMap::new(); - let mut replacements: HashMap = HashMap::new(); - - for msg in &mut request.messages { - if msg.role != Role::User { - continue; - } - self.redact_parts( - &mut msg.parts, - &mut counters, - &mut replacements, - "user message", - ); + let mut ledger = Ledger::new(SCHEME); + if self.rules.is_empty() { + return ledger; } - - RedactionContext { replacements } - } - - /// Apply the redaction patterns to a single text blob. Shared - /// between the single-string and multimodal-array branches of - /// `redact_messages` so both shapes get identical treatment. - fn redact_text( - &self, - content_str: &str, - counters: &mut HashMap, - replacements: &mut HashMap, - log_origin: &str, - ) -> String { - let mut all_matches: Vec<(usize, usize, usize)> = Vec::new(); - for (pattern_idx, pattern) in self.patterns.iter().enumerate() { - for m in pattern.regex.find_iter(content_str) { - all_matches.push((m.start(), m.end(), pattern_idx)); - } - } - - if all_matches.is_empty() { - return content_str.to_string(); - } - - all_matches.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| (b.1 - b.0).cmp(&(a.1 - a.0)))); - - let mut filtered: Vec<(usize, usize, usize)> = Vec::new(); - for m in &all_matches { - if filtered.iter().all(|f| m.0 >= f.1 || m.1 <= f.0) { - filtered.push(*m); + for msg in &mut request.messages { + if msg.role == Role::User { + ledger = self.redact_parts(&mut msg.parts, ledger); } } - filtered.sort_by_key(|b| std::cmp::Reverse(b.0)); - - let redacted_pattern_names: Vec = filtered - .iter() - .map(|(_, _, idx)| self.patterns[*idx].name.clone()) - .collect(); - - let mut redacted_content = content_str.to_string(); - for (start, end, pattern_idx) in filtered { - let pattern = &self.patterns[pattern_idx]; - let matched_value = redacted_content[start..end].to_string(); - // One placeholder per value. A model shown `{{EMAIL_1}}` and - // `{{EMAIL_2}}` treats them as two people; and a forwarded - // request needs value → placeholder to be a function to carry - // it onto the raw JSON. - let prefix = format!("{{{{{}_", pattern.placeholder_prefix); - let existing = replacements - .iter() - .find(|(ph, orig)| ph.starts_with(&prefix) && **orig == matched_value) - .map(|(ph, _)| ph.clone()); - let placeholder = match existing { - Some(ph) => ph, - None => { - let counter = counters - .entry(pattern.placeholder_prefix.clone()) - .or_insert(0); - *counter += 1; - let ph = format!("{{{{{}_{}}}}}", pattern.placeholder_prefix, counter); - replacements.insert(ph.clone(), matched_value); - ph - } - }; - redacted_content.replace_range(start..end, &placeholder); + if !ledger.is_empty() { + tracing::debug!(values = ledger.len(), "PII redacted"); } - - if !redacted_pattern_names.is_empty() { - tracing::debug!( - patterns = ?redacted_pattern_names, - count = redacted_pattern_names.len(), - origin = log_origin, - "PII redacted" - ); - } - - redacted_content + ledger } - /// The recursive part of [`Self::redact_request`]: redact a list of - /// parts in place. + /// Redact a list of parts in place. /// /// `Part::ToolResult` is recursed into. Tool results often carry data - /// a tool fetched on the user's behalf — a mailbox, an order — and the - /// earlier `Value`-based redactor had no notion of a tool result at - /// all. + /// a tool fetched on the user's behalf — a mailbox, an order. /// /// `Image` / `File` / `Thinking` / `ToolCall` are left alone: media is /// not redactable text, thinking is the model's own reasoning, and /// changing `ToolCall.input` would break the call itself. - fn redact_parts( - &self, - parts: &mut [tw_dialect::ir::Part], - counters: &mut HashMap, - replacements: &mut HashMap, - log_origin: &str, - ) { + fn redact_parts(&self, parts: &mut [tw_dialect::ir::Part], mut ledger: Ledger) -> Ledger { use tw_dialect::ir::Part; for part in parts { match part { Part::Text(s) => { - *s = self.redact_text(s, counters, replacements, log_origin); - } - Part::ToolResult(r) => { - self.redact_parts( - &mut r.content, - counters, - replacements, - "user message (tool result)", - ); + let r = tw_guard::redact::replace::redact_text(s, &self.rules, ledger); + *s = r.text; + ledger = r.ledger; } + Part::ToolResult(r) => ledger = self.redact_parts(&mut r.content, ledger), Part::Image(_) | Part::File { .. } | Part::Thinking(_) | Part::ToolCall(_) => {} } } + ledger } - /// Apply redaction patterns to an arbitrary serialized blob (e.g. - /// a JSON string going into the audit log). Drops the per-match - /// restoration context — the result is write-only audit data, - /// never round-tripped back to a caller, so we replace with the - /// pattern name alone instead of a position-salted placeholder. - /// - /// Used by the body-capture pipeline when an operator sets - /// `audit.body_redact_pii = true`. Distinct from - /// `redact_messages` which is the in-flight redactor that DOES - /// need a restoration context so the user's own response can be - /// painted with the original PII. + /// Redact a serialized blob for the audit log. See + /// `think_watch_common::pii::redact_blob`. pub fn redact_blob(&self, input: &str) -> String { - if self.patterns.is_empty() { - return input.to_string(); - } - // Gather all matches first so overlapping patterns get a - // deterministic non-overlapping resolution (longest match - // wins on tie) — same algorithm as `redact_text` to keep the - // in-flight and at-rest redaction story consistent. - let mut all_matches: Vec<(usize, usize, usize)> = Vec::new(); - for (pattern_idx, pattern) in self.patterns.iter().enumerate() { - for m in pattern.regex.find_iter(input) { - all_matches.push((m.start(), m.end(), pattern_idx)); - } - } - if all_matches.is_empty() { - return input.to_string(); - } - all_matches.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| (b.1 - b.0).cmp(&(a.1 - a.0)))); - let mut filtered: Vec<(usize, usize, usize)> = Vec::new(); - for m in &all_matches { - if filtered.iter().all(|f| m.0 >= f.1 || m.1 <= f.0) { - filtered.push(*m); - } - } - filtered.sort_by_key(|b| std::cmp::Reverse(b.0)); - - let mut result = input.to_string(); - for (start, end, pattern_idx) in filtered { - let replacement = format!("{{{{REDACTED_{}}}}}", self.patterns[pattern_idx].name); - result.replace_range(start..end, &replacement); - } - result + think_watch_common::pii::redact_blob(&self.rules, input) } } -/// Stateful restorer for streaming responses. Placeholders have the -/// shape `{{TYPE_SALT_N}}` which a token stream may fragment across -/// arbitrary chunks — `{{` in one chunk and `EMAIL_abc_1}}` in the next. +/// Carry the PII found on the decoded request onto the **raw** one. /// -/// The restorer buffers the tail of unflushed content whenever it sees -/// an unclosed `{{` (or a lone trailing `{` that might be the start of -/// one) and releases it as soon as the closing `}}` arrives. All -/// complete placeholders are replaced with their original values before -/// emission; anything that *looks* like a placeholder but doesn't match -/// any known key passes through verbatim. +/// A request forwarded in its own format never goes through the decoded +/// form — that is how `cache_control` and everything else the decoded +/// form does not model survive. But PII is found on the decoded form, +/// where the structure is known, so the value → placeholder mapping has +/// to be carried back onto the raw JSON. /// -/// Emit ordering is preserved: the concatenation of `process()` outputs -/// plus the final `flush()` equals what `restore_response` would return -/// for the same content seen as a single string. -pub struct PiiStreamRestorer { - /// Placeholder → original lookup. Cloned out of a RedactionContext - /// because we need ownership once and it's cheap (typically < 10 entries). - replacements: HashMap, - /// Unflushed tail that might still grow into a complete placeholder. - buffer: String, -} - -impl PiiStreamRestorer { - pub fn new(ctx: &RedactionContext) -> Self { - Self { - replacements: ctx.replacements.clone(), - buffer: String::new(), - } - } - - /// Returns true when the restorer has no work to do — callers can - /// short-circuit and pass the chunk through untouched. - pub fn is_noop(&self) -> bool { - self.replacements.is_empty() - } - - /// Feed the next piece of decoded content. Returns whatever is safe - /// to emit now (placeholders already restored). The unreleased tail - /// stays in the buffer for the next call. - pub fn process(&mut self, next: &str) -> String { - if self.is_noop() { - // Nothing to restore; never buffer — avoid introducing - // latency when the feature isn't even active. - return next.to_string(); - } - self.buffer.push_str(next); - let cut = Self::safe_emit_boundary(&self.buffer); - if cut == 0 { - return String::new(); +/// **On the parsed `Value`, not the bytes**: a client may send `@` as an +/// escape sequence, and the bytes would not contain the value at all. +/// +/// Longer values first, so `a@x.com` does not eat part of `aa@x.com`. +/// +/// A value that also appears in the system prompt is replaced there too — +/// which only happens when the caller also wrote it. +pub fn apply_to(ledger: &Ledger, value: &mut Value) { + if ledger.is_empty() { + return; + } + let mut pairs: Vec<(&str, &str)> = ledger.replacements().collect(); + pairs.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(b.0))); + walk_strings(value, &mut |s| { + for (orig, ph) in &pairs { + if s.contains(orig) { + *s = s.replace(orig, ph); + } } - // Emit [0..cut) with replacements; keep [cut..) in the buffer. - let emit_slice = self.buffer[..cut].to_string(); - let restored = self.restore_complete(&emit_slice); - self.buffer.drain(..cut); - restored - } + }); +} - /// One-shot restoration for a string that is NOT part of the - /// streaming content path (typically an error message or a cached - /// chunk). Does not touch the internal buffer, so a successful - /// chunk's unflushed tail survives — important when an upstream - /// error interrupts a stream mid-placeholder and we still want the - /// trailing `flush()` to behave correctly. - pub fn restore_oneshot(&self, s: &str) -> String { - self.restore_complete(s) +/// Paint the original values back into a whole response's bytes, each +/// JSON-escaped. A stream is restored frame by frame instead (see +/// `proxy::shaper`): there a placeholder can be split across frames. +pub fn restore_body(ledger: &Ledger, body: &[u8]) -> Vec { + if ledger.is_empty() { + return body.to_vec(); } - - /// Final drain — called once when the source stream ends. Any - /// residual buffer is emitted verbatim (an unterminated `{{...` at - /// the very end of a stream never becomes a placeholder, so the - /// safest thing is to let the client see what the upstream actually - /// said). - pub fn flush(&mut self) -> String { - if self.buffer.is_empty() { - return String::new(); - } - let out = self.restore_complete(&self.buffer); - self.buffer.clear(); - out - } - - /// Replace every known placeholder in `s` with its original value. - /// Linear in `s.len() × replacements.len()`; the replacements map - /// is expected to be small (single-digit entries) so the nested - /// loop is fine in practice. - fn restore_complete(&self, s: &str) -> String { - let mut out = s.to_string(); - for (placeholder, original) in &self.replacements { - if out.contains(placeholder) { - out = out.replace(placeholder, original); - } - } - out + match std::str::from_utf8(body) { + Ok(text) => tw_guard::redact::replace::restore_json(text, ledger).into_bytes(), + Err(_) => body.to_vec(), } +} - /// Given a buffer, return the byte index up to which it is safe to - /// emit now. Everything from the returned index onwards must stay - /// buffered because it might still grow into a `{{...}}` placeholder. - /// - /// Rules: - /// 1. Find the rightmost `{{`. If there is no matching `}}` after - /// it, cut there — that `{{` is still open. - /// 2. Otherwise, if the buffer ends with a single `{`, cut one - /// byte back so the next chunk's leading `{` can join it. - /// 3. Otherwise, the whole buffer is releasable. - fn safe_emit_boundary(buf: &str) -> usize { - let bytes = buf.as_bytes(); - if let Some(open_pos) = buf.rfind("{{") { - // Is there a `}}` strictly after the `{{`? Start looking - // two bytes past the `{{` so a literal `{{}}` doesn't - // match itself (nonsense but cheap to guard). - let after_open = open_pos + 2; - if after_open >= bytes.len() { - // `{{` at the very end → definitely still open. - return open_pos; - } - if buf[after_open..].contains("}}") { - // Complete placeholder — fall through to the trailing- - // `{` check so we don't release a lone brace. - } else { - return open_pos; +fn walk_strings(v: &mut Value, f: &mut impl FnMut(&mut String)) { + match v { + Value::String(s) => f(s), + Value::Array(items) => items.iter_mut().for_each(|i| walk_strings(i, f)), + Value::Object(map) => { + for (k, child) in map.iter_mut() { + if !BASE64_CARRIERS.contains(&k.as_str()) { + walk_strings(child, f); + } } } - // No unclosed `{{`. But a single trailing `{` could be the - // first half of a future `{{` — hold it back by one byte. - if bytes.last() == Some(&b'{') { - return bytes.len() - 1; - } - bytes.len() + _ => {} } } @@ -554,38 +169,75 @@ impl PiiStreamRestorer { mod tests { use super::*; - /// Find the placeholder replacement that maps to the given original value. + /// The patterns `db/seeds.sql` ships with. + fn seeded() -> PiiRedactor { + let p = |name: &str, regex: &str, prefix: &str| PiiPatternConfig { + name: name.into(), + regex: regex.into(), + placeholder_prefix: prefix.into(), + }; + PiiRedactor::from_config(&[ + p( + "email", + r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", + "EMAIL", + ), + p("id_card_cn", r"\b\d{17}[\dXx]\b", "ID"), + p( + "credit_card", + r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b", + "CARD", + ), + p("phone_cn", r"1[3-9]\d{9}", "PHONE"), + p("phone_us", r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b", "PHONE"), + p("ipv4", r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", "IP"), + ]) + } + + /// A ledger holding exactly these `(label, value)` pairs, issued in + /// order — built through the redactor, the only way to get one. + fn ledger_of(pairs: &[(&str, &str)]) -> Ledger { + let configs: Vec = pairs + .iter() + .enumerate() + .map(|(i, (label, value))| PiiPatternConfig { + name: format!("p{i}"), + regex: regex::escape(value), + placeholder_prefix: label.to_string(), + }) + .collect(); + let text: Vec<&str> = pairs.iter().map(|p| p.1).collect(); + PiiRedactor::from_config(&configs) + .redact_str(&text.join(" ")) + .1 + } + #[test] fn applying_to_a_raw_request_touches_nothing_but_the_redacted_text() { // A request forwarded as sent must reach the upstream whole — // `name`, `cache_control`, everything — apart from the PII. - let ctx = RedactionContext { - replacements: [("{{EMAIL_1}}".to_string(), "alice@example.com".to_string())] - .into_iter() - .collect(), - }; + let ctx = ledger_of(&[("EMAIL", "alice@example.com")]); let mut v = serde_json::json!({ "role": "user", "name": "alice", "content": [{"type": "text", "text": "mail alice@example.com", "cache_control": {"type": "ephemeral"}}] }); - ctx.apply_to(&mut v); + apply_to(&ctx, &mut v); assert_eq!(v["name"], "alice"); assert_eq!(v["content"][0]["cache_control"]["type"], "ephemeral"); assert_eq!(v["content"][0]["text"], "mail {{EMAIL_1}}"); } - fn find_placeholder(ctx: &RedactionContext, original: &str) -> String { - ctx.replacements - .iter() - .find(|(_, v)| v.as_str() == original) - .map(|(k, _)| k.clone()) + fn find_placeholder(ctx: &Ledger, original: &str) -> String { + ctx.replacements() + .find(|(v, _)| *v == original) + .map(|(_, ph)| ph.to_string()) .unwrap_or_else(|| panic!("no placeholder for {original}")) } #[test] fn redact_email() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (redacted, ctx) = redactor.redact_str("Contact me at alice@example.com please"); let content = redacted.as_str(); @@ -597,7 +249,7 @@ mod tests { #[test] fn redact_china_phone() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (redacted, ctx) = redactor.redact_str("Call me at 13812345678"); let content = redacted.as_str(); @@ -609,7 +261,7 @@ mod tests { #[test] fn redact_us_phone() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); // Simplified US phone regex matches 10-digit patterns like 555-123-4567 let (redacted, _ctx) = redactor.redact_str("Call 555-123-4567"); @@ -623,7 +275,7 @@ mod tests { #[test] fn redact_credit_card() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (redacted, ctx) = redactor.redact_str("My card is 4111-1111-1111-1111"); let content = redacted.as_str(); @@ -635,7 +287,7 @@ mod tests { #[test] fn redact_china_id_card() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (redacted, ctx) = redactor.redact_str("ID: 110101199001011234"); let content = redacted.as_str(); @@ -647,7 +299,7 @@ mod tests { #[test] fn redact_ipv4() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (redacted, ctx) = redactor.redact_str("Server is at 192.168.1.100"); let content = redacted.as_str(); @@ -659,12 +311,12 @@ mod tests { #[test] fn restore_response_replaces_placeholders() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (redacted, ctx) = redactor.redact_str("Email alice@example.com and bob@test.org"); // Simulate the LLM echoing back the redacted content let redacted_content = redacted.as_str(); - let content = String::from_utf8(ctx.restore_bytes(redacted_content.as_bytes())).unwrap(); + let content = String::from_utf8(restore_body(&ctx, redacted_content.as_bytes())).unwrap(); assert!(content.contains("alice@example.com"), "got: {content}"); assert!(content.contains("bob@test.org"), "got: {content}"); assert!(!content.contains("{{EMAIL_")); @@ -679,7 +331,7 @@ mod tests { // cache to actually hit. Two callers with identical text // must also have identical contexts (PII values come from // the text itself), so the symmetry is safe. - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (_redacted, ctx) = redactor.redact_str("Reach me at alice@example.com"); let placeholder = find_placeholder(&ctx, "alice@example.com"); assert_eq!( @@ -693,7 +345,7 @@ mod tests { // The cache keys on the redacted request and stores the // placeholder-form response; two callers sharing a slot only // works if redaction is deterministic on the input. - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (_, ctx_a) = redactor.redact_str("alice@example.com"); let (_, ctx_b) = redactor.redact_str("alice@example.com"); let ph_a = find_placeholder(&ctx_a, "alice@example.com"); @@ -706,7 +358,7 @@ mod tests { #[test] fn multiple_pii_types() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let (redacted, ctx) = redactor.redact_str("Email alice@example.com, IP 10.0.0.1, card 4111 1111 1111 1111"); @@ -718,7 +370,7 @@ mod tests { assert!(!content.contains("10.0.0.1")); // Verify restore round-trip - let restored = String::from_utf8(ctx.restore_bytes(content.as_bytes())).unwrap(); + let restored = String::from_utf8(restore_body(&ctx, content.as_bytes())).unwrap(); assert!(restored.contains("alice@example.com"), "got: {restored}"); assert!(restored.contains("10.0.0.1"), "got: {restored}"); } @@ -768,118 +420,6 @@ mod tests { assert!(!content.contains("alice@test.org")); } - // --------------------------------------------------------------- - // PiiStreamRestorer — rebuilds restored text across arbitrary chunk - // boundaries. The invariant we're testing: - // concat(restorer.process(chunk_i) for i in 0..N) + restorer.flush() - // == restore_complete(concat(chunk_i)) - // --------------------------------------------------------------- - - fn sample_ctx() -> RedactionContext { - let mut r = HashMap::new(); - r.insert("{{EMAIL_abc123_1}}".into(), "alice@example.com".into()); - r.insert("{{PHONE_def456_1}}".into(), "13812345678".into()); - RedactionContext { replacements: r } - } - - fn restore_whole(chunks: &[&str]) -> String { - let ctx = sample_ctx(); - let mut r = PiiStreamRestorer::new(&ctx); - let mut out = String::new(); - for c in chunks { - out.push_str(&r.process(c)); - } - out.push_str(&r.flush()); - out - } - - #[test] - fn stream_restore_handles_whole_placeholder_in_one_chunk() { - let out = restore_whole(&["Hi {{EMAIL_abc123_1}}!"]); - assert_eq!(out, "Hi alice@example.com!"); - } - - #[test] - fn stream_restore_reassembles_placeholder_split_across_chunks() { - // Split right after the opening `{{`. - let out = restore_whole(&["Hi {{", "EMAIL_abc123_1}}!"]); - assert_eq!(out, "Hi alice@example.com!"); - } - - #[test] - fn stream_restore_reassembles_single_byte_split() { - // Every boundary case at once — one byte per chunk. - let input = "{{EMAIL_abc123_1}}"; - let chunks: Vec = input.chars().map(|c| c.to_string()).collect(); - let refs: Vec<&str> = chunks.iter().map(|s| s.as_str()).collect(); - let out = restore_whole(&refs); - assert_eq!(out, "alice@example.com"); - } - - #[test] - fn stream_restore_handles_trailing_lone_brace() { - // The first chunk ends with a single `{` — it might be the - // start of a placeholder. Must hold it back. - let out = restore_whole(&["prefix {", "{EMAIL_abc123_1}} tail"]); - assert_eq!(out, "prefix alice@example.com tail"); - } - - #[test] - fn stream_restore_passes_unknown_placeholder_like_tokens_through() { - // The model echoed something that *looks* like a placeholder - // but isn't in the replacements map. Must flow through as-is - // after the closing `}}`, not stay buffered forever. - let out = restore_whole(&["see {{NOT_", "A_REAL_KEY}} done"]); - assert_eq!(out, "see {{NOT_A_REAL_KEY}} done"); - } - - #[test] - fn stream_restore_flush_emits_unterminated_tail_verbatim() { - // Upstream ended mid-placeholder. We don't silently drop the - // tail — emit it so the client at least sees something. - let out = restore_whole(&["oops {{EMAIL_incompl"]); - assert_eq!(out, "oops {{EMAIL_incompl"); - } - - #[test] - fn stream_restore_noop_when_context_is_empty() { - let ctx = RedactionContext { - replacements: HashMap::new(), - }; - let mut r = PiiStreamRestorer::new(&ctx); - assert!(r.is_noop()); - // Even with a `{{` in the input, no buffering happens — we - // want zero latency overhead when the feature isn't active. - let out1 = r.process("partial {{foo"); - assert_eq!(out1, "partial {{foo"); - let out2 = r.process(" bar}}"); - assert_eq!(out2, " bar}}"); - assert_eq!(r.flush(), ""); - } - - #[test] - fn stream_restore_anthropic_style_fragmented_deltas() { - // Mimics Anthropic `content_block_delta` events that each carry - // one or two tokens. Placeholders can land on any boundary. - let out = restore_whole(&[ - "Hello ", - "{{", - "EMAIL_", - "abc123_1", - "}}", - " and ", - "{{PHONE_def456_1}}", - ".", - ]); - assert_eq!(out, "Hello alice@example.com and 13812345678."); - } - - #[test] - fn stream_restore_multiple_placeholders_same_chunk() { - let out = restore_whole(&["a {{EMAIL_abc123_1}} b {{PHONE_def456_1}} c"]); - assert_eq!(out, "a alice@example.com b 13812345678 c"); - } - // ── redact_request: redaction on the decoded request ────────────── use tw_dialect::ir::{Message, Part, Request, Role, ToolResult}; @@ -907,7 +447,7 @@ mod tests { #[test] fn redact_request_redacts_a_plain_text_part_in_a_user_message() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let mut request = ir_request(vec![ir_user_message(vec![Part::Text( "Email me at alice@example.com".into(), )])]); @@ -930,7 +470,7 @@ mod tests { /// order — fed back into the same conversation. #[test] fn redact_request_redacts_pii_nested_inside_a_tool_result() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let mut request = ir_request(vec![ir_user_message(vec![Part::ToolResult(ToolResult { id: "call_1".into(), content: vec![Part::Text( @@ -955,7 +495,7 @@ mod tests { #[test] fn redact_request_does_not_redact_assistant_messages() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let mut request = ir_request(vec![ir_assistant_message(vec![Part::Text( "Sure, contact alice@example.com".into(), )])]); @@ -966,14 +506,14 @@ mod tests { panic!("expected a text part"); }; assert_eq!(text, "Sure, contact alice@example.com"); - assert!(ctx.replacements.is_empty()); + assert!(ctx.is_empty()); } /// The system prompt is the operator's, not the caller's: redacting /// it rewrites the instructions, and values there are configuration. #[test] fn redact_request_does_not_redact_the_system_prompt() { - let redactor = PiiRedactor::new(); + let redactor = seeded(); let mut request = Request { model: "test".into(), system: vec!["Escalate to ops@example.com when unsure.".into()], @@ -995,7 +535,7 @@ mod tests { fn a_value_repeated_across_a_tool_result_restores_everywhere() { // The same value twice gets one placeholder, and both places restore // — including the one inside the tool result. - let redactor = PiiRedactor::new(); + let redactor = seeded(); let mut request = ir_request(vec![ir_user_message(vec![ Part::Text("Contact alice@example.com".into()), Part::ToolResult(ToolResult { @@ -1025,11 +565,7 @@ mod tests { "the same value should get the same placeholder" ); - let restore = |s: &str| { - ctx.replacements - .iter() - .fold(s.to_string(), |acc, (ph, orig)| acc.replace(ph, orig)) - }; + let restore = |s: &str| tw_guard::redact::replace::restore(s, &ctx); assert_eq!(restore(first), "Contact alice@example.com"); assert_eq!(restore(second), "Confirmed: alice@example.com"); } @@ -1037,19 +573,19 @@ mod tests { fn the_same_value_gets_the_same_placeholder() { // Two placeholders read as two people to a model, and a forwarded // request needs value → placeholder to be a function. - let redactor = PiiRedactor::new(); + let redactor = seeded(); let mut request = ir_request(vec![ir_user_message(vec![Part::Text( "to a@example.com, cc a@example.com, bcc b@example.com".into(), )])]); let ctx = redactor.redact_request(&mut request); - assert_eq!(ctx.replacements.len(), 2, "{:?}", ctx.replacements); + assert_eq!(ctx.len(), 2, "{ctx:?}"); } #[test] fn applying_to_a_raw_request_reaches_text_the_client_escaped() { // A client may send `\u0040`, and then the bytes hold no `@`. // On the parsed Value the string is already unescaped. - let redactor = PiiRedactor::new(); + let redactor = seeded(); let mut ir = ir_request(vec![ir_user_message(vec![Part::Text( "mail a@example.com".into(), )])]); @@ -1057,7 +593,7 @@ mod tests { let raw = r#"{"messages":[{"role":"user","content":"mail a\u0040example.com"}]}"#; let mut v: serde_json::Value = serde_json::from_str(raw).unwrap(); - ctx.apply_to(&mut v); + apply_to(&ctx, &mut v); let text = v["messages"][0]["content"].as_str().unwrap(); assert!(!text.contains("a@example.com"), "{text}"); assert!(text.starts_with("mail {{EMAIL_"), "{text}"); @@ -1065,18 +601,14 @@ mod tests { #[test] fn applying_to_a_raw_request_leaves_base64_alone() { - let ctx = RedactionContext { - replacements: [("{{PHONE_1}}".to_string(), "13800138000".to_string())] - .into_iter() - .collect(), - }; + let ctx = ledger_of(&[("PHONE", "13800138000")]); let mut v = serde_json::json!({ "content": [ {"type": "text", "text": "call 13800138000"}, {"type": "image", "source": {"type": "base64", "data": "AB13800138000CD"}} ] }); - ctx.apply_to(&mut v); + apply_to(&ctx, &mut v); assert_eq!(v["content"][0]["text"], "call {{PHONE_1}}"); assert_eq!( v["content"][1]["source"]["data"], "AB13800138000CD", @@ -1086,29 +618,18 @@ mod tests { #[test] fn the_longer_value_is_replaced_first() { - let ctx = RedactionContext { - replacements: [ - ("{{EMAIL_1}}".to_string(), "a@x.com".to_string()), - ("{{EMAIL_2}}".to_string(), "aa@x.com".to_string()), - ] - .into_iter() - .collect(), - }; + let ctx = ledger_of(&[("EMAIL", "a@x.com"), ("EMAIL", "aa@x.com")]); let mut v = serde_json::json!({"text": "aa@x.com and a@x.com"}); - ctx.apply_to(&mut v); + apply_to(&ctx, &mut v); assert_eq!(v["text"], "{{EMAIL_2}} and {{EMAIL_1}}"); } #[test] fn restoring_bytes_escapes_the_original_so_the_json_survives() { // An original containing a quote, put back as-is, breaks the JSON. - let ctx = RedactionContext { - replacements: [("{{NAME_1}}".to_string(), r#"O"Brien"#.to_string())] - .into_iter() - .collect(), - }; + let ctx = ledger_of(&[("NAME", r#"O"Brien"#)]); let body = br#"{"content":[{"type":"text","text":"Hi {{NAME_1}}"}]}"#; - let out = ctx.restore_bytes(body); + let out = restore_body(&ctx, body); let v: serde_json::Value = serde_json::from_slice(&out).expect("still valid JSON"); assert_eq!(v["content"][0]["text"], r#"Hi O"Brien"#); } diff --git a/crates/gateway/src/proxy/generate.rs b/crates/gateway/src/proxy/generate.rs index 3d583346..5ba99f4a 100644 --- a/crates/gateway/src/proxy/generate.rs +++ b/crates/gateway/src/proxy/generate.rs @@ -408,7 +408,7 @@ async fn generate( let pii_redactor = state.pii_redactor.load_full(); let redaction = pii_redactor.redact_request(&mut decoded.request); let mut redacted = raw; - redaction.apply_to(&mut redacted); + crate::pii_redactor::apply_to(&redaction, &mut redacted); let request_for_audit = body.to_vec(); // 6. Quota, keyed on the model the caller named — that is what their @@ -475,7 +475,7 @@ async fn generate( capture, ); - let restored = redaction.restore_bytes(&cached.body); + let restored = crate::pii_redactor::restore_body(&redaction, &cached.body); let mut response = if is_stream { // The stored answer is whole; replay it as one event so the // client gets the framing it asked for. @@ -571,7 +571,7 @@ async fn generate( }; let deps = snapshot(entry, sel_record); - let shaper = StreamShaper::new(mapped_model.clone(), &redaction); + let shaper = StreamShaper::new(mapped_model.clone(), &redaction, surface.dialect); return Ok(launch_stream_pump(deps, open, shaper, surface.dialect)); } @@ -645,7 +645,10 @@ async fn generate( "Audit log: request completed" ); - let mut response = json_response(redaction.restore_bytes(&completed.body)); + let mut response = json_response(crate::pii_redactor::restore_body( + &redaction, + &completed.body, + )); response .headers_mut() .insert("X-Cache", HeaderValue::from_static("MISS")); diff --git a/crates/gateway/src/proxy/mod.rs b/crates/gateway/src/proxy/mod.rs index f36e03a8..5a7b6fda 100644 --- a/crates/gateway/src/proxy/mod.rs +++ b/crates/gateway/src/proxy/mod.rs @@ -159,6 +159,7 @@ impl IntoResponse for GatewayErrorResponse { "rate_limited" } GatewayError::UpstreamAuthError => "auth_error", + GatewayError::PolicyBlocked(_) => "policy_blocked", }; let retry_after = self.0.retry_after_secs(); @@ -221,6 +222,7 @@ mod helper_tests { ), (GatewayError::LocalRateLimited("rule".into()), 429), (GatewayError::UpstreamAuthError, 401), + (GatewayError::PolicyBlocked("rule".into()), 403), ] { assert_eq!( gateway_error_status(&err), diff --git a/crates/gateway/src/proxy/shaper.rs b/crates/gateway/src/proxy/shaper.rs index 15bc3678..89b77b67 100644 --- a/crates/gateway/src/proxy/shaper.rs +++ b/crates/gateway/src/proxy/shaper.rs @@ -12,16 +12,18 @@ //! asking which format this is. //! //! **PII.** A whole response has its placeholders intact and is restored -//! in one pass. A stream does not: `{{EMA` can end one frame and `IL_1}}` -//! start the next, and between them sits `"}}]}\n\ndata: {"choices":…` — -//! the placeholder is not contiguous in the byte stream. So restoration -//! happens on the text field of each frame, with a restorer that holds -//! back an unclosed `{{` until the rest arrives. +//! in one pass (`pii_redactor::restore_body`). A stream does not: `{{EMA` +//! can end one frame and `IL_1}}` start the next, with frame structure in +//! between. Restoration happens per frame, on the text and the tool +//! arguments of whichever format this is, with one lane per content block +//! or tool call — thinkwatch-core's `FrameRestorer`, the same one the +//! desktop gateway uses. use serde_json::Value; use tw_dialect::frame::{self, Decoder, Frame}; - -use crate::pii_redactor::{PiiStreamRestorer, RedactionContext}; +use tw_dialect::ir::Dialect; +use tw_guard::redact::replace::Ledger; +use tw_guard::redact::sse::{FrameRestorer, Synth}; /// Rewrite the model name in a whole (non-streaming) response. pub fn rewrite_model(body: &[u8], model: &str) -> Vec { @@ -54,12 +56,12 @@ fn set_model(v: &mut Value, model: &str) -> bool { pub struct StreamShaper { decoder: Decoder, model: String, - restorer: Option, + restorer: Option, } impl StreamShaper { - pub fn new(model: String, redaction: &RedactionContext) -> Self { - let restorer = PiiStreamRestorer::new(redaction); + pub fn new(model: String, redaction: &Ledger, client: Dialect) -> Self { + let restorer = FrameRestorer::new(redaction, client); Self { decoder: Decoder::default(), model, @@ -69,145 +71,64 @@ impl StreamShaper { pub fn process(&mut self, chunk: &[u8]) -> Vec { let frames = self.decoder.feed(chunk); - self.write(frames) + self.write(frames).into_bytes() } - /// The stream ended. Emits whatever the decoder was still holding. + /// The stream ended. Emits whatever the decoder was still holding, then + /// any text held back waiting to be a placeholder. pub fn finish(&mut self) -> Vec { let frames = self.decoder.flush(); - self.write(frames) + let mut out = self.write(frames); + self.drain(&mut out); + out.into_bytes() } - fn write(&mut self, frames: Vec) -> Vec { + fn write(&mut self, frames: Vec) -> String { let mut out = String::new(); for f in frames { self.frame(f, &mut out); } - out.into_bytes() + out } fn frame(&mut self, f: Frame, out: &mut String) { let Ok(mut v) = serde_json::from_str::(&f.data) else { // `[DONE]` and anything else that is not JSON. A held-back // tail has to go out before the stream's own terminator. - if let Some(tail) = self.drain() { - out.push_str(&frame::data(&chat_text_chunk(&self.model, &tail))); - } + self.drain(out); out.push_str(&raw(&f)); return; }; - - set_model(&mut v, &self.model); - - if self.restorer.is_some() { - if let Some(text) = text_delta_mut(&mut v) { - if let Some(r) = self.restorer.as_mut() { - *text = r.process(text); - } - } else { - // A frame that closes a text run: release anything held - // back first, as a delta of its own, so it lands inside - // the block it belongs to. - if closes_text(&v) - && let Some(tail) = self.drain() - { - out.push_str(&synthetic_delta(&v, &self.model, &tail)); - } - // Frames that carry the whole text again (`output_text.done`, - // `response.completed`) hold complete placeholders. - if let Some(r) = self.restorer.as_ref() { - walk_strings(&mut v, &mut |s| *s = r.restore_oneshot(s)); - } + if let Some(r) = self.restorer.as_mut() { + for s in r.frame(&mut v).before { + self.synth(s, out); } } - + set_model(&mut v, &self.model); out.push_str(&match &f.event { Some(e) => frame::named(e, &v), None => frame::data(&v), }); } - fn drain(&mut self) -> Option { - let tail = self.restorer.as_mut()?.flush(); - (!tail.is_empty()).then_some(tail) - } -} - -/// The streamed text in a frame, in whichever format it is. -fn text_delta_mut(v: &mut Value) -> Option<&mut String> { - match v.get("type").and_then(Value::as_str) { - // Anthropic - Some("content_block_delta") => { - let d = v.get_mut("delta")?; - if d.get("type").and_then(Value::as_str) != Some("text_delta") { - return None; - } - string_mut(d.get_mut("text")?) - } - // Responses - Some("response.output_text.delta") => string_mut(v.get_mut("delta")?), - Some(_) => None, - // Chat has no `type` - None => { - let choice = v.get_mut("choices")?.get_mut(0)?; - string_mut(choice.get_mut("delta")?.get_mut("content")?) + fn drain(&mut self, out: &mut String) { + let Some(r) = self.restorer.as_mut() else { + return; + }; + for s in r.drain() { + self.synth(s, out); } } -} -fn string_mut(v: &mut Value) -> Option<&mut String> { - match v { - Value::String(s) => Some(s), - _ => None, - } -} - -/// Does this frame end a run of text? -fn closes_text(v: &Value) -> bool { - match v.get("type").and_then(Value::as_str) { - Some("content_block_stop") | Some("response.output_text.done") => true, - Some(_) => false, - None => v - .get("choices") - .and_then(|c| c.get(0)) - .and_then(|c| c.get("finish_reason")) - .is_some_and(|f| !f.is_null()), - } -} - -/// A text delta carrying `tail`, shaped like the frame it precedes. -fn synthetic_delta(closing: &Value, model: &str, tail: &str) -> String { - match closing.get("type").and_then(Value::as_str) { - Some("content_block_stop") => frame::named( - "content_block_delta", - &serde_json::json!({ - "type": "content_block_delta", - "index": closing.get("index").cloned().unwrap_or(Value::from(0)), - "delta": { "type": "text_delta", "text": tail }, - }), - ), - Some("response.output_text.done") => frame::named( - "response.output_text.delta", - &serde_json::json!({ - "type": "response.output_text.delta", - "item_id": closing.get("item_id").cloned().unwrap_or(Value::Null), - "output_index": closing.get("output_index").cloned().unwrap_or(Value::from(0)), - "content_index": closing.get("content_index").cloned().unwrap_or(Value::from(0)), - "delta": tail, - }), - ), - _ => frame::data(&chat_text_chunk(model, tail)), + fn synth(&self, mut s: Synth, out: &mut String) { + set_model(&mut s.data, &self.model); + out.push_str(&match &s.event { + Some(e) => frame::named(e, &s.data), + None => frame::data(&s.data), + }); } } -fn chat_text_chunk(model: &str, text: &str) -> Value { - serde_json::json!({ - "object": "chat.completion.chunk", - "model": model, - "choices": [{ "index": 0, "delta": { "content": text }, "finish_reason": null }], - }) -} - fn raw(f: &Frame) -> String { match &f.event { Some(e) => format!("event: {e}\ndata: {}\n\n", f.data), @@ -215,27 +136,20 @@ fn raw(f: &Frame) -> String { } } -fn walk_strings(v: &mut Value, f: &mut impl FnMut(&mut String)) { - match v { - Value::String(s) => f(s), - Value::Array(items) => items.iter_mut().for_each(|i| walk_strings(i, f)), - Value::Object(map) => map.values_mut().for_each(|c| walk_strings(c, f)), - _ => {} - } -} - #[cfg(test)] mod tests { use super::*; - use std::collections::HashMap; - fn ctx(pairs: &[(&str, &str)]) -> RedactionContext { - RedactionContext { - replacements: pairs - .iter() - .map(|(a, b)| (a.to_string(), b.to_string())) - .collect::>(), - } + /// A ledger that issued `{{EMAIL_1}}` for `a@x.com`, or nothing. + fn ctx(email: Option<&str>) -> Ledger { + let r = crate::pii_redactor::PiiRedactor::from_config(&[ + think_watch_common::pii::PiiPatternConfig { + name: "email".into(), + regex: r"[a-z]+@x\.com".into(), + placeholder_prefix: "EMAIL".into(), + }, + ]); + r.redact_str(email.unwrap_or("")).1 } fn frames(bytes: &[u8]) -> Vec { @@ -276,7 +190,7 @@ mod tests { #[test] fn every_streamed_chunk_gets_the_callers_model_back() { - let mut s = StreamShaper::new("gpt-4".into(), &ctx(&[])); + let mut s = StreamShaper::new("gpt-4".into(), &ctx(None), Dialect::Chat); let mut out = s.process(chat_chunk("hi").as_bytes()); out.extend(s.process(chat_chunk(" there").as_bytes())); out.extend(s.finish()); @@ -289,7 +203,7 @@ mod tests { fn a_placeholder_split_across_two_frames_is_restored() { // Exactly why this cannot be done on bytes: frame structure sits // between the two halves. - let mut s = StreamShaper::new("m".into(), &ctx(&[("{{EMAIL_1}}", "a@x.com")])); + let mut s = StreamShaper::new("m".into(), &ctx(Some("a@x.com")), Dialect::Chat); let mut out = s.process(chat_chunk("mail {{EMA").as_bytes()); out.extend(s.process(chat_chunk("IL_1}} now").as_bytes())); out.extend(s.finish()); @@ -306,7 +220,7 @@ mod tests { #[test] fn an_anthropic_text_delta_is_restored() { - let mut s = StreamShaper::new("m".into(), &ctx(&[("{{EMAIL_1}}", "a@x.com")])); + let mut s = StreamShaper::new("m".into(), &ctx(Some("a@x.com")), Dialect::Anthropic); let ev = |d: Value| format!("event: content_block_delta\ndata: {d}\n\n"); let mut out = s.process( ev(serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"to {{EMAIL_"}})).as_bytes(), @@ -326,7 +240,7 @@ mod tests { fn a_held_back_tail_is_released_before_the_block_closes() { // Text ending in an unclosed `{{` is not a placeholder: it goes out // verbatim, inside the block it belongs to, not after the block ends. - let mut s = StreamShaper::new("m".into(), &ctx(&[("{{EMAIL_1}}", "a@x.com")])); + let mut s = StreamShaper::new("m".into(), &ctx(Some("a@x.com")), Dialect::Anthropic); let ev = |name: &str, d: Value| format!("event: {name}\ndata: {d}\n\n"); let mut out = s.process( ev("content_block_delta", serde_json::json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"literal {{"}})).as_bytes(), @@ -354,7 +268,7 @@ mod tests { fn a_frame_carrying_the_whole_text_again_is_restored_too() { // Responses repeats the whole text in output_text.done and // response.completed. - let mut s = StreamShaper::new("m".into(), &ctx(&[("{{EMAIL_1}}", "a@x.com")])); + let mut s = StreamShaper::new("m".into(), &ctx(Some("a@x.com")), Dialect::Responses); let out = s.process( format!( "event: response.output_text.done\ndata: {}\n\n", @@ -365,9 +279,36 @@ mod tests { assert_eq!(frames(&out)[0]["text"], "mail a@x.com"); } + #[test] + fn a_tool_calls_arguments_get_the_callers_pii_back() { + // The old shaper restored text only: a model asked to "email + // a@x.com" called the tool with `{{EMAIL_1}}` as the address. + let mut s = StreamShaper::new("m".into(), &ctx(Some("a@x.com")), Dialect::Chat); + let call = |args: &str| { + format!( + "data: {}\n\n", + serde_json::json!({"model":"up","choices":[{"index":0,"delta":{"tool_calls":[ + {"index":0,"function":{"arguments":args}} + ]},"finish_reason":null}]}) + ) + }; + let mut out = s.process(call(r#"{"to":"{{EMA"#).as_bytes()); + out.extend(s.process(call(r#"IL_1}}"}"#).as_bytes())); + out.extend(s.finish()); + let args: String = frames(&out) + .iter() + .filter_map(|f| { + f["choices"][0]["delta"]["tool_calls"][0]["function"]["arguments"] + .as_str() + .map(str::to_string) + }) + .collect(); + assert_eq!(args, r#"{"to":"a@x.com"}"#); + } + #[test] fn done_passes_through_untouched() { - let mut s = StreamShaper::new("m".into(), &ctx(&[])); + let mut s = StreamShaper::new("m".into(), &ctx(None), Dialect::Chat); let out = s.process(b"data: [DONE]\n\n"); assert_eq!(out, b"data: [DONE]\n\n"); } diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index ef311ec6..c912b209 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -18,6 +18,7 @@ think-watch-gateway = { workspace = true } think-watch-mcp-gateway = { workspace = true } tw-dialect = { workspace = true } tw-types = { workspace = true } +tw-guard = { workspace = true } axum = { workspace = true } futures = { workspace = true } tower = { workspace = true } diff --git a/crates/server/src/app.rs b/crates/server/src/app.rs index 232933bd..22b6d8ed 100644 --- a/crates/server/src/app.rs +++ b/crates/server/src/app.rs @@ -139,7 +139,7 @@ pub async fn load_content_filter(dc: &DynamicConfig) -> ContentFilter { /// Build a `PiiRedactor` from the current `system_settings` value. pub async fn load_pii_redactor(dc: &DynamicConfig) -> PiiRedactor { - let configs: Vec = dc + let configs: Vec = dc .get("security.pii_redactor_patterns") .await .and_then(|v| serde_json::from_value(v).ok()) diff --git a/crates/server/src/handlers/admin/content_filter.rs b/crates/server/src/handlers/admin/content_filter.rs index c31e9652..4758a9e4 100644 --- a/crates/server/src/handlers/admin/content_filter.rs +++ b/crates/server/src/handlers/admin/content_filter.rs @@ -121,7 +121,7 @@ pub async fn list_content_filter_presets( #[derive(Debug, Deserialize)] pub struct PiiRedactorTestRequest { pub text: String, - pub patterns: Vec, + pub patterns: Vec, } #[derive(Debug, Serialize)] @@ -167,21 +167,20 @@ pub async fn test_pii_redactor( let (redacted_text, ctx) = redactor.redact_str(&req.text); let matches = ctx - .replacements - .into_iter() - .map(|(placeholder, original)| { - // Extract pattern name from placeholder format "{{NAME_salt_n}}" + .replacements() + .map(|(original, placeholder)| { + // `{{CUSTOM_EMAIL_2}}` → `CUSTOM_EMAIL`: the prefix may itself + // contain underscores, so cut at the last one let name = placeholder .trim_start_matches("{{") .trim_end_matches("}}") - .split('_') - .next() - .unwrap_or("") + .rsplit_once('_') + .map_or("", |(label, _)| label) .to_string(); PiiRedactorTestMatch { name, - original, - placeholder, + original: original.to_string(), + placeholder: placeholder.to_string(), } }) .collect(); diff --git a/crates/server/src/handlers/admin/settings.rs b/crates/server/src/handlers/admin/settings.rs index 6a4a858a..19f7e10e 100644 --- a/crates/server/src/handlers/admin/settings.rs +++ b/crates/server/src/handlers/admin/settings.rs @@ -666,23 +666,32 @@ fn validate_setting(key: &str, value: &serde_json::Value) -> Result<(), AppError "PII pattern {i}: regex max 1000 characters" ))); } - // Validate regex compiles AND fits the bounded size budget. - // Bare `regex::Regex::new` accepts 10 MiB NFA + 2 MiB DFA - // by default — large enough to ReDoS the gateway at - // request time. Use the shared bounded helper so save-time - // rejection matches what the runtime would accept. - if think_watch_common::regex_util::compile_bounded(regex_str).is_err() { + // Compiled exactly as the redactor will compile it, bounds + // included, so what is saved is what runs. + if tw_guard::redact::rules::compile("", regex_str).is_err() { return Err(AppError::BadRequest(format!( "PII pattern {i}: invalid or oversized regex" ))); } - if item + // The prefix lands inside the placeholder (`{{EMAIL_1}}`); + // a brace or a space there would make one that can never be + // told apart from ordinary text. + let prefix = item .get("placeholder_prefix") .and_then(|v| v.as_str()) - .is_none() + .ok_or_else(|| { + AppError::BadRequest(format!( + "PII pattern {i}: missing 'placeholder_prefix'" + )) + })?; + if prefix.is_empty() + || prefix.len() > 32 + || !prefix + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') { return Err(AppError::BadRequest(format!( - "PII pattern {i}: missing 'placeholder_prefix'" + "PII pattern {i}: 'placeholder_prefix' must be 1-32 letters, digits or underscores" ))); } if item.get("name").and_then(|v| v.as_str()).is_none() {