rightkit-browser 0.3.12

Shared Chrome DevTools Protocol browser runtime for Right Suite: multi-page sessions, named profiles, real CDP input, observations with stale-ref checks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! Installer-time and updater-time delivery of Chrome for Testing to ONE fixed path
//! (cargo feature `install`).
//!
//! [`ensure_chrome_for_testing`] puts a pinned, digest-checked Chrome for Testing at
//! `<managed root>/current`, keeps exactly one rollback copy at `current.previous`, and
//! extracts into `current.staging` first, so `current` is never half written. No per-version
//! folder and no new id: every app resolves the same path ([`chrome_for_testing_path`]
//! prefers `current`).
//!
//! * Download: `rightkit-models`' vetted, resumable, hash-verified downloader (rightkit-http
//!   address policy and redirect vetting). This module has no HTTP client of its own.
//! * Digest: each pinned archive's SHA-256 is required ([`Sha256Pin`]). A pin entry whose digest
//!   is still [`Sha256Pin::Todo`] is refused with [`InstallError::DigestNotPinned`]; nothing is
//!   downloaded for it. The digest is checked again on the file on disk before it is opened.
//! * Extraction: zip only, hardened: every member must sit under the expected top-level
//!   folder, no absolute or `..` paths, no duplicate members, nothing written through a symlink,
//!   symlinks only on Unix and only with a relative target that stays inside the folder, bounded
//!   member count and total size, no set-id bits.
//! * Windows: Chrome's sandbox read-and-execute grant is applied to the staged folder before the
//!   swap, so `current` never appears without it.
//! * Idempotent: when `current/install.json` already records the pinned version, platform and
//!   digests and the executable exists, nothing is downloaded.
//!
//! [`chrome_for_testing_path`]: crate::chrome_for_testing_path

use crate::config::{executable_in, platform_key, ManagedRoot};
use rightkit_fs::digest::sha256_file;
use rightkit_fs::{FileLock, LockOptions};
use rightkit_models::download::{download_resumable, part_path_for, DownloadRequest};
use rightkit_models::http::{http_client, ModelHttp};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{self, Read};
use std::path::{Component, Path, PathBuf};
use std::time::Duration;

/// How long an install waits for another install of the same managed root.
const LOCK_WAIT: Duration = Duration::from_secs(300);
/// Most members one archive may hold (Chrome for Testing has a few thousand).
const MAX_MEMBERS: usize = 50_000;
/// Most bytes one archive may expand to (Chrome for Testing is about 0.5 GiB).
const MAX_EXPANDED_BYTES: u64 = 4 * 1024 * 1024 * 1024;
/// Marker written into `current` once an install is complete.
const MARKER: &str = "install.json";

/// Which Chrome for Testing archive a [`PinnedDownload`] is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DownloadKind {
    /// `chrome-<platform>.zip`: the browser (required on every platform).
    Chrome,
    /// `chrome-headless-shell-<platform>.zip`: the Windows fixture's browser (see
    /// `chrome-headless-shell` in the crate changelog); optional elsewhere.
    HeadlessShell,
}

impl DownloadKind {
    /// The single top-level folder every member of this archive must sit under.
    fn top_level(self, platform: &str) -> String {
        match self {
            Self::Chrome => format!("chrome-{platform}"),
            Self::HeadlessShell => format!("chrome-headless-shell-{platform}"),
        }
    }
}

/// A pinned archive digest. **Required:** the installer refuses [`Sha256Pin::Todo`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sha256Pin {
    /// Lowercase hex SHA-256 of the archive (64 characters).
    Pinned(&'static str),
    /// TODO(#267): the published digest has not been recorded yet. Never guess one: compute it
    /// from the archive Google serves at the pinned URL, record it here, and review the change.
    Todo,
}

/// One archive of a pinned Chrome for Testing build.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PinnedDownload {
    /// Google's platform key: `mac-arm64`, `mac-x64`, `win64` or `linux64`.
    pub platform: &'static str,
    pub kind: DownloadKind,
    /// `https` URL of the archive. Immutable: it names the version.
    pub url: &'static str,
    pub sha256: Sha256Pin,
}

