mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Bubblewrap availability + version probing.
//!
//! Presence of `bwrap` on PATH is not sufficient: the argument vector built by
//! [`crate::bwrap_common::bwrap_command`] uses flags that were added over the life of the
//! project, so an old `bwrap` would fail at spawn time with an opaque
//! "unknown option" error. This module probes `bwrap --version` once and
//! reports a precise, actionable reason when the host cannot run the backend.
//!
//! The parsing half is pure (no I/O), so it is unit-tested on every host; only
//! [`probe_bwrap`] shells out.

use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{mpsc, Condvar, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};

use crate::bwrap_common::host_tools::{self, LookupError};
use crate::bwrap_common::probe_exec::{self, CapturedOutput};

/// The minimum `bwrap` version the Bubblewrap backend supports.
///
/// This is the oldest release that has **every** flag
/// [`crate::bwrap_common::bwrap_command::build_args_classified`] emits. The binding
/// constraints, in order of introduction:
///
/// | Flag         | First `bwrap` release |
/// |--------------|-----------------------|
/// | `--bind`, `--ro-bind`, `--dev`, `--proc`, `--tmpfs`, `--symlink`, `--chdir`, `--setenv`, `--unshare-*` | 0.1.0 |
/// | `--seccomp` (address-family filter descriptor) | 0.2.1 |
/// | `--ro-bind-try` (deny-by-default baseline mounts) | 0.3.1 |
/// | `--die-with-parent` (descendants die with the sandbox) | 0.4.0 |
/// | `--clearenv` (minimal sandbox environment) | **0.5.0** |
///
/// `--clearenv` is therefore the flag that sets the floor. If the argument
/// builder ever adopts a newer flag, raise this constant in the same change.
pub const MIN_BWRAP_VERSION: BwrapVersion = BwrapVersion::new(0, 5, 0);

/// Why [`MIN_BWRAP_VERSION`] is the compatibility floor.
pub const MIN_BWRAP_VERSION_REASON: &str = "the sandbox uses `--clearenv`, added in bwrap 0.5.0";

const BWRAP_VERSION_TIMEOUT: Duration = Duration::from_secs(5);
/// The shared probe cap, named locally so the user-facing message can cite it.
const MAX_BWRAP_VERSION_OUTPUT_BYTES: usize = probe_exec::MAX_PROBE_OUTPUT_BYTES;

static CACHED_BWRAP_VERSION: OnceLock<BwrapVersion> = OnceLock::new();
static CACHED_BWRAP_PROBE_GATE: OnceLock<ProbeGate> = OnceLock::new();
static BWRAP_PROBE_GATE: OnceLock<ProbeGate> = OnceLock::new();

fn cached_probe_gate() -> &'static ProbeGate {
    CACHED_BWRAP_PROBE_GATE.get_or_init(ProbeGate::default)
}

fn probe_gate() -> &'static ProbeGate {
    BWRAP_PROBE_GATE.get_or_init(ProbeGate::default)
}

#[derive(Debug, Default)]
struct ProbeGate {
    in_flight: Mutex<bool>,
    available: Condvar,
}

#[derive(Debug)]
struct ProbeGatePermit<'a> {
    gate: &'a ProbeGate,
}

impl Drop for ProbeGatePermit<'_> {
    fn drop(&mut self) {
        self.gate.release();
    }
}

impl ProbeGate {
    fn acquire_until(&self, deadline: Instant) -> bool {
        let mut in_flight = self
            .in_flight
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return false;
            }

            if !*in_flight {
                *in_flight = true;
                return true;
            }

            let (next, wait_result) = self
                .available
                .wait_timeout(in_flight, remaining)
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            in_flight = next;
            if wait_result.timed_out() {
                return false;
            }
        }
    }

    fn release(&self) {
        let mut in_flight = self
            .in_flight
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        *in_flight = false;
        self.available.notify_all();
    }

    fn acquire_permit_until(&self, deadline: Instant) -> Option<ProbeGatePermit<'_>> {
        self.acquire_until(deadline)
            .then_some(ProbeGatePermit { gate: self })
    }
}

/// A `major.minor.patch` Bubblewrap version.
///
/// Ordering is the derived field order (major, then minor, then patch), which
/// is exactly the semantic precedence bwrap releases use.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct BwrapVersion {
    major: u32,
    minor: u32,
    patch: u32,
}

impl BwrapVersion {
    /// Construct a version from its components.
    pub const fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }
}

impl fmt::Display for BwrapVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

/// Why the Bubblewrap backend cannot run on this host.
///
/// [`fmt::Display`] renders the user-facing reason, so callers (the runner's
/// `validate` and the engine's platform probe) share one message source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BwrapUnavailable {
    /// This build cannot generate a seccomp program for the host architecture.
    UnsupportedArchitecture(String),
    /// No `bwrap` was found on `PATH` or in the standard system directories.
    NotFound,
    /// The `bwrap --version` probe failed to start or did not complete
    /// successfully (e.g. a permissions problem or a non-zero exit). Distinct
    /// from [`Self::NotFound`] so observed failures preserve their underlying
    /// cause. A `bwrap` file that is not executable, or whose loader or
    /// shebang target is missing, maps here rather than to [`Self::NotFound`].
    ProbeFailed {
        /// Exit status of `bwrap --version`, when the process ran at all.
        status: Option<i32>,
        /// Captured stderr, or the OS error when the process could not start.
        detail: String,
    },
    /// `bwrap --version` ran but printed something we could not parse. We fail
    /// closed here: without a version we cannot assert the required flags exist.
    UnrecognizedVersion(String),
    /// `bwrap` is present but predates [`MIN_BWRAP_VERSION`].
    TooOld { found: BwrapVersion, path: PathBuf },
}

