Skip to main content

rightkit_browser/
session.rs

1use crate::cdp_ext::{DownloadBehavior, RequestInterceptor};
2use crate::config::{
3    reject_real_browser_profile, resolve_executable, validate_extra_args, validate_profile_dir,
4    validate_profile_name, LaunchOptions, ProfileSpec,
5};
6use crate::error::{cdp, BrowserError, Result};
7use crate::fixture_protocol::FixtureError;
8use crate::page::BrowserPage;
9#[cfg(target_os = "macos")]
10use crate::policy::NetworkPolicy;
11use crate::policy::{Guard, LifecycleKind};
12use crate::proc::ChromeProc;
13use crate::proxy::{FixtureProxyPolicy, PinProxy, PinnedConnection};
14use chromiumoxide::browser::Browser;
15use chromiumoxide::cdp::browser_protocol::browser::{
16    PermissionDescriptor, PermissionSetting, ResetPermissionsParams, SetDownloadBehaviorBehavior,
17    SetDownloadBehaviorParams, SetPermissionParams,
18};
19use chromiumoxide::handler::HandlerConfig;
20use futures::StreamExt;
21use std::collections::HashSet;
22use std::ffi::OsString;
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
25use std::sync::{Arc, Mutex as StdMutex};
26use std::time::{Duration, Instant};
27use tokio::sync::Mutex;
28use tokio::task::JoinHandle;
29
30static SESSION_SEQ: AtomicU64 = AtomicU64::new(0);
31
32/// Per-step wait before escalating a close (CDP -> SIGTERM -> SIGKILL).
33const GRACE: Duration = Duration::from_secs(5);
34const FIXTURE_STOP_RECEIPT_GRACE: Duration = Duration::from_secs(12);
35
36#[cfg(windows)]
37#[derive(Clone, Copy)]
38enum FixtureBackend {
39    WinAppcontainer,
40}
41
42enum ProfileGuard {
43    Temp(#[allow(dead_code)] tempfile::TempDir),
44    Named {
45        _lock: std::fs::File,
46    },
47    /// Caller-owned directory: dropping this guard has no filesystem effects.
48    Existing,
49}
50
51struct FixtureLaunchState {
52    process: Arc<StdMutex<Option<ChromeProc>>>,
53    profile: StdMutex<Option<ProfileGuard>>,
54    proxy: StdMutex<Option<PinProxy>>,
55    spawn_complete: tokio::sync::watch::Sender<u8>,
56    armed: AtomicBool,
57    cleanup_started: AtomicBool,
58}
59
60struct FixtureLaunchOwner {
61    state: Arc<FixtureLaunchState>,
62}
63
64struct SpawnCompleteGuard {
65    state: Option<Arc<FixtureLaunchState>>,
66    result: u8,
67}
68
69struct FixtureStopCompletionGuard {
70    status: tokio::sync::watch::Sender<u8>,
71    complete: bool,
72}
73
74impl Drop for SpawnCompleteGuard {
75    fn drop(&mut self) {
76        if let Some(state) = &self.state {
77            state.spawn_complete.send_replace(self.result);
78        }
79    }
80}
81
82impl FixtureStopCompletionGuard {
83    fn stopped(&mut self) {
84        self.status.send_replace(2);
85        self.complete = true;
86    }
87}
88
89impl Drop for FixtureStopCompletionGuard {
90    fn drop(&mut self) {
91        if !self.complete {
92            self.status.send_replace(3);
93        }
94    }
95}
96
97impl FixtureLaunchOwner {
98    fn new(profile: ProfileGuard, proxy: Option<PinProxy>) -> Self {
99        let (spawn_complete, _) = tokio::sync::watch::channel(0u8);
100        Self {
101            state: Arc::new(FixtureLaunchState {
102                process: Arc::new(StdMutex::new(None)),
103                profile: StdMutex::new(Some(profile)),
104                proxy: StdMutex::new(proxy),
105                spawn_complete,
106                armed: AtomicBool::new(true),
107                cleanup_started: AtomicBool::new(false),
108            }),
109        }
110    }
111
112    fn process_slot(&self) -> Arc<StdMutex<Option<ChromeProc>>> {
113        self.state.process.clone()
114    }
115
116    fn spawn_state(&self) -> Arc<FixtureLaunchState> {
117        self.state.clone()
118    }
119
120    fn into_parts(
121        self,
122    ) -> (
123        Arc<StdMutex<Option<ChromeProc>>>,
124        ProfileGuard,
125        Option<PinProxy>,
126    ) {
127        self.state.armed.store(false, Ordering::SeqCst);
128        let profile = self.state.profile.lock().unwrap().take().unwrap();
129        let proxy = self.state.proxy.lock().unwrap().take();
130        (self.state.process.clone(), profile, proxy)
131    }
132}
133
134impl FixtureLaunchState {
135    async fn cleanup(self: Arc<Self>) {
136        let mut complete = self.spawn_complete.subscribe();
137        while *complete.borrow() == 0 {
138            if complete.changed().await.is_err() {
139                self.keep_profile();
140                return;
141            }
142        }
143
144        let process = self
145            .process
146            .lock()
147            .unwrap_or_else(|error| error.into_inner())
148            .take();
149        let spawn_status = *complete.borrow();
150        let process_stopped = match (spawn_status, process) {
151            (_, Some(mut process)) => {
152                process.begin_fixture_transport_shutdown();
153                let terminated = tokio::task::spawn_blocking(move || {
154                    let result = process.terminate_fixture_tree();
155                    (process, result)
156                })
157                .await;
158                let Ok((process, result)) = terminated else {
159                    return self.keep_profile();
160                };
161                if result.is_err() {
162                    *self
163                        .process
164                        .lock()
165                        .unwrap_or_else(|error| error.into_inner()) = Some(process);
166                    false
167                } else {
168                    #[cfg(windows)]
169                    {
170                        let mut process = process;
171                        if process
172                            .finish_fixture_transport_shutdown(Instant::now() + GRACE)
173                            .await
174                            .is_err()
175                        {
176                            *self
177                                .process
178                                .lock()
179                                .unwrap_or_else(|error| error.into_inner()) = Some(process);
180                            false
181                        } else {
182                            true
183                        }
184                    }
185                    #[cfg(not(windows))]
186                    {
187                        true
188                    }
189                }
190            }
191            (2, None) => true,
192            (_, None) => false,
193        };
194        if !process_stopped {
195            self.keep_profile();
196            return;
197        }
198
199        let proxy = self
200            .proxy
201            .lock()
202            .unwrap_or_else(|error| error.into_inner())
203            .take();
204        let proxy_stopped = match proxy {
205            Some(proxy) => proxy.shutdown(GRACE).await.is_ok(),
206            None => true,
207        };
208        if proxy_stopped {
209            release_profile(
210                self.profile
211                    .lock()
212                    .unwrap_or_else(|error| error.into_inner())
213                    .take(),
214            );
215        } else {
216            self.keep_profile();
217        }
218    }
219
220    fn keep_profile(&self) {
221        if let Some(ProfileGuard::Temp(profile)) = self
222            .profile
223            .lock()
224            .unwrap_or_else(|error| error.into_inner())
225            .take()
226        {
227            let _ = profile.keep();
228        }
229    }
230}
231
232impl Drop for FixtureLaunchOwner {
233    fn drop(&mut self) {
234        if !self.state.armed.load(Ordering::SeqCst)
235            || self.state.cleanup_started.swap(true, Ordering::SeqCst)
236        {
237            return;
238        }
239        let state = self.state.clone();
240        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
241            runtime.spawn(state.cleanup());
242        } else {
243            if *self.state.spawn_complete.subscribe().borrow() == 0 {
244                self.state.keep_profile();
245                return;
246            }
247            let process = self
248                .state
249                .process
250                .lock()
251                .unwrap_or_else(|error| error.into_inner())
252                .take();
253            let spawn_status = *self.state.spawn_complete.subscribe().borrow();
254            let process_stopped = match (spawn_status, process) {
255                (_, Some(mut process)) => process.terminate_fixture_tree().is_ok(),
256                (2, None) => true,
257                (_, None) => false,
258            };
259            if process_stopped {
260                #[cfg(windows)]
261                {
262                    // No async runtime means bridge finalization cannot obtain its
263                    // inertness receipt. Keep profile evidence instead of claiming
264                    // an unverified cleanup path.
265                    self.state.keep_profile();
266                }
267                #[cfg(not(windows))]
268                {
269                    self.state
270                        .proxy
271                        .lock()
272                        .unwrap_or_else(|error| error.into_inner())
273                        .take();
274                    release_profile(
275                        self.state
276                            .profile
277                            .lock()
278                            .unwrap_or_else(|error| error.into_inner())
279                            .take(),
280                    );
281                }
282            } else {
283                self.state.keep_profile();
284            }
285        }
286    }
287}
288
289/// Remove the session's profile. A temporary profile is deleted with bounded retries:
290/// on Windows a just-terminated helper can hold a handle for a moment after its job ends.
291fn release_profile(guard: Option<ProfileGuard>) {
292    if let Some(ProfileGuard::Temp(dir)) = guard {
293        let path = dir.path().to_path_buf();
294        drop(dir);
295        let deadline = std::time::Instant::now() + Duration::from_secs(3);
296        while path.exists()
297            && std::fs::remove_dir_all(&path).is_err()
298            && std::time::Instant::now() < deadline
299        {
300            std::thread::sleep(Duration::from_millis(100));
301        }
302    }
303}
304
305fn lock_named_profile(root: &Path, name: &str) -> Result<(ProfileGuard, PathBuf, PathBuf)> {
306    validate_profile_name(name)?;
307    reject_real_browser_profile(root)?;
308    let dir = root.join(name);
309    std::fs::create_dir_all(&dir)?;
310    let lock = std::fs::OpenOptions::new()
311        .create(true)
312        .write(true)
313        .truncate(false)
314        .open(dir.join(".rightkit-browser.lock"))?;
315    match lock.try_lock() {
316        Ok(()) => {}
317        Err(std::fs::TryLockError::WouldBlock) => {
318            return Err(BrowserError::ProfileInUse(name.to_string()));
319        }
320        Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
321    }
322    let dl = dir.join("rightkit-downloads");
323    Ok((ProfileGuard::Named { _lock: lock }, dir, dl))
324}
325
326fn prepare_profile(profile: &ProfileSpec) -> Result<(ProfileGuard, PathBuf, PathBuf)> {
327    match profile {
328        ProfileSpec::Temporary => {
329            let t = tempfile::tempdir()?;
330            let p = t.path().to_path_buf();
331            let dl = p.join("downloads");
332            Ok((ProfileGuard::Temp(t), p, dl))
333        }
334        ProfileSpec::Named { root, name } => lock_named_profile(root, name),
335        ProfileSpec::ImportedFrom { root, name, import } => {
336            // Consent is checked before any directory is created or browser data is read.
337            import.validate()?;
338            let locked = lock_named_profile(root, name)?;
339            crate::real_session::import_if_needed(import, &locked.1)?;
340            Ok(locked)
341        }
342        ProfileSpec::Directory(path) => {
343            validate_profile_dir(path)?;
344            Ok((
345                ProfileGuard::Existing,
346                path.clone(),
347                path.join("rightkit-downloads"),
348            ))
349        }
350    }
351}
352
353/// What to install on a page before its first navigation; see `BrowserSession::new_page_with`.
354#[derive(Default)]
355pub struct PageSetup {
356    /// Request interceptor (see `BrowserPage::set_request_interceptor`).
357    pub interceptor: Option<RequestInterceptor>,
358    /// Download behaviour (see `BrowserPage::set_download_behavior`).
359    pub download: Option<DownloadBehavior>,
360}
361
362/// One Chrome process with any number of pages.
363pub struct BrowserSession {
364    id: String,
365    browser: Mutex<Browser>,
366    pages: StdMutex<Vec<Arc<BrowserPage>>>,
367    current: StdMutex<Option<String>>,
368    page_seq: AtomicU64,
369    handler: StdMutex<Option<JoinHandle<()>>>,
370    watcher: StdMutex<Option<JoinHandle<()>>>,
371    /// Released (temporary profile deleted) once Chrome has exited, on shutdown or drop.
372    profile_guard: StdMutex<Option<ProfileGuard>>,
373    profile_dir: PathBuf,
374    fixture_profile_path: Option<PathBuf>,
375    download_dir: PathBuf,
376    upload_root: Option<PathBuf>,
377    headless: bool,
378    guard: Arc<Guard>,
379    pid: Option<u32>,
380    proc: Arc<StdMutex<Option<ChromeProc>>>,
381    fixture_stop_status: tokio::sync::watch::Sender<u8>,
382    fixture_stop_failure: Arc<StdMutex<Option<String>>>,
383    fixture_stop_lock: Mutex<()>,
384    proxy: Option<PinProxy>,
385    /// Set before an intentional stop so the CDP pump does not report a crash.
386    stopping: Arc<AtomicBool>,
387    stopped: AtomicBool,
388    fixture_mode: bool,
389    #[cfg(windows)]
390    fixture_backend: Option<FixtureBackend>,
391}
392
393/// Flags every session launch starts from, before profile, viewport, proxy and caller flags.
394const BASE_CHROME_ARGS: &[&str] = &[
395    "--remote-debugging-port=0",
396    "--no-first-run",
397    "--no-default-browser-check",
398    "--disable-background-networking",
399    // Chrome's own traffic: the component updater (clients2.google.com) still runs
400    // with background networking off, and a session must see only its pages' requests.
401    "--disable-component-update",
402    "--disable-domain-reliability",
403    "--no-pings",
404    "--disable-background-timer-throttling",
405    "--disable-backgrounding-occluded-windows",
406    "--disable-breakpad",
407    "--disable-client-side-phishing-detection",
408    "--disable-component-extensions-with-background-pages",
409    "--disable-default-apps",
410    "--disable-dev-shm-usage",
411    "--disable-extensions",
412    "--disable-hang-monitor",
413    "--disable-ipc-flooding-protection",
414    "--disable-prompt-on-repost",
415    "--disable-renderer-backgrounding",
416    "--disable-sync",
417    "--force-color-profile=srgb",
418    "--metrics-recording-only",
419    "--password-store=basic",
420    "--use-mock-keychain",
421    // No unmanaged windows: a pop-up would be a page the policy never saw.
422    "--block-new-web-contents",
423];
424
425impl BrowserSession {
426    pub async fn launch(opts: LaunchOptions) -> Result<Self> {
427        Self::launch_inner(opts, None).await
428    }
429
430    /// Start a visible session that reuses the user's own browser sign-ins, with consent.
431    ///
432    /// Chrome 136+ ignores a debugging port on the browser's default user-data directory and a
433    /// profile in use is locked, so the user's running browser is not driven in place: the
434    /// consented profile's sign-in files are copied into a private RightKit profile under `root`
435    /// and the same browser (same executable, so its sign-in key applies) is launched on that
436    /// copy over a debugging pipe. The consented domains confine every action, passwords are
437    /// refused, and `consent` is checked at launch and before each action.
438    ///
439    /// Chromium-family browsers only (Chrome, Edge, Brave, Chromium); Safari and Firefox return
440    /// [`BrowserError::Unsupported`]. `opts` supplies timeouts, network policy and the admission
441    /// hook (which runs after the consent check); its profile, executable and window mode are
442    /// replaced.
443    pub async fn attach_user_browser(
444        consent: crate::real_session::UserConsentReceipt,
445        root: impl Into<PathBuf>,
446        opts: LaunchOptions,
447    ) -> Result<Self> {
448        Self::attach_user_browser_revocable(
449            consent,
450            crate::real_session::ConsentRevocation::new(),
451            root,
452            opts,
453        )
454        .await
455    }
456
457    /// [`Self::attach_user_browser`] with a live [`crate::ConsentRevocation`]: revoking it
458    /// makes the session's next action fail.
459    pub async fn attach_user_browser_revocable(
460        consent: crate::real_session::UserConsentReceipt,
461        revocation: crate::real_session::ConsentRevocation,
462        root: impl Into<PathBuf>,
463        mut opts: LaunchOptions,
464    ) -> Result<Self> {
465        use crate::real_session::{
466            attach_profile_name, browser_executable, BrowserKind, BrowserSource, ImportSpec,
467        };
468        consent.check_active()?;
469        let source = match consent.browser {
470            BrowserKind::Chrome => BrowserSource::Chrome,
471            BrowserKind::Edge => BrowserSource::Edge,
472            BrowserKind::Safari | BrowserKind::Firefox => {
473                return Err(BrowserError::Unsupported(format!(
474                    "{} cannot be attached over CDP; drive it through rightkit-automation",
475                    consent.browser.name()
476                )));
477            }
478            other => {
479                return Err(BrowserError::Unsupported(format!(
480                    "attach supports Chrome and Edge; {} is not covered yet",
481                    other.name()
482                )));
483            }
484        };
485        let exe = browser_executable(consent.browser).ok_or(BrowserError::ChromeNotFound)?;
486        let name = attach_profile_name(&consent);
487        let import = ImportSpec {
488            browser: source,
489            source_profile: Some(consent.profile.clone()),
490            domains: consent.domains.clone(),
491            consent,
492            revocation,
493            reimport: false,
494        };
495        opts.chrome_path = Some(exe);
496        opts.use_system_chrome_only = false;
497        opts.allow_system_chrome = false;
498        opts.headless = false;
499        opts.profile = ProfileSpec::ImportedFrom {
500            root: root.into(),
501            name,
502            import,
503        };
504        Self::launch(opts).await
505    }
506
507    /// Launch the sealed source-only fixture browser. This private constructor fixes every
508    /// option that could widen authority and installs the fixture-only network policy.
509    pub(crate) async fn launch_fixture(
510        policy: FixtureProxyPolicy,
511    ) -> std::result::Result<Self, FixtureError> {
512        #[cfg(not(any(target_os = "macos", windows)))]
513        #[allow(clippy::needless_return)]
514        {
515            let _ = policy;
516            return Err(FixtureError::ConfinementUnsupported(
517                "source-only browser fixtures require macOS Seatbelt confinement".into(),
518            ));
519        }
520        #[cfg(target_os = "macos")]
521        {
522            use crate::policy::{AddressClass, PolicyDecision};
523            let permitted_urls = policy.permitted_urls.clone();
524            let remaining = policy.expires_at.saturating_duration_since(Instant::now());
525            if remaining.is_zero() {
526                return Err(FixtureError::Revoked(
527                    "fixture lease expired before browser launch".into(),
528                ));
529            }
530            let opts = LaunchOptions {
531                headless: true,
532                mute_audio: true,
533                profile: ProfileSpec::Temporary,
534                chrome_path: None,
535                allow_system_chrome: false,
536                use_system_chrome_only: false,
537                extra_args: Vec::new(),
538                download_dir: None,
539                upload_root: None,
540                network: NetworkPolicy::default()
541                    .allow_class(AddressClass::Loopback)
542                    .allow_with(move |request| {
543                        if permitted_urls.contains(&request.url) {
544                            PolicyDecision::Allow
545                        } else {
546                            PolicyDecision::Deny(
547                                "fixture URL is outside the immutable bundle".into(),
548                            )
549                        }
550                    }),
551                launch_timeout: remaining,
552                request_timeout: remaining.min(Duration::from_secs(5)),
553                ..Default::default()
554            };
555            Self::launch_inner(opts, Some(policy))
556                .await
557                .map_err(|error| FixtureError::ConfinementUnavailable(error.to_string()))
558        }
559        #[cfg(windows)]
560        {
561            let remaining = policy.expires_at.saturating_duration_since(Instant::now());
562            if remaining.is_zero() {
563                return Err(FixtureError::Revoked(
564                    "fixture lease expired before browser launch".into(),
565                ));
566            }
567            // AppContainer denies all network. CDP uses inherited pipes, while
568            // Fetch fulfills immutable fixture bytes without a TCP proxy.
569            let opts = LaunchOptions {
570                headless: true,
571                mute_audio: true,
572                profile: ProfileSpec::Temporary,
573                chrome_path: None,
574                allow_system_chrome: false,
575                use_system_chrome_only: false,
576                extra_args: Vec::new(),
577                download_dir: None,
578                upload_root: None,
579                network: crate::policy::NetworkPolicy::unrestricted(),
580                launch_timeout: remaining,
581                request_timeout: remaining.min(Duration::from_secs(5)),
582                ..Default::default()
583            };
584            Self::launch_inner(opts, Some(policy))
585                .await
586                .map_err(|error| FixtureError::ConfinementUnavailable(error.to_string()))
587        }
588    }
589
590    async fn launch_inner(
591        #[cfg_attr(not(windows), allow(unused_mut))] mut opts: LaunchOptions,
592        fixture_proxy_policy: Option<FixtureProxyPolicy>,
593    ) -> Result<Self> {
594        validate_extra_args(&opts.extra_args)?;
595        let exe = resolve_executable(&opts)?;
596        // A sandbox that cannot read its own browser crashes the network service at startup;
597        // refuse that launch with the directory and the fix instead of a browser that hangs.
598        let sandboxed = !opts
599            .extra_args
600            .iter()
601            .any(|arg| arg.trim_start_matches('-') == "no-sandbox");
602        if sandboxed {
603            if let Some(missing) = crate::sandbox_access::missing_access(&exe) {
604                return Err(BrowserError::ChromeSandboxAccess {
605                    fix: crate::sandbox_access::grant_command(&missing.directory),
606                    directory: missing.directory,
607                    principals: missing.principals,
608                });
609            }
610        }
611        let (profile, profile_dir, default_dl) = prepare_profile(&opts.profile)?;
612        // A consented real-session profile confines every action to the consented domains.
613        let admission = match &opts.profile {
614            ProfileSpec::ImportedFrom { import, .. } => Some(
615                crate::real_session::scoped_admission(import, opts.admission.clone())?,
616            ),
617            _ => opts.admission.clone(),
618        };
619        let mut profile_guard = Some(profile);
620        let download_dir = opts.download_dir.clone().unwrap_or(default_dl);
621        std::fs::create_dir_all(&download_dir)?;
622
623        let id = format!("bs-{}", SESSION_SEQ.fetch_add(1, Ordering::Relaxed));
624        let guard = Arc::new(Guard {
625            session_id: id.clone(),
626            admission,
627            network: opts.network.clone(),
628            events: opts.on_event.clone(),
629            page_allowed: StdMutex::default(),
630        });
631        let fixture_mode = fixture_proxy_policy.is_some();
632        #[cfg(windows)]
633        let fixture_backend = fixture_mode.then_some(FixtureBackend::WinAppcontainer);
634        #[cfg(windows)]
635        let windows_fixture = matches!(fixture_backend, Some(FixtureBackend::WinAppcontainer));
636        #[cfg(not(windows))]
637        let windows_fixture = false;
638        let mut proxy = if let Some(policy) = fixture_proxy_policy {
639            if windows_fixture {
640                None
641            } else {
642                Some(
643                    PinProxy::start_fixture(guard.clone(), policy)
644                        .await
645                        .map_err(|error| {
646                            BrowserError::Launch(format!("fixture proxy unavailable: {error}"))
647                        })?,
648                )
649            }
650        } else if opts.network.unrestricted {
651            None
652        } else {
653            Some(PinProxy::start(guard.clone()).await?)
654        };
655
656        let mut args: Vec<OsString> = BASE_CHROME_ARGS.iter().map(OsString::from).collect();
657        args.push(crate::proc::profile_arg(&profile_dir));
658        args.push(format!("--window-size={},{}", opts.viewport.0, opts.viewport.1).into());
659        args.push(if opts.headless {
660            "--headless=new".into()
661        } else {
662            "--hide-crash-restore-bubble".into()
663        });
664        if opts.mute_audio {
665            args.push("--mute-audio".into());
666        }
667        if let Some(p) = &proxy {
668            // Every connection, loopback included, goes through the pinning proxy;
669            // Chrome itself resolves nothing but the proxy address.
670            args.push(format!("--proxy-server=http://{}", p.addr).into());
671            args.push("--proxy-bypass-list=<-loopback>".into());
672            args.push("--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1".into());
673            // Keep cross-site frames in the page process so interception covers them.
674            args.push("--disable-site-isolation-trials".into());
675            // No UDP path around the proxy: WebRTC only over proxied routes, no QUIC.
676            args.push("--force-webrtc-ip-handling-policy=disable_non_proxied_udp".into());
677            args.push("--disable-quic".into());
678        }
679        for a in &opts.extra_args {
680            args.push(format!("--{}", a.trim_start_matches('-')).into());
681        }
682        args.push("about:blank".into());
683        let launch_timeout = opts.launch_timeout;
684        let request_timeout = opts.request_timeout;
685        let fixture_profile_dir = fixture_mode.then(|| profile_dir.clone());
686        let fixture_proxy_addr = fixture_mode
687            .then(|| proxy.as_ref().map(|proxy| proxy.addr))
688            .flatten();
689        let fixture_owner = if fixture_mode {
690            Some(FixtureLaunchOwner::new(
691                profile_guard.take().expect("fixture profile is owned"),
692                proxy.take(),
693            ))
694        } else {
695            None
696        };
697        let proc = fixture_owner
698            .as_ref()
699            .map(FixtureLaunchOwner::process_slot)
700            .unwrap_or_else(|| Arc::new(StdMutex::new(None)));
701        let spawn_owner = fixture_owner.as_ref().map(FixtureLaunchOwner::spawn_state);
702        #[cfg(windows)]
703        let job = opts.windows_job.take();
704        #[cfg(not(windows))]
705        let job = None;
706        let spawn_proc_slot = proc.clone();
707        let spawn_proc = tokio::task::spawn_blocking(move || {
708            let mut completion = SpawnCompleteGuard {
709                state: spawn_owner.clone(),
710                result: 3,
711            };
712            let spawned = if fixture_profile_dir.is_some() && windows_fixture {
713                #[cfg(windows)]
714                {
715                    args.retain(|arg| {
716                        !arg.to_string_lossy()
717                            .starts_with("--remote-debugging-port=")
718                    });
719                    args.push("--remote-debugging-pipe".into());
720                    // Chrome's browser process always starts the crashpad handler, which cannot
721                    // create its pipe in an AppContainer; the fixture runs the headless shell.
722                    crate::config::chrome_headless_shell_path(&exe).and_then(|shell| {
723                        crate::proc::spawn_chrome_fixture_windows(
724                            &shell,
725                            &args,
726                            fixture_profile_dir.as_deref().expect("fixture profile"),
727                        )
728                    })
729                }
730                #[cfg(not(windows))]
731                unreachable!("windows fixture is cfg-gated")
732            } else if let (Some(profile), Some(proxy_addr)) =
733                (fixture_profile_dir.as_deref(), fixture_proxy_addr)
734            {
735                #[cfg(target_os = "macos")]
736                {
737                    crate::proc::spawn_chrome_fixture(
738                        &exe,
739                        &args,
740                        launch_timeout,
741                        profile,
742                        proxy_addr,
743                    )
744                }
745                #[cfg(not(target_os = "macos"))]
746                {
747                    let _ = (profile, proxy_addr);
748                    Err(BrowserError::Launch(
749                        "fixture confinement is unsupported on this platform".into(),
750                    ))
751                }
752            } else {
753                crate::proc::spawn_chrome(&exe, &args, launch_timeout, job)
754            };
755            match spawned {
756                Ok(process) => {
757                    let info = (process.id(), process.ws_url.clone());
758                    *spawn_proc_slot
759                        .lock()
760                        .unwrap_or_else(|error| error.into_inner()) = Some(process);
761                    completion.result = 1;
762                    Ok(info)
763                }
764                Err(error) => {
765                    completion.result = 2;
766                    Err(error)
767                }
768            }
769        })
770        .await;
771        let spawn_info = match spawn_proc {
772            Ok(Ok(info)) => info,
773            Ok(Err(error)) => return Err(error),
774            Err(error) => {
775                if let Some(owner) = &fixture_owner {
776                    owner.state.spawn_complete.send_replace(3);
777                }
778                return Err(BrowserError::Launch(error.to_string()));
779            }
780        };
781        let pid = Some(spawn_info.0);
782        #[cfg(windows)]
783        let connect_url = if windows_fixture {
784            let deadline = Instant::now() + launch_timeout;
785            let mut process = proc.lock().unwrap_or_else(|error| error.into_inner());
786            process
787                .as_mut()
788                .ok_or_else(|| {
789                    BrowserError::Launch("Windows fixture process ownership is absent".into())
790                })?
791                .start_fixture_pipe_bridge(deadline)?
792        } else {
793            spawn_info.1
794        };
795        #[cfg(not(windows))]
796        let connect_url = spawn_info.1;
797        let config = HandlerConfig {
798            request_timeout,
799            ..HandlerConfig::default()
800        };
801        let (browser, mut handler) = Browser::connect_with_config(connect_url, config)
802            .await
803            .map_err(|e| {
804                #[cfg(windows)]
805                if windows_fixture {
806                    let diagnostics = proc
807                        .lock()
808                        .unwrap_or_else(|error| error.into_inner())
809                        .as_ref()
810                        .map(ChromeProc::fixture_diagnostics)
811                        .unwrap_or_else(|| {
812                            "windows fixture diagnostic process ownership absent".into()
813                        });
814                    return BrowserError::Launch(format!(
815                        "Windows fixture CDP connection failed: {e}; {diagnostics}"
816                    ));
817                }
818                BrowserError::Launch(e.to_string())
819            })?;
820        let (fixture_stop_status, _) = tokio::sync::watch::channel(0u8);
821        let stopping = Arc::new(AtomicBool::new(false));
822        let crashed = Arc::new(AtomicBool::new(false));
823        let (pump_proc, pump_stopping, pump_guard, pump_crashed) = (
824            proc.clone(),
825            stopping.clone(),
826            guard.clone(),
827            crashed.clone(),
828        );
829        let pump_fixture_mode = fixture_mode;
830        let pump = tokio::spawn(async move {
831            // Transient handler errors are tolerated while Chrome is alive; the
832            // stream ending (or Chrome exiting) ends the session.
833            let mut errors = 0u32;
834            while let Some(ev) = handler.next().await {
835                if ev.is_err() {
836                    errors += 1;
837                    if errors > 50
838                        || if pump_fixture_mode {
839                            chrome_has_exited(&pump_proc)
840                        } else {
841                            chrome_exit(&pump_proc).is_some()
842                        }
843                    {
844                        break;
845                    }
846                } else {
847                    errors = 0;
848                }
849            }
850            // Give the OS a moment to reap so the reason carries the exit status.
851            let mut status = None;
852            for _ in 0..25 {
853                status = if pump_fixture_mode {
854                    None
855                } else {
856                    chrome_exit(&pump_proc)
857                };
858                if (pump_fixture_mode && chrome_has_exited(&pump_proc))
859                    || status.is_some()
860                    || pump_stopping.load(Ordering::SeqCst)
861                {
862                    break;
863                }
864                tokio::time::sleep(Duration::from_millis(20)).await;
865            }
866            report_crash(&pump_guard, &pump_stopping, &pump_crashed, status, pid);
867        });
868        // The CDP stream does not always end when Chrome dies, so also watch the process.
869        let (w_proc, w_stopping, w_crashed, w_guard) = (
870            proc.clone(),
871            stopping.clone(),
872            crashed.clone(),
873            guard.clone(),
874        );
875        let watcher_fixture_mode = fixture_mode;
876        let watcher = tokio::spawn(async move {
877            loop {
878                tokio::time::sleep(Duration::from_millis(200)).await;
879                if w_stopping.load(Ordering::SeqCst) || w_crashed.load(Ordering::SeqCst) {
880                    return;
881                }
882                if watcher_fixture_mode && chrome_has_exited(&w_proc) {
883                    report_crash(&w_guard, &w_stopping, &w_crashed, None, pid);
884                    return;
885                }
886                if let Some(status) = (!watcher_fixture_mode)
887                    .then(|| chrome_exit(&w_proc))
888                    .flatten()
889                {
890                    report_crash(&w_guard, &w_stopping, &w_crashed, Some(status), pid);
891                    return;
892                }
893            }
894        });
895        let (proc, profile_guard, proxy) = match fixture_owner {
896            Some(owner) => {
897                let (proc, profile, proxy) = owner.into_parts();
898                (proc, Some(profile), proxy)
899            }
900            None => (proc, profile_guard.take(), proxy),
901        };
902        let fixture_profile_path = fixture_mode.then(|| profile_dir.clone());
903        let session = Self {
904            id,
905            browser: Mutex::new(browser),
906            pages: StdMutex::new(Vec::new()),
907            current: StdMutex::new(None),
908            page_seq: AtomicU64::new(0),
909            handler: StdMutex::new(Some(pump)),
910            watcher: StdMutex::new(Some(watcher)),
911            profile_guard: StdMutex::new(profile_guard),
912            profile_dir,
913            fixture_profile_path,
914            download_dir,
915            upload_root: opts.upload_root,
916            headless: opts.headless,
917            guard,
918            pid,
919            proc,
920            fixture_stop_status,
921            fixture_stop_failure: Arc::new(StdMutex::new(None)),
922            fixture_stop_lock: Mutex::new(()),
923            proxy,
924            stopping,
925            stopped: AtomicBool::new(false),
926            fixture_mode,
927            #[cfg(windows)]
928            fixture_backend,
929        };
930        if !fixture_mode {
931            let download_setup = session
932                .browser
933                .lock()
934                .await
935                .execute(
936                    SetDownloadBehaviorParams::builder()
937                        .behavior(SetDownloadBehaviorBehavior::Allow)
938                        .download_path(session.download_dir.to_string_lossy().to_string())
939                        .build()
940                        .map_err(BrowserError::Launch)?,
941                )
942                .await
943                .map_err(cdp);
944            if let Err(error) = download_setup {
945                session.stop(false).await;
946                return Err(BrowserError::Launch(error.to_string()));
947            }
948        }
949
950        let mode = if opts.headless { "headless" } else { "headed" };
951        session
952            .guard
953            .emit_kind(LifecycleKind::Start, format!("launched ({mode})"), |e| {
954                e.pid = pid
955            });
956        Ok(session)
957    }
958
959    pub fn id(&self) -> &str {
960        &self.id
961    }
962
963    pub(crate) async fn configure_fixture_downloads(
964        &self,
965    ) -> std::result::Result<(), FixtureError> {
966        let configured = self
967            .browser
968            .lock()
969            .await
970            .execute(
971                SetDownloadBehaviorParams::builder()
972                    .behavior(SetDownloadBehaviorBehavior::Deny)
973                    .download_path(self.download_dir.to_string_lossy().to_string())
974                    .build()
975                    .map_err(|error| FixtureError::Browser(error.to_string()))?,
976            )
977            .await
978            .map_err(|error| FixtureError::Browser(error.to_string()));
979        #[cfg(windows)]
980        if let Err(error) = configured {
981            return Err(FixtureError::Browser(format!(
982                "{error}; {}",
983                self.fixture_cdp_diagnostics()
984            )));
985        }
986        #[cfg(not(windows))]
987        configured?;
988        Ok(())
989    }
990
991    #[cfg(windows)]
992    fn fixture_cdp_diagnostics(&self) -> String {
993        self.proc
994            .lock()
995            .unwrap_or_else(|error| error.into_inner())
996            .as_ref()
997            .map(ChromeProc::fixture_diagnostics)
998            .unwrap_or_else(|| "windows fixture diagnostic process ownership absent".into())
999    }
1000    /// OS process id of the Chrome child this session owns.
1001    pub fn process_id(&self) -> Option<u32> {
1002        self.pid
1003    }
1004    /// Connections the pinning proxy made, with the address it pinned for each.
1005    pub fn pinned_connections(&self) -> Vec<PinnedConnection> {
1006        self.proxy
1007            .as_ref()
1008            .map(|p| p.log.lock().unwrap().clone())
1009            .unwrap_or_default()
1010    }
1011    pub fn is_headless(&self) -> bool {
1012        self.headless
1013    }
1014    pub fn profile_dir(&self) -> &Path {
1015        &self.profile_dir
1016    }
1017    pub fn download_dir(&self) -> &Path {
1018        &self.download_dir
1019    }
1020
1021    /// Open a new page (tab), make it current, and navigate to `url`.
1022    pub async fn new_page(&self, url: &str) -> Result<Arc<BrowserPage>> {
1023        let page = self.open_tab().await?;
1024        if url != "about:blank" {
1025            // The tab's own about:blank must have committed, or it discards this navigation.
1026            page.settle_initial_document().await;
1027            self.navigate_new_page(&page, url).await?;
1028        }
1029        Ok(page)
1030    }
1031
1032    /// Open a new page, install `setup` (request interceptor, download behaviour) before its
1033    /// first navigation, then navigate to `url`. Unlike `new_page` followed by `goto`, the
1034    /// interceptor sees the very first request: the tab's own about:blank commit is waited out
1035    /// first, and `url` is only requested once the setup is in place. `about:blank` opens a
1036    /// page with the setup installed and no navigation.
1037    pub async fn new_page_with(&self, url: &str, setup: PageSetup) -> Result<Arc<BrowserPage>> {
1038        let page = self.open_tab().await?;
1039        page.settle_initial_document().await;
1040        if let Some(hook) = setup.interceptor {
1041            page.set_request_interceptor(Some(hook)).await?;
1042        }
1043        if let Some(behavior) = setup.download {
1044            page.set_download_behavior(&behavior).await?;
1045        }
1046        if url != "about:blank" {
1047            self.navigate_new_page(&page, url).await?;
1048        }
1049        Ok(page)
1050    }
1051
1052    /// Create the tab at about:blank, register it and make it current.
1053    async fn open_tab(&self) -> Result<Arc<BrowserPage>> {
1054        let inner = self
1055            .browser
1056            .lock()
1057            .await
1058            .new_page("about:blank")
1059            .await
1060            .map_err(cdp)?;
1061        let id = format!("p{}", self.page_seq.fetch_add(1, Ordering::Relaxed) + 1);
1062        let page = Arc::new(
1063            BrowserPage::attach(
1064                id.clone(),
1065                inner,
1066                self.upload_root.clone(),
1067                self.guard.clone(),
1068                {
1069                    #[cfg(windows)]
1070                    {
1071                        matches!(self.fixture_backend, Some(FixtureBackend::WinAppcontainer))
1072                    }
1073                    #[cfg(not(windows))]
1074                    {
1075                        false
1076                    }
1077                },
1078            )
1079            .await?,
1080        );
1081        self.pages.lock().unwrap().push(page.clone());
1082        *self.current.lock().unwrap() = Some(id);
1083        Ok(page)
1084    }
1085
1086    async fn navigate_new_page(&self, page: &BrowserPage, url: &str) -> Result<()> {
1087        if let Err(error) = page.goto(url).await {
1088            // What Chrome itself said, when it said anything: a navigation that fails
1089            // inside the browser leaves no other trace on this side.
1090            return Err(match error {
1091                crate::error::BrowserError::Cdp(text) => {
1092                    let stderr = self
1093                        .proc
1094                        .lock()
1095                        .unwrap()
1096                        .as_ref()
1097                        .map(|chrome| chrome.stderr_tail.text())
1098                        .unwrap_or_default();
1099                    crate::error::BrowserError::Cdp(format!("{text}; chrome stderr: {stderr}"))
1100                }
1101                other => other,
1102            });
1103        }
1104        Ok(())
1105    }
1106
1107    pub fn pages(&self) -> Vec<Arc<BrowserPage>> {
1108        self.pages.lock().unwrap().clone()
1109    }
1110
1111    pub fn page(&self, id: &str) -> Result<Arc<BrowserPage>> {
1112        self.pages
1113            .lock()
1114            .unwrap()
1115            .iter()
1116            .find(|p| p.id() == id)
1117            .cloned()
1118            .ok_or_else(|| BrowserError::UnknownPage(id.into()))
1119    }
1120
1121    /// The page actions default to.
1122    pub fn current(&self) -> Result<Arc<BrowserPage>> {
1123        let id = self
1124            .current
1125            .lock()
1126            .unwrap()
1127            .clone()
1128            .ok_or_else(|| BrowserError::UnknownPage("<none>".into()))?;
1129        self.page(&id)
1130    }
1131
1132    /// Make `id` current and bring it to the front.
1133    pub async fn select_page(&self, id: &str) -> Result<Arc<BrowserPage>> {
1134        let p = self.page(id)?;
1135        p.bring_to_front().await?;
1136        *self.current.lock().unwrap() = Some(id.into());
1137        Ok(p)
1138    }
1139
1140    pub async fn close_page(&self, id: &str) -> Result<()> {
1141        let p = self.page(id)?;
1142        self.pages.lock().unwrap().retain(|x| x.id() != id);
1143        {
1144            let mut cur = self.current.lock().unwrap();
1145            if cur.as_deref() == Some(id) {
1146                *cur = self
1147                    .pages
1148                    .lock()
1149                    .unwrap()
1150                    .last()
1151                    .map(|p| p.id().to_string());
1152            }
1153        }
1154        p.close_inner().await
1155    }
1156
1157    /// Completed files currently in the download directory.
1158    pub fn downloads(&self) -> HashSet<PathBuf> {
1159        completed_files(&self.download_dir)
1160    }
1161
1162    /// Wait for a download not in `before` to finish (no `.crdownload`, stable size).
1163    pub async fn wait_download(
1164        &self,
1165        before: &HashSet<PathBuf>,
1166        timeout: Duration,
1167    ) -> Result<PathBuf> {
1168        let deadline = Instant::now() + timeout;
1169        loop {
1170            let now = completed_files(&self.download_dir);
1171            if let Some(p) = now.difference(before).next() {
1172                let size = std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
1173                tokio::time::sleep(Duration::from_millis(100)).await;
1174                if std::fs::metadata(p).map(|m| m.len()).unwrap_or(1) == size {
1175                    return Ok(p.clone());
1176                }
1177            }
1178            if Instant::now() >= deadline {
1179                return Err(BrowserError::Timeout("download did not complete".into()));
1180            }
1181            tokio::time::sleep(Duration::from_millis(100)).await;
1182        }
1183    }
1184
1185    /// Set a W3C permission (`geolocation`, `notifications`, `clipboard-read`,
1186    /// `midi`, ...) to granted or denied for `origin`, or every origin when `None`.
1187    pub async fn set_permission(
1188        &self,
1189        origin: Option<&str>,
1190        name: &str,
1191        granted: bool,
1192    ) -> Result<()> {
1193        let mut params = SetPermissionParams::new(
1194            PermissionDescriptor::new(name),
1195            if granted {
1196                PermissionSetting::Granted
1197            } else {
1198                PermissionSetting::Denied
1199            },
1200        );
1201        params.origin = origin.map(str::to_string);
1202        self.browser
1203            .lock()
1204            .await
1205            .execute(params)
1206            .await
1207            .map_err(cdp)?;
1208        Ok(())
1209    }
1210
1211    pub async fn reset_permissions(&self) -> Result<()> {
1212        self.browser
1213            .lock()
1214            .await
1215            .execute(ResetPermissionsParams::default())
1216            .await
1217            .map_err(cdp)?;
1218        Ok(())
1219    }
1220
1221    /// Close Chrome gracefully: CDP `Browser.close` and up to 5 s for exit, then SIGTERM to
1222    /// the process group and up to 5 s more, then SIGKILL (job termination on Windows).
1223    /// Safe to call twice. A temporary profile is deleted once Chrome has exited.
1224    pub async fn shutdown(&self) {
1225        self.stop(false).await;
1226    }
1227
1228    /// Stop the fixture browser process tree while retaining its profile until the fixture
1229    /// proxy and immutable source server have both been shut down.
1230    pub(crate) async fn stop_fixture_process(&self) -> std::result::Result<(), FixtureError> {
1231        self.stopping.store(true, Ordering::SeqCst);
1232        let mut status = self.fixture_stop_status.subscribe();
1233        let stop_result = loop {
1234            let lock = self.fixture_stop_lock.lock().await;
1235            let current = *status.borrow();
1236            match current {
1237                2 => break Ok(()),
1238                3 => {
1239                    let detail = self
1240                        .fixture_stop_failure
1241                        .lock()
1242                        .unwrap_or_else(|error| error.into_inner())
1243                        .clone()
1244                        .unwrap_or_else(|| "terminal stop worker gave no detail".into());
1245                    break Err(FixtureError::Cleanup(format!(
1246                        "browser termination previously failed without a stop receipt: {detail}"
1247                    )));
1248                }
1249                1 => {
1250                    drop(lock);
1251                    tokio::time::timeout(FIXTURE_STOP_RECEIPT_GRACE, status.changed())
1252                        .await
1253                        .map_err(|_| {
1254                            FixtureError::Cleanup(
1255                                "browser termination receipt did not arrive before deadline".into(),
1256                            )
1257                        })?
1258                        .map_err(|_| {
1259                            FixtureError::Cleanup(
1260                                "browser termination status channel closed".into(),
1261                            )
1262                        })?;
1263                }
1264                _ => {
1265                    self.fixture_stop_status.send_replace(1);
1266                    let process = self.proc.lock().unwrap().take();
1267                    let Some(mut process) = process else {
1268                        *self
1269                            .fixture_stop_failure
1270                            .lock()
1271                            .unwrap_or_else(|error| error.into_inner()) = Some(
1272                            "browser process ownership is absent without a stop receipt".into(),
1273                        );
1274                        self.fixture_stop_status.send_replace(3);
1275                        break Err(FixtureError::Cleanup(
1276                            "browser process ownership is absent without a stop receipt".into(),
1277                        ));
1278                    };
1279                    process.begin_fixture_transport_shutdown();
1280                    // This transaction owns Chrome until it publishes a terminal
1281                    // receipt. The caller can time out or cancel during terminal
1282                    // fencing without abandoning status=1 or the process handle.
1283                    let process_slot = self.proc.clone();
1284                    let status_sender = self.fixture_stop_status.clone();
1285                    let failure_slot = self.fixture_stop_failure.clone();
1286                    tokio::spawn(async move {
1287                        let mut completion = FixtureStopCompletionGuard {
1288                            status: status_sender,
1289                            complete: false,
1290                        };
1291                        let terminated = tokio::task::spawn_blocking(move || {
1292                            let result = process.terminate_fixture_tree();
1293                            (process, result)
1294                        })
1295                        .await;
1296                        let (process, result) = match terminated {
1297                            Ok(result) => result,
1298                            Err(error) => {
1299                                *failure_slot
1300                                    .lock()
1301                                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(
1302                                    format!("fixture browser termination worker failed: {error}"),
1303                                );
1304                                return;
1305                            }
1306                        };
1307                        if let Err(error) = result {
1308                            *failure_slot
1309                                .lock()
1310                                .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(format!(
1311                                "fixture browser process tree termination failed: {error}"
1312                            ));
1313                            *process_slot
1314                                .lock()
1315                                .unwrap_or_else(|error| error.into_inner()) = Some(process);
1316                            return;
1317                        }
1318                        #[cfg(windows)]
1319                        {
1320                            let mut process = process;
1321                            if let Err(error) = process
1322                                .finish_fixture_transport_shutdown(Instant::now() + GRACE)
1323                                .await
1324                            {
1325                                *failure_slot
1326                                    .lock()
1327                                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(
1328                                    format!("fixture CDP bridge finalization failed: {error}"),
1329                                );
1330                                *process_slot
1331                                    .lock()
1332                                    .unwrap_or_else(|error| error.into_inner()) = Some(process);
1333                                return;
1334                            }
1335                        }
1336                        completion.stopped();
1337                    });
1338                    drop(lock);
1339                    tokio::time::timeout(FIXTURE_STOP_RECEIPT_GRACE, status.changed())
1340                        .await
1341                        .map_err(|_| {
1342                            FixtureError::Cleanup(
1343                                "browser termination receipt did not arrive before deadline".into(),
1344                            )
1345                        })?
1346                        .map_err(|_| {
1347                            FixtureError::Cleanup(
1348                                "browser termination status channel closed".into(),
1349                            )
1350                        })?;
1351                }
1352            }
1353        };
1354        stop_result?;
1355        for page in self.pages.lock().unwrap().drain(..) {
1356            page.abort_pumps();
1357        }
1358        if let Some(handler) = self.handler.lock().unwrap().take() {
1359            handler.abort();
1360        }
1361        if let Some(watcher) = self.watcher.lock().unwrap().take() {
1362            watcher.abort();
1363        }
1364        self.emit_stopped("fixture shutdown");
1365        Ok(())
1366    }
1367
1368    pub(crate) fn process_alive(&self) -> bool {
1369        let Ok(mut process) = self.proc.lock() else {
1370            return false;
1371        };
1372        process
1373            .as_mut()
1374            .is_some_and(|process| process.has_exited().is_ok_and(|exited| !exited))
1375    }
1376
1377    pub(crate) async fn stop_fixture_proxy(&self) -> std::result::Result<(), FixtureError> {
1378        if let Some(proxy) = &self.proxy {
1379            proxy
1380                .shutdown(GRACE)
1381                .await
1382                .map_err(|error| FixtureError::Cleanup(format!("fixture proxy: {error}")))?;
1383        }
1384        Ok(())
1385    }
1386
1387    pub(crate) fn remove_fixture_profile(&self) -> std::result::Result<(), FixtureError> {
1388        let path = self.fixture_profile_path.as_ref().ok_or_else(|| {
1389            FixtureError::Cleanup("fixture browser did not own a disposable profile".into())
1390        })?;
1391        match self.profile_guard.lock().unwrap().take() {
1392            Some(ProfileGuard::Temp(dir)) => drop(dir),
1393            Some(_) => {
1394                return Err(FixtureError::Cleanup(
1395                    "fixture browser did not own a disposable profile".into(),
1396                ))
1397            }
1398            None => {}
1399        }
1400        let deadline = std::time::Instant::now() + Duration::from_secs(3);
1401        while path.exists()
1402            && std::fs::remove_dir_all(path).is_err()
1403            && std::time::Instant::now() < deadline
1404        {
1405            std::thread::sleep(Duration::from_millis(100));
1406        }
1407        if path.exists() {
1408            Err(FixtureError::Cleanup(
1409                "disposable browser profile still exists after cleanup".into(),
1410            ))
1411        } else {
1412            Ok(())
1413        }
1414    }
1415
1416    /// Cancel: kill the owned Chrome now and wait for it to exit. Helper
1417    /// processes exit with their parent; none are detached.
1418    pub async fn cancel(&self) {
1419        self.stop(true).await;
1420    }
1421
1422    async fn stop(&self, hard: bool) {
1423        self.stop_inner(hard, true).await;
1424    }
1425
1426    async fn stop_inner(&self, hard: bool, release_profile_dir: bool) {
1427        self.stopping.store(true, Ordering::SeqCst);
1428        if !hard {
1429            let graceful = async {
1430                let _ = self.browser.lock().await.close().await;
1431                let end = Instant::now() + GRACE;
1432                loop {
1433                    let done = match self.proc.lock().unwrap().as_mut() {
1434                        Some(p) => matches!(p.try_wait(), Ok(Some(_)) | Err(_)),
1435                        None => true,
1436                    };
1437                    if done || Instant::now() >= end {
1438                        break;
1439                    }
1440                    tokio::time::sleep(Duration::from_millis(20)).await;
1441                }
1442            };
1443            let _ = tokio::time::timeout(Duration::from_secs(6), graceful).await;
1444        }
1445        // Whatever is left: SIGTERM the process group with a bounded wait, SIGKILL last
1446        // (cancel kills at once). Windows: the job object takes the whole tree.
1447        let taken = self.proc.lock().unwrap().take();
1448        if let Some(mut p) = taken {
1449            let grace = if hard { Duration::ZERO } else { GRACE };
1450            let _ = tokio::task::spawn_blocking(move || p.terminate_gracefully(grace)).await;
1451        }
1452        if release_profile_dir {
1453            release_profile(self.profile_guard.lock().unwrap().take());
1454        }
1455        for p in self.pages.lock().unwrap().drain(..) {
1456            p.abort_pumps();
1457        }
1458        if let Some(h) = self.handler.lock().unwrap().take() {
1459            h.abort();
1460        }
1461        if let Some(w) = self.watcher.lock().unwrap().take() {
1462            w.abort();
1463        }
1464        let reason = if hard { "cancelled" } else { "shutdown" };
1465        self.emit_stopped(reason);
1466    }
1467
1468    fn emit_stopped(&self, reason: &str) {
1469        if !self.stopped.swap(true, Ordering::SeqCst) {
1470            let pid = self.pid;
1471            self.guard
1472                .emit_kind(LifecycleKind::Stop, reason, |e| e.pid = pid);
1473        }
1474    }
1475}
1476
1477/// Emit at most one `Crash` per session, never during an intentional stop.
1478fn report_crash(
1479    guard: &Guard,
1480    stopping: &AtomicBool,
1481    crashed: &AtomicBool,
1482    status: Option<std::process::ExitStatus>,
1483    pid: Option<u32>,
1484) {
1485    if stopping.load(Ordering::SeqCst) || crashed.swap(true, Ordering::SeqCst) {
1486        return;
1487    }
1488    let reason = match status {
1489        Some(s) => format!("chrome exited unexpectedly ({s})"),
1490        None => "devtools connection lost".to_string(),
1491    };
1492    guard.emit_kind(LifecycleKind::Crash, reason, |e| e.pid = pid);
1493}
1494
1495/// Exit status of the owned Chrome, if it has exited.
1496fn chrome_exit(proc: &StdMutex<Option<ChromeProc>>) -> Option<std::process::ExitStatus> {
1497    proc.lock()
1498        .ok()?
1499        .as_mut()
1500        .and_then(|p| p.try_wait().ok().flatten())
1501}
1502
1503/// Fixture monitoring observes exit without reaping the process-group leader; cleanup must
1504/// retain that identity until `terminate_tree_bounded` has killed every descendant.
1505fn chrome_has_exited(proc: &StdMutex<Option<ChromeProc>>) -> bool {
1506    proc.lock()
1507        .ok()
1508        .and_then(|guard| guard.as_ref().map(|p| p.has_exited()))
1509        .and_then(std::result::Result::ok)
1510        .unwrap_or(true)
1511}
1512
1513impl Drop for BrowserSession {
1514    fn drop(&mut self) {
1515        self.stopping.store(true, Ordering::SeqCst);
1516        for p in self.pages.lock().unwrap().iter() {
1517            p.abort_pumps();
1518        }
1519        if let Some(h) = self.handler.lock().unwrap().take() {
1520            h.abort();
1521        }
1522        if let Some(w) = self.watcher.lock().unwrap().take() {
1523            w.abort();
1524        }
1525        if self.fixture_mode {
1526            if let Some(mut process) = self.proc.lock().unwrap().take() {
1527                let _ = process.terminate_fixture_tree();
1528            }
1529            if let Some(ProfileGuard::Temp(profile)) = self.profile_guard.lock().unwrap().take() {
1530                let _ = profile.keep();
1531            }
1532            return;
1533        }
1534        // An abandoned session (cancelled caller, panic, early return) still closes
1535        // gracefully: SIGTERM to Chrome's process group, a bounded wait, SIGKILL last.
1536        if let Some(mut p) = self.proc.lock().unwrap().take() {
1537            let _ = p.terminate_gracefully(GRACE);
1538        }
1539        // Chrome has exited: now the temporary profile can go.
1540        release_profile(self.profile_guard.lock().unwrap().take());
1541        self.emit_stopped("dropped");
1542    }
1543}
1544
1545fn completed_files(dir: &Path) -> HashSet<PathBuf> {
1546    std::fs::read_dir(dir)
1547        .map(|rd| {
1548            rd.filter_map(|e| e.ok())
1549                .map(|e| e.path())
1550                .filter(|p| {
1551                    p.is_file()
1552                        && !p
1553                            .extension()
1554                            .is_some_and(|e| e == "crdownload" || e == "tmp")
1555                })
1556                .collect()
1557        })
1558        .unwrap_or_default()
1559}
1560
1561#[cfg(test)]
1562mod tests {
1563    use super::*;
1564
1565    #[test]
1566    fn launch_args_disable_the_component_updater() {
1567        // Chrome's component updater (clients2.google.com) runs even with background
1568        // networking off; a session must see only its pages' requests.
1569        assert!(BASE_CHROME_ARGS.contains(&"--disable-component-update"));
1570        assert!(BASE_CHROME_ARGS.contains(&"--disable-background-networking"));
1571    }
1572
1573    #[test]
1574    fn profile_dir_accepts_spaces_and_preserves_caller_directory_on_cleanup() {
1575        let temp = tempfile::tempdir().unwrap();
1576        let name = format!(".ScrapeRight profile's ΓΌ & (data) {}", "x".repeat(65));
1577        assert!(validate_profile_name(&name).is_err());
1578        let path = temp.path().join(name);
1579        std::fs::create_dir(&path).unwrap();
1580        let sentinel = path.join("Preferences");
1581        std::fs::write(&sentinel, "caller data").unwrap();
1582        let opts = LaunchOptions::default().profile_dir(&path);
1583        assert_eq!(opts.profile, ProfileSpec::Directory(path.clone()));
1584        let (guard, resolved, downloads) = prepare_profile(&opts.profile).unwrap();
1585        assert!(matches!(&guard, ProfileGuard::Existing));
1586        assert_eq!(resolved, path);
1587        assert_eq!(downloads, path.join("rightkit-downloads"));
1588        assert_eq!(std::fs::read_dir(&path).unwrap().count(), 1);
1589        // shutdown/cancel/Drop all release this same guard through Option::take.
1590        let guard = StdMutex::new(Some(guard));
1591        drop(guard.lock().unwrap().take());
1592        drop(guard.lock().unwrap().take());
1593        assert!(path.is_dir());
1594        assert_eq!(std::fs::read_to_string(sentinel).unwrap(), "caller data");
1595        assert_eq!(std::fs::read_dir(&path).unwrap().count(), 1);
1596    }
1597
1598    #[test]
1599    fn profile_dir_rejects_relative_missing_and_file_paths_without_creation() {
1600        let temp = tempfile::tempdir().unwrap();
1601        let missing = temp.path().join("missing profile");
1602        let file = temp.path().join("not a directory");
1603        std::fs::write(&file, "keep").unwrap();
1604        for (path, message) in [
1605            (PathBuf::from("relative profile"), "must be absolute"),
1606            (missing.clone(), "must exist"),
1607            (file.clone(), "not a directory"),
1608        ] {
1609            let opts = LaunchOptions::default().profile_dir(path);
1610            let err = match prepare_profile(&opts.profile) {
1611                Ok(_) => panic!("invalid profile was accepted"),
1612                Err(err) => err,
1613            };
1614            assert!(matches!(&err, BrowserError::Profile(_)));
1615            assert!(err.to_string().contains(message), "{err}");
1616        }
1617        assert!(!missing.exists());
1618        assert_eq!(std::fs::read_to_string(file).unwrap(), "keep");
1619    }
1620
1621    #[test]
1622    fn temporary_profile_still_uses_cleanup_guard() {
1623        let opts = LaunchOptions::default();
1624        assert_eq!(opts.profile, ProfileSpec::Temporary);
1625        let (guard, path, downloads) = prepare_profile(&opts.profile).unwrap();
1626        assert!(matches!(&guard, ProfileGuard::Temp(_)));
1627        assert_eq!(downloads, path.join("downloads"));
1628        assert!(path.is_dir());
1629        drop(guard);
1630        assert!(!path.exists());
1631    }
1632
1633    // APFS (macOS) rejects non-UTF-8 file names with EILSEQ; Linux filesystems accept them.
1634    #[cfg(target_os = "linux")]
1635    #[test]
1636    fn profile_dir_accepts_non_utf8_names() {
1637        use std::os::unix::ffi::OsStringExt;
1638        let temp = tempfile::tempdir().unwrap();
1639        let path = temp
1640            .path()
1641            .join(OsString::from_vec(b"profile \xff".to_vec()));
1642        std::fs::create_dir(&path).unwrap();
1643        let opts = LaunchOptions::default().profile_dir(&path);
1644        let (guard, resolved, _) = prepare_profile(&opts.profile).unwrap();
1645        assert_eq!(resolved, path);
1646        drop(guard);
1647        assert!(path.is_dir());
1648    }
1649}