/// A Chrome for Testing version with a per-platform URL and SHA-256 table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PinnedChrome {
    /// Dotted numeric version, for example `156.0.8078.47`.
    pub version: &'static str,
    pub downloads: &'static [PinnedDownload],
}

macro_rules! cft_url {
    ($version:literal, $platform:literal, $name:literal) => {
        concat!(
            "https://storage.googleapis.com/chrome-for-testing-public/",
            $version,
            "/",
            $platform,
            "/",
            $name,
            "-",
            $platform,
            ".zip"
        )
    };
}

macro_rules! cft_chrome {
    ($version:literal, $platform:literal) => {
        PinnedDownload {
            platform: $platform,
            kind: DownloadKind::Chrome,
            url: cft_url!($version, $platform, "chrome"),
            sha256: Sha256Pin::Todo,
        }
    };
    // Digest recorded by `scripts/chrome-pins.mjs --apply` from the real download (#267).
    ($version:literal, $platform:literal, $sha:literal) => {
        PinnedDownload {
            platform: $platform,
            kind: DownloadKind::Chrome,
            url: cft_url!($version, $platform, "chrome"),
            sha256: Sha256Pin::Pinned($sha),
        }
    };
}

/// The Chrome for Testing build this crate version installs.
///
/// Every archive below carries a recorded SHA-256 (computed once from the real archive by
/// `scripts/chrome-pins.mjs --apply`, because Google publishes no digests for Chrome for Testing).
/// A new version is pinned only together with its digests; an entry left as [`Sha256Pin::Todo`]
/// makes [`ensure_chrome_for_testing`] return [`InstallError::DigestNotPinned`] before any download.
pub const PINNED_CHROME_FOR_TESTING: PinnedChrome = PinnedChrome {
    version: "156.0.8078.47",
    downloads: &[
        cft_chrome!(
            "156.0.8078.47",
            "mac-arm64",
            "ad7f2b49a4dc679af286b1b1b386670d93ca7868079f69012d21ba0ac8293df3"
        ),
        cft_chrome!(
            "156.0.8078.47",
            "mac-x64",
            "5a38b8e3d621514fff0775dcae678a152ce378890188c88eef79fc97aa59fccd"
        ),
        cft_chrome!(
            "156.0.8078.47",
            "linux64",
            "e6c94490f0b6b337225aeb2d2a5034858516b7017356980ba94f5176d8774a50"
        ),
        cft_chrome!(
            "156.0.8078.47",
            "win64",
            "a4e0d57245e167e98a9d465af1e3774d2b4ec9f04e483d19bcd97a6f63cf46dd"
        ),
        PinnedDownload {
            platform: "win64",
            kind: DownloadKind::HeadlessShell,
            url: cft_url!("156.0.8078.47", "win64", "chrome-headless-shell"),
            sha256: Sha256Pin::Pinned(
                "e0af9b23f8051cca4f37ca49cd425e8055701bfc0383c198d67f8d5cc5884249",
            ),
        },
    ],
};

/// Result of [`ensure_chrome_for_testing`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChromeInstall {
    pub version: String,
    /// The Chrome executable inside `current`.
    pub executable: PathBuf,
    /// False when the pinned version was already installed and nothing was downloaded.
    pub changed: bool,
}

/// Why an install did not happen. The managed `current` is unchanged on every error except an
/// [`InstallError::Swap`] that reports a failed rollback.
#[derive(Debug, thiserror::Error)]
pub enum InstallError {
    #[error("the pin has no Chrome for Testing download for platform {0}")]
    UnsupportedPlatform(String),
    #[error("pinned {kind:?} digest for {platform} is not recorded (Sha256Pin::Todo); refusing to download without one")]
    DigestNotPinned {
        platform: String,
        kind: DownloadKind,
    },
    #[error("invalid pin: {0}")]
    InvalidPin(String),
    #[error("another install holds {0}: {1}")]
    Busy(PathBuf, String),
    #[error("download of {url} failed: {message}")]
    Download { url: String, message: String },
    #[error("{url}: archive digest {actual} does not match the pinned {expected}")]
    DigestMismatch {
        url: String,
        expected: String,
        actual: String,
    },
    #[error("unsafe or invalid archive: {0}")]
    Archive(String),
    #[error("Windows sandbox grant failed: {0}")]
    SandboxGrant(String),
    #[error("could not swap the new install into place: {0}")]
    Swap(String),
    #[error("io on {}: {source}", .path.display())]
    Io {
        path: PathBuf,
        #[source]
        source: io::Error,
    },
}

