Skip to main content

agentmux_srv/server/streamed_browser/
address_policy.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which addresses a page in the server's Chromium may connect to. The browser opens pages from the web on a
5//! machine that holds the user's workspace, so everything it connects to goes through `address_proxy`, which asks
6//! this module about each address it is about to connect to, after it has resolved the name itself. Plain data and
7//! functions, so every rule is tested without a network.
8//!
9//! Refused: this server's own listening ports on the loopback address, every private, link-local (the cloud
10//! metadata addresses among them), shared, documentation, multicast and reserved range, IPv6 forms that embed an
11//! IPv4 address (translated, 6to4, Teredo), and port 0. Allowed: the public internet, and other ports on the
12//! loopback address (a development server the user runs in the same workspace).
13
14use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
15use std::sync::Mutex;
16
17/// The ports this server listens on, noted as each listener binds. A page may never connect to one of them,
18/// whatever address it names for this machine.
19static OWN_PORTS: Mutex<Vec<u16>> = Mutex::new(Vec::new());
20
21/// Note a port this server listens on.
22pub fn note_own_port(port: u16) {
23    let mut ports = OWN_PORTS.lock().unwrap_or_else(|e| e.into_inner());
24    if !ports.contains(&port) {
25        ports.push(port);
26    }
27}
28
29/// Other loopback ports the person who runs this server wants kept from pages (a gateway or another service in the
30/// same network namespace), as a comma-separated list. Read by the server's own process: a page, or an agent, cannot
31/// set it.
32pub const DENY_PORTS_ENV: &str = "AGENTMUX_STREAMED_BROWSER_DENY_PORTS";
33
34/// The ports in a comma-separated list; anything that is not a port number is skipped.
35pub fn parse_ports(list: &str) -> Vec<u16> {
36    list.split(',').filter_map(|p| p.trim().parse::<u16>().ok()).filter(|p| *p != 0).collect()
37}
38
39/// Note the ports `DENY_PORTS_ENV` names.
40pub fn note_ports_from_env() {
41    if let Ok(list) = std::env::var(DENY_PORTS_ENV) {
42        parse_ports(&list).into_iter().for_each(note_own_port);
43    }
44}
45
46/// The ports noted so far.
47pub fn own_ports() -> Vec<u16> {
48    OWN_PORTS.lock().unwrap_or_else(|e| e.into_inner()).clone()
49}
50
51fn v4_refused(ip: Ipv4Addr) -> Option<&'static str> {
52    let o = ip.octets();
53    Some(match (o[0], o[1], o[2]) {
54        (0, _, _) => "this-network address",
55        (10, _, _) => "private address",
56        (100, 64..=127, _) => "shared (carrier-grade NAT) address",
57        (169, 254, _) => "link-local address (cloud metadata is here)",
58        (172, 16..=31, _) => "private address",
59        (192, 0, 0) => "reserved address",
60        (192, 0, 2) => "documentation address",
61        (192, 88, 99) => "reserved address",
62        (192, 168, _) => "private address",
63        (198, 18..=19, _) => "benchmarking address",
64        (198, 51, 100) => "documentation address",
65        (203, 0, 113) => "documentation address",
66        (224..=255, _, _) => "multicast or reserved address",
67        _ => return None,
68    })
69}
70
71fn v6_refused(ip: Ipv6Addr) -> Option<&'static str> {
72    let s = ip.segments();
73    if ip.is_unspecified() {
74        return Some("unspecified address");
75    }
76    // fc00::/7 unique local (the cloud's IPv6 metadata address is in it), fe80::/10 link-local, fec0::/10 site-local.
77    if s[0] & 0xfe00 == 0xfc00 {
78        return Some("private address");
79    }
80    if s[0] & 0xffc0 == 0xfe80 || s[0] & 0xffc0 == 0xfec0 {
81        return Some("link-local address");
82    }
83    if s[0] & 0xff00 == 0xff00 {
84        return Some("multicast address");
85    }
86    // Forms that carry an IPv4 address inside: a name server could hide a private one in them.
87    if s[0] == 0x0064 && s[1] == 0xff9b {
88        return Some("translated (NAT64) address");
89    }
90    if s[0] == 0x2002 {
91        return Some("6to4 address");
92    }
93    if s[0] == 0x2001 && s[1] == 0 {
94        return Some("Teredo address");
95    }
96    if s[0] == 0x2001 && s[1] == 0x0db8 {
97        return Some("documentation address");
98    }
99    None
100}
101
102/// The address with an IPv4 address written as IPv6 (`::ffff:a00:1`) read as the IPv4 one it is.
103fn plain(ip: IpAddr) -> IpAddr {
104    match ip {
105        IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(IpAddr::V6(v6)),
106        v4 => v4,
107    }
108}
109
110/// Whether a page may connect to `ip` on `port`; the reason in words when it may not. `own_ports` are this
111/// server's own listening ports.
112pub fn check(ip: IpAddr, port: u16, own_ports: &[u16]) -> Result<(), &'static str> {
113    if port == 0 {
114        return Err("port 0");
115    }
116    let ip = plain(ip);
117    if ip.is_loopback() {
118        return if own_ports.contains(&port) { Err("this server's own port") } else { Ok(()) };
119    }
120    let refused = match ip {
121        IpAddr::V4(v4) => v4_refused(v4),
122        IpAddr::V6(v6) => v6_refused(v6),
123    };
124    refused.map_or(Ok(()), Err)
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    fn ip(s: &str) -> IpAddr {
132        s.parse().unwrap()
133    }
134
135    #[test]
136    fn a_page_cannot_reach_the_cloud_metadata_address() {
137        // The container task metadata and credentials endpoint, the instance metadata address, and the IPv6 one.
138        for a in ["169.254.170.2", "169.254.169.254", "fd00:ec2::254"] {
139            assert!(check(ip(a), 80, &[]).is_err(), "{a}");
140        }
141        // The whole link-local range, not just the two known addresses.
142        assert!(check(ip("169.254.1.1"), 80, &[]).is_err());
143        assert!(check(ip("fe80::1"), 80, &[]).is_err());
144    }
145
146    #[test]
147    fn a_page_cannot_reach_a_private_range() {
148        let private_v4: Vec<String> = [[10, 0, 0, 1], [10, 255, 255, 255], [172, 16, 0, 1], [172, 31, 255, 255], [192, 168, 1, 1]]
149            .map(|o| std::net::Ipv4Addr::from(o).to_string())
150            .into();
151        for a in private_v4.iter().map(String::as_str).chain([
152            "100.64.0.1", "100.127.255.255",
153            "0.0.0.0", "192.0.0.1", "198.18.0.1", "224.0.0.1", "239.255.255.250", "240.0.0.1", "255.255.255.255",
154            "fc00::1", "fdff::1", "fec0::1", "ff02::1", "::",
155        ]) {
156            assert!(check(ip(a), 443, &[]).is_err(), "{a}");
157        }
158    }
159
160    #[test]
161    fn the_edges_of_a_private_range_are_not_private() {
162        for a in ["172.15.255.255", "172.32.0.1", "100.63.255.255", "100.128.0.1", "11.0.0.1", "169.253.0.1", "169.255.0.1"] {
163            assert!(check(ip(a), 443, &[]).is_ok(), "{a}");
164        }
165    }
166
167    #[test]
168    fn an_ipv4_address_written_as_ipv6_is_judged_as_ipv4() {
169        for a in ["::ffff:a00:1", "::ffff:169.254.170.2", "::ffff:c0a8:1"] {
170            assert!(check(ip(a), 80, &[]).is_err(), "{a}");
171        }
172        assert!(check(ip("::ffff:8.8.8.8"), 443, &[]).is_ok());
173        // Loopback written that way is loopback, with a loopback's rules.
174        assert!(check(ip("::ffff:127.0.0.1"), 3000, &[]).is_ok());
175        assert!(check(ip("::ffff:127.0.0.1"), 8190, &[8190]).is_err());
176    }
177
178    #[test]
179    fn forms_that_hide_an_ipv4_address_are_refused() {
180        for a in ["64:ff9b::a00:1", "2002:a00:1::1", "2001:0:4136:e378:8000:63bf:3fff:fdd2", "2001:db8::1"] {
181            assert!(check(ip(a), 443, &[]).is_err(), "{a}");
182        }
183    }
184
185    #[test]
186    fn a_page_cannot_reach_this_servers_own_ports_on_any_loopback_form() {
187        let own = [8190, 8191];
188        for a in ["127.0.0.1", "127.1.2.3", "::1", "::ffff:127.0.0.1"] {
189            for p in own {
190                assert!(check(ip(a), p, &own).is_err(), "{a}:{p}");
191            }
192            // The user's own development server on any other port is fine.
193            assert!(check(ip(a), 3000, &own).is_ok(), "{a}:3000");
194        }
195    }
196
197    #[test]
198    fn the_public_internet_is_allowed_and_port_zero_is_not() {
199        for a in ["8.8.8.8", "93.184.216.34", "1.1.1.1", "2606:4700:4700::1111", "2a00:1450:4001:81b::200e"] {
200            assert!(check(ip(a), 443, &[8190]).is_ok(), "{a}");
201        }
202        assert!(check(ip("8.8.8.8"), 0, &[]).is_err());
203    }
204
205    #[test]
206    fn the_list_of_extra_denied_ports_reads_numbers_and_skips_the_rest() {
207        assert_eq!(parse_ports("8080, 9000,x,0,70000, 3001"), vec![8080, 9000, 3001]);
208        assert!(parse_ports("").is_empty());
209        // A port in the list is refused on the loopback address like srv's own.
210        assert!(check(ip("127.0.0.1"), 8080, &parse_ports("8080")).is_err());
211        assert!(check(ip("127.0.0.1"), 3000, &parse_ports("8080")).is_ok());
212    }
213
214    #[test]
215    fn own_ports_are_kept_once() {
216        note_own_port(40111);
217        note_own_port(40111);
218        assert_eq!(own_ports().iter().filter(|p| **p == 40111).count(), 1);
219    }
220}