impl fmt::Display for BwrapUnavailable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedArchitecture(architecture) => write!(
                f,
                "Bubblewrap is unavailable on {architecture}: MXC cannot generate its required \
                 seccomp address-family filter for this architecture."
            ),
            Self::NotFound => write!(
                f,
                "Bubblewrap (bwrap) is not installed: it {}. \
                 Install it via your package manager (e.g., apt install bubblewrap). \
                 Version {MIN_BWRAP_VERSION} or newer is required.",
                LookupError::NotFound
            ),
            Self::ProbeFailed { status, detail } => {
                write!(
                    f,
                    "The Bubblewrap (bwrap) availability probe `bwrap --version` "
                )?;
                match status {
                    Some(code) => write!(f, "exited with status {code}")?,
                    // Covers both a spawn failure and termination by a signal,
                    // neither of which yields an exit code.
                    None => write!(f, "failed without an exit status")?,
                }
                if !detail.is_empty() {
                    write!(f, ": {detail}")?;
                }
                write!(
                    f,
                    ". Version {MIN_BWRAP_VERSION} or newer is required; check \
                     PATH and the installation before using the Bubblewrap backend."
                )
            }
            Self::UnrecognizedVersion(output) => write!(
                f,
                "Could not determine the Bubblewrap (bwrap) version: \
                 `bwrap --version` printed {output:?}. \
                 Version {MIN_BWRAP_VERSION} or newer is required."
            ),
            Self::TooOld { found, path } => write!(
                f,
                "Bubblewrap (bwrap) {found} at {} is too old: version {MIN_BWRAP_VERSION} or \
                 newer is required ({MIN_BWRAP_VERSION_REASON}). \
                 Upgrade the bubblewrap package.",
                path.display()
            ),
        }
    }
}

impl std::error::Error for BwrapUnavailable {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProbedBwrap {
    pub(crate) path: PathBuf,
    pub(crate) version: BwrapVersion,
    pub(crate) is_setuid: bool,
}

/// Probe the host for a usable `bwrap`.
///
/// Runs `bwrap --version` and validates the reported version against
/// [`MIN_BWRAP_VERSION`]. Successful advisory probes are cached.
pub fn probe_bwrap() -> Result<BwrapVersion, BwrapUnavailable> {
    ensure_filter_architecture()?;
    probe_bwrap_cached(
        &CACHED_BWRAP_VERSION,
        cached_probe_gate(),
        BWRAP_VERSION_TIMEOUT,
        |deadline, timeout| {
            probe_bwrap_uncached_until(deadline, timeout).map(|bwrap| bwrap.version)
        },
    )
}

fn probe_bwrap_cached<F>(
    cache: &OnceLock<BwrapVersion>,
    gate: &ProbeGate,
    timeout: Duration,
    probe: F,
) -> Result<BwrapVersion, BwrapUnavailable>
where
    F: FnOnce(Instant, Duration) -> Result<BwrapVersion, BwrapUnavailable>,
{
    if let Some(version) = cache.get() {
        return Ok(*version);
    }

    let deadline = Instant::now() + timeout;
    let Some(_permit) = gate.acquire_permit_until(deadline) else {
        return Err(probe_timeout(timeout));
    };
    if let Some(version) = cache.get() {
        return Ok(*version);
    }

    let version = probe(deadline, timeout)?;
    let _ = cache.set(version);
    Ok(version)
}

/// Probe immediately without consulting the advisory success cache.
///
/// Execution validation uses this so a prior platform-support query cannot
/// approve a different executable after `PATH` or its contents change.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn probe_bwrap_uncached() -> Result<ProbedBwrap, BwrapUnavailable> {
    ensure_filter_architecture()?;
    probe_bwrap_uncached_until(
        Instant::now() + BWRAP_VERSION_TIMEOUT,
        BWRAP_VERSION_TIMEOUT,
    )
}

#[cfg(target_os = "linux")]
fn ensure_filter_architecture() -> Result<(), BwrapUnavailable> {
    crate::bwrap_common::seccomp_filter::unsupported_architecture(std::env::consts::ARCH)
        .map(BwrapUnavailable::UnsupportedArchitecture)
        .map_or(Ok(()), Err)
}

#[cfg(not(target_os = "linux"))]
fn ensure_filter_architecture() -> Result<(), BwrapUnavailable> {
    Ok(())
}

fn probe_bwrap_uncached_until(
    deadline: Instant,
    timeout: Duration,
) -> Result<ProbedBwrap, BwrapUnavailable> {
    probe_bwrap_uncached_with(|| run_bwrap_version_until(deadline, timeout))
}

fn probe_bwrap_uncached_with<F>(run: F) -> Result<ProbedBwrap, BwrapUnavailable>
where
    F: FnOnce() -> Result<(PathBuf, ProbeOutput, bool), BwrapUnavailable>,
{
    let (path, output, is_setuid) = run()?;
    let version = check_probe_output(output)?;
    if version < MIN_BWRAP_VERSION {
        return Err(BwrapUnavailable::TooOld {
            found: version,
            path,
        });
    }
    Ok(ProbedBwrap {
        path,
        version,
        is_setuid,
    })
}

#[derive(Debug)]
struct ProbeOutput {
    success: bool,
    status: Option<i32>,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
}