fn io_err(path: &Path) -> impl FnOnce(io::Error) -> InstallError + '_ {
    move |source| InstallError::Io {
        path: path.to_path_buf(),
        source,
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct MarkerFile {
    kind: DownloadKind,
    url: String,
    sha256: String,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct Marker {
    version: String,
    platform: String,
    files: Vec<MarkerFile>,
}

/// A validated plan: what to fetch for this platform, digests normalized to lowercase.
struct Plan<'a> {
    platform: &'a str,
    items: Vec<(&'a PinnedDownload, String)>,
}

fn plan<'a>(pin: &'a PinnedChrome, platform: &'a str) -> Result<Plan<'a>, InstallError> {
    let version_ok = !pin.version.is_empty()
        && pin
            .version
            .split('.')
            .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()));
    if !version_ok {
        return Err(InstallError::InvalidPin(format!(
            "version {:?} is not a dotted numeric version",
            pin.version
        )));
    }
    let mut items = Vec::new();
    for d in pin.downloads.iter().filter(|d| d.platform == platform) {
        if !d.url.starts_with("https://") {
            return Err(InstallError::InvalidPin(format!(
                "{} is not an https URL",
                d.url
            )));
        }
        if items
            .iter()
            .any(|(o, _): &(&PinnedDownload, String)| o.kind == d.kind)
        {
            return Err(InstallError::InvalidPin(format!(
                "two {:?} downloads for {platform}",
                d.kind
            )));
        }
        let digest = match d.sha256 {
            Sha256Pin::Pinned(hex) => {
                if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
                    return Err(InstallError::InvalidPin(format!(
                        "digest for {} is not 64 hex characters",
                        d.url
                    )));
                }
                hex.to_ascii_lowercase()
            }
            Sha256Pin::Todo => {
                return Err(InstallError::DigestNotPinned {
                    platform: platform.to_string(),
                    kind: d.kind,
                })
            }
        };
        items.push((d, digest));
    }
    if !items.iter().any(|(d, _)| d.kind == DownloadKind::Chrome) {
        return Err(InstallError::UnsupportedPlatform(platform.to_string()));
    }
    Ok(Plan { platform, items })
}

fn marker_for(pin: &PinnedChrome, plan: &Plan<'_>) -> Marker {
    Marker {
        version: pin.version.to_string(),
        platform: plan.platform.to_string(),
        files: plan
            .items
            .iter()
            .map(|(d, sha)| MarkerFile {
                kind: d.kind,
                url: d.url.to_string(),
                sha256: sha.clone(),
            })
            .collect(),
    }
}

/// Put the pinned Chrome for Testing at `root/current` (see the module docs). Blocking: call it
/// from an installer or updater step, or from `spawn_blocking`.
pub fn ensure_chrome_for_testing(
    root: &ManagedRoot,
    pin: &PinnedChrome,
) -> Result<ChromeInstall, InstallError> {
    let http = http_client();
    ensure_with(root, pin, platform_key(), &|d, sha, dest| {
        fetch(&http, d, sha, dest)
    })
}

/// Put the pinned Chrome for Testing ([`PINNED_CHROME_FOR_TESTING`]) at the suite-wide managed
/// root ([`ManagedRoot::resolve`]), the same place every RightKit app resolves. `progress` receives
/// `(downloaded, total)` bytes of the archive. Blocking: call it from an installer or updater
/// step, or from `spawn_blocking`.
pub fn ensure_default_chrome_for_testing(
    progress: impl FnMut(u64, u64),
) -> Result<ChromeInstall, InstallError> {
    let http = http_client();
    let root = ManagedRoot::resolve();
    let progress = std::cell::RefCell::new(progress);
    ensure_with(
        &root,
        &PINNED_CHROME_FOR_TESTING,
        platform_key(),
        &|d, sha, dest| {
            fetch_reporting(&http, d, sha, dest, |done, total| {
                (*progress.borrow_mut())(done, total)
            })
        },
    )
}

