Skip to main content

agentmux_common/
allowed_origins.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sites an agent's browser pane may go to, when the agent limited it
5//! with `OpenBrowser({allowed_origins})`
6//! (docs/specs/SPEC_BROWSER_PANE_ALLOWED_ORIGINS_2026_10_09.md §2).
7//!
8//! Shared by srv, which checks the list it is given and re-checks every
9//! request, and the CEF host, which stops a navigation off the list before it
10//! happens. A list is kept in its normal form (`parse`): `https://example.com`,
11//! `https://*.example.com`, `http://localhost:3000`.
12
13/// Most entries one pane's list may have.
14pub const MAX_ENTRIES: usize = 32;
15
16/// `entry` in its normal form, or why it isn't a valid entry:
17/// - `example.com` → `https://example.com`
18/// - `*.example.com` → `https://*.example.com` (the domain and its subdomains)
19/// - `https://example.com:8443/any/path` → `https://example.com:8443`
20/// - `http://localhost:3000` → itself: `http` only when written out.
21pub fn parse(entry: &str) -> Result<String, String> {
22    let entry = entry.trim();
23    if entry.is_empty() {
24        return Err("an empty entry".to_string());
25    }
26    let (wildcard, rest) = match entry.strip_prefix("*.") {
27        Some(rest) => (true, rest),
28        None => (false, entry),
29    };
30    let with_scheme = if rest.contains("://") { rest.to_string() } else { format!("https://{rest}") };
31    let bad = || format!("{entry:?} isn't a site (write example.com, *.example.com or https://example.com:8443)");
32    let url = url::Url::parse(&with_scheme).map_err(|_| bad())?;
33    if !matches!(url.scheme(), "http" | "https") {
34        return Err(format!("{entry:?} isn't an http or https site"));
35    }
36    let Some(host) = url.host() else { return Err(bad()) };
37    let Some(origin) = crate::url_guard::origin_string(&url) else { return Err(bad()) };
38    if !wildcard {
39        return Ok(origin);
40    }
41    match host {
42        url::Host::Domain(d) if d.contains('.') => {
43            // The origin with `*.` in front of its host.
44            Ok(origin.replacen("://", "://*.", 1))
45        }
46        _ => Err(format!("{entry:?}: `*.` goes in front of a domain name with a dot in it")),
47    }
48}
49
50/// Parse every entry of `entries`, deduplicated, in order. Fails on the
51/// first bad entry, or past `MAX_ENTRIES`.
52pub fn parse_list(entries: &[String]) -> Result<Vec<String>, String> {
53    let mut out: Vec<String> = Vec::new();
54    for e in entries {
55        let p = parse(e)?;
56        if !out.contains(&p) {
57            out.push(p);
58        }
59    }
60    if out.len() > MAX_ENTRIES {
61        return Err(format!("at most {MAX_ENTRIES} sites"));
62    }
63    Ok(out)
64}
65
66/// The origin a navigation to `url` goes to, as an entry would name it
67/// exactly (a `blob:` URL's is the origin it belongs to). `None` for an
68/// address with no such origin (`about:`, `data:`, a `blob:` address that carries another `blob:` address).
69pub fn target_origin(url: &str) -> Option<String> {
70    let u = url::Url::parse(url).ok()?;
71    let origin = crate::url_guard::checked_origin(&u)?;
72    match &origin {
73        url::Origin::Tuple(scheme, _, _) if scheme == "http" || scheme == "https" => Some(origin.ascii_serialization()),
74        _ => None,
75    }
76}
77
78/// `url` as an origin and nothing else: the origin ([`target_origin`]) when `url` names no more than one (no path
79/// beyond `/`, no query, fragment or user information), else `None`. What a saved site is stored as when it is only
80/// an origin written another way (`HTTPS://Example.com:443/` becomes `https://example.com`); an address with a path
81/// is a login's own page and is left as it was typed.
82pub fn bare_origin(url: &str) -> Option<String> {
83    let u = url::Url::parse(url.trim()).ok()?;
84    let bare = u.path() == "/" && u.query().is_none() && u.fragment().is_none() && u.username().is_empty() && u.password().is_none();
85    if bare { target_origin(u.as_str()) } else { None }
86}
87
88/// Whether `a` and `b` name the same origin: the same scheme, host (any case) and port (the scheme's default when
89/// absent), whatever else either carries (a trailing slash, a path, a query, user information). Never true for
90/// another host, port or scheme. An address with no web origin is the same as another only when written the same.
91pub fn same_origin(a: &str, b: &str) -> bool {
92    match (target_origin(a.trim()), target_origin(b.trim())) {
93        (Some(x), Some(y)) => x == y,
94        _ => a.trim() == b.trim(),
95    }
96}
97
98/// May a pane limited to `list` (normal form) go to `url`? `about:` pages
99/// always; any other address with no web origin, never.
100pub fn allows(list: &[String], url: &str) -> bool {
101    if url::Url::parse(url).is_ok_and(|u| u.scheme() == "about") {
102        return true;
103    }
104    let Some(target) = target_origin(url) else { return false };
105    list.iter().any(|entry| entry_allows(entry, &target))
106}
107
108fn entry_allows(entry: &str, target: &str) -> bool {
109    if entry == target {
110        return true;
111    }
112    // `scheme://*.domain[:port]` matches the domain and any subdomain, on
113    // that scheme and port.
114    let Some((scheme, rest)) = entry.split_once("://*.") else { return false };
115    let Some(t_rest) = target.strip_prefix(scheme).and_then(|t| t.strip_prefix("://")) else {
116        return false;
117    };
118    let (domain, port) = split_port(rest);
119    let (t_host, t_port) = split_port(t_rest);
120    port == t_port && (t_host == domain || t_host.ends_with(&format!(".{domain}")))
121}
122
123/// `host[:port]` → (host, port), the port empty when there is none. An IPv6
124/// host (`[::1]`) without a port is left whole.
125fn split_port(s: &str) -> (&str, &str) {
126    if s.ends_with(']') {
127        return (s, "");
128    }
129    match s.rsplit_once(':') {
130        Some((h, p)) if !h.is_empty() && !p.is_empty() && p.bytes().all(|c| c.is_ascii_digit()) => (h, p),
131        _ => (s, ""),
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn a_saved_site_and_a_page_origin_match_as_origins_not_as_strings() {
141        // With and without the trailing slash, in both directions.
142        assert!(same_origin("http://host.example:8080", "http://host.example:8080/"));
143        assert!(same_origin("http://host.example:8080/", "http://host.example:8080"));
144        // Upper-case scheme and host.
145        assert!(same_origin("HTTPS://Example.COM", "https://example.com/"));
146        // The scheme's default port is the same as none, and an explicit other port is another origin.
147        assert!(same_origin("https://example.com:443", "https://example.com"));
148        assert!(same_origin("http://example.com:80/", "http://example.com"));
149        assert!(!same_origin("https://example.com:8443", "https://example.com"));
150        assert!(!same_origin("http://example.com:8080", "http://example.com:8081"));
151        // Another scheme is another origin: http is not https.
152        assert!(!same_origin("http://example.com", "https://example.com"));
153        // A look-alike host is another host, however it is written.
154        assert!(!same_origin("https://example.com.evil.test", "https://example.com"));
155        assert!(!same_origin("https://exarnple.com", "https://example.com"));
156        assert!(!same_origin("https://example.com@evil.test", "https://example.com"), "the host is what follows the @");
157        assert!(!same_origin("https://sub.example.com", "https://example.com"));
158        // A path, query or user information is ignored for the match, and widens it to no other host or port.
159        assert!(same_origin("https://example.com/login?next=/a", "https://example.com"));
160        assert!(same_origin("https://user@example.com/app", "https://example.com/"));
161        assert!(!same_origin("https://example.com/app", "https://example.com:8443"));
162        // What has no web origin is the same only as written.
163        assert!(same_origin("example.com", " example.com "));
164        assert!(!same_origin("example.com", "https://example.com"));
165    }
166
167    #[test]
168    fn a_site_that_is_only_an_origin_is_stored_in_one_form_and_a_login_page_is_left_alone() {
169        assert_eq!(bare_origin("HTTPS://Example.com:443/").as_deref(), Some("https://example.com"));
170        assert_eq!(bare_origin("http://host.example:8080/").as_deref(), Some("http://host.example:8080"));
171        assert_eq!(bare_origin(" https://example.com ").as_deref(), Some("https://example.com"));
172        assert_eq!(bare_origin("https://example.com/login"), None, "a path is the login's own page");
173        assert_eq!(bare_origin("https://example.com/?a=1"), None);
174        assert_eq!(bare_origin("https://user@example.com"), None, "user information is not dropped without being asked");
175        assert_eq!(bare_origin("example.com"), None);
176        assert_eq!(bare_origin("about:blank"), None);
177    }
178
179    #[test]
180    fn entries_parse_to_their_normal_form() {
181        assert_eq!(parse("example.com").unwrap(), "https://example.com");
182        assert_eq!(parse(" Example.COM ").unwrap(), "https://example.com");
183        assert_eq!(parse("*.example.com").unwrap(), "https://*.example.com");
184        assert_eq!(parse("https://example.com:8443/a?b#c").unwrap(), "https://example.com:8443");
185        assert_eq!(parse("https://example.com:443").unwrap(), "https://example.com");
186        assert_eq!(parse("http://localhost:3000").unwrap(), "http://localhost:3000");
187        assert_eq!(parse("example.com/some/path").unwrap(), "https://example.com");
188        assert_eq!(parse("bücher.example").unwrap(), "https://xn--bcher-kva.example");
189        assert_eq!(parse("http://[::1]:8080").unwrap(), "http://[::1]:8080");
190        assert_eq!(parse("*.example.com:8443").unwrap(), "https://*.example.com:8443");
191    }
192
193    #[test]
194    fn bad_entries_are_refused() {
195        for bad in ["", "  ", "ftp://example.com", "javascript:alert(1)", "*.localhost", "*.192.0.2.1", "https://", "*."] {
196            assert!(parse(bad).is_err(), "{bad:?}");
197        }
198        let many: Vec<String> = (0..=MAX_ENTRIES).map(|i| format!("s{i}.example.com")).collect();
199        assert!(parse_list(&many).is_err());
200        assert_eq!(parse_list(&["a.example".into(), "https://a.example/".into()]).unwrap(), vec!["https://a.example"]);
201    }
202
203    #[test]
204    fn a_list_allows_its_sites_and_nothing_else() {
205        let list = parse_list(&["example.com".into(), "*.docs.example.org".into(), "http://localhost:3000".into()]).unwrap();
206        let ok = |u: &str| allows(&list, u);
207        assert!(ok("https://example.com/"));
208        assert!(ok("https://example.com/deep/path?q=1"));
209        assert!(!ok("https://www.example.com/"), "a bare domain is just that host");
210        assert!(!ok("http://example.com/"), "http only when written out");
211        assert!(!ok("https://example.com:8443/"));
212        assert!(ok("https://docs.example.org/"));
213        assert!(ok("https://a.b.docs.example.org/"));
214        assert!(!ok("https://evil-docs.example.org/"));
215        assert!(!ok("https://docs.example.org.evil.example/"));
216        assert!(ok("http://localhost:3000/app"));
217        assert!(!ok("http://localhost:3001/"));
218        assert!(!ok("https://evil.example/"));
219        // A blob belongs to its origin.
220        assert!(ok("blob:https://example.com/0f0e"));
221        assert!(!ok("blob:https://evil.example/0f0e"));
222        // about: pages are always fine; other non-web addresses never.
223        assert!(ok("about:blank"));
224        assert!(!ok("data:text/html,hi"));
225        assert!(!ok("file:///etc/passwd"));
226        assert!(!ok("not a url"));
227    }
228
229    #[test]
230    fn a_wildcard_keeps_its_port() {
231        let list = parse_list(&["*.example.com:8443".into()]).unwrap();
232        assert!(allows(&list, "https://a.example.com:8443/"));
233        assert!(!allows(&list, "https://a.example.com/"));
234    }
235
236    #[test]
237    fn target_origin_is_what_allow_adds() {
238        assert_eq!(target_origin("https://Evil.Example:443/x?y").as_deref(), Some("https://evil.example"));
239        assert_eq!(target_origin("blob:https://a.example/id").as_deref(), Some("https://a.example"));
240        assert_eq!(target_origin("about:blank"), None);
241        assert_eq!(target_origin("data:text/html,x"), None);
242        // What Allow adds then allows the same address.
243        let added = vec![target_origin("https://new.example/path").unwrap()];
244        assert!(allows(&added, "https://new.example/other"));
245    }
246
247    #[test]
248    fn an_address_that_nests_blob_addresses_has_no_origin_and_is_not_allowed() {
249        let list = parse_list(&["https://a.example".into()]).unwrap();
250        let deep = format!("{}https://a.example/id", "blob:".repeat(50_000));
251        for url in ["blob:blob:https://a.example/id", deep.as_str()] {
252            assert_eq!(target_origin(url), None);
253            assert!(!allows(&list, url));
254            assert!(!same_origin(url, "https://a.example/"));
255        }
256        // An ordinary blob address is as before.
257        assert!(allows(&list, "blob:https://a.example/id"));
258    }
259}