Skip to main content

agentmux_srv/server/streamed_browser/screen/
policy.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the browser may open. The streamed pane blocks local files and the browser's own pages through the debugging channel
5//! (`pane.rs`, `BLOCKED_URLS`); in screen mode a person has the browser's own address bar, so the block is the browser's managed policy,
6//! which the browser reads before it starts. Screen mode does not start without it. This server only checks that the policy is there: the file
7//! is system-wide (every browser of that kind on the machine reads it), so whoever runs the machine or builds its image installs it.
8
9use std::path::{Path, PathBuf};
10
11use serde_json::{json, Value};
12
13/// Address patterns the browser never opens: local files, its own pages and tools, and an address a page could make from a string.
14pub const BLOCKED: &[&str] = &[
15    "file://*",
16    "chrome://*",
17    "chrome-untrusted://*",
18    "chrome-extension://*",
19    "chrome-search://*",
20    "chrome-error://*",
21    "devtools://*",
22    "view-source:*",
23    "javascript:*",
24    "ftp://*",
25];
26
27const FILE_NAME: &str = "agentmux-screen-mode.json";
28
29/// The folder the browser reads managed policy from, by the kind of browser it is.
30pub fn policy_dir(binary: &Path) -> PathBuf {
31    let name = binary.file_name().and_then(|n| n.to_str()).unwrap_or("").to_ascii_lowercase();
32    if name.contains("chromium") {
33        PathBuf::from("/etc/chromium/policies/managed")
34    } else {
35        PathBuf::from("/etc/opt/chrome/policies/managed")
36    }
37}
38
39/// The policy: the blocked addresses, no developer tools, no extensions, no sign-in to the browser itself, no file dialogs and no downloads
40/// (as in the streamed pane, which denies downloads), and the network the browser has: only the address proxy on `proxy_port` (every name is
41/// looked up by the proxy), no QUIC and no DNS over HTTPS. The browser is started with none of these as switches.
42pub fn wanted(proxy_port: u16) -> Value {
43    json!({
44        "URLBlocklist": BLOCKED,
45        "DeveloperToolsAvailability": 2,
46        "ExtensionInstallBlocklist": ["*"],
47        "BrowserSignin": 0,
48        "AllowFileSelectionDialogs": false,
49        "DownloadRestrictions": 3,
50        "ProxyMode": "fixed_servers",
51        "ProxyServer": format!("socks5://127.0.0.1:{proxy_port}"),
52        "ProxyBypassList": "<-loopback>",
53        "QuicAllowed": false,
54        "DnsOverHttpsMode": "off",
55    })
56}
57
58/// The strings in a policy key that holds a list (none when the key is absent or not a list).
59fn listed<'a>(v: &'a Value, key: &str) -> Vec<&'a str> {
60    v[key].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default()
61}
62
63/// Does the policy in `text` hold every key `wanted` names: every address in `BLOCKED` blocked, the developer tools off, no extension may be
64/// installed, no sign-in to the browser itself, no file dialog, no download, and the network only through the address proxy?
65pub fn holds(text: &str, proxy_port: u16) -> bool {
66    let Ok(v) = serde_json::from_str::<Value>(text) else { return false };
67    let blocked = listed(&v, "URLBlocklist");
68    BLOCKED.iter().all(|b| blocked.contains(b))
69        && listed(&v, "ExtensionInstallBlocklist").contains(&"*")
70        && v["BrowserSignin"] == json!(0)
71        && v["DeveloperToolsAvailability"] == json!(2)
72        && v["AllowFileSelectionDialogs"] == json!(false)
73        && v["DownloadRestrictions"] == json!(3)
74        && v["ProxyMode"] == json!("fixed_servers")
75        && v["ProxyServer"] == json!(format!("socks5://127.0.0.1:{proxy_port}"))
76        && v["ProxyBypassList"] == json!("<-loopback>")
77        && v["QuicAllowed"] == json!(false)
78        && v["DnsOverHttpsMode"] == json!("off")
79}
80
81/// Is the browser a snap or a flatpak, or the shim that starts one? Such a browser reads its policy from inside its own sandbox, not from the
82/// folder checked here, so a file there would pass the check and be ignored by the browser.
83pub fn sandboxed_install(binary: &Path) -> bool {
84    use std::io::Read;
85    let real = std::fs::canonicalize(binary).unwrap_or_else(|_| binary.to_path_buf());
86    let named = |p: &Path| {
87        let s = p.to_string_lossy();
88        s.contains("/snap/") || s.contains("/flatpak/") || p.file_name().is_some_and(|n| n == "snap" || n == "flatpak")
89    };
90    if named(binary) || named(&real) {
91        return true;
92    }
93    // A small script that starts a snap (the deb that only hands over to the snap on Ubuntu).
94    let mut head = [0u8; 4096];
95    let n = std::fs::File::open(&real).and_then(|mut f| f.read(&mut head)).unwrap_or(0);
96    let text = String::from_utf8_lossy(&head[..n]);
97    text.starts_with("#!") && (text.contains("/snap/") || text.contains("snap run") || text.contains("flatpak run"))
98}
99
100/// Whether any of these program names is a Chrome or Chromium (a process's `comm`).
101fn any_browser(names: &[String]) -> bool {
102    names.iter().any(|n| n.starts_with("chrome") || n.starts_with("chromium"))
103}
104
105/// Is a browser (Chrome or Chromium, or one of its helpers) running in this container right now?
106pub fn browser_running() -> bool {
107    any_browser(&running_programs())
108}
109
110/// The names of the programs running in this container (each process's `comm`).
111fn running_programs() -> Vec<String> {
112    let Ok(dir) = std::fs::read_dir("/proc") else { return Vec::new() };
113    dir.flatten()
114        .filter(|e| e.file_name().to_string_lossy().bytes().all(|b| b.is_ascii_digit()))
115        .filter_map(|e| std::fs::read_to_string(e.path().join("comm")).ok())
116        .map(|s| s.trim().to_string())
117        .collect()
118}
119
120/// The browser will start under the policy, or the words that say what is missing. The policy is the folder of the container (or dedicated
121/// machine) this server runs in, which holds this one browser: it is never written by the server, and screen mode serves no streamed browser
122/// next to it. `first` is true for the first screen session: no other browser may already be running in the container then.
123pub fn ensure(binary: &Path, first: bool, proxy_port: u16) -> Result<(), String> {
124    if sandboxed_install(binary) {
125        return Err(format!(
126            "screen mode does not run with {}: a snap or flatpak browser reads its policy from inside its own sandbox, where this check cannot see it. Use the Google Chrome or Chromium package",
127            binary.display()
128        ));
129    }
130    let path = policy_dir(binary).join(FILE_NAME);
131    if !std::fs::read_to_string(&path).is_ok_and(|t| holds(&t, proxy_port)) {
132        return Err(missing_words(&path, proxy_port));
133    }
134    if first && any_browser(&running_programs()) {
135        return Err("screen mode needs the container to hold this one browser: another browser is already running in it".to_string());
136    }
137    Ok(())
138}
139
140/// What to install, in words: the file, and what it holds.
141fn missing_words(path: &Path, proxy_port: u16) -> String {
142    let text = serde_json::to_string_pretty(&wanted(proxy_port)).unwrap_or_default();
143    format!(
144        "screen mode needs the browser's managed policy file {} (it blocks local files, the browser's own pages, developer tools, extensions, the browser's own sign-in, file dialogs and downloads, and sets its network); it is missing or does not hold. Install it as the machine's administrator, with this content:
145{text}",
146        path.display()
147    )
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn the_wanted_policy_holds_and_blocks_what_the_streamed_pane_blocks() {
156        let text = wanted(41234).to_string();
157        assert!(holds(&text, 41234));
158        assert!(!holds(&text, 41235), "the policy names the proxy's port");
159        for scheme in ["file:", "chrome:", "chrome-untrusted:", "chrome-extension:", "devtools:", "view-source:"] {
160            assert!(BLOCKED.iter().any(|b| b.starts_with(scheme)), "{scheme} is not blocked");
161        }
162    }
163
164    /// The file the screen-mode image installs (docker/Dockerfile.srv, SCREEN_BROWSER) is exactly the policy this server wants for the proxy port
165    /// the image names, so the image's policy cannot drift from the check.
166    #[test]
167    fn the_images_policy_file_is_the_policy_this_server_wants() {
168        let file: Value = serde_json::from_str(include_str!("../../../../../../docker/screen-mode-policy.json")).expect("the image's policy file is JSON");
169        assert_eq!(file, wanted(41234));
170        assert!(holds(&file.to_string(), 41234));
171    }
172
173    #[test]
174    fn a_policy_that_leaves_something_open_does_not_hold() {
175        assert!(!holds("not json", 1));
176        assert!(!holds("{}", 1));
177        let mut v = wanted(1);
178        v["DeveloperToolsAvailability"] = json!(1);
179        assert!(!holds(&v.to_string(), 1));
180        for (key, open) in [("AllowFileSelectionDialogs", json!(true)), ("DownloadRestrictions", json!(0))] {
181            let mut v = wanted(1);
182            v[key] = open;
183            assert!(!holds(&v.to_string(), 1), "{key} left open still holds");
184        }
185        let mut v = wanted(1);
186        v["URLBlocklist"] = json!(BLOCKED.iter().filter(|b| !b.starts_with("file")).collect::<Vec<_>>());
187        assert!(!holds(&v.to_string(), 1));
188    }
189
190    #[test]
191    fn a_policy_without_the_extension_block_or_with_browser_sign_in_on_does_not_hold() {
192        for key in ["ExtensionInstallBlocklist", "BrowserSignin"] {
193            let mut v = wanted(1);
194            v.as_object_mut().unwrap().remove(key);
195            assert!(!holds(&v.to_string(), 1), "{key} left out still holds");
196        }
197        for (key, open) in [
198            ("ExtensionInstallBlocklist", json!([])),
199            ("ExtensionInstallBlocklist", json!(["abcdefghijklmnop"])),
200            ("ExtensionInstallBlocklist", json!("*")),
201            ("BrowserSignin", json!(1)),
202            ("BrowserSignin", json!(2)),
203        ] {
204            let mut v = wanted(1);
205            v[key] = open.clone();
206            assert!(!holds(&v.to_string(), 1), "{key} = {open} still holds");
207        }
208    }
209
210    #[test]
211    fn every_key_the_wanted_policy_names_is_checked() {
212        // `wanted` and `holds` cannot drift apart: dropping any one key from the wanted policy must make it not hold.
213        let all = wanted(1);
214        for key in all.as_object().unwrap().keys() {
215            let mut v = all.clone();
216            v.as_object_mut().unwrap().remove(key);
217            assert!(!holds(&v.to_string(), 1), "{key} is named by the policy but not checked");
218        }
219    }
220
221    #[test]
222    fn a_snap_or_flatpak_browser_is_refused_and_a_plain_one_is_not() {
223        assert!(sandboxed_install(Path::new("/snap/bin/chromium")));
224        assert!(sandboxed_install(Path::new("/var/lib/flatpak/app/org.chromium.Chromium/x")));
225        let dir = tempfile::tempdir().unwrap();
226        let shim = dir.path().join("chromium-browser");
227        std::fs::write(&shim, "#!/bin/sh
228exec /snap/bin/chromium \"$@\"
229").unwrap();
230        assert!(sandboxed_install(&shim), "a script that starts the snap");
231        let plain = dir.path().join("google-chrome");
232        std::fs::write(&plain, "#!/bin/sh
233exec /opt/google/chrome/chrome \"$@\"
234").unwrap();
235        assert!(!sandboxed_install(&plain));
236        assert!(ensure(&shim, true, 1).unwrap_err().contains("snap or flatpak"));
237    }
238
239    #[test]
240    fn another_browser_in_the_container_is_seen_by_its_program_name() {
241        let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
242        assert!(any_browser(&names(&["srv", "chrome"])));
243        assert!(any_browser(&names(&["chromium"])));
244        assert!(!any_browser(&names(&["srv", "Xvfb", "openbox"])));
245    }
246
247    #[test]
248    fn a_missing_policy_is_refused_in_words_and_nothing_is_written() {
249        let dir = std::env::temp_dir().join("agentmux-policy-check-only");
250        let path = dir.join(FILE_NAME);
251        let words = missing_words(&path, 41234);
252        assert!(words.contains("DownloadRestrictions") && words.contains("URLBlocklist") && words.contains(FILE_NAME), "{words}");
253        assert!(!path.exists(), "checking must not write the file");
254    }
255
256    #[test]
257    fn the_policy_folder_follows_the_kind_of_browser() {
258        assert_eq!(policy_dir(Path::new("/usr/bin/chromium")), PathBuf::from("/etc/chromium/policies/managed"));
259        assert_eq!(policy_dir(Path::new("/usr/bin/chromium-browser")), PathBuf::from("/etc/chromium/policies/managed"));
260        assert_eq!(policy_dir(Path::new("/usr/bin/google-chrome")), PathBuf::from("/etc/opt/chrome/policies/managed"));
261    }
262}