fn fetch(
    http: &ModelHttp,
    d: &PinnedDownload,
    sha256: &str,
    dest: &Path,
) -> Result<(), InstallError> {
    fetch_reporting(http, d, sha256, dest, |_, _| {})
}

fn fetch_reporting(
    http: &ModelHttp,
    d: &PinnedDownload,
    sha256: &str,
    dest: &Path,
    progress: impl FnMut(u64, u64),
) -> Result<(), InstallError> {
    let part = part_path_for(dest);
    download_resumable(
        http,
        DownloadRequest {
            url: d.url,
            part_path: &part,
            dest_path: dest,
            expected_sha256: Some(sha256),
            authorization: None,
            cancelled: &|| false,
        },
        progress,
    )
    .map(|_| ())
    .map_err(|e| InstallError::Download {
        url: d.url.to_string(),
        message: e.to_string(),
    })
}

type Fetch<'a> = &'a dyn Fn(&PinnedDownload, &str, &Path) -> Result<(), InstallError>;

fn ensure_with(
    root: &ManagedRoot,
    pin: &PinnedChrome,
    platform: &str,
    fetch: Fetch<'_>,
) -> Result<ChromeInstall, InstallError> {
    let plan = plan(pin, platform)?;
    let marker = marker_for(pin, &plan);
    let base = root.path();
    fs::create_dir_all(base).map_err(io_err(base))?;
    let lock_path = base.join("current.lock");
    let _lock = FileLock::acquire(
        &lock_path,
        &LockOptions::wait(LOCK_WAIT).labeled("rightkit-browser chrome-for-testing install"),
    )
    .map_err(|e| InstallError::Busy(lock_path.clone(), e.to_string()))?;

    let current = root.current();
    let executable = executable_in(&current);
    if installed_marker(&current).as_ref() == Some(&marker) && executable.is_file() {
        #[cfg(windows)]
        grant_sandbox_access(&current, &executable)?;
        return Ok(ChromeInstall {
            version: pin.version.to_string(),
            executable,
            changed: false,
        });
    }

    let staging = root.staging();
    let downloads = base.join("current.download");
    remove_dir_if_exists(&staging)?;
    fs::create_dir_all(&downloads).map_err(io_err(&downloads))?;
    fs::create_dir(&staging).map_err(io_err(&staging))?;

    let built = (|| {
        for (d, sha) in &plan.items {
            let archive = downloads.join(format!("{}.zip", d.kind.top_level(plan.platform)));
            fetch(d, sha, &archive)?;
            // Never open an archive whose digest was not checked here, whatever fetched it.
            let actual = sha256_file(&archive).map_err(io_err(&archive))?;
            if &actual != sha {
                let _ = fs::remove_file(&archive);
                return Err(InstallError::DigestMismatch {
                    url: d.url.to_string(),
                    expected: sha.clone(),
                    actual,
                });
            }
            extract_zip(&archive, &staging, &d.kind.top_level(plan.platform))?;
        }
        if !executable_in(&staging).is_file() {
            return Err(InstallError::Archive(format!(
                "the archive has no Chrome executable at {}",
                executable_in(&staging).display()
            )));
        }
        let json = serde_json::to_vec_pretty(&marker)
            .map_err(|e| InstallError::Archive(format!("marker: {e}")))?;
        let marker_path = staging.join(MARKER);
        fs::write(&marker_path, json).map_err(io_err(&marker_path))?;
        #[cfg(windows)]
        grant_sandbox_access(&staging, &executable_in(&staging))?;
        Ok(())
    })();
    let _ = fs::remove_dir_all(&downloads);
    if let Err(e) = built {
        let _ = fs::remove_dir_all(&staging);
        return Err(e);
    }

    swap_into_place(root).inspect_err(|_| {
        let _ = fs::remove_dir_all(&staging);
    })?;
    Ok(ChromeInstall {
        version: pin.version.to_string(),
        executable,
        changed: true,
    })
}

fn installed_marker(current: &Path) -> Option<Marker> {
    let bytes = fs::read(current.join(MARKER)).ok()?;
    serde_json::from_slice(&bytes).ok()
}

