Skip to main content

blyte_agent/
redact.rs

1use std::ffi::OsStr;
2use std::path::{Path, PathBuf};
3use std::process::Command;
4
5use blyte_provider::{Message, Request, UserPart};
6
7use crate::shell;
8
9pub const MIN_SECRET_BYTES: usize = 8;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Redactor {
13    pairs: Vec<(String, String)>,
14}
15
16enum Piece<'a> {
17    Raw(&'a str),
18    Redacted(&'a str),
19}
20
21impl Redactor {
22    pub fn from_pairs(pairs: Vec<(String, String)>) -> Redactor {
23        let mut filtered: Vec<(String, String)> = pairs
24            .into_iter()
25            .filter(|(_, value)| value.len() >= MIN_SECRET_BYTES)
26            .collect();
27        filtered.sort_by(|a, b| {
28            b.1.len()
29                .cmp(&a.1.len())
30                .then_with(|| a.1.cmp(&b.1))
31                .then_with(|| a.0.cmp(&b.0))
32        });
33        filtered.dedup_by(|a, b| a.1 == b.1);
34        Redactor { pairs: filtered }
35    }
36
37    pub fn for_root(root: &Path) -> Result<Redactor, String> {
38        let main_checkout = resolve_main_checkout(root)?;
39        let mut pairs = Vec::new();
40        for &name in shell::HARNESS_ENV {
41            if let Some(value) = std::env::var_os(name) {
42                pairs.push((name.to_string(), value.to_string_lossy().into_owned()));
43            }
44        }
45        for name in shell::withheld_env() {
46            if let Some(value) = std::env::var_os(&name) {
47                pairs.push((name, value.to_string_lossy().into_owned()));
48            }
49        }
50        read_env_file(&root.join(".env"), &mut pairs)?;
51        if let Some(main_root) = main_checkout.as_deref() {
52            if !same_path(main_root, root) {
53                read_env_file(&main_root.join(".env"), &mut pairs)?;
54            }
55        }
56        Ok(Redactor::from_pairs(pairs))
57    }
58
59    pub fn redact_request(&self, req: &Request) -> Request {
60        if self.pairs.is_empty() {
61            return req.clone();
62        }
63        Request {
64            system: self.apply(&req.system),
65            messages: req
66                .messages
67                .iter()
68                .map(|m| self.redact_message(m))
69                .collect(),
70            tools: req.tools.clone(),
71            max_output_tokens: req.max_output_tokens,
72            timeout: req.timeout,
73        }
74    }
75
76    fn redact_message(&self, msg: &Message) -> Message {
77        match msg {
78            Message::User(text) => Message::User(self.apply(text)),
79            Message::UserParts(parts) => Message::UserParts(
80                parts
81                    .iter()
82                    .map(|p| match p {
83                        UserPart::Text(t) => UserPart::Text(self.apply(t)),
84                        UserPart::Image { mime_type, data } => UserPart::Image {
85                            mime_type: mime_type.clone(),
86                            data: data.clone(),
87                        },
88                    })
89                    .collect(),
90            ),
91            Message::Assistant(text) => Message::Assistant(self.apply(text)),
92            Message::ToolCall {
93                id,
94                name,
95                arguments,
96                signature,
97            } => Message::ToolCall {
98                id: id.clone(),
99                name: name.clone(),
100                arguments: self.redact_json(arguments),
101                signature: signature.clone(),
102            },
103            Message::ToolResult {
104                id,
105                name,
106                content,
107                is_error,
108            } => Message::ToolResult {
109                id: id.clone(),
110                name: name.clone(),
111                content: self.apply(content),
112                is_error: *is_error,
113            },
114        }
115    }
116
117    fn redact_json(&self, val: &serde_json::Value) -> serde_json::Value {
118        match val {
119            serde_json::Value::String(s) => serde_json::Value::String(self.apply(s)),
120            serde_json::Value::Array(items) => {
121                serde_json::Value::Array(items.iter().map(|v| self.redact_json(v)).collect())
122            }
123            serde_json::Value::Object(map) => serde_json::Value::Object(
124                map.iter()
125                    .map(|(k, v)| (k.clone(), self.redact_json(v)))
126                    .collect(),
127            ),
128            other => other.clone(),
129        }
130    }
131
132    pub fn apply(&self, text: &str) -> String {
133        if self.pairs.is_empty() || text.is_empty() {
134            return text.to_string();
135        }
136        let mut pieces = vec![Piece::Raw(text)];
137        for (name, value) in &self.pairs {
138            if !pieces
139                .iter()
140                .any(|p| matches!(p, Piece::Raw(s) if s.contains(value.as_str())))
141            {
142                continue;
143            }
144            let mut next = Vec::with_capacity(pieces.len() + 2);
145            for piece in pieces {
146                match piece {
147                    Piece::Redacted(n) => next.push(Piece::Redacted(n)),
148                    Piece::Raw(s) => {
149                        if !s.contains(value.as_str()) {
150                            next.push(Piece::Raw(s));
151                            continue;
152                        }
153                        let mut first = true;
154                        for part in s.split(value.as_str()) {
155                            if !first {
156                                next.push(Piece::Redacted(name.as_str()));
157                            }
158                            first = false;
159                            if !part.is_empty() {
160                                next.push(Piece::Raw(part));
161                            }
162                        }
163                    }
164                }
165            }
166            pieces = next;
167        }
168        let mut out = String::with_capacity(text.len());
169        for piece in pieces {
170            match piece {
171                Piece::Raw(s) => out.push_str(s),
172                Piece::Redacted(name) => {
173                    out.push_str("[redacted ");
174                    out.push_str(name);
175                    out.push(']');
176                }
177            }
178        }
179        out
180    }
181}
182
183fn in_git_tree(root: &Path) -> Result<bool, String> {
184    if std::env::var_os("GIT_DIR").is_some() {
185        return Ok(true);
186    }
187    let abs_root =
188        std::path::absolute(root).map_err(|e| format!("cannot resolve {}: {e}", root.display()))?;
189    Ok(abs_root
190        .ancestors()
191        .any(|dir| std::fs::symlink_metadata(dir.join(".git")).is_ok()))
192}
193
194fn resolve_main_checkout(root: &Path) -> Result<Option<PathBuf>, String> {
195    if !in_git_tree(root)? {
196        return Ok(None);
197    }
198    let output = Command::new("git")
199        .args(["-C"])
200        .arg(root)
201        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
202        .output()
203        .map_err(|e| format!("cannot run git rev-parse in {}: {e}", root.display()))?;
204    if !output.status.success() {
205        let stderr = String::from_utf8_lossy(&output.stderr);
206        if stderr.contains("not a git repository (or any") {
207            return Ok(None);
208        }
209        return Err(format!(
210            "git rev-parse --git-common-dir failed in {}: {}",
211            root.display(),
212            stderr.trim()
213        ));
214    }
215    let text = String::from_utf8_lossy(&output.stdout);
216    let line = text
217        .lines()
218        .map(str::trim)
219        .find(|s| !s.is_empty())
220        .ok_or_else(|| {
221            format!(
222                "git rev-parse --git-common-dir returned empty output in {}",
223                root.display()
224            )
225        })?;
226    let common_dir = Path::new(line);
227    if common_dir.file_name() == Some(OsStr::new(".git")) {
228        if let Some(main_root) = common_dir.parent() {
229            return Ok(Some(main_root.to_path_buf()));
230        }
231    }
232    Ok(None)
233}
234
235fn read_env_file(env_path: &Path, pairs: &mut Vec<(String, String)>) -> Result<(), String> {
236    match std::fs::read_to_string(env_path) {
237        Ok(text) => {
238            for (name, value) in parse_env_file(&text) {
239                if shell::credential_like(&name, &value) {
240                    pairs.push((name, value));
241                }
242            }
243            Ok(())
244        }
245        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
246            if std::fs::symlink_metadata(env_path).is_ok() {
247                return Err(format!("cannot read {}: {e}", env_path.display()));
248            }
249            Ok(())
250        }
251        Err(e) => Err(format!("cannot read {}: {e}", env_path.display())),
252    }
253}
254
255fn same_path(a: &Path, b: &Path) -> bool {
256    match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
257        (Ok(ca), Ok(cb)) => ca == cb,
258        _ => a == b,
259    }
260}
261
262pub fn parse_env_file(text: &str) -> Vec<(String, String)> {
263    let mut pairs = Vec::new();
264    for raw_line in text.lines() {
265        let line = raw_line.trim();
266        if line.is_empty() || line.starts_with('#') {
267            continue;
268        }
269        let line = if let Some(rest) = line.strip_prefix("export ") {
270            rest.trim_start()
271        } else if let Some(rest) = line.strip_prefix("export\t") {
272            rest.trim_start()
273        } else {
274            line
275        };
276        let Some((raw_name, raw_val)) = line.split_once('=') else {
277            continue;
278        };
279        let name = raw_name.trim();
280        if name.is_empty() {
281            continue;
282        }
283        let val = raw_val.trim();
284        let unquoted = if val.len() >= 2
285            && ((val.starts_with('"') && val.ends_with('"'))
286                || (val.starts_with('\'') && val.ends_with('\'')))
287        {
288            &val[1..val.len() - 1]
289        } else {
290            val
291        };
292        pairs.push((name.to_string(), unquoted.to_string()));
293    }
294    pairs
295}