Skip to main content

nexo_plugin_browser/
chrome.rs

1use std::path::PathBuf;
2use std::time::Duration;
3
4use anyhow::anyhow;
5use tokio::io::AsyncBufReadExt;
6use tokio::process::Command;
7
8use crate::config::BrowserConfig;
9
10// Discovery logic lives in its own module so the per-platform
11// candidate lists can grow and be tested independently.
12mod discovery;
13use discovery::find_chrome_executable;
14
15/// Categorisation of a discovered browser. Drives kind-specific
16/// quirks at launch time (e.g. Edge in some builds requires
17/// `--remote-allow-origins=*` for CDP). The taxonomy is pruned
18/// to the kinds we actually launch via CDP — derivative browsers
19/// (Brave, Vivaldi, Opera) are intentionally excluded from
20/// auto-detect; operators run them via the explicit
21/// `NEXO_PLUGIN_BROWSER_EXECUTABLE` override.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum BrowserKind {
24    Chrome,
25    Chromium,
26    /// `msedge` — Chromium-based, CDP-compatible. Common on
27    /// Windows enterprise installs where Chrome may be absent.
28    Edge,
29    /// Operator-supplied path via
30    /// `NEXO_PLUGIN_BROWSER_EXECUTABLE`. We cannot infer kind
31    /// from a custom path without sniffing the binary, so we
32    /// keep it opaque.
33    Custom,
34}
35
36/// A successfully discovered browser executable. The `kind` is
37/// informational (logged on launch); `path` is the absolute
38/// filesystem path the launcher will spawn.
39#[derive(Debug, Clone)]
40pub struct BrowserExecutable {
41    pub kind: BrowserKind,
42    pub path: PathBuf,
43}
44
45/// Errors produced by the discovery layer. Public so future
46/// integration tests can match on the shape; `launch()` wraps
47/// these in `anyhow::Error` for the operator-facing path.
48#[derive(Debug, thiserror::Error)]
49pub enum DiscoveryError {
50    /// Auto-detect exhausted every Tier 1 (bundled candidates)
51    /// and Tier 2 (PATH lookup) check without finding a usable
52    /// browser. `searched` lists every concrete path the
53    /// resolver tested so the operator can copy-paste it into a
54    /// bug report or set `NEXO_PLUGIN_BROWSER_EXECUTABLE`.
55    #[error(
56        "no Chrome/Chromium/Edge executable found; searched {} paths; \
57         set NEXO_PLUGIN_BROWSER_EXECUTABLE to override",
58        searched.len()
59    )]
60    NotFound { searched: Vec<String> },
61
62    /// `NEXO_PLUGIN_BROWSER_EXECUTABLE` was set but points at a
63    /// path that doesn't exist. We fail-fast here rather than
64    /// silently fall back to auto-detect — explicit override
65    /// implies strong intent; a typo masked by silent fallback
66    /// is harder to diagnose than a clear error.
67    #[error("NEXO_PLUGIN_BROWSER_EXECUTABLE points to non-existent path: {path}")]
68    OverrideMissing { path: String },
69}
70
71pub struct RunningChrome {
72    pub ws_url: String,
73    pub pid: u32,
74    child: tokio::process::Child,
75}
76
77impl RunningChrome {
78    /// Kill Chrome and reap the process entry.
79    /// Must be called from an async context before the value goes out of scope.
80    /// Consuming self ensures the Child is dropped only after wait() completes,
81    /// preventing a <defunct> entry in the process table.
82    pub async fn shutdown(mut self) {
83        let _ = self.child.kill().await;
84        let _ = self.child.wait().await;
85    }
86}
87
88impl Drop for RunningChrome {
89    fn drop(&mut self) {
90        // Safety-net: reached only on unexpected drops (panic path, test teardown).
91        // Normal teardown must go through shutdown() to avoid zombie processes.
92        tracing::warn!(
93            pid = self.pid,
94            "RunningChrome dropped without shutdown() — Chrome process may become a zombie"
95        );
96        let _ = self.child.start_kill();
97    }
98}
99
100pub struct ChromeLauncher;
101
102impl ChromeLauncher {
103    pub async fn launch(config: &BrowserConfig) -> anyhow::Result<RunningChrome> {
104        // Resolve the browser via the two-tier (bundled candidates
105        // + PATH) discovery in `chrome::discovery`. The override
106        // branch wraps the operator-supplied path in a `Custom`
107        // kind so the log line below is deterministic regardless
108        // of which path the caller took.
109        let (resolved, source): (BrowserExecutable, &'static str) = if config.executable.is_empty()
110        {
111            // Auto-detect via the two-tier resolver. On `Err` the
112            // resolver hands back the full searched-paths list so
113            // the operator's actionable hint quotes every probe
114            // site.
115            let exe = find_chrome_executable().map_err(|e| match &e {
116                DiscoveryError::NotFound { searched } => anyhow!(
117                    "no Chrome/Chromium/Edge executable found — searched {} location(s):\n  {}\nset \
118                     NEXO_PLUGIN_BROWSER_EXECUTABLE to an absolute path to override",
119                    searched.len(),
120                    searched.join("\n  "),
121                ),
122                // `OverrideMissing` only originates from the
123                // override branch below; the auto-detect arm
124                // can't produce it.
125                DiscoveryError::OverrideMissing { .. } => anyhow!(e.to_string()),
126            })?;
127            (exe, "auto-detect")
128        } else {
129            // Fail-fast when an explicit override points at a
130            // missing path. Otherwise we'd fall through to spawn
131            // and the operator would see a generic
132            // "failed to spawn Chrome (...)" with the real cause
133            // (NotFound) buried in the OS error chain. An explicit
134            // override implies strong intent — a typo is far more
135            // likely than the operator wanting an implicit
136            // fallback to auto-detect.
137            let override_path = PathBuf::from(&config.executable);
138            if !override_path.exists() {
139                anyhow::bail!(DiscoveryError::OverrideMissing {
140                    path: config.executable.clone(),
141                });
142            }
143            (
144                BrowserExecutable {
145                    kind: BrowserKind::Custom,
146                    path: override_path,
147                },
148                "env-override",
149            )
150        };
151        tracing::info!(
152            target: "browser.discovery",
153            kind = ?resolved.kind,
154            path = %resolved.path.display(),
155            source = source,
156            "Chrome/Chromium/Edge executable resolved"
157        );
158        let exe = &resolved.path;
159
160        let mut args = vec![
161            format!("--remote-debugging-port=0"),
162            format!("--user-data-dir={}", config.user_data_dir),
163            format!(
164                "--window-size={},{}",
165                config.window_width, config.window_height
166            ),
167            "--no-first-run".to_string(),
168            "--no-default-browser-check".to_string(),
169            "--disable-background-networking".to_string(),
170            "--disable-client-side-phishing-detection".to_string(),
171            "--disable-default-apps".to_string(),
172            "--disable-extensions".to_string(),
173            "--disable-hang-monitor".to_string(),
174            "--disable-popup-blocking".to_string(),
175            "--disable-prompt-on-repost".to_string(),
176            "--disable-sync".to_string(),
177            "--disable-translate".to_string(),
178            "--metrics-recording-only".to_string(),
179            "--safebrowsing-disable-auto-update".to_string(),
180            "about:blank".to_string(),
181        ];
182
183        if config.headless {
184            args.push("--headless=new".to_string());
185            args.push("--disable-gpu".to_string());
186        }
187
188        // Operator-supplied extra flags (`browser.args` in YAML). Appended
189        // after our built-ins so the operator can override if a flag
190        // conflicts — later args win with Chrome's CLI parser.
191        for extra in &config.args {
192            args.push(extra.clone());
193        }
194
195        let mut child = Command::new(&exe)
196            .args(&args)
197            .stderr(std::process::Stdio::piped())
198            .stdout(std::process::Stdio::null())
199            .kill_on_drop(true)
200            .spawn()
201            .map_err(|e| anyhow!("failed to spawn Chrome ({}): {e}", exe.display()))?;
202
203        let pid = child.id().unwrap_or(0);
204
205        let stderr = child
206            .stderr
207            .take()
208            .ok_or_else(|| anyhow!("failed to capture Chrome stderr"))?;
209
210        let ws_url = wait_for_devtools_url(stderr, config.connect_timeout_ms)
211            .await
212            .inspect_err(|_e| {
213                let _ = child.start_kill();
214            })?;
215
216        Ok(RunningChrome { ws_url, pid, child })
217    }
218
219    /// Attach to an already-running Chrome at a CDP HTTP URL.
220    pub async fn connect_existing(cdp_url: &str, timeout_ms: u64) -> anyhow::Result<String> {
221        // Delegate to the canonical discovery path in cdp::client which also
222        // rewrites the authority of the returned webSocketDebuggerUrl
223        // (Chrome echoes the Host header and drops the real port).
224        crate::cdp::CdpClient::discover_ws_url(cdp_url, timeout_ms).await
225    }
226}
227
228async fn wait_for_devtools_url(
229    stderr: tokio::process::ChildStderr,
230    timeout_ms: u64,
231) -> anyhow::Result<String> {
232    let reader = tokio::io::BufReader::new(stderr);
233    let mut lines = reader.lines();
234
235    let timeout = Duration::from_millis(timeout_ms);
236    let deadline = tokio::time::Instant::now() + timeout;
237
238    loop {
239        let remaining = deadline
240            .checked_duration_since(tokio::time::Instant::now())
241            .unwrap_or(Duration::ZERO);
242
243        if remaining.is_zero() {
244            return Err(anyhow!("timed out waiting for Chrome DevTools URL"));
245        }
246
247        let line = tokio::time::timeout(remaining, lines.next_line())
248            .await
249            .map_err(|_| anyhow!("timed out waiting for Chrome DevTools URL"))?
250            .map_err(|e| anyhow!("error reading Chrome stderr: {e}"))?;
251
252        let Some(line) = line else {
253            return Err(anyhow!("Chrome exited before DevTools URL appeared"));
254        };
255
256        if let Some(rest) = line.strip_prefix("DevTools listening on ") {
257            return Ok(rest.trim().to_string());
258        }
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    #[cfg(unix)] // only the Unix-only `shutdown_reaps_process` test uses it
266    use tokio::process::Command as TokioCommand;
267
268    #[test]
269    fn browser_kind_debug_shape() {
270        // Smoke check that the public Debug projection lines up
271        // with what we log on launch — operators grep this.
272        assert_eq!(format!("{:?}", BrowserKind::Chrome), "Chrome");
273        assert_eq!(format!("{:?}", BrowserKind::Chromium), "Chromium");
274        assert_eq!(format!("{:?}", BrowserKind::Edge), "Edge");
275        assert_eq!(format!("{:?}", BrowserKind::Custom), "Custom");
276    }
277
278    #[test]
279    fn browser_executable_round_trips_through_clone() {
280        let exe = BrowserExecutable {
281            kind: BrowserKind::Chrome,
282            path: PathBuf::from("/usr/bin/google-chrome"),
283        };
284        let cloned = exe.clone();
285        assert_eq!(cloned.kind, BrowserKind::Chrome);
286        assert_eq!(cloned.path, exe.path);
287    }
288
289    #[test]
290    fn discovery_error_not_found_displays_searched_count() {
291        let err = DiscoveryError::NotFound {
292            searched: vec!["/a".into(), "/b".into(), "/c".into()],
293        };
294        let msg = format!("{err}");
295        assert!(msg.contains("3 paths"), "got: {msg}");
296        assert!(msg.contains("NEXO_PLUGIN_BROWSER_EXECUTABLE"), "got: {msg}");
297    }
298
299    #[test]
300    fn discovery_error_override_missing_includes_path() {
301        let err = DiscoveryError::OverrideMissing {
302            path: "/nonexistent/chrome.exe".into(),
303        };
304        let msg = format!("{err}");
305        assert!(msg.contains("/nonexistent/chrome.exe"), "got: {msg}");
306    }
307
308    /// Minimal `BrowserConfig` with `executable` field set;
309    /// other fields populated with the same defaults the YAML
310    /// loader applies. Local helper so the override-missing
311    /// test below doesn't need to deserialize a TOML/YAML stub.
312    fn config_with_executable(exe: &str) -> BrowserConfig {
313        BrowserConfig {
314            instance: None,
315            headless: false,
316            executable: exe.to_string(),
317            cdp_url: String::new(),
318            user_data_dir: "./data/browser/profile".to_string(),
319            window_width: 1280,
320            window_height: 800,
321            connect_timeout_ms: 10_000,
322            command_timeout_ms: 15_000,
323            args: Vec::new(),
324            allow_agents: Vec::new(),
325        }
326    }
327
328    #[tokio::test]
329    async fn launch_fails_fast_when_override_path_missing() {
330        // `NEXO_PLUGIN_BROWSER_EXECUTABLE` (surface form: the
331        // `executable` field on `BrowserConfig`) was set to a
332        // path that doesn't exist. We must surface the typed
333        // `DiscoveryError::OverrideMissing` so the operator sees
334        // the typo immediately rather than an OS NotFound buried
335        // inside a generic spawn failure.
336        let cfg = config_with_executable("/definitely-not-a-real/chrome-binary-xyz");
337        // `RunningChrome` doesn't derive `Debug` (holds a
338        // `tokio::process::Child`), so `.expect_err` won't
339        // compile. Match instead.
340        let err = match ChromeLauncher::launch(&cfg).await {
341            Ok(_) => panic!("launch must fail-fast on missing override"),
342            Err(e) => e,
343        };
344        let msg = err.to_string();
345        assert!(
346            msg.contains("/definitely-not-a-real/chrome-binary-xyz"),
347            "error must echo the bad path: {msg}"
348        );
349        assert!(
350            msg.contains("non-existent path"),
351            "error must label the failure mode: {msg}"
352        );
353    }
354
355    #[cfg(unix)] // only used by the Unix-only `shutdown_reaps_process` test
356    fn make_running_chrome(child: tokio::process::Child, pid: u32) -> RunningChrome {
357        RunningChrome {
358            ws_url: String::new(),
359            pid,
360            child,
361        }
362    }
363
364    // Unix-only: relies on the `sleep` binary + `libc::kill(pid, 0)`
365    // ESRCH probe to verify process reaping. Windows uses different
366    // process-management primitives (`OpenProcess` / `WaitForSingleObject`)
367    // and ships no `sleep`. The reaping logic in `RunningChrome::shutdown`
368    // itself is portable (uses `tokio::process::Child::wait`); only the
369    // test harness is Unix-specific.
370    #[cfg(unix)]
371    #[tokio::test]
372    async fn shutdown_reaps_process() {
373        let child = TokioCommand::new("sleep")
374            .arg("30")
375            .kill_on_drop(false)
376            .spawn()
377            .expect("failed to spawn sleep");
378        let pid = child.id().expect("missing PID");
379        let running = make_running_chrome(child, pid);
380
381        running.shutdown().await;
382
383        // After shutdown(), the process must be reaped.
384        // kill(pid, 0) returns ESRCH when no such process exists.
385        let alive = unsafe { libc::kill(pid as libc::pid_t, 0) == 0 };
386        assert!(!alive, "process {pid} still exists after shutdown()");
387    }
388}