fn remove_dir_if_exists(path: &Path) -> Result<(), InstallError> {
    match fs::remove_dir_all(path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(io_err(path)(e)),
    }
}

/// `current` -> `current.previous` (the one rollback copy), `current.staging` -> `current`.
/// A failure after the first step puts the old `current` back.
fn swap_into_place(root: &ManagedRoot) -> Result<(), InstallError> {
    let (current, previous, staging) = (root.current(), root.previous(), root.staging());
    let had_current = current.exists();
    if had_current {
        remove_dir_if_exists(&previous)?;
        fs::rename(&current, &previous).map_err(|e| {
            InstallError::Swap(format!(
                "cannot move {} aside (is Chrome for Testing running?): {e}",
                current.display()
            ))
        })?;
    }
    if let Err(e) = fs::rename(&staging, &current) {
        let restored = !had_current || fs::rename(&previous, &current).is_ok();
        return Err(InstallError::Swap(format!(
            "cannot move {} into place: {e}{}",
            staging.display(),
            if restored {
                ""
            } else {
                "; the previous install could not be put back and is at current.previous"
            }
        )));
    }
    Ok(())
}

/// A member's path under `staging`, or `None` when it is absolute, escapes, or is not made of
/// plain components. `top` must be its first component.
fn safe_member_path(name: &str, top: &str) -> Option<PathBuf> {
    if name.contains('\\') || name.contains('\0') {
        return None;
    }
    let mut out = PathBuf::new();
    let mut first = true;
    for part in Path::new(name).components() {
        match part {
            Component::Normal(p) => {
                let p = p.to_str()?;
                if p.contains(':') {
                    return None;
                }
                if first && p != top {
                    return None;
                }
                first = false;
                out.push(p);
            }
            Component::CurDir => {}
            _ => return None,
        }
    }
    (!first).then_some(out)
}

/// True when `target`, a symlink target placed at `link` (both relative to the staging root),
/// is relative and stays under the first component of `link`.
#[cfg(unix)]
fn symlink_target_stays_inside(link: &Path, target: &str) -> bool {
    if target.is_empty() || target.contains('\\') || target.contains('\0') {
        return false;
    }
    let t = Path::new(target);
    if t.is_absolute() {
        return false;
    }
    // Depth of the link's folder below the top-level folder; `..` may not climb above it.
    let mut depth = link.components().count().saturating_sub(2);
    for part in t.components() {
        match part {
            Component::Normal(_) => depth += 1,
            Component::CurDir => {}
            Component::ParentDir => {
                if depth == 0 {
                    return false;
                }
                depth -= 1;
            }
            _ => return false,
        }
    }
    true
}

fn archive_err(message: impl std::fmt::Display) -> InstallError {
    InstallError::Archive(message.to_string())
}

/// Refuse to create anything below a symlink or reparse point already in `staging`.
fn ensure_no_link_ancestors(staging: &Path, relative: &Path) -> Result<(), InstallError> {
    let mut at = staging.to_path_buf();
    let count = relative.components().count();
    for (i, part) in relative.components().enumerate() {
        at.push(part);
        if i + 1 == count {
            break;
        }
        match fs::symlink_metadata(&at) {
            Ok(m) if m.file_type().is_symlink() => {
                return Err(archive_err(format!(
                    "member path passes through a symlink: {}",
                    relative.display()
                )))
            }
            Ok(m) if !m.is_dir() => {
                return Err(archive_err(format!(
                    "member path passes through a file: {}",
                    relative.display()
                )))
            }
            Ok(_) => {}
            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
            Err(e) => return Err(io_err(&at)(e)),
        }
    }
    Ok(())
}