fn run_bwrap_version_until(
    deadline: Instant,
    timeout: Duration,
) -> Result<(PathBuf, ProbeOutput, bool), BwrapUnavailable> {
    let gate = probe_gate();
    let Some(gate_permit) = gate.acquire_permit_until(deadline) else {
        return Err(probe_timeout(timeout));
    };

    let (sender, receiver) = mpsc::sync_channel(1);
    let worker = thread::Builder::new()
        .name("bwrap-probe".to_string())
        .spawn(move || {
            let _gate_permit = gate_permit;

            // The lookup runs on this worker too, so a stalled filesystem
            // cannot hold the caller past its deadline.
            let result = host_tools::find("bwrap")
                .map_err(lookup_failure)
                .and_then(|path| {
                    let is_setuid = bwrap_is_setuid(&path)?;
                    run_version_command_until(&path, &["--version"], deadline, timeout)
                        .map(|output| (path, output, is_setuid))
                });
            let _ = sender.send(result);
        });
    if let Err(err) = worker {
        return Err(BwrapUnavailable::ProbeFailed {
            status: None,
            detail: format!("failed to start the `bwrap --version` probe: {err}"),
        });
    }

    match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
        Ok(result) => result,
        Err(mpsc::RecvTimeoutError::Timeout) => Err(probe_timeout(timeout)),
        Err(mpsc::RecvTimeoutError::Disconnected) => Err(probe_internal_error(
            "`bwrap --version` probe worker disconnected",
        )),
    }
}

#[cfg(target_os = "linux")]
fn bwrap_is_setuid(path: &Path) -> Result<bool, BwrapUnavailable> {
    use std::os::unix::fs::MetadataExt;

    std::fs::metadata(path)
        .map(|metadata| metadata.mode() & 0o4000 != 0)
        .map_err(|error| BwrapUnavailable::ProbeFailed {
            status: None,
            detail: format!(
                "could not inspect Bubblewrap at '{}': {error}",
                path.display()
            ),
        })
}

#[cfg(not(target_os = "linux"))]
fn bwrap_is_setuid(_path: &Path) -> Result<bool, BwrapUnavailable> {
    Ok(false)
}

fn probe_timeout(timeout: Duration) -> BwrapUnavailable {
    BwrapUnavailable::ProbeFailed {
        status: None,
        detail: format!("timed out after {}ms", timeout.as_millis()),
    }
}

#[cfg(all(test, unix))]
fn run_version_command_with_timeout(
    executable: &std::path::Path,
    args: &[&str],
    timeout: Duration,
) -> Result<ProbeOutput, BwrapUnavailable> {
    run_version_command_until(executable, args, Instant::now() + timeout, timeout)
}

fn run_version_command_until(
    executable: &Path,
    args: &[&str],
    deadline: Instant,
    timeout: Duration,
) -> Result<ProbeOutput, BwrapUnavailable> {
    // The public probe runs this entire operation in a deadline-watched worker,
    // so the spawn is bounded too. `probe_exec` owns the process group, the
    // poll-bounded readers and the termination sweep; this layer only decides
    // what each outcome *means* for `bwrap` specifically.
    let mut command = Command::new(executable);
    command.args(args);

    match probe_exec::run_bounded(&mut command, deadline) {
        Ok(captured) => finish_probe(
            captured.status,
            captured.stdout,
            captured.stderr,
            captured.cleanup_error,
        ),
        Err(probe_exec::ProbeFailure::Spawn(err)) => Err(classify_spawn_failure(executable, err)),
        Err(probe_exec::ProbeFailure::TimedOut { cleanup_error }) => {
            let suffix = cleanup_error
                .map(|err| format!("; failed to terminate it: {err}"))
                .unwrap_or_default();
            Err(BwrapUnavailable::ProbeFailed {
                status: None,
                detail: format!("timed out after {}ms{suffix}", timeout.as_millis()),
            })
        }
        Err(probe_exec::ProbeFailure::Wait { stage, error }) => {
            Err(BwrapUnavailable::ProbeFailed {
                status: None,
                detail: format!("failed while {} `bwrap --version`: {error}", stage.as_str()),
            })
        }
        Err(probe_exec::ProbeFailure::Internal(detail)) => Err(probe_internal_error(&detail)),
    }
}

fn finish_probe(
    status: std::process::ExitStatus,
    stdout: CapturedOutput,
    stderr: CapturedOutput,
    _cleanup_error: Option<io::Error>,
) -> Result<ProbeOutput, BwrapUnavailable> {
    // A completed version command is authoritative. Some setuid bwrap
    // installations reject signalling their post-exit process group with
    // EPERM; that cleanup diagnostic must not turn a valid version into an
    // unavailable backend.
    if stdout.truncated || stderr.truncated {
        return Err(BwrapUnavailable::ProbeFailed {
            status: status.code(),
            detail: format!(
                "`bwrap --version` output exceeded the {} byte limit",
                MAX_BWRAP_VERSION_OUTPUT_BYTES
            ),
        });
    }
    Ok(ProbeOutput {
        success: status.success(),
        status: status.code(),
        stdout: stdout.bytes,
        stderr: stderr.bytes,
    })
}

fn lookup_failure(error: LookupError) -> BwrapUnavailable {
    match error {
        LookupError::NotFound => BwrapUnavailable::NotFound,
        not_executable @ LookupError::NotExecutable(_) => BwrapUnavailable::ProbeFailed {
            status: None,
            detail: format!("`bwrap` {not_executable}"),
        },
    }
}

