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 a three-tier strategy:
105        //   Tier 0 (auto-download, opt-in)
106        //     — chrome-for-testing managed binary under the
107        //       user cache. Gated on the `auto-download` cargo
108        //       feature AND the `NEXO_PLUGIN_BROWSER_AUTO_DOWNLOAD=1`
109        //       runtime env var. Off by default; flip both to opt in.
110        //   Tier 1+2 (auto-detect, default)
111        //     — bundled candidate paths + $PATH lookup via
112        //       `chrome::discovery`.
113        //   Override (explicit)
114        //     — `BrowserConfig.executable` is non-empty (env
115        //       surface form: `NEXO_PLUGIN_BROWSER_EXECUTABLE`).
116        //       Fails fast if the path doesn't exist.
117        let (resolved, source): (BrowserExecutable, &'static str) = if config.executable.is_empty()
118        {
119            // Tier 0 — auto-download. Only fires when the
120            // `auto-download` cargo feature is on AND the
121            // runtime env var is set. Soft-errors fall through
122            // to Tier 1+2 so a network outage on first launch
123            // doesn't block the plugin if a system Chrome is
124            // sitting on $PATH.
125            if let Some(exe) = try_auto_download().await {
126                (exe, "chrome-for-testing")
127            } else {
128                // Tier 1+2 — auto-detect via the two-tier resolver.
129                // On `Err` the resolver hands back the full searched-
130                // paths list so the operator's actionable hint
131                // quotes every probe site.
132                let exe = find_chrome_executable().map_err(|e| match &e {
133                DiscoveryError::NotFound { searched } => anyhow!(
134                    "no Chrome/Chromium/Edge executable found — searched {} location(s):\n  {}\nset \
135                     NEXO_PLUGIN_BROWSER_EXECUTABLE to an absolute path to override, or build \
136                     with `--features auto-download` + `NEXO_PLUGIN_BROWSER_AUTO_DOWNLOAD=1` \
137                     to fetch chrome-headless-shell automatically",
138                    searched.len(),
139                    searched.join("\n  "),
140                ),
141                // `OverrideMissing` only originates from the
142                // override branch below; the auto-detect arm
143                // can't produce it.
144                    DiscoveryError::OverrideMissing { .. } => anyhow!(e.to_string()),
145                })?;
146                (exe, "auto-detect")
147            }
148        } else {
149            // Fail-fast when an explicit override points at a
150            // missing path. Otherwise we'd fall through to spawn
151            // and the operator would see a generic
152            // "failed to spawn Chrome (...)" with the real cause
153            // (NotFound) buried in the OS error chain. An explicit
154            // override implies strong intent — a typo is far more
155            // likely than the operator wanting an implicit
156            // fallback to auto-detect.
157            let override_path = PathBuf::from(&config.executable);
158            if !override_path.exists() {
159                anyhow::bail!(DiscoveryError::OverrideMissing {
160                    path: config.executable.clone(),
161                });
162            }
163            (
164                BrowserExecutable {
165                    kind: BrowserKind::Custom,
166                    path: override_path,
167                },
168                "env-override",
169            )
170        };
171        tracing::info!(
172            target: "browser.discovery",
173            kind = ?resolved.kind,
174            path = %resolved.path.display(),
175            source = source,
176            "Chrome/Chromium/Edge executable resolved"
177        );
178        let exe = &resolved.path;
179
180        let mut args = vec![
181            format!("--remote-debugging-port=0"),
182            format!("--user-data-dir={}", config.user_data_dir),
183            format!(
184                "--window-size={},{}",
185                config.window_width, config.window_height
186            ),
187            "--no-first-run".to_string(),
188            "--no-default-browser-check".to_string(),
189            "--disable-background-networking".to_string(),
190            "--disable-client-side-phishing-detection".to_string(),
191            "--disable-default-apps".to_string(),
192            "--disable-extensions".to_string(),
193            "--disable-hang-monitor".to_string(),
194            "--disable-popup-blocking".to_string(),
195            "--disable-prompt-on-repost".to_string(),
196            "--disable-sync".to_string(),
197            "--disable-translate".to_string(),
198            "--metrics-recording-only".to_string(),
199            "--safebrowsing-disable-auto-update".to_string(),
200            "about:blank".to_string(),
201        ];
202
203        if config.headless {
204            args.push("--headless=new".to_string());
205            args.push("--disable-gpu".to_string());
206        }
207
208        // Operator-supplied extra flags (`browser.args` in YAML). Appended
209        // after our built-ins so the operator can override if a flag
210        // conflicts — later args win with Chrome's CLI parser.
211        for extra in &config.args {
212            args.push(extra.clone());
213        }
214
215        let mut child = Command::new(&exe)
216            .args(&args)
217            .stderr(std::process::Stdio::piped())
218            .stdout(std::process::Stdio::null())
219            .kill_on_drop(true)
220            .spawn()
221            .map_err(|e| anyhow!("failed to spawn Chrome ({}): {e}", exe.display()))?;
222
223        let pid = child.id().unwrap_or(0);
224
225        let stderr = child
226            .stderr
227            .take()
228            .ok_or_else(|| anyhow!("failed to capture Chrome stderr"))?;
229
230        let ws_url = wait_for_devtools_url(stderr, config.connect_timeout_ms)
231            .await
232            .inspect_err(|_e| {
233                let _ = child.start_kill();
234            })?;
235
236        Ok(RunningChrome { ws_url, pid, child })
237    }
238
239    /// Attach to an already-running Chrome at a CDP HTTP URL.
240    pub async fn connect_existing(cdp_url: &str, timeout_ms: u64) -> anyhow::Result<String> {
241        // Delegate to the canonical discovery path in cdp::client which also
242        // rewrites the authority of the returned webSocketDebuggerUrl
243        // (Chrome echoes the Host header and drops the real port).
244        crate::cdp::CdpClient::discover_ws_url(cdp_url, timeout_ms).await
245    }
246}
247
248async fn wait_for_devtools_url(
249    stderr: tokio::process::ChildStderr,
250    timeout_ms: u64,
251) -> anyhow::Result<String> {
252    let reader = tokio::io::BufReader::new(stderr);
253    let mut lines = reader.lines();
254
255    let timeout = Duration::from_millis(timeout_ms);
256    let deadline = tokio::time::Instant::now() + timeout;
257
258    loop {
259        let remaining = deadline
260            .checked_duration_since(tokio::time::Instant::now())
261            .unwrap_or(Duration::ZERO);
262
263        if remaining.is_zero() {
264            return Err(anyhow!("timed out waiting for Chrome DevTools URL"));
265        }
266
267        let line = tokio::time::timeout(remaining, lines.next_line())
268            .await
269            .map_err(|_| anyhow!("timed out waiting for Chrome DevTools URL"))?
270            .map_err(|e| anyhow!("error reading Chrome stderr: {e}"))?;
271
272        let Some(line) = line else {
273            return Err(anyhow!("Chrome exited before DevTools URL appeared"));
274        };
275
276        if let Some(rest) = line.strip_prefix("DevTools listening on ") {
277            return Ok(rest.trim().to_string());
278        }
279    }
280}
281
282/// Tier 0 of the discovery flow: when the `auto-download` cargo
283/// feature is on **and** the `NEXO_PLUGIN_BROWSER_AUTO_DOWNLOAD=1`
284/// env var is set, fetch (or reuse from cache) Google's
285/// `chrome-headless-shell` for the running platform via the
286/// `chrome-for-testing` crate.
287///
288/// Both gates intentional — the cargo feature controls whether
289/// the dep is even compiled in, and the env var lets operators
290/// flip behaviour without rebuilding the plugin. Returns `None`
291/// when either gate is off OR the download soft-fails (network
292/// outage etc.), letting `launch()` fall through to system
293/// discovery.
294async fn try_auto_download() -> Option<BrowserExecutable> {
295    #[cfg(feature = "auto-download")]
296    {
297        if std::env::var("NEXO_PLUGIN_BROWSER_AUTO_DOWNLOAD").as_deref() != Ok("1") {
298            return None;
299        }
300        match crate::auto_download::ensure_chrome_headless_shell().await {
301            Ok(path) => {
302                return Some(BrowserExecutable {
303                    kind: BrowserKind::Chromium,
304                    path,
305                });
306            }
307            Err(e) => {
308                tracing::warn!(
309                    target: "browser.discovery",
310                    error = %e,
311                    "auto-download (Tier 0) failed; falling back to system discovery"
312                );
313                return None;
314            }
315        }
316    }
317    #[cfg(not(feature = "auto-download"))]
318    None
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324    #[cfg(unix)] // only the Unix-only `shutdown_reaps_process` test uses it
325    use tokio::process::Command as TokioCommand;
326
327    #[test]
328    fn browser_kind_debug_shape() {
329        // Smoke check that the public Debug projection lines up
330        // with what we log on launch — operators grep this.
331        assert_eq!(format!("{:?}", BrowserKind::Chrome), "Chrome");
332        assert_eq!(format!("{:?}", BrowserKind::Chromium), "Chromium");
333        assert_eq!(format!("{:?}", BrowserKind::Edge), "Edge");
334        assert_eq!(format!("{:?}", BrowserKind::Custom), "Custom");
335    }
336
337    #[test]
338    fn browser_executable_round_trips_through_clone() {
339        let exe = BrowserExecutable {
340            kind: BrowserKind::Chrome,
341            path: PathBuf::from("/usr/bin/google-chrome"),
342        };
343        let cloned = exe.clone();
344        assert_eq!(cloned.kind, BrowserKind::Chrome);
345        assert_eq!(cloned.path, exe.path);
346    }
347
348    #[test]
349    fn discovery_error_not_found_displays_searched_count() {
350        let err = DiscoveryError::NotFound {
351            searched: vec!["/a".into(), "/b".into(), "/c".into()],
352        };
353        let msg = format!("{err}");
354        assert!(msg.contains("3 paths"), "got: {msg}");
355        assert!(msg.contains("NEXO_PLUGIN_BROWSER_EXECUTABLE"), "got: {msg}");
356    }
357
358    #[test]
359    fn discovery_error_override_missing_includes_path() {
360        let err = DiscoveryError::OverrideMissing {
361            path: "/nonexistent/chrome.exe".into(),
362        };
363        let msg = format!("{err}");
364        assert!(msg.contains("/nonexistent/chrome.exe"), "got: {msg}");
365    }
366
367    /// Minimal `BrowserConfig` with `executable` field set;
368    /// other fields populated with the same defaults the YAML
369    /// loader applies. Local helper so the override-missing
370    /// test below doesn't need to deserialize a TOML/YAML stub.
371    fn config_with_executable(exe: &str) -> BrowserConfig {
372        BrowserConfig {
373            instance: None,
374            headless: false,
375            executable: exe.to_string(),
376            cdp_url: String::new(),
377            user_data_dir: "./data/browser/profile".to_string(),
378            window_width: 1280,
379            window_height: 800,
380            connect_timeout_ms: 10_000,
381            command_timeout_ms: 15_000,
382            args: Vec::new(),
383            allow_agents: Vec::new(),
384        }
385    }
386
387    #[tokio::test]
388    async fn launch_fails_fast_when_override_path_missing() {
389        // `NEXO_PLUGIN_BROWSER_EXECUTABLE` (surface form: the
390        // `executable` field on `BrowserConfig`) was set to a
391        // path that doesn't exist. We must surface the typed
392        // `DiscoveryError::OverrideMissing` so the operator sees
393        // the typo immediately rather than an OS NotFound buried
394        // inside a generic spawn failure.
395        let cfg = config_with_executable("/definitely-not-a-real/chrome-binary-xyz");
396        // `RunningChrome` doesn't derive `Debug` (holds a
397        // `tokio::process::Child`), so `.expect_err` won't
398        // compile. Match instead.
399        let err = match ChromeLauncher::launch(&cfg).await {
400            Ok(_) => panic!("launch must fail-fast on missing override"),
401            Err(e) => e,
402        };
403        let msg = err.to_string();
404        assert!(
405            msg.contains("/definitely-not-a-real/chrome-binary-xyz"),
406            "error must echo the bad path: {msg}"
407        );
408        assert!(
409            msg.contains("non-existent path"),
410            "error must label the failure mode: {msg}"
411        );
412    }
413
414    #[cfg(unix)] // only used by the Unix-only `shutdown_reaps_process` test
415    fn make_running_chrome(child: tokio::process::Child, pid: u32) -> RunningChrome {
416        RunningChrome {
417            ws_url: String::new(),
418            pid,
419            child,
420        }
421    }
422
423    // Unix-only: relies on the `sleep` binary + `libc::kill(pid, 0)`
424    // ESRCH probe to verify process reaping. Windows uses different
425    // process-management primitives (`OpenProcess` / `WaitForSingleObject`)
426    // and ships no `sleep`. The reaping logic in `RunningChrome::shutdown`
427    // itself is portable (uses `tokio::process::Child::wait`); only the
428    // test harness is Unix-specific.
429    #[cfg(unix)]
430    #[tokio::test]
431    async fn shutdown_reaps_process() {
432        let child = TokioCommand::new("sleep")
433            .arg("30")
434            .kill_on_drop(false)
435            .spawn()
436            .expect("failed to spawn sleep");
437        let pid = child.id().expect("missing PID");
438        let running = make_running_chrome(child, pid);
439
440        running.shutdown().await;
441
442        // After shutdown(), the process must be reaped.
443        // kill(pid, 0) returns ESRCH when no such process exists.
444        let alive = unsafe { libc::kill(pid as libc::pid_t, 0) == 0 };
445        assert!(!alive, "process {pid} still exists after shutdown()");
446    }
447}