Skip to main content

orch/
security.rs

1//! Leak detection for agent output before it is posted to GitHub. It uses the strict rules of
2//! `secret-redact`, so a low-confidence pattern blocks a post as much as a known token does
3
4use secret_redact::Finding;
5
6/// Every leaked secret in `text`, with its rule and line
7pub fn scan(text: &str) -> Vec<Finding> {
8    secret_redact::strict().scan(text)
9}
10
11/// Whether `text` holds anything that looks like a secret. Nothing is posted to GitHub when it does
12pub fn has_leaks(text: &str) -> bool {
13    secret_redact::strict().contains_secret(text)
14}
15
16/// `text` with every secret replaced by `[REDACTED:{rule}]`
17pub fn redact(text: &str) -> String {
18    secret_redact::strict().redact(text).text
19}
20
21pub fn redact_posted_body(body: &str) -> String {
22    if !has_leaks(body) {
23        return body.to_string();
24    }
25    let leaks = scan(body);
26    let rules: Vec<&str> = leaks.iter().map(|leak| leak.rule).collect();
27    let warning = format!(
28        "\n\n> ⚠️ **Security Notice**: {} potential secret(s) detected and redacted: {}",
29        leaks.len(),
30        rules.join(", ")
31    );
32    format!("{}{warning}", redact(body))
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn detects_and_redacts_a_github_token() {
41        let text = "export GITHUB_TOKEN=ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij";
42        assert_eq!(scan(text)[0].rule, "github-pat");
43        let redacted = redact(text);
44        assert!(redacted.contains("[REDACTED:github-pat]"), "{redacted}");
45        assert!(!redacted.contains("ghp_"), "{redacted}");
46    }
47
48    #[test]
49    fn detects_private_keys_connection_strings_and_example_keys() {
50        assert!(has_leaks(
51            "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQ..."
52        ));
53        assert!(has_leaks(
54            "DATABASE_URL=postgres://user:pass@host:5432/mydb"
55        ));
56        assert!(has_leaks("AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE"));
57    }
58
59    #[test]
60    fn clean_text_has_no_leaks() {
61        let text = "This is normal agent output.\nFixed bug in parser.rs\nAll tests pass.";
62        assert!(!has_leaks(text));
63    }
64
65    #[test]
66    fn has_leaks_triggers_on_low_confidence_patterns() {
67        let text = "password = \"some_long_config_value_that_is_16_chars\"";
68        assert!(
69            has_leaks(text),
70            "generic_secret (low confidence) should trigger has_leaks"
71        );
72
73        let text = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0";
74        assert!(
75            has_leaks(text),
76            "bearer_token (low confidence) should trigger has_leaks"
77        );
78    }
79}