fn classify_spawn_failure(executable: &Path, err: io::Error) -> BwrapUnavailable {
    if err.kind() != io::ErrorKind::NotFound {
        return BwrapUnavailable::ProbeFailed {
            status: None,
            detail: err.to_string(),
        };
    }
    if !executable.exists() {
        return BwrapUnavailable::NotFound;
    }
    BwrapUnavailable::ProbeFailed {
        status: None,
        detail: format!(
            "`{}` was found but could not be executed ({err}); check for a missing interpreter or loader",
            executable.display()
        ),
    }
}

fn probe_internal_error(detail: &str) -> BwrapUnavailable {
    BwrapUnavailable::ProbeFailed {
        status: None,
        detail: detail.to_string(),
    }
}

fn check_probe_output(output: ProbeOutput) -> Result<BwrapVersion, BwrapUnavailable> {
    if !output.success {
        return Err(BwrapUnavailable::ProbeFailed {
            status: output.status,
            detail: String::from_utf8_lossy(&output.stderr).trim().to_string(),
        });
    }

    // The version banner goes to stdout; `parse_version` owns its format.
    let stdout = String::from_utf8_lossy(&output.stdout);
    check_version_output(&stdout)
}

fn check_version_output(output: &str) -> Result<BwrapVersion, BwrapUnavailable> {
    parse_version(output)
        .ok_or_else(|| BwrapUnavailable::UnrecognizedVersion(output.trim().to_string()))
}

/// Parse the version out of a `bwrap --version` line such as
/// `"bubblewrap 0.11.2"`.
///
/// Anchored on the `bubblewrap` package name, which is what makes unrecognized
/// output fail closed: without it any numeric token in arbitrary output (say
/// `"some other tool 999"`) would be read as a version and clear the
/// minimum-version gate.
///
/// Lenient about what *surrounds* each number so distro-patched version strings
/// (`0.4.1-1`, a bare `0.6`) still resolve: the version token is split on `.`
/// and each of the (up to three) components contributes its leading digits.
/// Debian's `+really` marker is honored rather than ignored — see below.
///
/// Strict about components that are *present but not numeric*: only a component
/// that is genuinely absent defaults to `0`, so `"0.6.invalid"` is rejected
/// rather than silently read as `0.6.0`. Returns `None` whenever the version
/// cannot be determined, which callers treat as fail-closed.
fn parse_version(output: &str) -> Option<BwrapVersion> {
    // bwrap prints its autotools/meson `PACKAGE_STRING` — "bubblewrap <version>"
    // — and that leading name has been stable since 0.1.0.
    let mut tokens = output.split_whitespace();
    if !tokens.next()?.eq_ignore_ascii_case("bubblewrap") {
        return None;
    }
    let token = tokens.next()?;

    // Debian's `+really` marker means the package ships the version that
    // FOLLOWS it (used when a maintainer must ship an older upstream without
    // decreasing the package version). Reading the leading version would
    // over-report: `0.5.0+really0.4.1` is really 0.4.1, which predates
    // `--clearenv` and must not clear the gate.
    let token = token.rsplit_once("+really").map_or(token, |(_, real)| real);

    // `map_or(Some(0), ..)` is the absent-vs-unreadable split: an exhausted
    // iterator yields 0, a component `leading_number` rejects fails the parse.
    let mut components = token.split('.');
    let major = leading_number(components.next()?)?;
    let minor = components.next().map_or(Some(0), leading_number)?;
    let patch = components.next().map_or(Some(0), leading_number)?;

    // Components past the patch are not significant, but they must still look
    // like a version: `0.5.0.invalid` is an unrecognized banner, not 0.5.0.
    // Checking them (rather than rejecting on count) keeps a distro four-part
    // build such as `0.6.0.1` working.
    if !components.all(|extra| leading_number(extra).is_some()) {
        return None;
    }
    Some(BwrapVersion::new(major, minor, patch))
}

