Skip to main content

agentmux_common/
capture_shape.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The shape a `Browser` `capture` can ask a value to have (#47629).
5//!
6//! A capture of text with no ref of its own chooses the value among the text around it, and nothing is
7//! saved if it is not the shape the agent said. A guard that answers yes or no about a value the agent
8//! cannot read is a question about the value, so the shapes are a closed list, never an expression the
9//! agent writes: a short `prefix` (at most [`MAX_PREFIX`] characters), one of the [`NAMES`] of a kind of
10//! secret, and a length range. The host (to choose among the words of a row) and srv (before anything is
11//! stored) use the same rule from here, and srv budgets how many shaped captures an agent may make
12//! (`browser_capture_shape.rs`).
13
14use serde::{Deserialize, Serialize};
15
16/// The longest prefix taken: enough to tell a kind of key from its neighbours, too little to read a value out.
17pub const MAX_PREFIX: usize = 12;
18/// The longest value a range can allow.
19pub const MAX_LENGTH: u32 = 16 * 1024;
20
21/// The named shapes, as the agent is told them. `digits:N` is N digits, 1 to 32 (a six-digit code).
22pub const NAMES: &[&str] =
23    &["stripe-secret", "stripe-publishable", "stripe-webhook", "aws-access-key", "aws-secret-key", "github-token", "slack-token", "jwt", "uuid", "hex", "base64", "alnum", "digits:N"];
24
25fn all(text: &str, ok: impl Fn(char) -> bool) -> bool {
26    !text.is_empty() && text.chars().all(ok)
27}
28
29fn alnum(c: char) -> bool {
30    c.is_ascii_alphanumeric()
31}
32
33/// `text` after one of `prefixes`, when it has one.
34fn after<'a>(text: &'a str, prefixes: &[&str]) -> Option<&'a str> {
35    prefixes.iter().find_map(|p| text.strip_prefix(p))
36}
37
38fn is_uuid(text: &str) -> bool {
39    let groups: Vec<&str> = text.split('-').collect();
40    groups.len() == 5 && groups.iter().zip([8, 4, 4, 4, 12]).all(|(g, n)| g.len() == n && g.bytes().all(|b| b.is_ascii_hexdigit()))
41}
42
43/// Whether `value` is the kind of secret `name` says; `None` when there is no such name.
44fn is_named(name: &str, value: &str) -> Option<bool> {
45    let rest_alnum = |rest: Option<&str>, min: usize| rest.is_some_and(|r| r.len() >= min && all(r, alnum));
46    Some(match name {
47        "stripe-secret" => rest_alnum(after(value, &["sk_live_", "sk_test_", "rk_live_", "rk_test_"]), 16),
48        "stripe-publishable" => rest_alnum(after(value, &["pk_live_", "pk_test_"]), 16),
49        "stripe-webhook" => rest_alnum(after(value, &["whsec_"]), 16),
50        "aws-access-key" => value.len() == 20 && after(value, &["AKIA", "ASIA"]).is_some_and(|r| all(r, |c| c.is_ascii_uppercase() || c.is_ascii_digit())),
51        "aws-secret-key" => value.len() == 40 && all(value, |c| alnum(c) || c == '/' || c == '+'),
52        "github-token" => {
53            rest_alnum(after(value, &["ghp_", "gho_", "ghu_", "ghs_", "ghr_"]), 36)
54                || after(value, &["github_pat_"]).is_some_and(|r| r.len() >= 22 && all(r, |c| alnum(c) || c == '_'))
55        }
56        "slack-token" => after(value, &["xoxb-", "xoxp-", "xoxa-", "xoxr-", "xoxs-"]).is_some_and(|r| r.len() >= 10 && all(r, |c| alnum(c) || c == '-')),
57        "jwt" => {
58            let parts: Vec<&str> = value.split('.').collect();
59            parts.len() == 3 && parts[0].starts_with("eyJ") && parts.iter().all(|p| all(p, |c| alnum(c) || c == '-' || c == '_' || c == '='))
60        }
61        "uuid" => is_uuid(value),
62        "hex" => value.len() >= 8 && all(value, |c| c.is_ascii_hexdigit()),
63        "base64" => value.len() >= 8 && all(value, |c| alnum(c) || "+/=_-".contains(c)),
64        "alnum" => value.len() >= 8 && all(value, alnum),
65        n => {
66            let digits: usize = n.strip_prefix("digits:")?.parse().ok().filter(|d| (1..=32).contains(d))?;
67            value.len() == digits && all(value, |c| c.is_ascii_digit())
68        }
69    })
70}
71
72/// What the agent asked a captured value to be.
73#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
74pub struct CaptureShape {
75    /// The value starts with this.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub prefix: Option<String>,
78    /// The value is this kind of secret, one of [`NAMES`].
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub name: Option<String>,
81    /// The value is this many characters at least, and at most.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub min_length: Option<u32>,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub max_length: Option<u32>,
86}
87
88impl CaptureShape {
89    /// The shape asked for, or none when nothing was; an error says what to fix.
90    pub fn new(prefix: Option<&str>, name: Option<&str>, min_length: Option<u32>, max_length: Option<u32>) -> Result<Option<Self>, String> {
91        let prefix = prefix.map(str::trim).filter(|p| !p.is_empty());
92        let name = name.map(str::trim).filter(|n| !n.is_empty());
93        if prefix.is_none() && name.is_none() && min_length.is_none() && max_length.is_none() {
94            return Ok(None);
95        }
96        if prefix.is_some_and(|p| p.chars().count() > MAX_PREFIX || p.chars().any(char::is_whitespace)) {
97            return Err(format!("prefix is one word of at most {MAX_PREFIX} characters"));
98        }
99        if name.is_some_and(|n| is_named(n, "").is_none()) {
100            return Err(format!("shape is one of: {}", NAMES.join(", ")));
101        }
102        let (min, max) = (min_length.unwrap_or(1), max_length.unwrap_or(MAX_LENGTH));
103        if min == 0 || max > MAX_LENGTH || min > max {
104            return Err(format!("min_length and max_length are from 1 to {MAX_LENGTH}, the first not above the second"));
105        }
106        Ok(Some(Self { prefix: prefix.map(str::to_string), name: name.map(str::to_string), min_length, max_length }))
107    }
108
109    /// Whether `value` (trimmed) has the shape.
110    pub fn matches(&self, value: &str) -> bool {
111        let v = value.trim();
112        let len = v.chars().count() as u32;
113        self.prefix.as_deref().is_none_or(|p| v.starts_with(p))
114            && self.name.as_deref().is_none_or(|n| is_named(n, v) == Some(true))
115            && self.min_length.is_none_or(|m| len >= m)
116            && self.max_length.is_none_or(|m| len <= m)
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    /// A fixture key, built from two pieces so no whole one sits in the source.
125    fn key(prefix: &str, body: &str) -> String {
126        format!("{prefix}{body}")
127    }
128
129    fn shape(prefix: Option<&str>, name: Option<&str>, min: Option<u32>, max: Option<u32>) -> CaptureShape {
130        CaptureShape::new(prefix, name, min, max).unwrap().unwrap()
131    }
132
133    #[test]
134    fn nothing_asked_for_is_no_shape() {
135        assert!(CaptureShape::new(None, None, None, None).unwrap().is_none());
136        assert!(CaptureShape::new(Some("  "), Some(""), None, None).unwrap().is_none());
137    }
138
139    #[test]
140    fn each_named_shape_takes_its_kind_of_value_and_refuses_the_others() {
141        let cases: [(&str, &str, &str); 11] = [
142            ("stripe-secret", &key("sk_live_", "abcdefghij123456"), &key("pk_live_", "abcdefghij123456")),
143            ("stripe-publishable", &key("pk_test_", "abcdefghij123456"), &key("sk_test_", "abcdefghij123456")),
144            ("stripe-webhook", &key("whsec_", "abcdefghij123456"), &key("whsec_", "short")),
145            ("aws-access-key", concat!("AKI", "AIOSFODNN7EXAMPLE"), concat!("AKI", "AIOSFODNN7EXAMPLE1")),
146            ("aws-secret-key", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKE"),
147            ("github-token", concat!("ghp", "_abcdefghijklmnopqrstuvwxyz0123456789"), concat!("ghp", "_short")),
148            ("slack-token", "xoxb-1234567890-abcdef", "xoxz-1234567890-abcdef"),
149            ("jwt", "eyJhbGciOi.eyJzdWIiOiIx.c2lnbmF0dXJl", "eyJhbGciOi.eyJzdWIiOiIx"),
150            ("uuid", "0f4c2a1e-9b7d-4e3a-8c6f-1a2b3c4d5e6f", "0f4c2a1e-9b7d-4e3a-8c6f"),
151            ("digits:6", "482913", "48291"),
152            ("hex", "c58ebaa8e2f1b0d9", "c58ebaa8e2f1b0dg"),
153        ];
154        for (name, yes, no) in cases {
155            let s = shape(None, Some(name), None, None);
156            assert!(s.matches(yes), "{name} takes {yes}");
157            assert!(!s.matches(no), "{name} refuses {no}");
158        }
159    }
160
161    #[test]
162    fn a_prefix_and_a_length_range_narrow_it_further() {
163        let s = shape(Some("sk_live_"), Some("stripe-secret"), Some(20), Some(40));
164        assert!(s.matches("  sk_live_abcdefghij123456\n"), "trimmed");
165        assert!(!s.matches(&key("sk_test_", "abcdefghij123456")), "the prefix");
166        assert!(!s.matches(&key("sk_live_", "abcdefghij1234567890abcdefghij1234567890")), "the range");
167        assert!(shape(Some("ab"), None, None, None).matches("abc") && !shape(Some("ab"), None, None, None).matches("ba"));
168    }
169
170    #[test]
171    fn a_shape_that_is_not_one_of_the_list_says_what_the_list_is() {
172        let err = CaptureShape::new(None, Some("[a-m].*"), None, None).unwrap_err();
173        assert!(err.contains("stripe-secret") && err.contains("digits:N"), "{err}");
174        assert!(CaptureShape::new(None, Some("digits:0"), None, None).is_err());
175        assert!(CaptureShape::new(None, Some("digits:33"), None, None).is_err());
176        assert!(CaptureShape::new(Some("thirteen_char"), None, None, None).unwrap_err().contains("12"));
177        assert!(CaptureShape::new(Some("two words"), None, None, None).is_err());
178        assert!(CaptureShape::new(None, None, Some(10), Some(5)).is_err());
179        assert!(CaptureShape::new(None, None, Some(0), None).is_err());
180    }
181}