fn extract_zip(archive: &Path, staging: &Path, top: &str) -> Result<(), InstallError> {
    let file = fs::File::open(archive).map_err(io_err(archive))?;
    let mut zip = zip::ZipArchive::new(file).map_err(archive_err)?;
    if zip.is_empty() || zip.len() > MAX_MEMBERS {
        return Err(archive_err(format!("{} members", zip.len())));
    }
    let mut budget = MAX_EXPANDED_BYTES;
    for i in 0..zip.len() {
        let mut entry = zip.by_index(i).map_err(archive_err)?;
        let name = entry.name().map_err(archive_err)?.to_string();
        let relative = safe_member_path(&name, top)
            .ok_or_else(|| archive_err(format!("unsafe member path {name:?}")))?;
        ensure_no_link_ancestors(staging, &relative)?;
        let dest = staging.join(&relative);
        if entry.is_dir() {
            fs::create_dir_all(&dest).map_err(io_err(&dest))?;
            continue;
        }
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent).map_err(io_err(parent))?;
        }
        if entry.is_symlink() {
            #[cfg(unix)]
            {
                let mut target = String::new();
                entry
                    .by_ref()
                    .take(4097)
                    .read_to_string(&mut target)
                    .map_err(archive_err)?;
                if !symlink_target_stays_inside(&relative, &target) {
                    return Err(archive_err(format!(
                        "symlink {name:?} points outside its folder: {target:?}"
                    )));
                }
                std::os::unix::fs::symlink(&target, &dest).map_err(io_err(&dest))?;
                continue;
            }
            #[cfg(not(unix))]
            return Err(archive_err(format!("symlink member {name:?} is refused")));
        }
        if !entry.is_file() {
            return Err(archive_err(format!(
                "member {name:?} is not a regular file"
            )));
        }
        budget = budget
            .checked_sub(entry.size())
            .ok_or_else(|| archive_err("archive expands beyond the size limit"))?;
        let mut out = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&dest)
            .map_err(|e| {
                if e.kind() == io::ErrorKind::AlreadyExists {
                    archive_err(format!("duplicate member {name:?}"))
                } else {
                    io_err(&dest)(e)
                }
            })?;
        let declared = entry.size();
        let written =
            io::copy(&mut entry.by_ref().take(declared + 1), &mut out).map_err(io_err(&dest))?;
        if written != declared {
            return Err(archive_err(format!(
                "member {name:?} is not its declared size"
            )));
        }
        drop(out);
        #[cfg(unix)]
        if let Some(mode) = entry.unix_mode() {
            use std::os::unix::fs::PermissionsExt;
            // Keep the execute bits; never set-id, sticky or group/other write.
            fs::set_permissions(&dest, fs::Permissions::from_mode((mode & 0o755) | 0o600))
                .map_err(io_err(&dest))?;
        }
    }
    Ok(())
}

/// Windows: give Chrome's sandbox read and execute on `directory` (the `icacls` grant described
/// by `BrowserError::ChromeSandboxAccess`) and check it took. An unpacked Chrome is unreadable
/// to its own AppContainer until this runs.
#[cfg(windows)]
fn grant_sandbox_access(directory: &Path, executable: &Path) -> Result<(), InstallError> {
    use crate::sandbox_access::{
        missing_access, ALL_APPLICATION_PACKAGES, ALL_RESTRICTED_APPLICATION_PACKAGES,
    };
    if missing_access(executable).is_none() {
        return Ok(());
    }
    let icacls = std::env::var_os("SystemRoot")
        .map(|r| PathBuf::from(r).join("System32").join("icacls.exe"))
        .unwrap_or_else(|| PathBuf::from("icacls.exe"));
    use std::os::windows::process::CommandExt;
    // CREATE_NO_WINDOW: icacls is a console tool; never flash a window from a GUI app.
    let status = std::process::Command::new(icacls)
        .creation_flags(0x0800_0000)
        .arg(directory)
        .arg("/grant")
        .arg(format!("*{ALL_APPLICATION_PACKAGES}:(OI)(CI)(RX)"))
        .arg(format!(
            "*{ALL_RESTRICTED_APPLICATION_PACKAGES}:(OI)(CI)(RX)"
        ))
        .args(["/T", "/C", "/Q"])
        .status()
        .map_err(|e| InstallError::SandboxGrant(e.to_string()))?;
    if !status.success() {
        return Err(InstallError::SandboxGrant(format!(
            "icacls exited {status}"
        )));
    }
    match missing_access(executable) {
        None => Ok(()),
        Some(m) => Err(InstallError::SandboxGrant(format!(
            "{} still lacks access for {}",
            m.directory.display(),
            m.principals.join(" and ")
        ))),
    }
}