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