Skip to main content

blyte_agent/
redact.rs

1use std::ffi::OsStr;
2use std::path::{Path, PathBuf};
3use std::process::Command;
4use std::sync::OnceLock;
5
6use blyte_provider::{Message, Request, UserPart};
7use regex::Regex;
8
9use crate::shell;
10
11pub const MIN_SECRET_BYTES: usize = 8;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Redactor {
15    pairs: Vec<(String, String)>,
16}
17
18enum Piece<'a> {
19    Raw(&'a str),
20    Literal(&'a str),
21    Redacted(&'a str),
22}
23
24struct PatternSet {
25    redacted_marker: Regex,
26    pem_private_key: Regex,
27    github_token: Regex,
28    aws_access_key: Regex,
29    api_key: Regex,
30    url_password: Regex,
31    bearer_header: Regex,
32}
33
34fn patterns() -> &'static PatternSet {
35    static PATTERNS: OnceLock<PatternSet> = OnceLock::new();
36    PATTERNS.get_or_init(|| PatternSet {
37        redacted_marker: Regex::new(r"\[redacted(?: [^\[\]\r\n]+)?\]").unwrap(),
38        pem_private_key: Regex::new(
39            r"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----(?:.*?-----END [A-Z0-9 ]*PRIVATE KEY-----|.*)",
40        )
41        .unwrap(),
42        github_token: Regex::new(
43            r"\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\b",
44        )
45        .unwrap(),
46        aws_access_key: Regex::new(r"\b(?:AKIA|ASIA)[A-Z0-9]{16}\b").unwrap(),
47        api_key: Regex::new(
48            r"(?:sk-ant-[A-Za-z0-9_-]{16,}|sk-proj-[A-Za-z0-9_-]{16,}|sk_live_[A-Za-z0-9]{16,}|rk_live_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9_-]{20,}|AIza[A-Za-z0-9_-]{35}|xox[baprs]-[A-Za-z0-9_-]{10,})",
49        )
50        .unwrap(),
51        url_password: Regex::new(
52            r#"\b([A-Za-z][A-Za-z0-9+.-]*://[^:@/\s"'<>`?#\[\]()]*:)([^\s/@"'<>?#`]+)(@[A-Za-z0-9.\[\]][A-Za-z0-9._\-\[\]:]*)"#,
53        )
54        .unwrap(),
55        bearer_header: Regex::new(
56            r#"(?i)\b(authorization[ \t]*:[ \t]*bearer[ \t]+)([^\s"'<>`]{8,})"#,
57        )
58        .unwrap(),
59    })
60}
61
62fn is_key_token_char(b: u8) -> bool {
63    b.is_ascii_alphanumeric() || b == b'_' || b == b'-'
64}
65
66fn split_preserved_markers<'a>(pieces: Vec<Piece<'a>>, re: &Regex) -> Vec<Piece<'a>> {
67    let mut next = Vec::with_capacity(pieces.len());
68    for piece in pieces {
69        match piece {
70            Piece::Raw(s) => {
71                let mut cursor = 0;
72                for m in re.find_iter(s) {
73                    if m.start() > cursor {
74                        next.push(Piece::Raw(&s[cursor..m.start()]));
75                    }
76                    next.push(Piece::Literal(m.as_str()));
77                    cursor = m.end();
78                }
79                if cursor < s.len() {
80                    next.push(Piece::Raw(&s[cursor..]));
81                }
82            }
83            other => next.push(other),
84        }
85    }
86    next
87}
88
89fn replace_whole_matches<'a>(
90    pieces: Vec<Piece<'a>>,
91    re: &Regex,
92    label: &'static str,
93    check_key_bounds: bool,
94) -> Vec<Piece<'a>> {
95    let mut next = Vec::with_capacity(pieces.len());
96    for piece in pieces {
97        match piece {
98            Piece::Raw(s) => {
99                let bytes = s.as_bytes();
100                let mut cursor = 0;
101                for m in re.find_iter(s) {
102                    if check_key_bounds {
103                        let left_ok = m.start() == 0 || !is_key_token_char(bytes[m.start() - 1]);
104                        let right_ok = m.end() == bytes.len() || !is_key_token_char(bytes[m.end()]);
105                        if !left_ok || !right_ok {
106                            continue;
107                        }
108                    }
109                    if m.start() > cursor {
110                        next.push(Piece::Raw(&s[cursor..m.start()]));
111                    }
112                    next.push(Piece::Redacted(label));
113                    cursor = m.end();
114                }
115                if cursor < s.len() {
116                    next.push(Piece::Raw(&s[cursor..]));
117                }
118            }
119            other => next.push(other),
120        }
121    }
122    next
123}
124
125fn replace_capture_group<'a>(
126    pieces: Vec<Piece<'a>>,
127    re: &Regex,
128    group_idx: usize,
129    label: &'static str,
130) -> Vec<Piece<'a>> {
131    let mut next = Vec::with_capacity(pieces.len());
132    for piece in pieces {
133        match piece {
134            Piece::Raw(s) => {
135                let mut cursor = 0;
136                for caps in re.captures_iter(s) {
137                    if let Some(m) = caps.get(group_idx) {
138                        if m.start() > cursor {
139                            next.push(Piece::Raw(&s[cursor..m.start()]));
140                        }
141                        next.push(Piece::Redacted(label));
142                        cursor = m.end();
143                    }
144                }
145                if cursor < s.len() {
146                    next.push(Piece::Raw(&s[cursor..]));
147                }
148            }
149            other => next.push(other),
150        }
151    }
152    next
153}
154
155impl Redactor {
156    pub fn from_pairs(pairs: Vec<(String, String)>) -> Redactor {
157        let mut filtered: Vec<(String, String)> = pairs
158            .into_iter()
159            .filter(|(_, value)| value.len() >= MIN_SECRET_BYTES)
160            .collect();
161        filtered.sort_by(|a, b| {
162            b.1.len()
163                .cmp(&a.1.len())
164                .then_with(|| a.1.cmp(&b.1))
165                .then_with(|| a.0.cmp(&b.0))
166        });
167        filtered.dedup_by(|a, b| a.1 == b.1);
168        Redactor { pairs: filtered }
169    }
170
171    pub fn for_root(root: &Path) -> Result<Redactor, String> {
172        let main_checkout = resolve_main_checkout(root)?;
173        let mut pairs = Vec::new();
174        for &name in shell::HARNESS_ENV {
175            if let Some(value) = std::env::var_os(name) {
176                pairs.push((name.to_string(), value.to_string_lossy().into_owned()));
177            }
178        }
179        for name in shell::withheld_env() {
180            if let Some(value) = std::env::var_os(&name) {
181                pairs.push((name, value.to_string_lossy().into_owned()));
182            }
183        }
184        read_env_file(&root.join(".env"), &mut pairs)?;
185        if let Some(main_root) = main_checkout.as_deref() {
186            if !same_path(main_root, root) {
187                read_env_file(&main_root.join(".env"), &mut pairs)?;
188            }
189        }
190        read_mcp_auth_secrets(&mut pairs);
191        read_mcp_config_secrets(&mut pairs, root, main_checkout.as_deref());
192        Ok(Redactor::from_pairs(pairs))
193    }
194
195    pub fn redact_request(&self, req: &Request) -> Request {
196        Request {
197            system: self.apply(&req.system),
198            messages: req
199                .messages
200                .iter()
201                .map(|m| self.redact_message(m))
202                .collect(),
203            tools: req.tools.clone(),
204            max_output_tokens: req.max_output_tokens,
205            timeout: req.timeout,
206        }
207    }
208
209    fn redact_message(&self, msg: &Message) -> Message {
210        match msg {
211            Message::User(text) => Message::User(self.apply(text)),
212            Message::UserParts(parts) => Message::UserParts(
213                parts
214                    .iter()
215                    .map(|p| match p {
216                        UserPart::Text(t) => UserPart::Text(self.apply(t)),
217                        UserPart::Image { mime_type, data } => UserPart::Image {
218                            mime_type: mime_type.clone(),
219                            data: data.clone(),
220                        },
221                    })
222                    .collect(),
223            ),
224            Message::Assistant(text) => Message::Assistant(self.apply(text)),
225            Message::ToolCall {
226                id,
227                name,
228                arguments,
229                signature,
230            } => Message::ToolCall {
231                id: id.clone(),
232                name: name.clone(),
233                arguments: self.redact_json(arguments),
234                signature: signature.clone(),
235            },
236            Message::ToolResult {
237                id,
238                name,
239                content,
240                is_error,
241            } => Message::ToolResult {
242                id: id.clone(),
243                name: name.clone(),
244                content: self.apply(content),
245                is_error: *is_error,
246            },
247        }
248    }
249
250    fn redact_json(&self, val: &serde_json::Value) -> serde_json::Value {
251        match val {
252            serde_json::Value::String(s) => serde_json::Value::String(self.apply(s)),
253            serde_json::Value::Array(items) => {
254                serde_json::Value::Array(items.iter().map(|v| self.redact_json(v)).collect())
255            }
256            serde_json::Value::Object(map) => serde_json::Value::Object(
257                map.iter()
258                    .map(|(k, v)| (k.clone(), self.redact_json(v)))
259                    .collect(),
260            ),
261            other => other.clone(),
262        }
263    }
264
265    pub fn apply(&self, text: &str) -> String {
266        if text.is_empty() {
267            return String::new();
268        }
269        let mut pieces = vec![Piece::Raw(text)];
270        for (name, value) in &self.pairs {
271            if !pieces
272                .iter()
273                .any(|p| matches!(p, Piece::Raw(s) if s.contains(value.as_str())))
274            {
275                continue;
276            }
277            let mut next = Vec::with_capacity(pieces.len() + 2);
278            for piece in pieces {
279                match piece {
280                    Piece::Redacted(n) => next.push(Piece::Redacted(n)),
281                    Piece::Literal(l) => next.push(Piece::Literal(l)),
282                    Piece::Raw(s) => {
283                        if !s.contains(value.as_str()) {
284                            next.push(Piece::Raw(s));
285                            continue;
286                        }
287                        let mut first = true;
288                        for part in s.split(value.as_str()) {
289                            if !first {
290                                next.push(Piece::Redacted(name.as_str()));
291                            }
292                            first = false;
293                            if !part.is_empty() {
294                                next.push(Piece::Raw(part));
295                            }
296                        }
297                    }
298                }
299            }
300            pieces = next;
301        }
302        let p = patterns();
303        pieces = split_preserved_markers(pieces, &p.redacted_marker);
304        pieces = replace_whole_matches(pieces, &p.pem_private_key, "private key", false);
305        pieces = replace_whole_matches(pieces, &p.github_token, "github token", false);
306        pieces = replace_whole_matches(pieces, &p.aws_access_key, "aws key", false);
307        pieces = replace_whole_matches(pieces, &p.api_key, "api key", true);
308        pieces = replace_capture_group(pieces, &p.url_password, 2, "password");
309        pieces = replace_capture_group(pieces, &p.bearer_header, 2, "bearer token");
310
311        let mut out = String::with_capacity(text.len());
312        for piece in pieces {
313            match piece {
314                Piece::Raw(s) | Piece::Literal(s) => out.push_str(s),
315                Piece::Redacted(name) => {
316                    out.push_str("[redacted ");
317                    out.push_str(name);
318                    out.push(']');
319                }
320            }
321        }
322        out
323    }
324}
325
326fn in_git_tree(root: &Path) -> Result<bool, String> {
327    if std::env::var_os("GIT_DIR").is_some() {
328        return Ok(true);
329    }
330    let abs_root =
331        std::path::absolute(root).map_err(|e| format!("cannot resolve {}: {e}", root.display()))?;
332    Ok(abs_root
333        .ancestors()
334        .any(|dir| std::fs::symlink_metadata(dir.join(".git")).is_ok()))
335}
336
337fn resolve_main_checkout(root: &Path) -> Result<Option<PathBuf>, String> {
338    if !in_git_tree(root)? {
339        return Ok(None);
340    }
341    let output = Command::new("git")
342        .args(["-C"])
343        .arg(root)
344        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
345        .output()
346        .map_err(|e| format!("cannot run git rev-parse in {}: {e}", root.display()))?;
347    if !output.status.success() {
348        let stderr = String::from_utf8_lossy(&output.stderr);
349        if stderr.contains("not a git repository (or any") {
350            return Ok(None);
351        }
352        return Err(format!(
353            "git rev-parse --git-common-dir failed in {}: {}",
354            root.display(),
355            stderr.trim()
356        ));
357    }
358    let text = String::from_utf8_lossy(&output.stdout);
359    let line = text
360        .lines()
361        .map(str::trim)
362        .find(|s| !s.is_empty())
363        .ok_or_else(|| {
364            format!(
365                "git rev-parse --git-common-dir returned empty output in {}",
366                root.display()
367            )
368        })?;
369    let common_dir = Path::new(line);
370    if common_dir.file_name() == Some(OsStr::new(".git")) {
371        if let Some(main_root) = common_dir.parent() {
372            return Ok(Some(main_root.to_path_buf()));
373        }
374    }
375    Ok(None)
376}
377
378fn mcp_config_dir() -> Option<PathBuf> {
379    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
380        if !xdg.is_empty() {
381            return Some(PathBuf::from(xdg).join("blyte"));
382        }
383    }
384    let home = std::env::var_os("HOME").filter(|h| !h.is_empty())?;
385    Some(PathBuf::from(home).join(".config").join("blyte"))
386}
387
388fn mcp_auth_file_path() -> Option<PathBuf> {
389    Some(mcp_config_dir()?.join("mcp-auth.json"))
390}
391
392fn read_mcp_config_secrets(
393    pairs: &mut Vec<(String, String)>,
394    root: &Path,
395    main_checkout: Option<&Path>,
396) {
397    let mut config_paths = Vec::new();
398    let mut blyte_env = std::collections::BTreeMap::new();
399    if let Some(dir) = mcp_config_dir() {
400        if let Ok(text) = std::fs::read_to_string(dir.join("env")) {
401            for (k, v) in parse_env_file(&text) {
402                blyte_env.insert(k, v);
403            }
404        }
405        config_paths.push(dir.join("mcp.json"));
406    }
407    config_paths.push(root.join(".mcp.json"));
408    if let Some(main_root) = main_checkout {
409        if !same_path(main_root, root) {
410            config_paths.push(main_root.join(".mcp.json"));
411        }
412    }
413    for path in config_paths {
414        let Ok(text) = std::fs::read_to_string(&path) else {
415            continue;
416        };
417        let Ok(doc) = serde_json::from_str::<serde_json::Value>(&text) else {
418            continue;
419        };
420        let Some(servers) = doc.get("mcpServers").and_then(|v| v.as_object()) else {
421            continue;
422        };
423        for (server_name, entry) in servers {
424            let Some(secret_raw) = entry
425                .get("oauth")
426                .and_then(|v| v.get("client_secret"))
427                .and_then(|v| v.as_str())
428                .map(str::trim)
429                .filter(|s| !s.is_empty())
430            else {
431                continue;
432            };
433            let label = format!("MCP_CLIENT_SECRET_{server_name}");
434            if let Some(expanded) = expand_simple_env_vars(secret_raw, &blyte_env) {
435                if !expanded.is_empty() {
436                    pairs.push((label.clone(), expanded));
437                }
438            }
439            if !secret_raw.contains("${") {
440                pairs.push((label, secret_raw.to_string()));
441            }
442        }
443    }
444}
445
446fn expand_simple_env_vars(
447    input: &str,
448    fallback_env: &std::collections::BTreeMap<String, String>,
449) -> Option<String> {
450    let mut out = String::with_capacity(input.len());
451    let mut rest = input;
452    while let Some(idx) = rest.find("${") {
453        out.push_str(&rest[..idx]);
454        let after_open = &rest[idx + 2..];
455        let end = after_open.find('}')?;
456        let var_name = &after_open[..end];
457        let val = std::env::var(var_name)
458            .ok()
459            .or_else(|| fallback_env.get(var_name).cloned())?;
460        out.push_str(&val);
461        rest = &after_open[end + 1..];
462    }
463    out.push_str(rest);
464    Some(out)
465}
466
467fn read_mcp_auth_secrets(pairs: &mut Vec<(String, String)>) {
468    let Some(path) = mcp_auth_file_path() else {
469        return;
470    };
471    let Ok(text) = std::fs::read_to_string(&path) else {
472        return;
473    };
474    let Ok(root) = serde_json::from_str::<serde_json::Value>(&text) else {
475        return;
476    };
477    let Some(servers) = root.get("servers").and_then(|v| v.as_object()) else {
478        return;
479    };
480    for (server_name, entry) in servers {
481        let Some(obj) = entry.as_object() else {
482            continue;
483        };
484        for (field, suffix) in [
485            ("access_token", "MCP_ACCESS_TOKEN"),
486            ("refresh_token", "MCP_REFRESH_TOKEN"),
487            ("client_secret", "MCP_CLIENT_SECRET"),
488        ] {
489            if let Some(val) = obj.get(field).and_then(|v| v.as_str()) {
490                if !val.is_empty() {
491                    pairs.push((format!("{suffix}_{server_name}"), val.to_string()));
492                }
493            }
494        }
495    }
496}
497
498fn read_env_file(env_path: &Path, pairs: &mut Vec<(String, String)>) -> Result<(), String> {
499    match std::fs::read_to_string(env_path) {
500        Ok(text) => {
501            for (name, value) in parse_env_file(&text) {
502                if shell::credential_like(&name, &value) {
503                    pairs.push((name, value));
504                }
505            }
506            Ok(())
507        }
508        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
509            if std::fs::symlink_metadata(env_path).is_ok() {
510                return Err(format!("cannot read {}: {e}", env_path.display()));
511            }
512            Ok(())
513        }
514        Err(e) => Err(format!("cannot read {}: {e}", env_path.display())),
515    }
516}
517
518fn same_path(a: &Path, b: &Path) -> bool {
519    match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
520        (Ok(ca), Ok(cb)) => ca == cb,
521        _ => a == b,
522    }
523}
524
525pub fn parse_env_file(text: &str) -> Vec<(String, String)> {
526    let mut pairs = Vec::new();
527    for raw_line in text.lines() {
528        let line = raw_line.trim();
529        if line.is_empty() || line.starts_with('#') {
530            continue;
531        }
532        let line = if let Some(rest) = line.strip_prefix("export ") {
533            rest.trim_start()
534        } else if let Some(rest) = line.strip_prefix("export\t") {
535            rest.trim_start()
536        } else {
537            line
538        };
539        let Some((raw_name, raw_val)) = line.split_once('=') else {
540            continue;
541        };
542        let name = raw_name.trim();
543        if name.is_empty() {
544            continue;
545        }
546        let val = raw_val.trim();
547        let unquoted = if val.len() >= 2
548            && ((val.starts_with('"') && val.ends_with('"'))
549                || (val.starts_with('\'') && val.ends_with('\'')))
550        {
551            &val[1..val.len() - 1]
552        } else {
553            val
554        };
555        pairs.push((name.to_string(), unquoted.to_string()));
556    }
557    pairs
558}