/// Parse the leading run of ASCII digits of `component`, ignoring any suffix
/// (so `"1-1"` yields `1`). Returns `None` when there is no leading digit or
/// the number overflows.
fn leading_number(component: &str) -> Option<u32> {
    let end = component
        .find(|c: char| !c.is_ascii_digit())
        .unwrap_or(component.len());
    component[..end].parse().ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(target_os = "linux")]
    #[test]
    fn setuid_mode_is_reported_from_the_selected_bwrap_file() {
        use std::os::unix::fs::PermissionsExt;

        let directory = tempfile::tempdir().unwrap();
        let executable = directory.path().join("bwrap");
        std::fs::write(&executable, "bwrap").unwrap();
        std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o4755)).unwrap();

        assert!(bwrap_is_setuid(&executable).unwrap());
    }

    const TEST_BWRAP: &str = "/usr/bin/bwrap";

    fn probe_with_banner(banner: &str) -> Result<ProbedBwrap, BwrapUnavailable> {
        probe_bwrap_uncached_with(|| {
            Ok((
                PathBuf::from(TEST_BWRAP),
                ProbeOutput {
                    success: true,
                    status: Some(0),
                    stdout: banner.as_bytes().to_vec(),
                    stderr: Vec::new(),
                },
                false,
            ))
        })
    }

    #[test]
    fn parses_standard_version_output() {
        assert_eq!(
            parse_version("bubblewrap 0.11.2\n"),
            Some(BwrapVersion::new(0, 11, 2))
        );
    }

    #[test]
    fn parses_distro_patched_and_short_versions() {
        // Debian-style revision suffix and a two-component version.
        assert_eq!(
            parse_version("bubblewrap 0.4.1-1"),
            Some(BwrapVersion::new(0, 4, 1))
        );
        assert_eq!(
            parse_version("bubblewrap 0.6"),
            Some(BwrapVersion::new(0, 6, 0))
        );
    }

    #[test]
    fn honors_the_debian_really_marker() {
        // `X+reallyY` ships upstream Y, not X, so Y is the effective version.
        assert_eq!(
            parse_version("bubblewrap 0.11.0+really0.10.0"),
            Some(BwrapVersion::new(0, 10, 0))
        );
        assert_eq!(
            parse_version("bubblewrap 0.11.0+really0.10.0-1"),
            Some(BwrapVersion::new(0, 10, 0))
        );
    }

    #[test]
    fn really_marker_cannot_smuggle_a_below_floor_version_past_the_gate() {
        // Regression: reading the leading version accepted this as 0.5.0, even
        // though the installed bwrap is 0.4.1 and has no `--clearenv`.
        assert_eq!(
            probe_with_banner("bubblewrap 0.5.0+really0.4.1"),
            Err(BwrapUnavailable::TooOld {
                found: BwrapVersion::new(0, 4, 1),
                path: PathBuf::from(TEST_BWRAP),
            })
        );
    }

    #[test]
    fn rejects_output_without_a_version() {
        assert_eq!(parse_version(""), None);
        assert_eq!(parse_version("bwrap: command not found"), None);
    }

    #[test]
    fn rejects_present_but_nonnumeric_components() {
        // A component that exists but has no leading digit must fail closed
        // rather than silently defaulting to 0 — "0.6.invalid" is not 0.6.0.
        assert_eq!(parse_version("bubblewrap 0.6.invalid"), None);
        assert_eq!(parse_version("bubblewrap 0.beta.1"), None);
        assert_eq!(parse_version("bubblewrap 0.6."), None);
        // ...but a genuinely absent component still defaults to 0.
        assert_eq!(
            parse_version("bubblewrap 1"),
            Some(BwrapVersion::new(1, 0, 0))
        );
    }

    #[test]
    fn rejects_junk_after_the_patch_component() {
        // Regression: components past the patch were dropped unchecked, so
        // "0.5.0.invalid" cleared the gate as 0.5.0.
        assert_eq!(parse_version("bubblewrap 0.5.0.invalid"), None);
        assert_eq!(
            check_version_output("bubblewrap 0.5.0.invalid"),
            Err(BwrapUnavailable::UnrecognizedVersion(
                "bubblewrap 0.5.0.invalid".to_string()
            ))
        );
        // A numeric fourth component is a plausible distro build, not junk.
        assert_eq!(
            parse_version("bubblewrap 0.6.0.1"),
            Some(BwrapVersion::new(0, 6, 0))
        );
    }

    #[test]
    fn rejects_components_that_overflow_u32() {
        // Shared contract with the SDK parser: an out-of-range component is a
        // malformed banner, not a very new bwrap. Both sides must fail closed
        // so the SDK gate cannot admit what this one rejects.
        assert_eq!(parse_version("bubblewrap 99999999999999999999.0.0"), None);
        assert_eq!(parse_version("bubblewrap 0.4294967296.0"), None);
        assert_eq!(
            parse_version("bubblewrap 4294967295.0.0"),
            Some(BwrapVersion::new(4_294_967_295, 0, 0))
        );
    }

    #[test]
    fn ordering_is_semantic() {
        assert!(BwrapVersion::new(0, 4, 9) < BwrapVersion::new(0, 5, 0));
        assert!(BwrapVersion::new(0, 11, 0) > BwrapVersion::new(0, 9, 9));
        assert!(BwrapVersion::new(1, 0, 0) > BwrapVersion::new(0, 99, 99));
    }

    #[test]
    fn accepts_minimum_and_newer_versions() {
        assert_eq!(
            probe_with_banner("bubblewrap 0.5.0").map(|bwrap| bwrap.version),
            Ok(MIN_BWRAP_VERSION)
        );
        assert_eq!(
            probe_with_banner("bubblewrap 0.11.2").map(|bwrap| bwrap.version),
            Ok(BwrapVersion::new(0, 11, 2))
        );
    }

    #[test]
    fn rejects_versions_below_the_minimum() {
        // 0.4.1 has `--ro-bind-try` but not `--clearenv`.
        let error = probe_with_banner("bubblewrap 0.4.1").unwrap_err();
        assert_eq!(
            error,
            BwrapUnavailable::TooOld {
                found: BwrapVersion::new(0, 4, 1),
                path: PathBuf::from(TEST_BWRAP),
            }
        );
        assert!(
            error
                .to_string()
                .contains("0.4.1 at /usr/bin/bwrap is too old"),
            "{error}"
        );
    }

    #[test]
    fn fails_closed_on_unparsable_output() {
        assert_eq!(
            check_version_output("some other tool\n"),
            Err(BwrapUnavailable::UnrecognizedVersion(
                "some other tool".to_string()
            ))
        );
    }

    #[test]
    fn fails_closed_on_a_stray_number_in_unrelated_output() {
        // Regression: searching for any numeric token let unrelated output
        // clear the gate — "some other tool 999" parsed as 999.0.0. Anchoring
        // on the `bubblewrap` package name is what keeps this fail-closed.
        assert_eq!(parse_version("some other tool 999"), None);
        assert_eq!(parse_version("bwrap 0.11.2"), None);
        assert_eq!(
            check_version_output("some other tool 999"),
            Err(BwrapUnavailable::UnrecognizedVersion(
                "some other tool 999".to_string()
            ))
        );
    }

    #[test]
    fn messages_name_the_required_version() {
        for err in [
            BwrapUnavailable::NotFound,
            BwrapUnavailable::ProbeFailed {
                status: Some(126),
                detail: "permission denied".to_string(),
            },
            BwrapUnavailable::UnrecognizedVersion("junk".to_string()),
            BwrapUnavailable::TooOld {
                found: BwrapVersion::new(0, 4, 1),
                path: PathBuf::from(TEST_BWRAP),
            },
        ] {
            let message = err.to_string();
            assert!(
                message.contains(&MIN_BWRAP_VERSION.to_string()),
                "message should name the minimum version: {message}"
            );
        }
    }

    #[test]
    fn unsupported_architecture_message_names_the_filter_requirement() {
        let message = BwrapUnavailable::UnsupportedArchitecture("riscv64".to_string()).to_string();
        assert!(message.contains("riscv64"));
        assert!(message.contains("seccomp address-family filter"));
    }

    #[test]
    fn not_found_names_every_place_bwrap_was_looked_for() {
        let message = BwrapUnavailable::NotFound.to_string();
        assert!(message.contains("PATH"), "{message}");
        for directory in host_tools::FALLBACK_DIRECTORIES {
            assert!(message.contains(directory), "{message}");
        }
    }

    #[test]
    fn an_unexecutable_bwrap_is_reported_as_broken_with_its_path() {
        let failure = lookup_failure(LookupError::NotExecutable(PathBuf::from("/opt/x/bwrap")));
        assert!(
            matches!(
                &failure,
                BwrapUnavailable::ProbeFailed { status: None, detail }
                    if detail.contains("/opt/x/bwrap") && detail.contains("not executable")
            ),
            "{failure:?}"
        );
        assert_eq!(
            lookup_failure(LookupError::NotFound),
            BwrapUnavailable::NotFound
        );
    }

    #[test]
    fn probe_failure_message_preserves_status_and_stderr() {
        // A broken-but-present bwrap must not be reported as "not installed":
        // that remediation would send the user to their package manager for a
        // package they already have.
        let message = BwrapUnavailable::ProbeFailed {
            status: Some(126),
            detail: "bwrap: permission denied".to_string(),
        }
        .to_string();
        assert!(message.contains("126"), "status should survive: {message}");
        assert!(
            message.contains("bwrap: permission denied"),
            "stderr should survive: {message}"
        );
        assert!(
            !message.contains("not installed"),
            "must not claim the package is missing: {message}"
        );
    }

    #[test]
    fn probe_failure_message_handles_a_missing_status() {
        // Spawn failures that are not `NotFound` (permissions, loader errors)
        // and signal-terminated runs both lack an exit status, so the wording
        // must not claim the process never ran.
        let message = BwrapUnavailable::ProbeFailed {
            status: None,
            detail: "Permission denied (os error 13)".to_string(),
        }
        .to_string();
        assert!(
            message.contains("failed without an exit status"),
            "should describe the missing status: {message}"
        );
        assert!(
            message.contains("os error 13"),
            "OS error should survive: {message}"
        );
    }

    #[test]
    fn probe_gate_serializes_callers_within_their_deadline() {
        let gate = std::sync::Arc::new(ProbeGate::default());
        assert!(gate.acquire_until(Instant::now() + Duration::from_secs(1)));

        let waiting_gate = std::sync::Arc::clone(&gate);
        let (waiting_tx, waiting_rx) = mpsc::channel();
        let waiter = thread::spawn(move || {
            waiting_tx.send(()).unwrap();
            let acquired = waiting_gate.acquire_until(Instant::now() + Duration::from_secs(5));
            if acquired {
                waiting_gate.release();
            }
            acquired
        });

        waiting_rx.recv().unwrap();
        gate.release();
        assert!(waiter.join().unwrap());
    }

    #[test]
    fn probe_gate_does_not_create_a_retry_after_the_deadline() {
        let gate = ProbeGate::default();
        assert!(gate.acquire_until(Instant::now() + Duration::from_millis(25)));
        assert!(!gate.acquire_until(Instant::now() + Duration::from_millis(10)));
        gate.release();
    }

    #[test]
    fn probe_gate_permit_releases_on_panic() {
        let gate = std::sync::Arc::new(ProbeGate::default());
        let panicking_gate = std::sync::Arc::clone(&gate);
        let worker = thread::spawn(move || {
            let _permit = panicking_gate
                .acquire_permit_until(Instant::now() + Duration::from_millis(50))
                .expect("permit should be acquired");
            panic!("simulated panic while probe is in-flight");
        });
        assert!(worker.join().is_err());

        assert!(
            gate.acquire_until(Instant::now() + Duration::from_millis(50)),
            "panic should release the gate"
        );
        gate.release();
    }

    #[cfg(unix)]
    #[test]
    fn a_bwrap_removed_after_the_lookup_is_classified_as_not_found() {
        let dir = tempfile::tempdir().unwrap();
        let error = run_version_command_with_timeout(
            &dir.path().join("bwrap"),
            &["--version"],
            Duration::from_secs(1),
        )
        .unwrap_err();
        assert_eq!(error, BwrapUnavailable::NotFound);
    }

    #[cfg(unix)]
    #[test]
    fn expired_deadline_does_not_launch_the_probe_command() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("bwrap");
        let marker = dir.path().join("launched");
        std::fs::write(&script, "#!/bin/sh\nprintf launched > \"$1\"\n").unwrap();
        let mut permissions = std::fs::metadata(&script).unwrap().permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&script, permissions).unwrap();

        let marker_arg = marker.to_string_lossy();
        let timeout = Duration::from_millis(50);
        let error = run_version_command_until(
            &script,
            &[marker_arg.as_ref()],
            Instant::now() - Duration::from_millis(1),
            timeout,
        )
        .unwrap_err();

        assert_eq!(error, probe_timeout(timeout));
        assert!(
            !marker.exists(),
            "an expired worker launched the probe command after the caller returned"
        );
    }

    #[cfg(unix)]
    #[test]
    fn missing_interpreter_is_classified_as_probe_failure() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("bwrap");
        std::fs::write(&script, "#!/this/interpreter/does/not/exist\nexit 0\n").unwrap();
        let mut permissions = std::fs::metadata(&script).unwrap().permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&script, permissions).unwrap();

        let error =
            run_version_command_with_timeout(&script, &["--version"], Duration::from_secs(1))
                .unwrap_err();
        assert!(matches!(
            error,
            BwrapUnavailable::ProbeFailed { status: None, detail }
                if detail.contains("missing interpreter or loader")
        ));
    }

    #[cfg(unix)]
    #[test]
    fn subprocess_probe_preserves_reader_results_until_all_are_ready() {
        for _ in 0..50 {
            let output = run_version_command_with_timeout(
                std::path::Path::new("/bin/sh"),
                &["-c", "printf 'bubblewrap 0.5.0\\n'"],
                Duration::from_secs(1),
            )
            .unwrap();
            assert_eq!(check_probe_output(output), Ok(MIN_BWRAP_VERSION));
        }
    }

    #[cfg(unix)]
    #[test]
    fn subprocess_probe_times_out_and_terminates_the_child() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("bwrap");
        std::fs::write(&script, "#!/bin/sh\nwhile true; do :; done\n").unwrap();
        let mut permissions = std::fs::metadata(&script).unwrap().permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&script, permissions).unwrap();

        let error =
            run_version_command_with_timeout(&script, &["--version"], Duration::from_millis(250))
                .unwrap_err();
        assert!(matches!(
            error,
            BwrapUnavailable::ProbeFailed {
                status: None,
                detail,
            } if detail.contains("timed out after 250ms")
        ));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn subprocess_probe_terminates_a_descendant_holding_the_pipes_open() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("bwrap");
        std::fs::write(
            &script,
            "#!/bin/sh\n(while true; do :; done) &\necho 'bubblewrap 0.5.0'\nexit 0\n",
        )
        .unwrap();
        let mut permissions = std::fs::metadata(&script).unwrap().permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&script, permissions).unwrap();

        let started = Instant::now();
        let output =
            run_version_command_with_timeout(&script, &["--version"], Duration::from_millis(30))
                .unwrap();
        assert!(started.elapsed() < Duration::from_secs(1));
        assert_eq!(check_probe_output(output), Ok(MIN_BWRAP_VERSION));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn subprocess_probe_terminates_a_descendant_with_closed_pipes() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("bwrap");
        let pid_file = dir.path().join("descendant.pid");
        std::fs::write(
            &script,
            "#!/bin/sh\n(while true; do :; done) >/dev/null 2>&1 &\necho \"$!\" > \"$1\"\necho 'bubblewrap 0.5.0'\nexit 0\n",
        )
        .unwrap();
        let mut permissions = std::fs::metadata(&script).unwrap().permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&script, permissions).unwrap();

        let pid_file_arg = pid_file.to_string_lossy();
        let output = run_version_command_with_timeout(
            &script,
            &[pid_file_arg.as_ref()],
            Duration::from_secs(1),
        )
        .unwrap();
        assert_eq!(check_probe_output(output), Ok(MIN_BWRAP_VERSION));

        let pid: u32 = std::fs::read_to_string(pid_file)
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        let poll_deadline = Instant::now() + Duration::from_secs(1);
        let terminated = loop {
            let terminated = match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
                Ok(stat) => {
                    stat.rfind(") ")
                        .and_then(|index| stat[index + 2..].chars().next())
                        == Some('Z')
                }
                Err(err) if err.kind() == io::ErrorKind::NotFound => true,
                Err(err) => panic!("failed to inspect probe descendant {pid}: {err}"),
            };
            if terminated || Instant::now() >= poll_deadline {
                break terminated;
            }
            thread::sleep(Duration::from_millis(10));
        };
        assert!(terminated, "probe descendant {pid} is still running");
    }

    #[test]
    fn uncached_probe_maps_injected_process_outcomes() {
        let bwrap = probe_bwrap_uncached_with(|| {
            Ok((
                PathBuf::from("/usr/sbin/bwrap"),
                ProbeOutput {
                    success: true,
                    status: Some(0),
                    stdout: b"bubblewrap 0.5.0\n".to_vec(),
                    stderr: Vec::new(),
                },
                false,
            ))
        })
        .unwrap();
        assert_eq!(
            bwrap,
            ProbedBwrap {
                path: PathBuf::from("/usr/sbin/bwrap"),
                version: MIN_BWRAP_VERSION,
                is_setuid: false,
            }
        );

        let failure = BwrapUnavailable::ProbeFailed {
            status: Some(126),
            detail: "permission denied".to_string(),
        };
        assert_eq!(
            probe_bwrap_uncached_with(|| Err(failure.clone())),
            Err(failure)
        );
    }

    #[test]
    fn probe_output_preserves_nonzero_status_and_stderr() {
        let error = check_probe_output(ProbeOutput {
            success: false,
            status: Some(126),
            stdout: Vec::new(),
            stderr: b"permission denied".to_vec(),
        })
        .unwrap_err();
        assert!(matches!(
            error,
            BwrapUnavailable::ProbeFailed {
                detail,
                ..
            } if detail == "permission denied"
        ));
    }

    #[cfg(unix)]
    #[test]
    fn successful_probe_ignores_post_exit_group_cleanup_failure() {
        use std::os::unix::process::ExitStatusExt;

        let output = finish_probe(
            std::process::ExitStatus::from_raw(0),
            CapturedOutput {
                bytes: b"bubblewrap 0.5.0\n".to_vec(),
                truncated: false,
            },
            CapturedOutput {
                bytes: Vec::new(),
                truncated: false,
            },
            Some(io::Error::from_raw_os_error(nix::libc::EPERM)),
        )
        .unwrap();
        assert_eq!(check_probe_output(output), Ok(MIN_BWRAP_VERSION));
    }

    #[test]
    fn successful_probe_result_is_cached() {
        let cache = OnceLock::new();
        let gate = ProbeGate::default();
        let first = probe_bwrap_cached(&cache, &gate, Duration::from_secs(1), |_, _| {
            Ok(MIN_BWRAP_VERSION)
        })
        .unwrap();
        assert_eq!(first, MIN_BWRAP_VERSION);

        let second = probe_bwrap_cached(&cache, &gate, Duration::from_secs(1), |_, _| {
            panic!("successful probe should be reused from the cache")
        })
        .unwrap();
        assert_eq!(second, MIN_BWRAP_VERSION);
    }

    #[test]
    fn expired_probe_gate_deadline_does_not_start_probe() {
        let gate = ProbeGate::default();
        assert!(gate
            .acquire_permit_until(Instant::now() - Duration::from_millis(1))
            .is_none());
        assert!(!*gate
            .in_flight
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()));
    }

    #[test]
    fn failed_probe_result_is_not_cached() {
        let cache = OnceLock::new();
        let gate = ProbeGate::default();
        assert_eq!(
            probe_bwrap_cached(&cache, &gate, Duration::from_secs(1), |_, _| {
                Err(BwrapUnavailable::NotFound)
            }),
            Err(BwrapUnavailable::NotFound)
        );
        assert_eq!(
            probe_bwrap_cached(&cache, &gate, Duration::from_secs(1), |_, _| {
                Ok(MIN_BWRAP_VERSION)
            }),
            Ok(MIN_BWRAP_VERSION)
        );
    }

    #[test]
    fn concurrent_cached_callers_reuse_the_first_success() {
        let cache = std::sync::Arc::new(OnceLock::new());
        let gate = std::sync::Arc::new(ProbeGate::default());
        let (started_tx, started_rx) = mpsc::channel();
        let synchronization = std::sync::Arc::new(std::sync::Barrier::new(2));
        let first_cache = std::sync::Arc::clone(&cache);
        let first_gate = std::sync::Arc::clone(&gate);
        let first_synchronization = std::sync::Arc::clone(&synchronization);
        let first = thread::spawn(move || {
            probe_bwrap_cached(&first_cache, &first_gate, Duration::from_secs(1), |_, _| {
                started_tx.send(()).unwrap();
                first_synchronization.wait();
                Ok(MIN_BWRAP_VERSION)
            })
        });

        started_rx.recv().unwrap();
        let second_cache = std::sync::Arc::clone(&cache);
        let second_gate = std::sync::Arc::clone(&gate);
        let second_synchronization = std::sync::Arc::clone(&synchronization);
        let second = thread::spawn(move || {
            second_synchronization.wait();
            probe_bwrap_cached(
                &second_cache,
                &second_gate,
                Duration::from_secs(1),
                |_, _| panic!("queued advisory caller should reuse the first success"),
            )
        });

        assert_eq!(first.join().unwrap(), Ok(MIN_BWRAP_VERSION));
        assert_eq!(second.join().unwrap(), Ok(MIN_BWRAP_VERSION));
    }

    #[test]
    fn concurrent_cached_callers_remain_deadline_bounded_after_failure() {
        let cache = std::sync::Arc::new(OnceLock::new());
        let gate = std::sync::Arc::new(ProbeGate::default());
        let (started_tx, started_rx) = mpsc::channel();
        let (release_tx, release_rx) = mpsc::channel();
        let first_cache = std::sync::Arc::clone(&cache);
        let first_gate = std::sync::Arc::clone(&gate);
        let first = thread::spawn(move || {
            probe_bwrap_cached(&first_cache, &first_gate, Duration::from_secs(1), |_, _| {
                started_tx.send(()).unwrap();
                release_rx.recv().unwrap();
                Err(BwrapUnavailable::NotFound)
            })
        });

        started_rx.recv().unwrap();
        let timeout = Duration::from_millis(50);
        let started = Instant::now();
        let second = probe_bwrap_cached(&cache, &gate, timeout, |_, _| {
            panic!("caller whose cache wait expired must not start a probe")
        });
        assert_eq!(second, Err(probe_timeout(timeout)));
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "cache wait exceeded its deadline by an unreasonable margin"
        );

        release_tx.send(()).unwrap();
        assert_eq!(first.join().unwrap(), Err(BwrapUnavailable::NotFound));
    }
}