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
261/// Dotted numeric version folders of the managed root, newest first (qa-chrome's layout);
262/// staging/metadata entries are ignored.
263fn managed_version_dirs(root: &Path) -> Vec<PathBuf> {
264    versioned_children(root, &[""])
265        .into_iter()
266        .filter(|dir| {
267            dir.is_dir()
268                && dir
269                    .file_name()
270                    .and_then(|n| n.to_str())
271                    .is_some_and(|name| {
272                        name.contains('.')
273                            && name.split('.').all(|part| {
274                                !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())
275                            })
276                    })
277        })
278        .collect()
279}
280
281fn managed_chrome_for_testing_candidates(root: &Path) -> Vec<PathBuf> {
282    managed_version_dirs(root)
283        .into_iter()
284        .map(|dir| {
285            if cfg!(target_os = "macos") {
286                let sub = if cfg!(target_arch = "aarch64") {
287                    "chrome-mac-arm64"
288                } else {
289                    "chrome-mac-x64"
290                };
291                dir.join(sub).join(MAC_CFT_APP)
292            } else if cfg!(target_os = "windows") {
293                dir.join("chrome-win64/chrome.exe")
294            } else {
295                dir.join("chrome-linux64/chrome")
296            }
297        })
298        .collect()
299}
300
301/// Windows fixture only: `chrome-headless-shell` of the same Chrome for Testing version, which
302/// never starts the crashpad handler (see [`chrome_headless_shell_path`]).
303#[cfg(windows)]
304pub(crate) const HEADLESS_SHELL_ENV: &str = "RIGHTKIT_CHROME_HEADLESS_SHELL";
305#[cfg(windows)]
306const HEADLESS_SHELL_WIN64: &str = "chrome-headless-shell-win64/chrome-headless-shell.exe";
307
308/// Candidate `chrome-headless-shell.exe` paths for the Windows fixture, in resolution order: the
309/// sibling of the resolved Chrome (`<version>/chrome-win64/chrome.exe` ->
310/// `<version>/chrome-headless-shell-win64/`), then each RightKit-managed version, newest first
311/// (`RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the root, as for Chrome).
312#[cfg(windows)]
313fn chrome_headless_shell_candidates(chrome: &Path, managed_root: &Path) -> Vec<PathBuf> {
314    let mut out = Vec::new();
315    if let Some(version_dir) = chrome.parent().and_then(Path::parent) {
316        out.push(version_dir.join(HEADLESS_SHELL_WIN64));
317    }
318    out.extend(
319        managed_version_dirs(managed_root)
320            .into_iter()
321            .map(|dir| dir.join(HEADLESS_SHELL_WIN64)),
322    );
323    out
324}
325
326/// Resolve `chrome-headless-shell.exe` for the Windows fixture: `RIGHTKIT_CHROME_HEADLESS_SHELL`
327/// (must exist), then [`chrome_headless_shell_candidates`]. Chrome's browser process starts the
328/// crashpad handler unconditionally, which cannot create its named pipe inside an AppContainer;
329/// the headless shell never starts it on Windows. Production launches never call this.
330#[cfg(windows)]
331pub(crate) fn chrome_headless_shell_path(chrome: &Path) -> Result<PathBuf> {
332    let missing = |what: String| {
333        BrowserError::ChromeForTestingNotFound(format!(
334            "{what}\nThe Windows fixture runs chrome-headless-shell from the same Chrome for Testing \
335             version (chrome-headless-shell-win64.zip, unpacked beside chrome-win64, or {HEADLESS_SHELL_ENV})"
336        ))
337    };
338    if let Some(p) = std::env::var_os(HEADLESS_SHELL_ENV).filter(|v| !v.is_empty()) {
339        let p = PathBuf::from(p);
340        return if p.exists() {
341            Ok(p)
342        } else {
343            Err(missing(format!(
344                "{HEADLESS_SHELL_ENV} points at a missing file: {}",
345                p.display()
346            )))
347        };
348    }
349    let home = home_dir().unwrap_or_default();
350    let env_path = |k: &str| {
351        std::env::var_os(k)
352            .filter(|v| !v.is_empty())
353            .map(PathBuf::from)
354    };
355    let root = managed_chrome_for_testing_root(&home, &env_path);
356    let candidates = chrome_headless_shell_candidates(chrome, &root);
357    if let Some(p) = candidates.iter().find(|p| p.exists()) {
358        return Ok(p.clone());
359    }
360    let searched: Vec<String> = candidates
361        .iter()
362        .map(|p| format!("  {}", p.display()))
363        .collect();
364    Err(missing(format!(
365        "chrome-headless-shell is not installed; searched:\n{}",
366        searched.join("\n")
367    )))
368}
369
370/// Known Chrome for Testing install locations, in resolution order: RightKit-managed
371/// versions (`RIGHTKIT_CHROME_FOR_TESTING_ROOT` overrides the root), app installs, then
372/// Puppeteer's cache (`PUPPETEER_CACHE_DIR`), then Playwright's (`PLAYWRIGHT_BROWSERS_PATH`),
373/// newest version first within each cache.
374pub fn chrome_for_testing_candidates() -> Vec<PathBuf> {
375    let home = home_dir().unwrap_or_default();
376    let env_path = |k: &str| {
377        std::env::var_os(k)
378            .filter(|v| !v.is_empty())
379            .map(PathBuf::from)
380    };
381    let puppeteer = env_path("PUPPETEER_CACHE_DIR")
382        .unwrap_or_else(|| home.join(".cache").join("puppeteer"))
383        .join("chrome");
384    let managed_root = managed_chrome_for_testing_root(&home, &env_path);
385    let mut out = managed_chrome_for_testing_candidates(&managed_root);
386    if cfg!(target_os = "macos") {
387        out.push(Path::new("/Applications").join(MAC_CFT_APP));
388        out.push(home.join("Applications").join(MAC_CFT_APP));
389        let subs: [&str; 2] = if cfg!(target_arch = "aarch64") {
390            ["chrome-mac-arm64", "chrome-mac-x64"]
391        } else {
392            ["chrome-mac-x64", "chrome-mac-arm64"]
393        };
394        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
395            .unwrap_or_else(|| home.join("Library/Caches/ms-playwright"));
396        for dir in versioned_children(&puppeteer, &["mac_arm-", "mac-"])
397            .into_iter()
398            .chain(versioned_children(&playwright, &["chromium-"]))
399        {
400            for sub in subs {
401                out.push(dir.join(sub).join(MAC_CFT_APP));
402            }
403        }
404    } else if cfg!(target_os = "windows") {
405        let local = env_path("LOCALAPPDATA").unwrap_or_else(|| home.join(r"AppData\Local"));
406        for dir in versioned_children(&puppeteer, &["win64-", "win32-"]) {
407            out.push(dir.join("chrome-win64").join("chrome.exe"));
408            out.push(dir.join("chrome-win32").join("chrome.exe"));
409        }
410        let playwright =
411            env_path("PLAYWRIGHT_BROWSERS_PATH").unwrap_or_else(|| local.join("ms-playwright"));
412        for dir in versioned_children(&playwright, &["chromium-"]) {
413            out.push(dir.join("chrome-win64").join("chrome.exe"));
414        }
415    } else {
416        for dir in versioned_children(&puppeteer, &["linux-", "linux_arm-"]) {
417            out.push(dir.join("chrome-linux64").join("chrome"));
418            out.push(dir.join("chrome-linux-arm64").join("chrome"));
419        }
420        let playwright = env_path("PLAYWRIGHT_BROWSERS_PATH")
421            .unwrap_or_else(|| home.join(".cache").join("ms-playwright"));
422        for dir in versioned_children(&playwright, &["chromium-"]) {
423            out.push(dir.join("chrome-linux64").join("chrome"));
424        }
425    }
426    out
427}
428
429/// Resolve Chrome for Testing: `explicit`, then `RIGHTKIT_CHROME_FOR_TESTING`, then
430/// [`chrome_for_testing_candidates`]. Errors with install instructions; never returns
431/// regular Chrome.
432pub fn chrome_for_testing_path(explicit: Option<&Path>) -> Result<PathBuf> {
433    let missing = |what: String| {
434        BrowserError::ChromeForTestingNotFound(format!("{what}\n{CHROME_FOR_TESTING_INSTALL_HINT}"))
435    };
436    if let Some(p) = explicit {
437        return if p.exists() {
438            Ok(p.to_path_buf())
439        } else {
440            Err(missing(format!(
441                "explicit Chrome for Testing executable does not exist: {}",
442                p.display()
443            )))
444        };
445    }
446    if let Some(p) = std::env::var_os(CHROME_FOR_TESTING_ENV).filter(|v| !v.is_empty()) {
447        let p = PathBuf::from(p);
448        return if p.exists() {
449            Ok(p)
450        } else {
451            Err(missing(format!(
452                "{CHROME_FOR_TESTING_ENV} points at a missing file: {}",
453                p.display()
454            )))
455        };
456    }
457    let candidates = chrome_for_testing_candidates();
458    if let Some(p) = candidates.iter().find(|p| p.exists()) {
459        return Ok(p.clone());
460    }
461    let searched: Vec<String> = candidates
462        .iter()
463        .map(|p| format!("  {}", p.display()))
464        .collect();
465    Err(missing(format!(
466        "Chrome for Testing is not installed; searched:\n{}",
467        if searched.is_empty() {
468            "  (nothing)".to_string()
469        } else {
470            searched.join("\n")
471        }
472    )))
473}
474
475/// System-only selection takes priority; otherwise `chrome_path` as given, then Chrome
476/// for Testing, then (only with [`LaunchOptions::system_chrome`]) the system browser.
477pub(crate) fn resolve_executable(opts: &LaunchOptions) -> Result<PathBuf> {
478    resolve_executable_with(opts, || chrome_for_testing_path(None), find_chrome)
479}
480
481fn resolve_executable_with(
482    opts: &LaunchOptions,
483    cft: impl FnOnce() -> Result<PathBuf>,
484    system: impl FnOnce() -> Option<PathBuf>,
485) -> Result<PathBuf> {
486    if opts.use_system_chrome_only {
487        return system().ok_or(BrowserError::ChromeNotFound);
488    }
489    if let Some(p) = &opts.chrome_path {
490        return Ok(p.clone());
491    }
492    match cft() {
493        Ok(p) => Ok(p),
494        Err(e) if opts.allow_system_chrome => system().ok_or(e),
495        Err(e) => Err(e),
496    }
497}
498
499/// System Chrome, Chromium, then Edge. `CHROME` env overrides. Launch uses this only with
500/// [`LaunchOptions::system_chrome`] or [`LaunchOptions::system_chrome_only`];
501/// prefer [`chrome_for_testing_path`] for isolated automation.
502pub fn find_chrome() -> Option<PathBuf> {
503    if let Ok(p) = std::env::var("CHROME") {
504        let p = PathBuf::from(p);
505        if p.exists() {
506            return Some(p);
507        }
508    }
509    let candidates: &[&str] = if cfg!(target_os = "windows") {
510        &[
511            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
512            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
513            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
514            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
515        ]
516    } else if cfg!(target_os = "macos") {
517        &[
518            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
519            "/Applications/Chromium.app/Contents/MacOS/Chromium",
520            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
521        ]
522    } else {
523        &[
524            "/usr/bin/google-chrome",
525            "/usr/bin/chromium",
526            "/usr/bin/chromium-browser",
527            "/usr/bin/microsoft-edge",
528        ]
529    };
530    candidates
531        .iter()
532        .map(PathBuf::from)
533        .find(|p| Path::new(p).exists())
534}
535
536/// Chrome flags a caller may not pass: they would redirect the profile to the
537/// user's real browser data or expose the debugging endpoint outside this session.
538pub(crate) fn validate_extra_args(args: &[String]) -> Result<()> {
539    const FORBIDDEN: &[&str] = &[
540        "user-data-dir",
541        "profile-directory",
542        "remote-debugging-port",
543        "remote-debugging-address",
544        "remote-debugging-pipe",
545        "remote-allow-origins",
546        "disable-web-security",
547        "incognito-bypass",
548    ];
549    for a in args {
550        let name = a.trim_start_matches('-').split('=').next().unwrap_or("");
551        if FORBIDDEN.contains(&name) {
552            return Err(BrowserError::Invalid(format!(
553                "chrome flag '--{name}' is managed by the session"
554            )));
555        }
556    }
557    Ok(())
558}
559
560/// Refuse roots that are (or sit inside) a real browser's own user-data directory.
561pub(crate) fn reject_real_browser_profile(root: &Path) -> Result<()> {
562    let mut real: Vec<PathBuf> = Vec::new();
563    if let Some(home) = std::env::var_os("HOME")
564        .or_else(|| std::env::var_os("USERPROFILE"))
565        .map(PathBuf::from)
566    {
567        for rel in [
568            "Library/Application Support/Google/Chrome",
569            "Library/Application Support/Chromium",
570            "Library/Application Support/Microsoft Edge",
571            ".config/google-chrome",
572            ".config/chromium",
573            ".config/microsoft-edge",
574        ] {
575            real.push(home.join(rel));
576        }
577    }
578    if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
579        for rel in [
580            r"Google\Chrome\User Data",
581            r"Chromium\User Data",
582            r"Microsoft\Edge\User Data",
583        ] {
584            real.push(local.join(rel));
585        }
586    }
587    std::fs::create_dir_all(root)?;
588    let root = root.canonicalize()?;
589    for r in real {
590        if let Ok(r) = r.canonicalize() {
591            if root.starts_with(&r) {
592                return Err(BrowserError::Profile(
593                    "refusing to use the user's real browser profile".into(),
594                ));
595            }
596        }
597    }
598    Ok(())
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604    use std::ffi::OsString;
605    use std::sync::{Mutex, MutexGuard};
606
607    // Serialize resolver tests that change process environment; restore even on panic.
608    static ENV_LOCK: Mutex<()> = Mutex::new(());
609
610    struct EnvGuard {
611        saved: Vec<(&'static str, Option<OsString>)>,
612        _lock: MutexGuard<'static, ()>,
613    }
614
615    impl EnvGuard {
616        fn new(values: &[(&'static str, Option<&Path>)]) -> Self {
617            let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
618            let saved = values
619                .iter()
620                .map(|(key, _)| (*key, std::env::var_os(key)))
621                .collect();
622            for (key, value) in values {
623                match value {
624                    Some(value) => std::env::set_var(key, value),
625                    None => std::env::remove_var(key),
626                }
627            }
628            Self { saved, _lock: lock }
629        }
630    }
631
632    impl Drop for EnvGuard {
633        fn drop(&mut self) {
634            for (key, value) in &self.saved {
635                match value {
636                    Some(value) => std::env::set_var(key, value),
637                    None => std::env::remove_var(key),
638                }
639            }
640        }
641    }
642
643    fn write_executable(path: &Path) {
644        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
645        std::fs::write(path, "fixture, not a browser").unwrap();
646    }
647
648    fn managed_executable(root: &Path, version: &str) -> PathBuf {
649        let relative = if cfg!(target_os = "macos") {
650            if cfg!(target_arch = "aarch64") {
651                "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
652            } else {
653                "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
654            }
655        } else if cfg!(target_os = "windows") {
656            "chrome-win64/chrome.exe"
657        } else {
658            "chrome-linux64/chrome"
659        };
660        root.join(version).join(relative)
661    }
662
663    #[test]
664    fn system_chrome_only_ignores_explicit_env_and_managed_cft() {
665        let temp = tempfile::tempdir().unwrap();
666        let root = temp.path().join("managed CfT");
667        let managed = managed_executable(&root, "130.10.0.0");
668        let explicit = temp.path().join("explicit CfT");
669        let system = temp.path().join("system Chrome");
670        for path in [&managed, &explicit, &system] {
671            write_executable(path);
672        }
673        let _env = EnvGuard::new(&[
674            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
675            (CHROME_FOR_TESTING_ENV, Some(&managed)),
676            ("CHROME", Some(&system)),
677        ]);
678        assert_eq!(chrome_for_testing_path(None).unwrap(), managed);
679        let opts = LaunchOptions {
680            chrome_path: Some(explicit),
681            ..LaunchOptions::default().system_chrome_only()
682        };
683        assert_eq!(resolve_executable(&opts).unwrap(), system);
684        assert_eq!(find_chrome().unwrap(), system);
685        // Also prove discovery is never called, regardless of installed CfT versions.
686        assert_eq!(
687            resolve_executable_with(
688                &opts,
689                || panic!("CfT discovery called"),
690                || Some(system.clone()),
691            )
692            .unwrap(),
693            system
694        );
695    }
696
697    #[cfg(windows)]
698    #[test]
699    fn headless_shell_candidates_are_the_sibling_then_managed_versions() {
700        let temp = tempfile::tempdir().unwrap();
701        let root = temp.path().join("root");
702        for v in ["154.0.1.1", "155.0.8059.39"] {
703            std::fs::create_dir_all(root.join(v)).unwrap();
704        }
705        let chrome = root.join("155.0.8059.39/chrome-win64/chrome.exe");
706        let got = chrome_headless_shell_candidates(&chrome, &root);
707        let shell = "chrome-headless-shell-win64/chrome-headless-shell.exe";
708        assert_eq!(
709            got,
710            vec![
711                root.join("155.0.8059.39").join(shell),
712                root.join("155.0.8059.39").join(shell),
713                root.join("154.0.1.1").join(shell),
714            ]
715        );
716    }
717
718    #[test]
719    fn system_chrome_only_errors_when_system_browser_is_missing() {
720        let opts = LaunchOptions::default().system_chrome_only();
721        let err =
722            resolve_executable_with(&opts, || panic!("CfT discovery called"), || None).unwrap_err();
723        assert!(matches!(&err, BrowserError::ChromeNotFound));
724        assert_eq!(
725            err.to_string(),
726            "no Chrome, Chromium, or Edge executable found"
727        );
728    }
729
730    #[test]
731    fn defaults_and_system_chrome_preserve_cft_preference_and_fallback() {
732        let temp = tempfile::tempdir().unwrap();
733        let cft = temp.path().join("CfT");
734        let system = temp.path().join("system Chrome");
735        write_executable(&cft);
736        write_executable(&system);
737        let defaults = LaunchOptions::default();
738        assert!(defaults.headless && defaults.mute_audio);
739        assert!(!defaults.allow_system_chrome && !defaults.use_system_chrome_only);
740        for opts in [defaults.clone(), defaults.clone().system_chrome()] {
741            assert_eq!(
742                resolve_executable_with(
743                    &opts,
744                    || Ok(cft.clone()),
745                    || panic!("system lookup called"),
746                )
747                .unwrap(),
748                cft
749            );
750        }
751        assert!(matches!(
752            resolve_executable_with(
753                &defaults,
754                || Err(BrowserError::ChromeForTestingNotFound("missing".into())),
755                || panic!("default must not fall back"),
756            ),
757            Err(BrowserError::ChromeForTestingNotFound(_))
758        ));
759        let fallback = defaults.system_chrome_only().system_chrome();
760        assert!(!fallback.use_system_chrome_only);
761        assert_eq!(
762            resolve_executable_with(
763                &fallback,
764                || Err(BrowserError::ChromeForTestingNotFound("missing".into())),
765                || Some(system.clone()),
766            )
767            .unwrap(),
768            system
769        );
770    }
771
772    #[test]
773    fn managed_root_uses_platform_data_directory_and_env_override() {
774        let temp = tempfile::tempdir().unwrap();
775        let home = temp.path();
776        let suffix = Path::new("Orthic Labs/shared/chrome-for-testing");
777        let default_data = if cfg!(target_os = "macos") {
778            home.join("Library/Application Support")
779        } else if cfg!(target_os = "windows") {
780            home.join("AppData/Local")
781        } else {
782            home.join(".local/share")
783        };
784        assert_eq!(
785            managed_chrome_for_testing_root(home, &|_| None),
786            default_data.join(suffix)
787        );
788        let data = home.join("custom app data");
789        let with_data = |key: &str| {
790            if key == "LOCALAPPDATA" || key == "XDG_DATA_HOME" {
791                Some(data.clone())
792            } else {
793                None
794            }
795        };
796        let expected_data = if cfg!(target_os = "macos") {
797            default_data
798        } else {
799            data.clone()
800        };
801        assert_eq!(
802            managed_chrome_for_testing_root(home, &with_data),
803            expected_data.join(suffix)
804        );
805        let override_root = home.join("custom managed root");
806        assert_eq!(
807            managed_chrome_for_testing_root(home, &|key| {
808                if key == CHROME_FOR_TESTING_ROOT_ENV {
809                    Some(override_root.clone())
810                } else {
811                    None
812                }
813            }),
814            override_root
815        );
816    }
817
818    #[test]
819    fn managed_folder_wins_with_newest_numeric_version_first() {
820        let temp = tempfile::tempdir().unwrap();
821        let root = temp.path().join("managed Chrome for Testing");
822        let puppeteer = temp.path().join("puppeteer");
823        // An empty stand-in, so discovery does not list the user's own Playwright folder.
824        let playwright = temp.path().join("ms-playwright");
825        std::fs::create_dir(&playwright).unwrap();
826        let older = managed_executable(&root, "129.99.0.0");
827        let recent = managed_executable(&root, "130.2.0.0");
828        let newest = managed_executable(&root, "130.10.0.0");
829        let legacy_dir = if cfg!(target_os = "macos") {
830            "mac-999.0.0.0"
831        } else if cfg!(target_os = "windows") {
832            "win64-999.0.0.0"
833        } else {
834            "linux-999.0.0.0"
835        };
836        let legacy = managed_executable(&puppeteer.join("chrome"), legacy_dir);
837        for path in [&older, &recent, &newest, &legacy] {
838            write_executable(path);
839        }
840        std::fs::create_dir(root.join("999.staging")).unwrap();
841        std::fs::write(root.join("999.0.0.0"), "not a version directory").unwrap();
842        let _env = EnvGuard::new(&[
843            (CHROME_FOR_TESTING_ROOT_ENV, Some(&root)),
844            (CHROME_FOR_TESTING_ENV, None),
845            ("PUPPETEER_CACHE_DIR", Some(&puppeteer)),
846            ("PLAYWRIGHT_BROWSERS_PATH", Some(&playwright)),
847        ]);
848        let candidates = chrome_for_testing_candidates();
849        assert_eq!(&candidates[..3], &[newest.clone(), recent.clone(), older]);
850        assert!(candidates.iter().position(|p| p == &legacy).unwrap() >= 3);
851        assert_eq!(chrome_for_testing_path(None).unwrap(), newest);
852        std::env::set_var(CHROME_FOR_TESTING_ENV, &legacy);
853        assert_eq!(chrome_for_testing_path(None).unwrap(), legacy);
854        std::env::remove_var(CHROME_FOR_TESTING_ENV);
855        std::fs::remove_file(&newest).unwrap();
856        assert_eq!(chrome_for_testing_path(None).unwrap(), recent);
857        // Explicit executable selection retains priority over managed discovery.
858        assert_eq!(chrome_for_testing_path(Some(&legacy)).unwrap(), legacy);
859    }
860}