Skip to main content

agentmux_common/
shown_url.rs

1//! How a page address is shown to an agent (in an action's answer, a wait, a snapshot header, the action log).
2//!
3//! A sign-in redirect carries one-time values in its query or fragment: the request's state and nonce, the
4//! authorization code and its code challenge, or a token. An agent that reads the whole address has them in its
5//! context, its transcript and anything it quotes. So an address whose query or fragment carries one of those keys
6//! is shown as its scheme, host and path, with the query shown as `?...` and the fragment as `#...`. Any other
7//! address keeps its query and fragment: a search (`?q=`) or a record (`?id=`) is what the agent needs to read.
8//! A user name and password in the authority are never shown.
9
10/// Keys (lowercase) that make an address one to cut.
11const SECRET_KEYS: &[&str] = &[
12    "state",
13    "nonce",
14    "code",
15    "code_challenge",
16    "code_verifier",
17    "id_token",
18    "access_token",
19    "refresh_token",
20    "session",
21    "session_id",
22    "sessionid",
23    "token",
24    "continue",
25    "client_secret",
26    "id_token_hint",
27    "samlrequest",
28    "samlresponse",
29    "relaystate",
30];
31
32/// `url` as an agent may read it. Every place a tool prints a page address goes through this.
33pub fn shown_url(url: &str) -> String {
34    let (before_fragment, fragment) = match url.split_once('#') {
35        Some((a, b)) => (a, Some(b)),
36        None => (url, None),
37    };
38    let (base, query) = match before_fragment.split_once('?') {
39        Some((a, b)) => (a, Some(b)),
40        None => (before_fragment, None),
41    };
42    let base = without_userinfo(base);
43    // A single-page app keeps its parameters after a `?` inside the fragment (`#/callback?code=...`).
44    let fragment_params = fragment.map(|f| f.split_once('?').map_or(f, |(_, q)| q));
45    let cut = query.is_some_and(carries_secret) || fragment_params.is_some_and(carries_secret);
46    let mut out = base;
47    if cut {
48        if query.is_some() {
49            out.push_str("?...");
50        }
51        if fragment.is_some() {
52            out.push_str("#...");
53        }
54        return out;
55    }
56    if let Some(q) = query {
57        out.push('?');
58        out.push_str(q);
59    }
60    if let Some(f) = fragment {
61        out.push('#');
62        out.push_str(f);
63    }
64    out
65}
66
67/// `scheme://host/path` without a `user:password@` in the authority.
68fn without_userinfo(base: &str) -> String {
69    let Some((scheme, rest)) = base.split_once("://") else { return base.to_string() };
70    let (authority, path) = match rest.find('/') {
71        Some(i) => rest.split_at(i),
72        None => (rest, ""),
73    };
74    let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
75    format!("{scheme}://{host}{path}")
76}
77
78/// Whether a `a=b&c=d` list has a pair whose key is one to cut. A bare word is not a pair (`#code` is an anchor).
79fn carries_secret(params: &str) -> bool {
80    params.split(['&', ';']).any(|pair| {
81        let Some((key, _)) = pair.split_once('=') else { return false };
82        let key = percent_decode(key).to_ascii_lowercase();
83        SECRET_KEYS.contains(&key.as_str())
84    })
85}
86
87fn percent_decode(s: &str) -> String {
88    let bytes = s.as_bytes();
89    let mut out = Vec::with_capacity(bytes.len());
90    let mut i = 0;
91    while i < bytes.len() {
92        let hex = |b: u8| (b as char).to_digit(16);
93        match bytes[i] {
94            b'%' if i + 2 < bytes.len() && hex(bytes[i + 1]).is_some() && hex(bytes[i + 2]).is_some() => {
95                out.push((hex(bytes[i + 1]).unwrap_or(0) * 16 + hex(bytes[i + 2]).unwrap_or(0)) as u8);
96                i += 3;
97            }
98            b'+' => {
99                out.push(b' ');
100                i += 1;
101            }
102            b => {
103                out.push(b);
104                i += 1;
105            }
106        }
107    }
108    String::from_utf8_lossy(&out).into_owned()
109}
110
111#[cfg(test)]
112mod tests {
113    use super::shown_url;
114
115    #[test]
116    fn a_provider_authorize_address_is_cut_to_its_path() {
117        let u = "https://idp.example/oauth2/authorize?client_id=abc&redirect_uri=https%3A%2F%2Fapp.example%2Fcb\
118                 &response_type=code&state=S3CRET&nonce=N0NCE&code_challenge=CHAL&code_challenge_method=S256";
119        assert_eq!(shown_url(u), "https://idp.example/oauth2/authorize?...");
120    }
121
122    #[test]
123    fn a_token_in_the_fragment_is_cut() {
124        assert_eq!(shown_url("https://app.example/cb#access_token=TOK&token_type=bearer&state=S"), "https://app.example/cb#...");
125        assert_eq!(shown_url("https://app.example/#/callback?code=ONE"), "https://app.example/#...");
126    }
127
128    #[test]
129    fn a_search_and_a_record_keep_their_query() {
130        assert_eq!(shown_url("https://shop.example/search?q=red+shoes&page=2"), "https://shop.example/search?q=red+shoes&page=2");
131        assert_eq!(shown_url("https://shop.example/orders?id=1042#items"), "https://shop.example/orders?id=1042#items");
132    }
133
134    #[test]
135    fn a_sign_in_address_with_no_query_is_unchanged() {
136        assert_eq!(shown_url("https://idp.example/signin"), "https://idp.example/signin");
137        assert_eq!(shown_url("https://docs.example/guide#code"), "https://docs.example/guide#code");
138    }
139
140    #[test]
141    fn an_ordinary_host_carrying_a_code_is_cut() {
142        assert_eq!(shown_url("https://shop.example/return?id=7&code=ABC123"), "https://shop.example/return?...");
143        assert_eq!(shown_url("https://shop.example/next?continue=https%3A%2F%2Fshop.example%2Fa%3Fx%3D1"), "https://shop.example/next?...");
144    }
145
146    #[test]
147    fn a_key_is_matched_whatever_its_case_or_encoding() {
148        assert_eq!(shown_url("https://x.example/p?Code=1"), "https://x.example/p?...");
149        assert_eq!(shown_url("https://x.example/p?st%61te=1"), "https://x.example/p?...");
150        assert_eq!(shown_url("https://x.example/p?statement=1&codex=2"), "https://x.example/p?statement=1&codex=2");
151    }
152
153    #[test]
154    fn a_user_name_and_password_are_never_shown() {
155        assert_eq!(shown_url("https://me:hunter2@host.example/a?q=1"), "https://host.example/a?q=1");
156        assert_eq!(shown_url("https://me:hunter2@host.example"), "https://host.example");
157    }
158
159    #[test]
160    fn what_is_not_an_address_passes_through() {
161        assert_eq!(shown_url(""), "");
162        assert_eq!(shown_url("about:blank"), "about:blank");
163    }
164}