Skip to main content

rightkit_browser/
config.rs

1use crate::error::{BrowserError, Result};
2use crate::policy::{AdmissionHook, EventSink, NetworkPolicy};
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6/// Where the browser keeps cookies, storage, and logins.
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub enum ProfileSpec {
9    /// Throwaway profile deleted when the session drops (default).
10    Temporary,
11    /// Named persistent profile at `<root>/<name>`. One live session per name;
12    /// a second launch fails with `ProfileInUse` instead of corrupting state.
13    Named { root: PathBuf, name: String },
14    /// Caller-owned, existing absolute user-data directory. Never created or deleted
15    /// by the session; no named-profile validation or real-profile exclusion applies.
16    Directory(PathBuf),
17}
18
19#[derive(Clone)]
20pub struct LaunchOptions {
21    pub headless: bool,
22    /// Passes `--mute-audio`. Default true.
23    pub mute_audio: bool,
24    pub profile: ProfileSpec,
25    /// Explicit browser executable. When `None`, launch resolves Chrome for Testing with
26    /// [`chrome_for_testing_path`]. Ignored by [`Self::system_chrome_only`].
27    pub chrome_path: Option<PathBuf>,
28    /// Opt-in: when Chrome for Testing is not installed, fall back to the system browser
29    /// ([`find_chrome`]). Off by default: regular Google Chrome on macOS leaves an APFS
30    /// code-sign clone of its bundle behind for every instance that does not shut down cleanly.
31    pub allow_system_chrome: bool,
32    /// Resolve only through [`find_chrome`], ignoring `chrome_path` and Chrome for
33    /// Testing discovery. Off by default; enabled by [`Self::system_chrome_only`].
34    pub use_system_chrome_only: bool,
35    pub viewport: (u32, u32),
36    pub launch_timeout: Duration,
37    /// Deadline for each CDP request, including `Page.navigate`. Default 30 s (chromiumoxide's).
38    /// Raise it for dev servers whose first load is slow (e.g. Vite's cold dependency optimizer).
39    pub request_timeout: Duration,
40    /// Extra Chrome flags, with or without leading `--`.
41    pub extra_args: Vec<String>,
42    /// Defaults to `<profile>/downloads` for temporary profiles and
43    /// `<profile>/rightkit-downloads` for persistent ones.
44    pub download_dir: Option<PathBuf>,
45    /// When set, `upload` refuses files outside this root.
46    pub upload_root: Option<PathBuf>,
47    /// Gates every navigation, input, and script action before it has any effect.
48    /// `None` admits everything (trusted callers).
49    pub admission: Option<AdmissionHook>,
50    /// Network/SSRF policy. Default blocks loopback, link-local, private ranges,
51    /// `localhost`, and `file:` unless allowed.
52    pub network: NetworkPolicy,
53    /// Receives start/stop/crash/denied lifecycle events (session id, reason, time).
54    pub on_event: Option<EventSink>,
55    /// Windows: the caller's job object (see [`Self::windows_job`]). Chromium and every
56    /// helper it starts are bound to it; a clone of these options keeps the duplicate open.
57    #[cfg(windows)]
58    pub windows_job: Option<std::sync::Arc<std::os::windows::io::OwnedHandle>>,
59}
60
61impl std::fmt::Debug for LaunchOptions {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("LaunchOptions")
64            .field("headless", &self.headless)
65            .field("profile", &self.profile)
66            .field("network", &self.network)
67            .field("admission", &self.admission.is_some())
68            .finish_non_exhaustive()
69    }
70}
71
72impl Default for LaunchOptions {
73    fn default() -> Self {
74        Self {
75            headless: true,
76            mute_audio: true,
77            profile: ProfileSpec::Temporary,
78            chrome_path: None,
79            allow_system_chrome: false,
80            use_system_chrome_only: false,
81            viewport: (1280, 800),
82            launch_timeout: Duration::from_secs(60),
83            request_timeout: Duration::from_secs(30),
84            extra_args: Vec::new(),
85            download_dir: None,
86            upload_root: None,
87            admission: None,
88            network: NetworkPolicy::default(),
89            on_event: None,
90            #[cfg(windows)]
91            windows_job: None,
92        }
93    }
94}
95
96impl LaunchOptions {
97    /// Opt in to the system Chrome/Chromium/Edge when Chrome for Testing is missing.
98    pub fn system_chrome(mut self) -> Self {
99        self.allow_system_chrome = true;
100        self.use_system_chrome_only = false;
101        self
102    }
103    /// Use only system Chrome/Chromium/Edge via [`find_chrome`]. Ignores explicit
104    /// `chrome_path` and Chrome for Testing installs/environment overrides; errors
105    /// with [`BrowserError::ChromeNotFound`] when no system browser is found.
106    pub fn system_chrome_only(mut self) -> Self {
107        self.use_system_chrome_only = true;
108        self.allow_system_chrome = false;
109        self
110    }
111    pub fn headed(mut self) -> Self {
112        self.headless = false;
113        self
114    }
115    pub fn admission(mut self, hook: AdmissionHook) -> Self {
116        self.admission = Some(hook);
117        self
118    }
119    /// Per-request CDP deadline (navigation included).
120    pub fn request_timeout(mut self, timeout: Duration) -> Self {
121        self.request_timeout = timeout;
122        self
123    }
124    pub fn network(mut self, policy: NetworkPolicy) -> Self {
125        self.network = policy;
126        self
127    }
128    pub fn on_event(
129        mut self,
130        f: impl Fn(&crate::policy::BrowserEvent) + Send + Sync + 'static,
131    ) -> Self {
132        self.on_event = Some(std::sync::Arc::new(f));
133        self
134    }
135    /// Windows: bind Chromium to the caller's job object (an in-process host's own job).
136    /// Chromium joins it before running its first instruction, beneath RightKit's own
137    /// kill-on-close jobs, none of which allow breakaway: terminating or closing the
138    /// caller's job kills the browser and all of its helpers. The handle is duplicated; the
139    /// session closes its duplicate as soon as Chromium has been bound.
140    #[cfg(windows)]
141    pub fn windows_job(
142        mut self,
143        job: std::os::windows::io::BorrowedHandle<'_>,
144    ) -> std::io::Result<Self> {
145        self.windows_job = Some(std::sync::Arc::new(job.try_clone_to_owned()?));
146        Ok(self)
147    }
148    pub fn named_profile(mut self, root: impl Into<PathBuf>, name: impl Into<String>) -> Self {
149        self.profile = ProfileSpec::Named {
150            root: root.into(),
151            name: name.into(),
152        };
153        self
154    }
155    /// Use an existing absolute Chrome user-data directory, including paths with
156    /// spaces or other filesystem-supported characters. Validated at launch; never
157    /// created or deleted. The caller owns exclusive access to this directory.
158    pub fn profile_dir(mut self, path: impl Into<PathBuf>) -> Self {
159        self.profile = ProfileSpec::Directory(path.into());
160        self
161    }
162}
163
164pub(crate) fn validate_profile_dir(path: &Path) -> Result<()> {
165    if !path.is_absolute() {
166        return Err(BrowserError::Profile(format!(
167            "profile directory must be absolute: {}",
168            path.display()
169        )));
170    }
171    let metadata = std::fs::metadata(path).map_err(|e| {
172        BrowserError::Profile(format!(
173            "profile directory must exist and be accessible: {} ({e})",
174            path.display()
175        ))
176    })?;
177    if !metadata.is_dir() {
178        return Err(BrowserError::Profile(format!(
179            "profile path is not a directory: {}",
180            path.display()
181        )));
182    }
183    Ok(())
184}
185
186pub(crate) fn validate_profile_name(name: &str) -> Result<()> {
187    let ok = !name.is_empty()
188        && name.len() <= 64
189        && !name.starts_with('.')
190        && name
191            .chars()
192            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
193    if ok {
194        Ok(())
195    } else {
196        Err(BrowserError::Profile(format!(
197            "invalid profile name '{name}'"
198        )))
199    }
200}
201
202/// Environment variable naming an explicit Chrome for Testing executable.
203pub const CHROME_FOR_TESTING_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING";
204
205/// Override the RightKit-managed Chrome for Testing version root.
206pub const CHROME_FOR_TESTING_ROOT_ENV: &str = "RIGHTKIT_CHROME_FOR_TESTING_ROOT";
207
208/// How to get Chrome for Testing; part of [`BrowserError::ChromeForTestingNotFound`].
209pub const CHROME_FOR_TESTING_INSTALL_HINT: &str = "Install Chrome for Testing (any one of):\n  \
210pnpm dlx @puppeteer/browsers install chrome@stable --path ~/.cache/puppeteer\n  \
211pnpm exec playwright install chromium\n\
212or point RIGHTKIT_CHROME_FOR_TESTING at its executable. Regular Google Chrome is used only \
213with LaunchOptions::system_chrome(): on macOS each killed instance leaks a code-sign clone.";
214
215const MAC_CFT_APP: &str = "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";
216
217fn home_dir() -> Option<PathBuf> {
218    std::env::var_os("HOME")
219        .or_else(|| std::env::var_os("USERPROFILE"))
220        .map(PathBuf::from)
221}
222
223fn version_key(name: &str) -> Vec<u64> {
224    name.split(|c: char| !c.is_ascii_digit())
225        .filter(|p| !p.is_empty())
226        .filter_map(|p| p.parse().ok())
227        .collect()
228}
229
230/// Children of `root` whose names start with one of `prefixes`, newest version first.
231fn versioned_children(root: &Path, prefixes: &[&str]) -> Vec<PathBuf> {
232    let mut names: Vec<String> = std::fs::read_dir(root)
233        .map(|rd| {
234            rd.filter_map(|e| e.ok())
235                .map(|e| e.file_name().to_string_lossy().into_owned())
236                .filter(|n| prefixes.iter().any(|p| n.starts_with(p)))
237                .collect()
238        })
239        .unwrap_or_default();
240    names.sort_by(|a, b| version_key(b).cmp(&version_key(a)).then_with(|| b.cmp(a)));
241    names.into_iter().map(|n| root.join(n)).collect()
242}
243
244fn managed_chrome_for_testing_root(
245    home: &Path,
246    env_path: &impl Fn(&str) -> Option<PathBuf>,
247) -> PathBuf {
248    if let Some(root) = env_path(CHROME_FOR_TESTING_ROOT_ENV) {
249        return root;
250    }
251    let app_data = if cfg!(target_os = "macos") {
252        home.join("Library/Application Support")
253    } else if cfg!(target_os = "windows") {
254        env_path("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local"))
255    } else {
256        env_path("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"))
257    };
258    app_data.join("Orthic Labs/shared/chrome-for-testing")
259}
260
261fn managed_chrome_for_testing_candidates(root: &Path) -> Vec<PathBuf> {
262    // Match qa-chrome's dotted numeric version folders; ignore staging/metadata entries.
263    versioned_children(root, &[""])
264        .into_iter()
265        .filter(|dir| {
266            dir.is_dir()
267                && dir
268                    .file_name()
269                    .and_then(|n| n.to_str())
270                    .is_some_and(|name| {
271                        name.contains('.')
272                            && name.split('.').all(|part| {
273                                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())
274                            })
275                    })
276        })
277        .map(|dir| {
278            if cfg!(target_os = "macos") {
279                let sub = if cfg!(target_arch = "aarch64") {
280                    "chrome-mac-arm64"
281                } else {
282                    "chrome-mac-x64"
283                };
284                dir.join(sub).join(MAC_CFT_APP)
285            } else if cfg!(target_os = "windows") {
286                dir.join("chrome-win64/chrome.exe")
287            } else {
288                dir.join("chrome-linux64/chrome")
289            }
290        })
291        .collect()
292}
293
294/// Known Chrome for Testing install locations, in resolution order: RightKit-managed
295/// versions (`RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the root), app installs, then
296/// Puppeteer's cache (`PUPPETEER_CACHE_DIR`), then Playwright's (`PLAYWRIGHT_BROWSERS_PATH`),
297/// newest version first within each cache.
298pub fn chrome_for_testing_candidates() -> Vec<PathBuf> {
299    let home = home_dir().unwrap_or_default();
300    let env_path = |k: &str| {
301        std::env::var_os(k)
302            .filter(|v| !v.is_empty())
303            .map(PathBuf::from)
304    };
305    let puppeteer = env_path("PUPPETEER_CACHE_DIR")
306        .unwrap_or_else(|| home.join(".cache").join("puppeteer"))
307        .join("chrome");
308    let managed_root = managed_chrome_for_testing_root(&home, &env_path);
309    let mut out = managed_chrome_for_testing_candidates(&managed_root);
310    if cfg!(target_os = "macos") {
311        out.push(Path::new("/Applications").join(MAC_CFT_APP));
312        out.push(home.join("Applications").join(MAC_CFT_APP));
313        let subs: [&str; 2] = if cfg!(target_arch = "aarch64") {
314            ["chrome-mac-arm64", "chrome-mac-x64"]
315        } else {
316            ["chrome-mac-x64", "chrome-mac-arm64"]
317        };
318        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
319            .unwrap_or_else(|| home.join("Library/Caches/ms-playwright"));
320        for dir in versioned_children(&puppeteer, &["mac_arm-", "mac-"])
321            .into_iter()
322            .chain(versioned_children(&playwright, &["chromium-"]))
323        {
324            for sub in subs {
325                out.push(dir.join(sub).join(MAC_CFT_APP));
326            }
327        }
328    } else if cfg!(target_os = "windows") {
329        let local = env_path("LOCALAPPDATA").unwrap_or_else(|| home.join(r"AppData\Local"));
330        for dir in versioned_children(&puppeteer, &["win64-", "win32-"]) {
331            out.push(dir.join("chrome-win64").join("chrome.exe"));
332            out.push(dir.join("chrome-win32").join("chrome.exe"));
333        }
334        let playwright =
335            env_path("PLAYWRIGHT_BROWSERS_PATH").unwrap_or_else(|| local.join("ms-playwright"));
336        for dir in versioned_children(&playwright, &["chromium-"]) {
337            out.push(dir.join("chrome-win64").join("chrome.exe"));
338        }
339    } else {
340        for dir in versioned_children(&puppeteer, &["linux-", "linux_arm-"]) {
341            out.push(dir.join("chrome-linux64").join("chrome"));
342            out.push(dir.join("chrome-linux-arm64").join("chrome"));
343        }
344        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
345            .unwrap_or_else(|| home.join(".cache").join("ms-playwright"));
346        for dir in versioned_children(&playwright, &["chromium-"]) {
347            out.push(dir.join("chrome-linux64").join("chrome"));
348        }
349    }
350    out
351}
352
353/// Resolve Chrome for Testing: `explicit`, then `RIGHTKIT_CHROME_FOR_TESTING`, then
354/// [`chrome_for_testing_candidates`]. Errors with install instructions; never returns
355/// regular Chrome.
356pub fn chrome_for_testing_path(explicit: Option<&Path>) -> Result<PathBuf> {
357    let missing = |what: String| {
358        BrowserError::ChromeForTestingNotFound(format!("{what}\n{CHROME_FOR_TESTING_INSTALL_HINT}"))
359    };
360    if let Some(p) = explicit {
361        return if p.exists() {
362            Ok(p.to_path_buf())
363        } else {
364            Err(missing(format!(
365                "explicit Chrome for Testing executable does not exist: {}",
366                p.display()
367            )))
368        };
369    }
370    if let Some(p) = std::env::var_os(CHROME_FOR_TESTING_ENV).filter(|v| !v.is_empty()) {
371        let p = PathBuf::from(p);
372        return if p.exists() {
373            Ok(p)
374        } else {
375            Err(missing(format!(
376                "{CHROME_FOR_TESTING_ENV} points at a missing file: {}",
377                p.display()
378            )))
379        };
380    }
381    let candidates = chrome_for_testing_candidates();
382    if let Some(p) = candidates.iter().find(|p| p.exists()) {
383        return Ok(p.clone());
384    }
385    let searched: Vec<String> = candidates
386        .iter()
387        .map(|p| format!("  {}", p.display()))
388        .collect();
389    Err(missing(format!(
390        "Chrome for Testing is not installed; searched:\n{}",
391        if searched.is_empty() {
392            "  (nothing)".to_string()
393        } else {
394            searched.join("\n")
395        }
396    )))
397}
398
399/// System-only selection takes priority; otherwise `chrome_path` as given, then Chrome
400/// for Testing, then (only with [`LaunchOptions::system_chrome`]) the system browser.
401pub(crate) fn resolve_executable(opts: &LaunchOptions) -> Result<PathBuf> {
402    resolve_executable_with(opts, || chrome_for_testing_path(None), find_chrome)
403}
404
405fn resolve_executable_with(
406    opts: &LaunchOptions,
407    cft: impl FnOnce() -> Result<PathBuf>,
408    system: impl FnOnce() -> Option<PathBuf>,
409) -> Result<PathBuf> {
410    if opts.use_system_chrome_only {
411        return system().ok_or(BrowserError::ChromeNotFound);
412    }
413    if let Some(p) = &opts.chrome_path {
414        return Ok(p.clone());
415    }
416    match cft() {
417        Ok(p) => Ok(p),
418        Err(e) if opts.allow_system_chrome => system().ok_or(e),
419        Err(e) => Err(e),
420    }
421}
422
423/// System Chrome, Chromium, then Edge. `CHROME` env overrides. Launch uses this only with
424/// [`LaunchOptions::system_chrome`] or [`LaunchOptions::system_chrome_only`];
425/// prefer [`chrome_for_testing_path`] for isolated automation.
426pub fn find_chrome() -> Option<PathBuf> {
427    if let Ok(p) = std::env::var("CHROME") {
428        let p = PathBuf::from(p);
429        if p.exists() {
430            return Some(p);
431        }
432    }
433    let candidates: &[&str] = if cfg!(target_os = "windows") {
434        &[
435            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
436            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
437            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
438            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
439        ]
440    } else if cfg!(target_os = "macos") {
441        &[
442            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
443            "/Applications/Chromium.app/Contents/MacOS/Chromium",
444            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
445        ]
446    } else {
447        &[
448            "/usr/bin/google-chrome",
449            "/usr/bin/chromium",
450            "/usr/bin/chromium-browser",
451            "/usr/bin/microsoft-edge",
452        ]
453    };
454    candidates
455        .iter()
456        .map(PathBuf::from)
457        .find(|p| Path::new(p).exists())
458}
459
460/// Chrome flags a caller may not pass: they would redirect the profile to the
461/// user's real browser data or expose the debugging endpoint outside this session.
462pub(crate) fn validate_extra_args(args: &[String]) -> Result<()> {
463    const FORBIDDEN: &[&str] = &[
464        "user-data-dir",
465        "profile-directory",
466        "remote-debugging-port",
467        "remote-debugging-address",
468        "remote-debugging-pipe",
469        "remote-allow-origins",
470        "disable-web-security",
471        "incognito-bypass",
472    ];
473    for a in args {
474        let name = a.trim_start_matches('-').split('=').next().unwrap_or("");
475        if FORBIDDEN.contains(&name) {
476            return Err(BrowserError::Invalid(format!(
477                "chrome flag '--{name}' is managed by the session"
478            )));
479        }
480    }
481    Ok(())
482}
483
484/// Refuse roots that are (or sit inside) a real browser's own user-data directory.
485pub(crate) fn reject_real_browser_profile(root: &Path) -> Result<()> {
486    let mut real: Vec<PathBuf> = Vec::new();
487    if let Some(home) = std::env::var_os("HOME")
488        .or_else(|| std::env::var_os("USERPROFILE"))
489        .map(PathBuf::from)
490    {
491        for rel in [
492            "Library/Application Support/Google/Chrome",
493            "Library/Application Support/Chromium",
494            "Library/Application Support/Microsoft Edge",
495            ".config/google-chrome",
496            ".config/chromium",
497            ".config/microsoft-edge",
498        ] {
499            real.push(home.join(rel));
500        }
501    }
502    if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
503        for rel in [
504            r"Google\Chrome\User Data",
505            r"Chromium\User Data",
506            r"Microsoft\Edge\User Data",
507        ] {
508            real.push(local.join(rel));
509        }
510    }
511    std::fs::create_dir_all(root)?;
512    let root = root.canonicalize()?;
513    for r in real {
514        if let Ok(r) = r.canonicalize() {
515            if root.starts_with(&r) {
516                return Err(BrowserError::Profile(
517                    "refusing to use the user's real browser profile".into(),
518                ));
519            }
520        }
521    }
522    Ok(())
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528    use std::ffi::OsString;
529    use std::sync::{Mutex, MutexGuard};
530
531    // Serialize resolver tests that change process environment; restore even on panic.
532    static ENV_LOCK: Mutex<()> = Mutex::new(());
533
534    struct EnvGuard {
535        saved: Vec<(&'static str, Option<OsString>)>,
536        _lock: MutexGuard<'static, ()>,
537    }
538
539    impl EnvGuard {
540        fn new(values: &[(&'static str, Option<&Path>)]) -> Self {
541            let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
542            let saved = values
543                .iter()
544                .map(|(key, _)| (*key, std::env::var_os(key)))
545                .collect();
546            for (key, value) in values {
547                match value {
548                    Some(value) => std::env::set_var(key, value),
549                    None => std::env::remove_var(key),
550                }
551            }
552            Self { saved, _lock: lock }
553        }
554    }
555
556    impl Drop for EnvGuard {
557        fn drop(&mut self) {
558            for (key, value) in &self.saved {
559                match value {
560                    Some(value) => std::env::set_var(key, value),
561                    None => std::env::remove_var(key),
562                }
563            }
564        }
565    }
566
567    fn write_executable(path: &Path) {
568        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
569        std::fs::write(path, "fixture, not a browser").unwrap();
570    }
571
572    fn managed_executable(root: &Path, version: &str) -> PathBuf {
573        let relative = if cfg!(target_os = "macos") {
574            if cfg!(target_arch = "aarch64") {
575                "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
576            } else {
577                "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
578            }
579        } else if cfg!(target_os = "windows") {
580            "chrome-win64/chrome.exe"
581        } else {
582            "chrome-linux64/chrome"
583        };
584        root.join(version).join(relative)
585    }
586
587    #[test]
588    fn system_chrome_only_ignores_explicit_env_and_managed_cft() {
589        let temp = tempfile::tempdir().unwrap();
590        let root = temp.path().join("managed CfT");
591        let managed = managed_executable(&root, "130.10.0.0");
592        let explicit = temp.path().join("explicit CfT");
593        let system = temp.path().join("system Chrome");
594        for path in [&managed, &explicit, &system] {
595            write_executable(path);
596        }
597        let _env = EnvGuard::new(&[
598            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
599            (CHROME_FOR_TESTING_ENV, Some(&managed)),
600            ("CHROME", Some(&system)),
601        ]);
602        assert_eq!(chrome_for_testing_path(None).unwrap(), managed);
603        let opts = LaunchOptions {
604            chrome_path: Some(explicit),
605            ..LaunchOptions::default().system_chrome_only()
606        };
607        assert_eq!(resolve_executable(&opts).unwrap(), system);
608        assert_eq!(find_chrome().unwrap(), system);
609        // Also prove discovery is never called, regardless of installed CfT versions.
610        assert_eq!(
611            resolve_executable_with(
612                &opts,
613                || panic!("CfT discovery called"),
614                || Some(system.clone()),
615            )
616            .unwrap(),
617            system
618        );
619    }
620
621    #[test]
622    fn system_chrome_only_errors_when_system_browser_is_missing() {
623        let opts = LaunchOptions::default().system_chrome_only();
624        let err =
625            resolve_executable_with(&opts, || panic!("CfT discovery called"), || None).unwrap_err();
626        assert!(matches!(&err, BrowserError::ChromeNotFound));
627        assert_eq!(
628            err.to_string(),
629            "no Chrome, Chromium, or Edge executable found"
630        );
631    }
632
633    #[test]
634    fn defaults_and_system_chrome_preserve_cft_preference_and_fallback() {
635        let temp = tempfile::tempdir().unwrap();
636        let cft = temp.path().join("CfT");
637        let system = temp.path().join("system Chrome");
638        write_executable(&cft);
639        write_executable(&system);
640        let defaults = LaunchOptions::default();
641        assert!(defaults.headless && defaults.mute_audio);
642        assert!(!defaults.allow_system_chrome && !defaults.use_system_chrome_only);
643        for opts in [defaults.clone(), defaults.clone().system_chrome()] {
644            assert_eq!(
645                resolve_executable_with(
646                    &opts,
647                    || Ok(cft.clone()),
648                    || panic!("system lookup called"),
649                )
650                .unwrap(),
651                cft
652            );
653        }
654        assert!(matches!(
655            resolve_executable_with(
656                &defaults,
657                || Err(BrowserError::ChromeForTestingNotFound("missing".into())),
658                || panic!("default must not fall back"),
659            ),
660            Err(BrowserError::ChromeForTestingNotFound(_))
661        ));
662        let fallback = defaults.system_chrome_only().system_chrome();
663        assert!(!fallback.use_system_chrome_only);
664        assert_eq!(
665            resolve_executable_with(
666                &fallback,
667                || Err(BrowserError::ChromeForTestingNotFound("missing".into())),
668                || Some(system.clone()),
669            )
670            .unwrap(),
671            system
672        );
673    }
674
675    #[test]
676    fn managed_root_uses_platform_data_directory_and_env_override() {
677        let temp = tempfile::tempdir().unwrap();
678        let home = temp.path();
679        let suffix = Path::new("Orthic Labs/shared/chrome-for-testing");
680        let default_data = if cfg!(target_os = "macos") {
681            home.join("Library/Application Support")
682        } else if cfg!(target_os = "windows") {
683            home.join("AppData/Local")
684        } else {
685            home.join(".local/share")
686        };
687        assert_eq!(
688            managed_chrome_for_testing_root(home, &|_| None),
689            default_data.join(suffix)
690        );
691        let data = home.join("custom app data");
692        let with_data = |key: &str| {
693            if key == "LOCALAPPDATA" || key == "XDG_DATA_HOME" {
694                Some(data.clone())
695            } else {
696                None
697            }
698        };
699        let expected_data = if cfg!(target_os = "macos") {
700            default_data
701        } else {
702            data.clone()
703        };
704        assert_eq!(
705            managed_chrome_for_testing_root(home, &with_data),
706            expected_data.join(suffix)
707        );
708        let override_root = home.join("custom managed root");
709        assert_eq!(
710            managed_chrome_for_testing_root(home, &|key| {
711                if key == CHROME_FOR_TESTING_ROOT_ENV {
712                    Some(override_root.clone())
713                } else {
714                    None
715                }
716            }),
717            override_root
718        );
719    }
720
721    #[test]
722    fn managed_folder_wins_with_newest_numeric_version_first() {
723        let temp = tempfile::tempdir().unwrap();
724        let root = temp.path().join("managed Chrome for Testing");
725        let puppeteer = temp.path().join("puppeteer");
726        let older = managed_executable(&root, "129.99.0.0");
727        let recent = managed_executable(&root, "130.2.0.0");
728        let newest = managed_executable(&root, "130.10.0.0");
729        let legacy_dir = if cfg!(target_os = "macos") {
730            "mac-999.0.0.0"
731        } else if cfg!(target_os = "windows") {
732            "win64-999.0.0.0"
733        } else {
734            "linux-999.0.0.0"
735        };
736        let legacy = managed_executable(&puppeteer.join("chrome"), legacy_dir);
737        for path in [&older, &recent, &newest, &legacy] {
738            write_executable(path);
739        }
740        std::fs::create_dir(root.join("999.staging")).unwrap();
741        std::fs::write(root.join("999.0.0.0"), "not a version directory").unwrap();
742        let _env = EnvGuard::new(&[
743            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
744            (CHROME_FOR_TESTING_ENV, None),
745            ("PUPPETEER_CACHE_DIR", Some(&puppeteer)),
746        ]);
747        let candidates = chrome_for_testing_candidates();
748        assert_eq!(&candidates[..3], &[newest.clone(), recent.clone(), older]);
749        assert!(candidates.iter().position(|p| p == &legacy).unwrap() >= 3);
750        assert_eq!(chrome_for_testing_path(None).unwrap(), newest);
751        std::env::set_var(CHROME_FOR_TESTING_ENV, &legacy);
752        assert_eq!(chrome_for_testing_path(None).unwrap(), legacy);
753        std::env::remove_var(CHROME_FOR_TESTING_ENV);
754        std::fs::remove_file(&newest).unwrap();
755        assert_eq!(chrome_for_testing_path(None).unwrap(), recent);
756        // Explicit executable selection retains priority over managed discovery.
757        assert_eq!(chrome_for_testing_path(Some(&legacy)).unwrap(), legacy);
758    }
759}