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        {
514            let _ = policy;
515            return Err(FixtureError::ConfinementUnsupported(
516                "source-only browser fixtures require macOS Seatbelt confinement".into(),
517            ));
518        }
519        #[cfg(target_os = "macos")]
520        {
521            use crate::policy::{AddressClass, PolicyDecision};
522            let permitted_urls = policy.permitted_urls.clone();
523            let remaining = policy.expires_at.saturating_duration_since(Instant::now());
524            if remaining.is_zero() {
525                return Err(FixtureError::Revoked(
526                    "fixture lease expired before browser launch".into(),
527                ));
528            }
529            let opts = LaunchOptions {
530                headless: true,
531                mute_audio: true,
532                profile: ProfileSpec::Temporary,
533                chrome_path: None,
534                allow_system_chrome: false,
535                use_system_chrome_only: false,
536                extra_args: Vec::new(),
537                download_dir: None,
538                upload_root: None,
539                network: NetworkPolicy::default()
540                    .allow_class(AddressClass::Loopback)
541                    .allow_with(move |request| {
542                        if permitted_urls.contains(&request.url) {
543                            PolicyDecision::Allow
544                        } else {
545                            PolicyDecision::Deny(
546                                "fixture URL is outside the immutable bundle".into(),
547                            )
548                        }
549                    }),
550                launch_timeout: remaining,
551                request_timeout: remaining.min(Duration::from_secs(5)),
552                ..Default::default()
553            };
554            Self::launch_inner(opts, Some(policy))
555                .await
556                .map_err(|error| FixtureError::ConfinementUnavailable(error.to_string()))
557        }
558        #[cfg(windows)]
559        {
560            let remaining = policy.expires_at.saturating_duration_since(Instant::now());
561            if remaining.is_zero() {
562                return Err(FixtureError::Revoked(
563                    "fixture lease expired before browser launch".into(),
564                ));
565            }
566            // AppContainer denies all network. CDP uses inherited pipes, while
567            // Fetch fulfills immutable fixture bytes without a TCP proxy.
568            let opts = LaunchOptions {
569                headless: true,
570                mute_audio: true,
571                profile: ProfileSpec::Temporary,
572                chrome_path: None,
573                allow_system_chrome: false,
574                use_system_chrome_only: false,
575                extra_args: Vec::new(),
576                download_dir: None,
577                upload_root: None,
578                network: crate::policy::NetworkPolicy::unrestricted(),
579                launch_timeout: remaining,
580                request_timeout: remaining.min(Duration::from_secs(5)),
581                ..Default::default()
582            };
583            Self::launch_inner(opts, Some(policy))
584                .await
585                .map_err(|error| FixtureError::ConfinementUnavailable(error.to_string()))
586        }
587    }
588
589    async fn launch_inner(
590        #[cfg_attr(not(windows), allow(unused_mut))] mut opts: LaunchOptions,
591        fixture_proxy_policy: Option<FixtureProxyPolicy>,
592    ) -> Result<Self> {
593        validate_extra_args(&opts.extra_args)?;
594        let exe = resolve_executable(&opts)?;
595        // A sandbox that cannot read its own browser crashes the network service at startup;
596        // refuse that launch with the directory and the fix instead of a browser that hangs.
597        let sandboxed = !opts
598            .extra_args
599            .iter()
600            .any(|arg| arg.trim_start_matches('-') == "no-sandbox");
601        if sandboxed {
602            if let Some(missing) = crate::sandbox_access::missing_access(&exe) {
603                return Err(BrowserError::ChromeSandboxAccess {
604                    fix: crate::sandbox_access::grant_command(&missing.directory),
605                    directory: missing.directory,
606                    principals: missing.principals,
607                });
608            }
609        }
610        let (profile, profile_dir, default_dl) = prepare_profile(&opts.profile)?;
611        // A consented real-session profile confines every action to the consented domains.
612        let admission = match &opts.profile {
613            ProfileSpec::ImportedFrom { import, .. } => Some(
614                crate::real_session::scoped_admission(import, opts.admission.clone())?,
615            ),
616            _ => opts.admission.clone(),
617        };
618        let mut profile_guard = Some(profile);
619        let download_dir = opts.download_dir.clone().unwrap_or(default_dl);
620        std::fs::create_dir_all(&download_dir)?;
621
622        let id = format!("bs-{}", SESSION_SEQ.fetch_add(1, Ordering::Relaxed));
623        let guard = Arc::new(Guard {
624            session_id: id.clone(),
625            admission,
626            network: opts.network.clone(),
627            events: opts.on_event.clone(),
628            page_allowed: StdMutex::default(),
629        });
630        let fixture_mode = fixture_proxy_policy.is_some();
631        #[cfg(windows)]
632        let fixture_backend = fixture_mode.then_some(FixtureBackend::WinAppcontainer);
633        #[cfg(windows)]
634        let windows_fixture = matches!(fixture_backend, Some(FixtureBackend::WinAppcontainer));
635        #[cfg(not(windows))]
636        let windows_fixture = false;
637        let mut proxy = if let Some(policy) = fixture_proxy_policy {
638            if windows_fixture {
639                None
640            } else {
641                Some(
642                    PinProxy::start_fixture(guard.clone(), policy)
643                        .await
644                        .map_err(|error| {
645                            BrowserError::Launch(format!("fixture proxy unavailable: {error}"))
646                        })?,
647                )
648            }
649        } else if opts.network.unrestricted {
650            None
651        } else {
652            Some(PinProxy::start(guard.clone()).await?)
653        };
654
655        let mut args: Vec<OsString> = BASE_CHROME_ARGS.iter().map(OsString::from).collect();
656        args.push(crate::proc::profile_arg(&profile_dir));
657        args.push(format!("--window-size={},{}", opts.viewport.0, opts.viewport.1).into());
658        args.push(if opts.headless {
659            "--headless=new".into()
660        } else {
661            "--hide-crash-restore-bubble".into()
662        });
663        if opts.mute_audio {
664            args.push("--mute-audio".into());
665        }
666        if let Some(p) = &proxy {
667            // Every connection, loopback included, goes through the pinning proxy;
668            // Chrome itself resolves nothing but the proxy address.
669            args.push(format!("--proxy-server=http://{}", p.addr).into());
670            args.push("--proxy-bypass-list=<-loopback>".into());
671            args.push("--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1".into());
672            // Keep cross-site frames in the page process so interception covers them.
673            args.push("--disable-site-isolation-trials".into());
674            // No UDP path around the proxy: WebRTC only over proxied routes, no QUIC.
675            args.push("--force-webrtc-ip-handling-policy=disable_non_proxied_udp".into());
676            args.push("--disable-quic".into());
677        }
678        for a in &opts.extra_args {
679            args.push(format!("--{}", a.trim_start_matches('-')).into());
680        }
681        args.push("about:blank".into());
682        let launch_timeout = opts.launch_timeout;
683        let request_timeout = opts.request_timeout;
684        let fixture_profile_dir = fixture_mode.then(|| profile_dir.clone());
685        let fixture_proxy_addr = fixture_mode
686            .then(|| proxy.as_ref().map(|proxy| proxy.addr))
687            .flatten();
688        let fixture_owner = if fixture_mode {
689            Some(FixtureLaunchOwner::new(
690                profile_guard.take().expect("fixture profile is owned"),
691                proxy.take(),
692            ))
693        } else {
694            None
695        };
696        let proc = fixture_owner
697            .as_ref()
698            .map(FixtureLaunchOwner::process_slot)
699            .unwrap_or_else(|| Arc::new(StdMutex::new(None)));
700        let spawn_owner = fixture_owner.as_ref().map(FixtureLaunchOwner::spawn_state);
701        #[cfg(windows)]
702        let job = opts.windows_job.take();
703        #[cfg(not(windows))]
704        let job = None;
705        let spawn_proc_slot = proc.clone();
706        let spawn_proc = tokio::task::spawn_blocking(move || {
707            let mut completion = SpawnCompleteGuard {
708                state: spawn_owner.clone(),
709                result: 3,
710            };
711            let spawned = if fixture_profile_dir.is_some() && windows_fixture {
712                #[cfg(windows)]
713                {
714                    args.retain(|arg| {
715                        !arg.to_string_lossy()
716                            .starts_with("--remote-debugging-port=")
717                    });
718                    args.push("--remote-debugging-pipe".into());
719                    // Chrome's browser process always starts the crashpad handler, which cannot
720                    // create its pipe in an AppContainer; the fixture runs the headless shell.
721                    crate::config::chrome_headless_shell_path(&exe).and_then(|shell| {
722                        crate::proc::spawn_chrome_fixture_windows(
723                            &shell,
724                            &args,
725                            fixture_profile_dir.as_deref().expect("fixture profile"),
726                        )
727                    })
728                }
729                #[cfg(not(windows))]
730                unreachable!("windows fixture is cfg-gated")
731            } else if let (Some(profile), Some(proxy_addr)) =
732                (fixture_profile_dir.as_deref(), fixture_proxy_addr)
733            {
734                #[cfg(target_os = "macos")]
735                {
736                    crate::proc::spawn_chrome_fixture(
737                        &exe,
738                        &args,
739                        launch_timeout,
740                        profile,
741                        proxy_addr,
742                    )
743                }
744                #[cfg(not(target_os = "macos"))]
745                {
746                    let _ = (profile, proxy_addr);
747                    Err(BrowserError::Launch(
748                        "fixture confinement is unsupported on this platform".into(),
749                    ))
750                }
751            } else {
752                crate::proc::spawn_chrome(&exe, &args, launch_timeout, job)
753            };
754            match spawned {
755                Ok(process) => {
756                    let info = (process.id(), process.ws_url.clone());
757                    *spawn_proc_slot
758                        .lock()
759                        .unwrap_or_else(|error| error.into_inner()) = Some(process);
760                    completion.result = 1;
761                    Ok(info)
762                }
763                Err(error) => {
764                    completion.result = 2;
765                    Err(error)
766                }
767            }
768        })
769        .await;
770        let spawn_info = match spawn_proc {
771            Ok(Ok(info)) => info,
772            Ok(Err(error)) => return Err(error),
773            Err(error) => {
774                if let Some(owner) = &fixture_owner {
775                    owner.state.spawn_complete.send_replace(3);
776                }
777                return Err(BrowserError::Launch(error.to_string()));
778            }
779        };
780        let pid = Some(spawn_info.0);
781        #[cfg(windows)]
782        let connect_url = if windows_fixture {
783            let deadline = Instant::now() + launch_timeout;
784            let mut process = proc.lock().unwrap_or_else(|error| error.into_inner());
785            process
786                .as_mut()
787                .ok_or_else(|| {
788                    BrowserError::Launch("Windows fixture process ownership is absent".into())
789                })?
790                .start_fixture_pipe_bridge(deadline)?
791        } else {
792            spawn_info.1
793        };
794        #[cfg(not(windows))]
795        let connect_url = spawn_info.1;
796        let config = HandlerConfig {
797            request_timeout,
798            ..HandlerConfig::default()
799        };
800        let (browser, mut handler) = Browser::connect_with_config(connect_url, config)
801            .await
802            .map_err(|e| {
803                #[cfg(windows)]
804                if windows_fixture {
805                    let diagnostics = proc
806                        .lock()
807                        .unwrap_or_else(|error| error.into_inner())
808                        .as_ref()
809                        .map(ChromeProc::fixture_diagnostics)
810                        .unwrap_or_else(|| {
811                            "windows fixture diagnostic process ownership absent".into()
812                        });
813                    return BrowserError::Launch(format!(
814                        "Windows fixture CDP connection failed: {e}; {diagnostics}"
815                    ));
816                }
817                BrowserError::Launch(e.to_string())
818            })?;
819        let (fixture_stop_status, _) = tokio::sync::watch::channel(0u8);
820        let stopping = Arc::new(AtomicBool::new(false));
821        let crashed = Arc::new(AtomicBool::new(false));
822        let (pump_proc, pump_stopping, pump_guard, pump_crashed) = (
823            proc.clone(),
824            stopping.clone(),
825            guard.clone(),
826            crashed.clone(),
827        );
828        let pump_fixture_mode = fixture_mode;
829        let pump = tokio::spawn(async move {
830            // Transient handler errors are tolerated while Chrome is alive; the
831            // stream ending (or Chrome exiting) ends the session.
832            let mut errors = 0u32;
833            while let Some(ev) = handler.next().await {
834                if ev.is_err() {
835                    errors += 1;
836                    if errors > 50
837                        || if pump_fixture_mode {
838                            chrome_has_exited(&pump_proc)
839                        } else {
840                            chrome_exit(&pump_proc).is_some()
841                        }
842                    {
843                        break;
844                    }
845                } else {
846                    errors = 0;
847                }
848            }
849            // Give the OS a moment to reap so the reason carries the exit status.
850            let mut status = None;
851            for _ in 0..25 {
852                status = if pump_fixture_mode {
853                    None
854                } else {
855                    chrome_exit(&pump_proc)
856                };
857                if (pump_fixture_mode && chrome_has_exited(&pump_proc))
858                    || status.is_some()
859                    || pump_stopping.load(Ordering::SeqCst)
860                {
861                    break;
862                }
863                tokio::time::sleep(Duration::from_millis(20)).await;
864            }
865            report_crash(&pump_guard, &pump_stopping, &pump_crashed, status, pid);
866        });
867        // The CDP stream does not always end when Chrome dies, so also watch the process.
868        let (w_proc, w_stopping, w_crashed, w_guard) = (
869            proc.clone(),
870            stopping.clone(),
871            crashed.clone(),
872            guard.clone(),
873        );
874        let watcher_fixture_mode = fixture_mode;
875        let watcher = tokio::spawn(async move {
876            loop {
877                tokio::time::sleep(Duration::from_millis(200)).await;
878                if w_stopping.load(Ordering::SeqCst) || w_crashed.load(Ordering::SeqCst) {
879                    return;
880                }
881                if watcher_fixture_mode && chrome_has_exited(&w_proc) {
882                    report_crash(&w_guard, &w_stopping, &w_crashed, None, pid);
883                    return;
884                }
885                if let Some(status) = (!watcher_fixture_mode)
886                    .then(|| chrome_exit(&w_proc))
887                    .flatten()
888                {
889                    report_crash(&w_guard, &w_stopping, &w_crashed, Some(status), pid);
890                    return;
891                }
892            }
893        });
894        let (proc, profile_guard, proxy) = match fixture_owner {
895            Some(owner) => {
896                let (proc, profile, proxy) = owner.into_parts();
897                (proc, Some(profile), proxy)
898            }
899            None => (proc, profile_guard.take(), proxy),
900        };
901        let fixture_profile_path = fixture_mode.then(|| profile_dir.clone());
902        let session = Self {
903            id,
904            browser: Mutex::new(browser),
905            pages: StdMutex::new(Vec::new()),
906            current: StdMutex::new(None),
907            page_seq: AtomicU64::new(0),
908            handler: StdMutex::new(Some(pump)),
909            watcher: StdMutex::new(Some(watcher)),
910            profile_guard: StdMutex::new(profile_guard),
911            profile_dir,
912            fixture_profile_path,
913            download_dir,
914            upload_root: opts.upload_root,
915            headless: opts.headless,
916            guard,
917            pid,
918            proc,
919            fixture_stop_status,
920            fixture_stop_failure: Arc::new(StdMutex::new(None)),
921            fixture_stop_lock: Mutex::new(()),
922            proxy,
923            stopping,
924            stopped: AtomicBool::new(false),
925            fixture_mode,
926            #[cfg(windows)]
927            fixture_backend,
928        };
929        if !fixture_mode {
930            let download_setup = session
931                .browser
932                .lock()
933                .await
934                .execute(
935                    SetDownloadBehaviorParams::builder()
936                        .behavior(SetDownloadBehaviorBehavior::Allow)
937                        .download_path(session.download_dir.to_string_lossy().to_string())
938                        .build()
939                        .map_err(BrowserError::Launch)?,
940                )
941                .await
942                .map_err(cdp);
943            if let Err(error) = download_setup {
944                session.stop(false).await;
945                return Err(BrowserError::Launch(error.to_string()));
946            }
947        }
948
949        let mode = if opts.headless { "headless" } else { "headed" };
950        session
951            .guard
952            .emit_kind(LifecycleKind::Start, format!("launched ({mode})"), |e| {
953                e.pid = pid
954            });
955        Ok(session)
956    }
957
958    pub fn id(&self) -> &str {
959        &self.id
960    }
961
962    pub(crate) async fn configure_fixture_downloads(
963        &self,
964    ) -> std::result::Result<(), FixtureError> {
965        let configured = self
966            .browser
967            .lock()
968            .await
969            .execute(
970                SetDownloadBehaviorParams::builder()
971                    .behavior(SetDownloadBehaviorBehavior::Deny)
972                    .download_path(self.download_dir.to_string_lossy().to_string())
973                    .build()
974                    .map_err(|error| FixtureError::Browser(error.to_string()))?,
975            )
976            .await
977            .map_err(|error| FixtureError::Browser(error.to_string()));
978        #[cfg(windows)]
979        if let Err(error) = configured {
980            return Err(FixtureError::Browser(format!(
981                "{error}; {}",
982                self.fixture_cdp_diagnostics()
983            )));
984        }
985        #[cfg(not(windows))]
986        configured?;
987        Ok(())
988    }
989
990    #[cfg(windows)]
991    fn fixture_cdp_diagnostics(&self) -> String {
992        self.proc
993            .lock()
994            .unwrap_or_else(|error| error.into_inner())
995            .as_ref()
996            .map(ChromeProc::fixture_diagnostics)
997            .unwrap_or_else(|| "windows fixture diagnostic process ownership absent".into())
998    }
999    /// OS process id of the Chrome child this session owns.
1000    pub fn process_id(&self) -> Option<u32> {
1001        self.pid
1002    }
1003    /// Connections the pinning proxy made, with the address it pinned for each.
1004    pub fn pinned_connections(&self) -> Vec<PinnedConnection> {
1005        self.proxy
1006            .as_ref()
1007            .map(|p| p.log.lock().unwrap().clone())
1008            .unwrap_or_default()
1009    }
1010    pub fn is_headless(&self) -> bool {
1011        self.headless
1012    }
1013    pub fn profile_dir(&self) -> &Path {
1014        &self.profile_dir
1015    }
1016    pub fn download_dir(&self) -> &Path {
1017        &self.download_dir
1018    }
1019
1020    /// Open a new page (tab), make it current, and navigate to `url`.
1021    pub async fn new_page(&self, url: &str) -> Result<Arc<BrowserPage>> {
1022        let page = self.open_tab().await?;
1023        if url != "about:blank" {
1024            // The tab's own about:blank must have committed, or it discards this navigation.
1025            page.settle_initial_document().await;
1026            self.navigate_new_page(&page, url).await?;
1027        }
1028        Ok(page)
1029    }
1030
1031    /// Open a new page, install `setup` (request interceptor, download behaviour) before its
1032    /// first navigation, then navigate to `url`. Unlike `new_page` followed by `goto`, the
1033    /// interceptor sees the very first request: the tab's own about:blank commit is waited out
1034    /// first, and `url` is only requested once the setup is in place. `about:blank` opens a
1035    /// page with the setup installed and no navigation.
1036    pub async fn new_page_with(&self, url: &str, setup: PageSetup) -> Result<Arc<BrowserPage>> {
1037        let page = self.open_tab().await?;
1038        page.settle_initial_document().await;
1039        if let Some(hook) = setup.interceptor {
1040            page.set_request_interceptor(Some(hook)).await?;
1041        }
1042        if let Some(behavior) = setup.download {
1043            page.set_download_behavior(&behavior).await?;
1044        }
1045        if url != "about:blank" {
1046            self.navigate_new_page(&page, url).await?;
1047        }
1048        Ok(page)
1049    }
1050
1051    /// Create the tab at about:blank, register it and make it current.
1052    async fn open_tab(&self) -> Result<Arc<BrowserPage>> {
1053        let inner = self
1054            .browser
1055            .lock()
1056            .await
1057            .new_page("about:blank")
1058            .await
1059            .map_err(cdp)?;
1060        let id = format!("p{}", self.page_seq.fetch_add(1, Ordering::Relaxed) + 1);
1061        let page = Arc::new(
1062            BrowserPage::attach(
1063                id.clone(),
1064                inner,
1065                self.upload_root.clone(),
1066                self.guard.clone(),
1067                {
1068                    #[cfg(windows)]
1069                    {
1070                        matches!(self.fixture_backend, Some(FixtureBackend::WinAppcontainer))
1071                    }
1072                    #[cfg(not(windows))]
1073                    {
1074                        false
1075                    }
1076                },
1077            )
1078            .await?,
1079        );
1080        self.pages.lock().unwrap().push(page.clone());
1081        *self.current.lock().unwrap() = Some(id);
1082        Ok(page)
1083    }
1084
1085    async fn navigate_new_page(&self, page: &BrowserPage, url: &str) -> Result<()> {
1086        if let Err(error) = page.goto(url).await {
1087            // What Chrome itself said, when it said anything: a navigation that fails
1088            // inside the browser leaves no other trace on this side.
1089            return Err(match error {
1090                crate::error::BrowserError::Cdp(text) => {
1091                    let stderr = self
1092                        .proc
1093                        .lock()
1094                        .unwrap()
1095                        .as_ref()
1096                        .map(|chrome| chrome.stderr_tail.text())
1097                        .unwrap_or_default();
1098                    crate::error::BrowserError::Cdp(format!("{text}; chrome stderr: {stderr}"))
1099                }
1100                other => other,
1101            });
1102        }
1103        Ok(())
1104    }
1105
1106    pub fn pages(&self) -> Vec<Arc<BrowserPage>> {
1107        self.pages.lock().unwrap().clone()
1108    }
1109
1110    pub fn page(&self, id: &str) -> Result<Arc<BrowserPage>> {
1111        self.pages
1112            .lock()
1113            .unwrap()
1114            .iter()
1115            .find(|p| p.id() == id)
1116            .cloned()
1117            .ok_or_else(|| BrowserError::UnknownPage(id.into()))
1118    }
1119
1120    /// The page actions default to.
1121    pub fn current(&self) -> Result<Arc<BrowserPage>> {
1122        let id = self
1123            .current
1124            .lock()
1125            .unwrap()
1126            .clone()
1127            .ok_or_else(|| BrowserError::UnknownPage("<none>".into()))?;
1128        self.page(&id)
1129    }
1130
1131    /// Make `id` current and bring it to the front.
1132    pub async fn select_page(&self, id: &str) -> Result<Arc<BrowserPage>> {
1133        let p = self.page(id)?;
1134        p.bring_to_front().await?;
1135        *self.current.lock().unwrap() = Some(id.into());
1136        Ok(p)
1137    }
1138
1139    pub async fn close_page(&self, id: &str) -> Result<()> {
1140        let p = self.page(id)?;
1141        self.pages.lock().unwrap().retain(|x| x.id() != id);
1142        {
1143            let mut cur = self.current.lock().unwrap();
1144            if cur.as_deref() == Some(id) {
1145                *cur = self
1146                    .pages
1147                    .lock()
1148                    .unwrap()
1149                    .last()
1150                    .map(|p| p.id().to_string());
1151            }
1152        }
1153        p.close_inner().await
1154    }
1155
1156    /// Completed files currently in the download directory.
1157    pub fn downloads(&self) -> HashSet<PathBuf> {
1158        completed_files(&self.download_dir)
1159    }
1160
1161    /// Wait for a download not in `before` to finish (no `.crdownload`, stable size).
1162    pub async fn wait_download(
1163        &self,
1164        before: &HashSet<PathBuf>,
1165        timeout: Duration,
1166    ) -> Result<PathBuf> {
1167        let deadline = Instant::now() + timeout;
1168        loop {
1169            let now = completed_files(&self.download_dir);
1170            if let Some(p) = now.difference(before).next() {
1171                let size = std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
1172                tokio::time::sleep(Duration::from_millis(100)).await;
1173                if std::fs::metadata(p).map(|m| m.len()).unwrap_or(1) == size {
1174                    return Ok(p.clone());
1175                }
1176            }
1177            if Instant::now() >= deadline {
1178                return Err(BrowserError::Timeout("download did not complete".into()));
1179            }
1180            tokio::time::sleep(Duration::from_millis(100)).await;
1181        }
1182    }
1183
1184    /// Set a W3C permission (`geolocation`, `notifications`, `clipboard-read`,
1185    /// `midi`, ...) to granted or denied for `origin`, or every origin when `None`.
1186    pub async fn set_permission(
1187        &self,
1188        origin: Option<&str>,
1189        name: &str,
1190        granted: bool,
1191    ) -> Result<()> {
1192        let mut params = SetPermissionParams::new(
1193            PermissionDescriptor::new(name),
1194            if granted {
1195                PermissionSetting::Granted
1196            } else {
1197                PermissionSetting::Denied
1198            },
1199        );
1200        params.origin = origin.map(str::to_string);
1201        self.browser
1202            .lock()
1203            .await
1204            .execute(params)
1205            .await
1206            .map_err(cdp)?;
1207        Ok(())
1208    }
1209
1210    pub async fn reset_permissions(&self) -> Result<()> {
1211        self.browser
1212            .lock()
1213            .await
1214            .execute(ResetPermissionsParams::default())
1215            .await
1216            .map_err(cdp)?;
1217        Ok(())
1218    }
1219
1220    /// Close Chrome gracefully: CDP `Browser.close` and up to 5 s for exit, then SIGTERM to
1221    /// the process group and up to 5 s more, then SIGKILL (job termination on Windows).
1222    /// Safe to call twice. A temporary profile is deleted once Chrome has exited.
1223    pub async fn shutdown(&self) {
1224        self.stop(false).await;
1225    }
1226
1227    /// Stop the fixture browser process tree while retaining its profile until the fixture
1228    /// proxy and immutable source server have both been shut down.
1229    pub(crate) async fn stop_fixture_process(&self) -> std::result::Result<(), FixtureError> {
1230        self.stopping.store(true, Ordering::SeqCst);
1231        let mut status = self.fixture_stop_status.subscribe();
1232        let stop_result = loop {
1233            let lock = self.fixture_stop_lock.lock().await;
1234            let current = *status.borrow();
1235            match current {
1236                2 => break Ok(()),
1237                3 => {
1238                    let detail = self
1239                        .fixture_stop_failure
1240                        .lock()
1241                        .unwrap_or_else(|error| error.into_inner())
1242                        .clone()
1243                        .unwrap_or_else(|| "terminal stop worker gave no detail".into());
1244                    break Err(FixtureError::Cleanup(format!(
1245                        "browser termination previously failed without a stop receipt: {detail}"
1246                    )));
1247                }
1248                1 => {
1249                    drop(lock);
1250                    tokio::time::timeout(FIXTURE_STOP_RECEIPT_GRACE, status.changed())
1251                        .await
1252                        .map_err(|_| {
1253                            FixtureError::Cleanup(
1254                                "browser termination receipt did not arrive before deadline".into(),
1255                            )
1256                        })?
1257                        .map_err(|_| {
1258                            FixtureError::Cleanup(
1259                                "browser termination status channel closed".into(),
1260                            )
1261                        })?;
1262                }
1263                _ => {
1264                    self.fixture_stop_status.send_replace(1);
1265                    let process = self.proc.lock().unwrap().take();
1266                    let Some(mut process) = process else {
1267                        *self
1268                            .fixture_stop_failure
1269                            .lock()
1270                            .unwrap_or_else(|error| error.into_inner()) = Some(
1271                            "browser process ownership is absent without a stop receipt".into(),
1272                        );
1273                        self.fixture_stop_status.send_replace(3);
1274                        break Err(FixtureError::Cleanup(
1275                            "browser process ownership is absent without a stop receipt".into(),
1276                        ));
1277                    };
1278                    process.begin_fixture_transport_shutdown();
1279                    // This transaction owns Chrome until it publishes a terminal
1280                    // receipt. The caller can time out or cancel during terminal
1281                    // fencing without abandoning status=1 or the process handle.
1282                    let process_slot = self.proc.clone();
1283                    let status_sender = self.fixture_stop_status.clone();
1284                    let failure_slot = self.fixture_stop_failure.clone();
1285                    tokio::spawn(async move {
1286                        let mut completion = FixtureStopCompletionGuard {
1287                            status: status_sender,
1288                            complete: false,
1289                        };
1290                        let terminated = tokio::task::spawn_blocking(move || {
1291                            let result = process.terminate_fixture_tree();
1292                            (process, result)
1293                        })
1294                        .await;
1295                        let (process, result) = match terminated {
1296                            Ok(result) => result,
1297                            Err(error) => {
1298                                *failure_slot
1299                                    .lock()
1300                                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(
1301                                    format!("fixture browser termination worker failed: {error}"),
1302                                );
1303                                return;
1304                            }
1305                        };
1306                        if let Err(error) = result {
1307                            *failure_slot
1308                                .lock()
1309                                .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(format!(
1310                                "fixture browser process tree termination failed: {error}"
1311                            ));
1312                            *process_slot
1313                                .lock()
1314                                .unwrap_or_else(|error| error.into_inner()) = Some(process);
1315                            return;
1316                        }
1317                        #[cfg(windows)]
1318                        {
1319                            let mut process = process;
1320                            if let Err(error) = process
1321                                .finish_fixture_transport_shutdown(Instant::now() + GRACE)
1322                                .await
1323                            {
1324                                *failure_slot
1325                                    .lock()
1326                                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(
1327                                    format!("fixture CDP bridge finalization failed: {error}"),
1328                                );
1329                                *process_slot
1330                                    .lock()
1331                                    .unwrap_or_else(|error| error.into_inner()) = Some(process);
1332                                return;
1333                            }
1334                        }
1335                        completion.stopped();
1336                    });
1337                    drop(lock);
1338                    tokio::time::timeout(FIXTURE_STOP_RECEIPT_GRACE, status.changed())
1339                        .await
1340                        .map_err(|_| {
1341                            FixtureError::Cleanup(
1342                                "browser termination receipt did not arrive before deadline".into(),
1343                            )
1344                        })?
1345                        .map_err(|_| {
1346                            FixtureError::Cleanup(
1347                                "browser termination status channel closed".into(),
1348                            )
1349                        })?;
1350                }
1351            }
1352        };
1353        stop_result?;
1354        for page in self.pages.lock().unwrap().drain(..) {
1355            page.abort_pumps();
1356        }
1357        if let Some(handler) = self.handler.lock().unwrap().take() {
1358            handler.abort();
1359        }
1360        if let Some(watcher) = self.watcher.lock().unwrap().take() {
1361            watcher.abort();
1362        }
1363        self.emit_stopped("fixture shutdown");
1364        Ok(())
1365    }
1366
1367    pub(crate) fn process_alive(&self) -> bool {
1368        let Ok(mut process) = self.proc.lock() else {
1369            return false;
1370        };
1371        process
1372            .as_mut()
1373            .is_some_and(|process| process.has_exited().is_ok_and(|exited| !exited))
1374    }
1375
1376    pub(crate) async fn stop_fixture_proxy(&self) -> std::result::Result<(), FixtureError> {
1377        if let Some(proxy) = &self.proxy {
1378            proxy
1379                .shutdown(GRACE)
1380                .await
1381                .map_err(|error| FixtureError::Cleanup(format!("fixture proxy: {error}")))?;
1382        }
1383        Ok(())
1384    }
1385
1386    pub(crate) fn remove_fixture_profile(&self) -> std::result::Result<(), FixtureError> {
1387        let path = self.fixture_profile_path.as_ref().ok_or_else(|| {
1388            FixtureError::Cleanup("fixture browser did not own a disposable profile".into())
1389        })?;
1390        match self.profile_guard.lock().unwrap().take() {
1391            Some(ProfileGuard::Temp(dir)) => drop(dir),
1392            Some(_) => {
1393                return Err(FixtureError::Cleanup(
1394                    "fixture browser did not own a disposable profile".into(),
1395                ))
1396            }
1397            None => {}
1398        }
1399        let deadline = std::time::Instant::now() + Duration::from_secs(3);
1400        while path.exists()
1401            && std::fs::remove_dir_all(path).is_err()
1402            && std::time::Instant::now() < deadline
1403        {
1404            std::thread::sleep(Duration::from_millis(100));
1405        }
1406        if path.exists() {
1407            Err(FixtureError::Cleanup(
1408                "disposable browser profile still exists after cleanup".into(),
1409            ))
1410        } else {
1411            Ok(())
1412        }
1413    }
1414
1415    /// Cancel: kill the owned Chrome now and wait for it to exit. Helper
1416    /// processes exit with their parent; none are detached.
1417    pub async fn cancel(&self) {
1418        self.stop(true).await;
1419    }
1420
1421    async fn stop(&self, hard: bool) {
1422        self.stop_inner(hard, true).await;
1423    }
1424
1425    async fn stop_inner(&self, hard: bool, release_profile_dir: bool) {
1426        self.stopping.store(true, Ordering::SeqCst);
1427        if !hard {
1428            let graceful = async {
1429                let _ = self.browser.lock().await.close().await;
1430                let end = Instant::now() + GRACE;
1431                loop {
1432                    let done = match self.proc.lock().unwrap().as_mut() {
1433                        Some(p) => matches!(p.try_wait(), Ok(Some(_)) | Err(_)),
1434                        None => true,
1435                    };
1436                    if done || Instant::now() >= end {
1437                        break;
1438                    }
1439                    tokio::time::sleep(Duration::from_millis(20)).await;
1440                }
1441            };
1442            let _ = tokio::time::timeout(Duration::from_secs(6), graceful).await;
1443        }
1444        // Whatever is left: SIGTERM the process group with a bounded wait, SIGKILL last
1445        // (cancel kills at once). Windows: the job object takes the whole tree.
1446        let taken = self.proc.lock().unwrap().take();
1447        if let Some(mut p) = taken {
1448            let grace = if hard { Duration::ZERO } else { GRACE };
1449            let _ = tokio::task::spawn_blocking(move || p.terminate_gracefully(grace)).await;
1450        }
1451        if release_profile_dir {
1452            release_profile(self.profile_guard.lock().unwrap().take());
1453        }
1454        for p in self.pages.lock().unwrap().drain(..) {
1455            p.abort_pumps();
1456        }
1457        if let Some(h) = self.handler.lock().unwrap().take() {
1458            h.abort();
1459        }
1460        if let Some(w) = self.watcher.lock().unwrap().take() {
1461            w.abort();
1462        }
1463        let reason = if hard { "cancelled" } else { "shutdown" };
1464        self.emit_stopped(reason);
1465    }
1466
1467    fn emit_stopped(&self, reason: &str) {
1468        if !self.stopped.swap(true, Ordering::SeqCst) {
1469            let pid = self.pid;
1470            self.guard
1471                .emit_kind(LifecycleKind::Stop, reason, |e| e.pid = pid);
1472        }
1473    }
1474}
1475
1476/// Emit at most one `Crash` per session, never during an intentional stop.
1477fn report_crash(
1478    guard: &Guard,
1479    stopping: &AtomicBool,
1480    crashed: &AtomicBool,
1481    status: Option<std::process::ExitStatus>,
1482    pid: Option<u32>,
1483) {
1484    if stopping.load(Ordering::SeqCst) || crashed.swap(true, Ordering::SeqCst) {
1485        return;
1486    }
1487    let reason = match status {
1488        Some(s) => format!("chrome exited unexpectedly ({s})"),
1489        None => "devtools connection lost".to_string(),
1490    };
1491    guard.emit_kind(LifecycleKind::Crash, reason, |e| e.pid = pid);
1492}
1493
1494/// Exit status of the owned Chrome, if it has exited.
1495fn chrome_exit(proc: &StdMutex<Option<ChromeProc>>) -> Option<std::process::ExitStatus> {
1496    proc.lock()
1497        .ok()?
1498        .as_mut()
1499        .and_then(|p| p.try_wait().ok().flatten())
1500}
1501
1502/// Fixture monitoring observes exit without reaping the process-group leader; cleanup must
1503/// retain that identity until `terminate_tree_bounded` has killed every descendant.
1504fn chrome_has_exited(proc: &StdMutex<Option<ChromeProc>>) -> bool {
1505    proc.lock()
1506        .ok()
1507        .and_then(|guard| guard.as_ref().map(|p| p.has_exited()))
1508        .and_then(std::result::Result::ok)
1509        .unwrap_or(true)
1510}
1511
1512impl Drop for BrowserSession {
1513    fn drop(&mut self) {
1514        self.stopping.store(true, Ordering::SeqCst);
1515        for p in self.pages.lock().unwrap().iter() {
1516            p.abort_pumps();
1517        }
1518        if let Some(h) = self.handler.lock().unwrap().take() {
1519            h.abort();
1520        }
1521        if let Some(w) = self.watcher.lock().unwrap().take() {
1522            w.abort();
1523        }
1524        if self.fixture_mode {
1525            if let Some(mut process) = self.proc.lock().unwrap().take() {
1526                let _ = process.terminate_fixture_tree();
1527            }
1528            if let Some(ProfileGuard::Temp(profile)) = self.profile_guard.lock().unwrap().take() {
1529                let _ = profile.keep();
1530            }
1531            return;
1532        }
1533        // An abandoned session (cancelled caller, panic, early return) still closes
1534        // gracefully: SIGTERM to Chrome's process group, a bounded wait, SIGKILL last.
1535        if let Some(mut p) = self.proc.lock().unwrap().take() {
1536            let _ = p.terminate_gracefully(GRACE);
1537        }
1538        // Chrome has exited: now the temporary profile can go.
1539        release_profile(self.profile_guard.lock().unwrap().take());
1540        self.emit_stopped("dropped");
1541    }
1542}
1543
1544fn completed_files(dir: &Path) -> HashSet<PathBuf> {
1545    std::fs::read_dir(dir)
1546        .map(|rd| {
1547            rd.filter_map(|e| e.ok())
1548                .map(|e| e.path())
1549                .filter(|p| {
1550                    p.is_file()
1551                        && !p
1552                            .extension()
1553                            .is_some_and(|e| e == "crdownload" || e == "tmp")
1554                })
1555                .collect()
1556        })
1557        .unwrap_or_default()
1558}
1559
1560#[cfg(test)]
1561mod tests {
1562    use super::*;
1563
1564    #[test]
1565    fn launch_args_disable_the_component_updater() {
1566        // Chrome's component updater (clients2.google.com) runs even with background
1567        // networking off; a session must see only its pages' requests.
1568        assert!(BASE_CHROME_ARGS.contains(&"--disable-component-update"));
1569        assert!(BASE_CHROME_ARGS.contains(&"--disable-background-networking"));
1570    }
1571
1572    #[test]
1573    fn profile_dir_accepts_spaces_and_preserves_caller_directory_on_cleanup() {
1574        let temp = tempfile::tempdir().unwrap();
1575        let name = format!(".ScrapeRight profile's ΓΌ & (data) {}", "x".repeat(65));
1576        assert!(validate_profile_name(&name).is_err());
1577        let path = temp.path().join(name);
1578        std::fs::create_dir(&path).unwrap();
1579        let sentinel = path.join("Preferences");
1580        std::fs::write(&sentinel, "caller data").unwrap();
1581        let opts = LaunchOptions::default().profile_dir(&path);
1582        assert_eq!(opts.profile, ProfileSpec::Directory(path.clone()));
1583        let (guard, resolved, downloads) = prepare_profile(&opts.profile).unwrap();
1584        assert!(matches!(&guard, ProfileGuard::Existing));
1585        assert_eq!(resolved, path);
1586        assert_eq!(downloads, path.join("rightkit-downloads"));
1587        assert_eq!(std::fs::read_dir(&path).unwrap().count(), 1);
1588        // shutdown/cancel/Drop all release this same guard through Option::take.
1589        let guard = StdMutex::new(Some(guard));
1590        drop(guard.lock().unwrap().take());
1591        drop(guard.lock().unwrap().take());
1592        assert!(path.is_dir());
1593        assert_eq!(std::fs::read_to_string(sentinel).unwrap(), "caller data");
1594        assert_eq!(std::fs::read_dir(&path).unwrap().count(), 1);
1595    }
1596
1597    #[test]
1598    fn profile_dir_rejects_relative_missing_and_file_paths_without_creation() {
1599        let temp = tempfile::tempdir().unwrap();
1600        let missing = temp.path().join("missing profile");
1601        let file = temp.path().join("not a directory");
1602        std::fs::write(&file, "keep").unwrap();
1603        for (path, message) in [
1604            (PathBuf::from("relative profile"), "must be absolute"),
1605            (missing.clone(), "must exist"),
1606            (file.clone(), "not a directory"),
1607        ] {
1608            let opts = LaunchOptions::default().profile_dir(path);
1609            let err = match prepare_profile(&opts.profile) {
1610                Ok(_) => panic!("invalid profile was accepted"),
1611                Err(err) => err,
1612            };
1613            assert!(matches!(&err, BrowserError::Profile(_)));
1614            assert!(err.to_string().contains(message), "{err}");
1615        }
1616        assert!(!missing.exists());
1617        assert_eq!(std::fs::read_to_string(file).unwrap(), "keep");
1618    }
1619
1620    #[test]
1621    fn temporary_profile_still_uses_cleanup_guard() {
1622        let opts = LaunchOptions::default();
1623        assert_eq!(opts.profile, ProfileSpec::Temporary);
1624        let (guard, path, downloads) = prepare_profile(&opts.profile).unwrap();
1625        assert!(matches!(&guard, ProfileGuard::Temp(_)));
1626        assert_eq!(downloads, path.join("downloads"));
1627        assert!(path.is_dir());
1628        drop(guard);
1629        assert!(!path.exists());
1630    }
1631
1632    // APFS (macOS) rejects non-UTF-8 file names with EILSEQ; Linux filesystems accept them.
1633    #[cfg(target_os = "linux")]
1634    #[test]
1635    fn profile_dir_accepts_non_utf8_names() {
1636        use std::os::unix::ffi::OsStringExt;
1637        let temp = tempfile::tempdir().unwrap();
1638        let path = temp
1639            .path()
1640            .join(OsString::from_vec(b"profile \xff".to_vec()));
1641        std::fs::create_dir(&path).unwrap();
1642        let opts = LaunchOptions::default().profile_dir(&path);
1643        let (guard, resolved, _) = prepare_profile(&opts.profile).unwrap();
1644        assert_eq!(resolved, path);
1645        drop(guard);
1646        assert!(path.is_dir());
1647    }
1648}