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