Skip to main content

agentmux_srv_core/backend/audit_activity/
scrub.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one-line summaries of tool calls. A summary is made when the row is written and never copies a raw call: a
5//! command is cut to its start, a path is the path, a MuxAPI tool is its tool and action. Text that still looks like a
6//! secret is dropped, and the row says only which tool it was.
7
8use serde_json::Value;
9
10/// The longest a command or pattern is kept.
11const TEXT_MAX: usize = 80;
12/// The longest a path is kept.
13const PATH_MAX: usize = 200;
14
15/// Words in the name of a variable or flag that make what follows a secret: `API_KEY=…`, `--token …`.
16const SECRET_NAMES: [&str; 8] = ["pass", "secret", "token", "key", "auth", "cred", "cookie", "bearer"];
17/// What a known kind of secret starts with.
18const SECRET_PREFIXES: [&str; 11] = ["sk-", "sk_", "ghp_", "gho_", "ghs_", "ghu_", "github_pat_", "xox", "akia", "asia", "aiza"];
19
20/// The one-line summary of the call `tool(input)`. Never longer than a line, and never a secret.
21pub fn summarize(tool: &str, input: &Value) -> String {
22    let field = |name: &str| input.get(name).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty());
23    let text = |value: &str| {
24        let one_line = first_line(value, TEXT_MAX);
25        if looks_secret(&one_line) {
26            None
27        } else {
28            Some(one_line)
29        }
30    };
31    let detail = match tool {
32        "Bash" => field("command").and_then(text),
33        "Read" | "Edit" | "Write" | "MultiEdit" | "NotebookEdit" => {
34            field("file_path").or_else(|| field("notebook_path")).map(|p| first_line(p, PATH_MAX))
35        }
36        "Glob" | "Grep" => field("pattern").and_then(text),
37        "WebFetch" | "WebSearch" => field("url").and_then(site_of).or_else(|| field("query").and_then(text)),
38        "Task" | "Agent" => field("description").and_then(text),
39        _ => mux_detail(tool, input),
40    };
41    match detail {
42        Some(d) => format!("{} {d}", short_name(tool)),
43        None => short_name(tool),
44    }
45}
46
47/// `mcp__agentmux__Message` is `Message`; any other tool keeps its name.
48fn short_name(tool: &str) -> String {
49    tool.strip_prefix("mcp__agentmux__").unwrap_or(tool).to_string()
50}
51
52/// A MuxAPI tool's action, and for a message who it goes to; the Vault's action only.
53fn mux_detail(tool: &str, input: &Value) -> Option<String> {
54    let name = tool.strip_prefix("mcp__agentmux__")?;
55    let action = input.get("action").and_then(Value::as_str).filter(|a| is_word(a))?;
56    if name == "Vault" {
57        return Some(action.to_string());
58    }
59    match input.get("to").and_then(Value::as_str).filter(|t| is_word(t)) {
60        Some(to) if action == "send" => Some(format!("{action} to {to}")),
61        _ => Some(action.to_string()),
62    }
63}
64
65/// An action word or an agent name: short, no spaces, nothing that carries text.
66fn is_word(s: &str) -> bool {
67    !s.is_empty() && s.len() <= 40 && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
68}
69
70/// `scheme://host` of a URL, and nothing after it: a path can hold a token (a webhook's), and the part before the host
71/// can hold a password. None when the URL has user information or does not look like a URL.
72fn site_of(url: &str) -> Option<String> {
73    let (scheme, rest) = url.split_once("://")?;
74    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
75    let site = format!("{scheme}://{authority}");
76    (!authority.is_empty() && !authority.contains('@') && is_word_like(scheme) && !looks_secret(&site)).then(|| first_line(&site, PATH_MAX))
77}
78
79/// A scheme: letters, digits and the few signs a scheme may have.
80fn is_word_like(s: &str) -> bool {
81    !s.is_empty() && s.len() <= 12 && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
82}
83
84/// The first line of `s`, at most `max` characters, with the cut marked.
85fn first_line(s: &str, max: usize) -> String {
86    let line = s.lines().next().unwrap_or("").trim();
87    if line.chars().count() > max {
88        let mut cut: String = line.chars().take(max).collect();
89        cut.push('…');
90        cut
91    } else {
92        line.to_string()
93    }
94}
95
96/// Whether `s` looks like it holds a secret: a token of a known kind, a long run of token characters, a secret-named
97/// variable or flag with a value, or an authorization header.
98pub fn looks_secret(s: &str) -> bool {
99    let lower = s.to_ascii_lowercase();
100    if lower.contains("authorization") || lower.contains("bearer ") || lower.contains("-----begin") || has_userinfo(s) {
101        return true;
102    }
103    if names_a_secret(&lower) {
104        return true;
105    }
106    s.split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '+'))).any(token_looks_secret)
107}
108
109/// A URL with user information (`scheme://user:password@host`): the part before the host can be a password.
110fn has_userinfo(s: &str) -> bool {
111    s.match_indices("://").any(|(at, _)| {
112        let rest = &s[at + 3..];
113        let authority = rest.split(|c: char| c == '/' || c == '?' || c == '#' || c.is_whitespace() || matches!(c, '\'' | '"')).next().unwrap_or("");
114        authority.contains('@')
115    })
116}
117
118/// `NAME=value`, `NAME: value` or `--name value` where the name is a secret's.
119fn names_a_secret(lower: &str) -> bool {
120    let words: Vec<&str> = lower.split_whitespace().collect();
121    for (i, word) in words.iter().enumerate() {
122        let (name, has_value) = match word.split_once(['=', ':']) {
123            Some((n, v)) => (n, !v.is_empty() || words.get(i + 1).is_some()),
124            None if word.starts_with("--") => (*word, words.get(i + 1).is_some_and(|next| !next.starts_with('-'))),
125            // A snake_case name such as `aws_secret_access_key` with a value after it.
126            None if word.contains('_') && words.get(i + 1).is_some() => (*word, true),
127            None => continue,
128        };
129        if has_value && SECRET_NAMES.iter().any(|s| name.contains(s)) {
130            return true;
131        }
132    }
133    false
134}
135
136fn token_looks_secret(token: &str) -> bool {
137    let lower = token.to_ascii_lowercase();
138    if token.len() >= 12 && SECRET_PREFIXES.iter().any(|p| lower.starts_with(p)) {
139        return true;
140    }
141    // A JWT starts with the encoded header `{"`.
142    if token.len() >= 20 && token.starts_with("eyJ") {
143        return true;
144    }
145    if token.len() < 32 || is_uuid(token) {
146        return false;
147    }
148    let (digits, letters) = (token.chars().any(|c| c.is_ascii_digit()), token.chars().any(|c| c.is_ascii_alphabetic()));
149    digits && letters
150}
151
152fn is_uuid(token: &str) -> bool {
153    let parts: Vec<&str> = token.split('-').collect();
154    parts.len() == 5 && [8, 4, 4, 4, 12].iter().zip(&parts).all(|(n, p)| p.len() == *n && p.chars().all(|c| c.is_ascii_hexdigit()))
155}