crabpot 0.10.7

Native Rust sandbox runtime for AI agents, rewritten from Anthropic's sandbox-runtime
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
//! The crabpot command line: upstream's `-s/--settings`, `-c`, `-d`,
//! `--control-fd`, `-V`, `-h` and `--`, then a program and its arguments.

use core::fmt;
use std::ffi::OsString;
use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};

use crate::windows::install::{InstallOptions, UninstallOptions};

/// What the command line asks for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Args {
    /// The settings file, when `-s` names one.
    pub(crate) settings: Option<PathBuf>,
    /// Whether `-d` was given.
    pub(crate) debug: bool,
    /// The descriptor `--control-fd` names: 3 or more.
    pub(crate) control_fd: Option<i32>,
    /// What to run.
    pub(crate) command: Invocation,
}

/// What `-h` and `--help` print.
pub(crate) const USAGE: &str = "\
Usage: crabpot [options] [command...]
       crabpot [options] -c <command>
       crabpot windows-install [options]
       crabpot windows-uninstall [options]

Runs a command with its filesystem and network access confined.

Options:
  -s, --settings <path>  settings file (default: ~/.srt-settings.json)
  -c <command>           run a line with `bash -c`, instead of a program
  -d, --debug            print the wrapped command to stderr
  --control-fd <fd>      read JSON lines that replace the network lists from <fd>
  -V, --version          print the version
  -h, --help             print this help

Put `--` before a program whose name starts with `-`. Everything after the
program's name belongs to the program.

Exit status: the command's own, or 125 when the sandbox or the command line is
refused.

Subcommands (Windows), which run no command and exit 0 when done and 1 when
their arguments are refused or the step fails:
  windows-install        set up the sandbox user and the network filters
  windows-uninstall      take them down
";

/// What the command line asks crabpot to do.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Parsed {
    /// `-V` or `--version`: print the package version.
    Version,
    /// `-h` or `--help`: print [`USAGE`].
    Help,
    /// Run a command in the sandbox.
    Run(Args),
}

/// How the sandboxed command is named.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Invocation {
    /// A program and its arguments, exec'd with no shell.
    Argv(Vec<OsString>),
    /// A line for `bash -c`.
    Shell(OsString),
}

/// The hidden first argument that makes the binary srt-win (see `run_from_args`).
pub(crate) const SRT_WIN_FLAG: &str = "--srt-win";

/// The hidden first argument that makes the binary the helper inside bwrap
/// (ADR-0014). It is followed by a [`HelperMode`], then the mode's own arguments.
pub(crate) const HELPER_FLAG: &str = "--crabpot-helper";

/// Which of the helper's jobs a re-entry asks for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HelperMode {
    /// Runs the command, as PID 1 of the sandbox.
    Init,
    /// Relays a TCP port to the proxy's Unix socket.
    Relay,
    /// Connects standard input and output to the proxy, through the relay port
    /// inside the sandbox. This is ssh's `ProxyCommand` hop.
    Connect,
}

impl HelperMode {
    /// The word that names the mode on the command line.
    pub(crate) const fn word(self) -> &'static str {
        match self {
            Self::Init => "init",
            Self::Relay => "relay",
            Self::Connect => "connect",
        }
    }
}

/// A re-entry as the helper: its mode and the mode's own arguments, which are
/// not read as options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Helper {
    pub(crate) mode: HelperMode,
    pub(crate) args: Vec<OsString>,
}

/// A subcommand that sets the Windows sandbox up or takes it down, in place of
/// running a command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Subcommand {
    /// `windows-install`.
    WindowsInstall(InstallOptions),
    /// `windows-uninstall`.
    WindowsUninstall(UninstallOptions),
    /// `-h` or `--help` among a subcommand's options: print [`USAGE`].
    Help,
}

/// Why the command line was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ArgsError {
    /// An option that takes a value was last.
    MissingValue(&'static str),
    /// An option before the command that crabpot does not know.
    UnknownOption(OsString),
    /// Upstream has it and crabpot does not yet.
    Unsupported(&'static str),
    /// No `-c`, and nothing to run.
    NoCommand,
    /// `--crabpot-helper` was followed by a word that names no mode.
    UnknownHelperMode(OsString),
    /// `--loopback` was followed by something other than an IP address or an
    /// `IP:port` socket address.
    InvalidLoopback(OsString),
    /// `--report-started` was followed by something other than a descriptor number.
    InvalidDescriptor(OsString),
}

impl fmt::Display for ArgsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingValue(option) => write!(f, "{option} needs a value"),
            Self::UnknownOption(option) => {
                write!(f, "unknown option {option:?}, put `--` before the command")
            }
            Self::Unsupported(what) => write!(f, "{what} is not supported yet"),
            Self::NoCommand => write!(f, "no command specified"),
            Self::UnknownHelperMode(mode) => write!(f, "unknown helper mode {mode:?}"),
            Self::InvalidLoopback(address) => write!(f, "invalid loopback address {address:?}"),
            Self::InvalidDescriptor(value) => write!(f, "invalid descriptor {value:?}"),
        }
    }
}

impl core::error::Error for ArgsError {}

/// Reads the arguments after the program's name as a helper re-entry. `None`
/// when the first one is not `--crabpot-helper`: it is recognised there and
/// nowhere else, so the arguments of a command the host runs are never read.
pub(crate) fn parse_helper(
    args: impl IntoIterator<Item = OsString>,
) -> Option<Result<Helper, ArgsError>> {
    let mut args = args.into_iter();
    if args.next()? != HELPER_FLAG {
        return None;
    }
    let mode = match args.next() {
        None => return Some(Err(ArgsError::MissingValue(HELPER_FLAG))),
        Some(word) => match word.to_str() {
            Some("init") => HelperMode::Init,
            Some("relay") => HelperMode::Relay,
            Some("connect") => HelperMode::Connect,
            _ => return Some(Err(ArgsError::UnknownHelperMode(word))),
        },
    };
    Some(Ok(Helper {
        mode,
        args: args.collect(),
    }))
}

/// Reads the arguments after the program's name as `windows-install` or
/// `windows-uninstall`. `None` when the first one is neither: the names are
/// recognised there and nowhere else, so a program of that name still runs
/// after `--`.
pub(crate) fn parse_subcommand(
    args: impl IntoIterator<Item = OsString>,
) -> Option<Result<Subcommand, ArgsError>> {
    let mut args = args.into_iter();
    let first = args.next()?;
    match first.to_str()? {
        "windows-install" => Some(parse_install(args)),
        "windows-uninstall" => Some(parse_uninstall(args)),
        _ => None,
    }
}

fn parse_install(mut args: impl Iterator<Item = OsString>) -> Result<Subcommand, ArgsError> {
    let mut options = InstallOptions::default();
    while let Some(arg) = args.next() {
        match flag(&arg, &mut args)? {
            ("-h" | "--help", None) => return Ok(Subcommand::Help),
            ("--allow-loopback", None) => options.allow_loopback = true,
            ("--force", None) => options.force = true,
            ("--sublayer-guid", Some(value)) => options.sublayer_guid = Some(value),
            ("--proxy-port-range", Some(value)) => options.proxy_port_range = Some(value),
            ("--sandbox-user", Some(value)) => options.sandbox_user = Some(value),
            ("--profile-exclude", Some(value)) => options.profile_exclude.push(value),
            ("--skip-profile-grant", None) => options.skip_profile_grant = true,
            _ => return Err(ArgsError::UnknownOption(arg)),
        }
    }
    Ok(Subcommand::WindowsInstall(options))
}

fn parse_uninstall(mut args: impl Iterator<Item = OsString>) -> Result<Subcommand, ArgsError> {
    let mut options = UninstallOptions::default();
    while let Some(arg) = args.next() {
        match flag(&arg, &mut args)? {
            ("-h" | "--help", None) => return Ok(Subcommand::Help),
            ("--keep-user", None) => options.keep_user = true,
            ("--sublayer-guid", Some(value)) => options.sublayer_guid = Some(value),
            _ => return Err(ArgsError::UnknownOption(arg)),
        }
    }
    Ok(Subcommand::WindowsUninstall(options))
}

/// Splits `arg` into an option's name and its value. A value comes from
/// `--name=value`, or from the next argument for the options that take one.
fn flag<'a>(
    arg: &'a OsString,
    rest: &mut impl Iterator<Item = OsString>,
) -> Result<(&'a str, Option<OsString>), ArgsError> {
    const TAKES_VALUE: [&str; 4] = [
        "--sublayer-guid",
        "--proxy-port-range",
        "--sandbox-user",
        "--profile-exclude",
    ];
    let text = arg
        .to_str()
        .ok_or_else(|| ArgsError::UnknownOption(arg.clone()))?;
    if let Some((name, value)) = text.split_once('=')
        && TAKES_VALUE.contains(&name)
    {
        return Ok((name, Some(value.into())));
    }
    match TAKES_VALUE.into_iter().find(|name| *name == text) {
        Some(name) => Ok((
            name,
            Some(rest.next().ok_or(ArgsError::MissingValue(name))?),
        )),
        None => Ok((text, None)),
    }
}

/// The flag that gives `init` the proxy's Unix socket to relay the sandbox's
/// proxy ports to. The sandbox always puts it before the command, and a direct
/// `init` leaves it out to run a command with no relay.
pub(crate) const RELAY_FLAG: &str = "--relay";

/// The flag that adds a loopback address, with an optional TCP relay port.
pub(crate) const LOOPBACK_FLAG: &str = "--loopback";

/// The flag that gives `init` the descriptor the launcher passes published
/// connections to the sandbox on.
pub(crate) const PUBLISH_FD_FLAG: &str = "--publish-fd";

/// Asks the helper to acknowledge startup through the inherited descriptor it names.
pub(crate) const REPORT_STARTED_FLAG: &str = "--report-started";

/// The helper's options and the command's untouched arguments.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Init<'a> {
    pub(crate) report_started: Option<u32>,
    pub(crate) publish_fd: Option<u32>,
    pub(crate) relay: Option<&'a Path>,
    pub(crate) loopback: Vec<IpAddr>,
    pub(crate) tcp: Vec<SocketAddr>,
    pub(crate) command: &'a [OsString],
}

/// Reads helper options until the command or `--` begins its arguments.
pub(crate) fn parse_init(mut args: &[OsString]) -> Result<Init<'_>, ArgsError> {
    let mut report_started = None;
    let mut publish_fd = None;
    let mut relay = None;
    let mut loopback = Vec::new();
    let mut tcp = Vec::new();
    while let Some(arg) = args.first() {
        let flag = match arg.to_str() {
            Some(REPORT_STARTED_FLAG) => REPORT_STARTED_FLAG,
            Some(PUBLISH_FD_FLAG) => PUBLISH_FD_FLAG,
            Some(RELAY_FLAG) => RELAY_FLAG,
            Some(LOOPBACK_FLAG) => LOOPBACK_FLAG,
            Some("--") => {
                args = &args[1..];
                break;
            }
            _ => break,
        };
        let value = args.get(1).ok_or(ArgsError::MissingValue(flag))?;
        if flag == RELAY_FLAG {
            relay = Some(Path::new(value));
        } else if flag == REPORT_STARTED_FLAG || flag == PUBLISH_FD_FLAG {
            let descriptor = value
                .to_str()
                .and_then(|text| text.parse().ok())
                .ok_or_else(|| ArgsError::InvalidDescriptor(value.clone()))?;
            if flag == REPORT_STARTED_FLAG {
                report_started = Some(descriptor);
            } else {
                publish_fd = Some(descriptor);
            }
        } else {
            let text = value.to_string_lossy();
            if let Ok(address) = text.parse::<SocketAddr>() {
                // Several grants may share an address, so a repeat is no error.
                if !tcp.contains(&address) {
                    tcp.push(address);
                }
            } else {
                loopback.push(
                    text.parse()
                        .map_err(|_| ArgsError::InvalidLoopback(value.clone()))?,
                );
            }
        }
        args = &args[2..];
    }
    Ok(Init {
        report_started,
        publish_fd,
        relay,
        loopback,
        tcp,
        command: args,
    })
}

/// Reads the arguments after the program's name. The first one that is not an
/// option begins the command, and everything from there is the command's own.
/// A `-c` line runs instead of any program named beside it, as upstream's does.
/// `-V`, `--version`, `-h` and `--help` before the command ask for the version
/// or the usage, as upstream's do.
pub(crate) fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Parsed, ArgsError> {
    let mut args = args.into_iter();
    let mut settings: Option<PathBuf> = None;
    let mut debug = false;
    let mut control_fd = None;
    let mut shell = None;
    let mut argv = Vec::new();
    while let Some(arg) = args.next() {
        match arg.to_str() {
            Some("-V" | "--version") => return Ok(Parsed::Version),
            Some("-h" | "--help") => return Ok(Parsed::Help),
            Some("-d" | "--debug") => debug = true,
            Some("-s" | "--settings") => {
                settings = Some(args.next().ok_or(ArgsError::MissingValue("-s"))?.into());
            }
            Some("-c") => shell = Some(args.next().ok_or(ArgsError::MissingValue("-c"))?),
            Some("--control-fd") => {
                let value = args.next().ok_or(ArgsError::MissingValue("--control-fd"))?;
                control_fd = Some(control_descriptor(value)?);
            }
            Some("proxy") => return Err(ArgsError::Unsupported("proxy")),
            Some("--") => {
                argv.extend(args.by_ref());
            }
            Some(option) if option.starts_with("--settings=") => {
                settings = Some(option["--settings=".len()..].into());
            }
            Some(option) if option.starts_with("--control-fd=") => {
                control_fd = Some(control_descriptor(option["--control-fd=".len()..].into())?);
            }
            Some(option) if option.starts_with('-') => {
                return Err(ArgsError::UnknownOption(arg));
            }
            _ => {
                argv.push(arg);
                argv.extend(args.by_ref());
            }
        }
    }
    let command = match shell {
        Some(line) => Invocation::Shell(line),
        None if argv.is_empty() => return Err(ArgsError::NoCommand),
        None => Invocation::Argv(argv),
    };
    Ok(Parsed::Run(Args {
        // Upstream tests the option for truthiness, so `-s ""` names no file.
        settings: settings.filter(|path| !path.as_os_str().is_empty()),
        debug,
        control_fd,
        command,
    }))
}

/// The descriptor `--control-fd` names: an integer of 3 or more, since 0, 1
/// and 2 are the command's own streams.
fn control_descriptor(value: OsString) -> Result<i32, ArgsError> {
    value
        .to_str()
        .and_then(|text| text.parse().ok())
        .filter(|&fd| fd >= 3)
        .ok_or(ArgsError::InvalidDescriptor(value))
}

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

    fn parse_strs(args: &[&str]) -> Result<Args, ArgsError> {
        match parse(args.iter().map(OsString::from))? {
            Parsed::Run(args) => Ok(args),
            Parsed::Version | Parsed::Help => panic!("{args:?} asked for no command"),
        }
    }

    fn argv(args: &[&str]) -> Invocation {
        Invocation::Argv(args.iter().map(OsString::from).collect())
    }

    #[test]
    fn the_parser_reads_settings_c_d_and_dash_dash() {
        assert_eq!(
            parse_strs(&["-s", "a.json", "-d", "--", "ls", "-la"]),
            Ok(Args {
                settings: Some("a.json".into()),
                debug: true,
                control_fd: None,
                command: argv(&["ls", "-la"]),
            })
        );
        assert_eq!(
            parse_strs(&["--settings=b.json", "--debug", "-c", "echo hi | cat"]),
            Ok(Args {
                settings: Some("b.json".into()),
                debug: true,
                control_fd: None,
                command: Invocation::Shell("echo hi | cat".into()),
            })
        );
        assert_eq!(
            parse_strs(&["--settings", "c.json", "ls", "-d"]),
            Ok(Args {
                settings: Some("c.json".into()),
                debug: false,
                control_fd: None,
                command: argv(&["ls", "-d"]),
            }),
            "an option after the program is the program's"
        );
        assert_eq!(
            parse_strs(&["--", "-d"]).map(|args| args.command),
            Ok(argv(&["-d"])),
            "`--` lets a program's name look like an option"
        );
    }

    #[test]
    fn version_flags_ask_for_the_version() {
        for flag in ["-V", "--version"] {
            assert_eq!(parse(os(&[flag])), Ok(Parsed::Version));
            assert_eq!(
                parse(os(&["-d", flag])),
                Ok(Parsed::Version),
                "it needs no command"
            );
        }
    }

    #[test]
    fn help_flags_ask_for_the_usage() {
        for flag in ["-h", "--help"] {
            assert_eq!(parse(os(&[flag])), Ok(Parsed::Help));
            assert_eq!(
                parse(os(&["-d", flag])),
                Ok(Parsed::Help),
                "it needs no command"
            );
        }
    }

    #[test]
    fn a_version_or_help_flag_after_the_command_belongs_to_the_command() {
        assert_eq!(
            parse_strs(&["--", "ls", "--version"]).map(|args| args.command),
            Ok(argv(&["ls", "--version"]))
        );
        assert_eq!(
            parse_strs(&["ls", "--version"]).map(|args| args.command),
            Ok(argv(&["ls", "--version"]))
        );
        assert_eq!(
            parse_strs(&["ls", "--help"]).map(|args| args.command),
            Ok(argv(&["ls", "--help"]))
        );
        assert_eq!(
            parse_strs(&["--", "-V"]).map(|args| args.command),
            Ok(argv(&["-V"]))
        );
        assert_eq!(
            parse_strs(&["--", "-h"]).map(|args| args.command),
            Ok(argv(&["-h"]))
        );
    }

    #[test]
    fn an_empty_settings_path_names_no_file() {
        assert_eq!(
            parse_strs(&["-s", "", "ls"]).map(|args| args.settings),
            Ok(None)
        );
        assert_eq!(
            parse_strs(&["--settings=", "ls"]).map(|args| args.settings),
            Ok(None)
        );
    }

    #[test]
    fn a_command_line_that_cannot_run_is_refused() {
        assert_eq!(parse_strs(&[]), Err(ArgsError::NoCommand));
        assert_eq!(parse_strs(&["-d"]), Err(ArgsError::NoCommand));
        assert_eq!(parse_strs(&["-s"]), Err(ArgsError::MissingValue("-s")));
        assert_eq!(
            parse_strs(&["--nope", "ls"]),
            Err(ArgsError::UnknownOption("--nope".into()))
        );
        assert_eq!(
            parse_strs(&["proxy", "start"]),
            Err(ArgsError::Unsupported("proxy"))
        );
    }

    #[test]
    fn control_fd_takes_an_integer_of_three_or_more() {
        for (args, fd) in [
            (&["--control-fd", "3", "ls"][..], 3),
            (&["--control-fd=17", "ls"][..], 17),
        ] {
            assert_eq!(
                parse_strs(args).map(|args| args.control_fd),
                Ok(Some(fd)),
                "{args:?}"
            );
        }
        assert_eq!(parse_strs(&["ls"]).map(|args| args.control_fd), Ok(None));
        assert_eq!(
            parse_strs(&["--control-fd"]),
            Err(ArgsError::MissingValue("--control-fd"))
        );
    }

    #[test]
    fn control_fd_below_three_is_refused() {
        for value in ["0", "2", "-1", "x", "", "3.5"] {
            assert_eq!(
                parse_strs(&["--control-fd", value, "ls"]),
                Err(ArgsError::InvalidDescriptor(value.into())),
                "{value:?}"
            );
        }
        assert_eq!(
            parse_strs(&["--control-fd=1", "ls"]),
            Err(ArgsError::InvalidDescriptor("1".into()))
        );
    }

    fn os(args: &[&str]) -> Vec<OsString> {
        args.iter().map(OsString::from).collect()
    }

    #[test]
    fn the_helper_argument_is_recognised_only_first() {
        assert_eq!(
            parse_helper(os(&["--crabpot-helper", "init", "sh", "-c", "exit 3"])),
            Some(Ok(Helper {
                mode: HelperMode::Init,
                args: os(&["sh", "-c", "exit 3"]),
            }))
        );
        for (mode, name) in [
            (HelperMode::Relay, "relay"),
            (HelperMode::Connect, "connect"),
        ] {
            assert_eq!(
                parse_helper(os(&["--crabpot-helper", name])),
                Some(Ok(Helper { mode, args: vec![] }))
            );
        }
        assert_eq!(parse_helper(os(&["ls", "--crabpot-helper", "init"])), None);
        assert_eq!(
            parse_helper(os(&["--crabpot", "--crabpot-helper", "init"])),
            None,
            "the sandboxed command's own arguments are its own"
        );
        assert_eq!(parse_helper(os(&[])), None);
    }

    #[test]
    fn windows_install_reads_upstreams_flags() {
        assert_eq!(
            parse_subcommand(os(&["windows-install"])),
            Some(Ok(Subcommand::WindowsInstall(InstallOptions::default())))
        );
        assert_eq!(
            parse_subcommand(os(&[
                "windows-install",
                "--allow-loopback",
                "--proxy-port-range",
                "61000-61009",
                "--sandbox-user=ci",
                "--sublayer-guid",
                "{G}",
                "--force",
            ])),
            Some(Ok(Subcommand::WindowsInstall(InstallOptions {
                sublayer_guid: Some("{G}".into()),
                proxy_port_range: Some("61000-61009".into()),
                allow_loopback: true,
                sandbox_user: Some("ci".into()),
                force: true,
                ..InstallOptions::default()
            })))
        );
    }

    #[test]
    fn windows_install_reads_the_profile_grant_flags() {
        assert_eq!(
            parse_subcommand(os(&[
                "windows-install",
                "--profile-exclude",
                r"C:\Users\me\.aws",
                "--profile-exclude=.ssh",
                "--skip-profile-grant",
            ])),
            Some(Ok(Subcommand::WindowsInstall(InstallOptions {
                profile_exclude: vec![r"C:\Users\me\.aws".into(), ".ssh".into()],
                skip_profile_grant: true,
                ..InstallOptions::default()
            })))
        );
        assert_eq!(
            parse_subcommand(os(&["windows-install", "--profile-exclude"])),
            Some(Err(ArgsError::MissingValue("--profile-exclude")))
        );
    }

    #[test]
    fn init_reads_tcp_ports_apart_from_loopback_addresses() {
        let args = os(&[
            "--loopback",
            "10.0.0.7",
            "--loopback",
            "10.0.0.5:5432",
            "--loopback",
            "10.0.0.5:5433",
            "--loopback",
            "[fd00::5]:5432",
            "--",
            "echo",
            "--loopback",
        ]);
        let init = parse_init(&args).unwrap();

        assert_eq!(init.loopback, ["10.0.0.7".parse::<IpAddr>().unwrap()]);
        assert_eq!(
            init.tcp,
            [
                "10.0.0.5:5432".parse::<SocketAddr>().unwrap(),
                "10.0.0.5:5433".parse().unwrap(),
                "[fd00::5]:5432".parse().unwrap()
            ]
        );
        assert_eq!(init.command, os(&["echo", "--loopback"]));
    }

    #[test]
    fn init_reads_repeated_loopback_addresses_before_the_command() {
        let args = os(&[
            "--loopback",
            "10.9.9.9",
            "--loopback",
            "fd00::5",
            "sh",
            "--loopback",
        ]);
        let init = parse_init(&args).unwrap();

        assert_eq!(init.relay, None);
        assert_eq!(
            init.loopback,
            [
                "10.9.9.9".parse::<std::net::IpAddr>().unwrap(),
                "fd00::5".parse().unwrap()
            ]
        );
        assert_eq!(init.command, &args[4..]);
    }

    #[test]
    fn init_reads_loopback_addresses_on_either_side_of_the_relay() {
        let args = os(&[
            "--loopback",
            "10.0.0.5",
            "--relay",
            "proxy.sock",
            "--loopback",
            "::5",
            "echo",
            "ok",
        ]);
        let init = parse_init(&args).unwrap();

        assert_eq!(init.relay, Some(Path::new("proxy.sock")));
        assert_eq!(
            init.loopback,
            [
                "10.0.0.5".parse::<IpAddr>().unwrap(),
                "::5".parse().unwrap()
            ]
        );
        assert_eq!(init.command, &args[6..]);
    }

    #[test]
    fn init_refuses_a_malformed_or_missing_loopback_address() {
        for address in ["10.9.9.999", "10.9.9.9/32", "localhost", ""] {
            assert_eq!(
                parse_init(&os(&["--loopback", address, "sh"])),
                Err(ArgsError::InvalidLoopback(address.into()))
            );
        }
        assert_eq!(
            parse_init(&os(&["--loopback"])),
            Err(ArgsError::MissingValue(LOOPBACK_FLAG))
        );
    }

    #[test]
    fn init_takes_the_startup_descriptor_before_the_command() {
        let args = os(&["--report-started", "12", "--relay", "/s", "--", "sh"]);
        let init = parse_init(&args).unwrap();
        assert_eq!(init.report_started, Some(12));
        assert_eq!(init.command, &args[5..]);

        assert_eq!(parse_init(&os(&["sh"])).unwrap().report_started, None);
    }

    #[test]
    fn init_refuses_a_missing_or_non_numeric_startup_descriptor() {
        assert_eq!(
            parse_init(&os(&["--report-started"])),
            Err(ArgsError::MissingValue(REPORT_STARTED_FLAG))
        );
        for value in ["x", "-1", "", "1.5", "4294967296"] {
            assert_eq!(
                parse_init(&os(&["--report-started", value, "sh"])),
                Err(ArgsError::InvalidDescriptor(value.into()))
            );
        }
    }

    #[test]
    fn init_takes_the_publish_descriptor_before_the_command() {
        let args = os(&["--publish-fd", "7", "--relay", "/s", "--", "sh"]);
        let init = parse_init(&args).unwrap();
        assert_eq!(init.publish_fd, Some(7));
        assert_eq!(init.command, &args[5..]);

        assert_eq!(parse_init(&os(&["sh"])).unwrap().publish_fd, None);
    }

    #[test]
    fn init_refuses_a_missing_or_non_numeric_publish_descriptor() {
        assert_eq!(
            parse_init(&os(&["--publish-fd"])),
            Err(ArgsError::MissingValue(PUBLISH_FD_FLAG))
        );
        for value in ["x", "-1", "", "1.5", "4294967296"] {
            assert_eq!(
                parse_init(&os(&["--publish-fd", value, "sh"])),
                Err(ArgsError::InvalidDescriptor(value.into()))
            );
        }
    }

    #[test]
    fn init_takes_the_relay_socket_before_the_command() {
        let args = os(&["--relay", "/tmp/p.sock", "--", "--relay", "x"]);
        let init = parse_init(&args).unwrap();
        assert_eq!(
            (init.relay, init.command),
            (Some(Path::new("/tmp/p.sock")), &args[3..])
        );

        let args = os(&["sh", "-c", "exit 3"]);
        let init = parse_init(&args).unwrap();
        assert_eq!((init.relay, init.command), (None, &args[..]));
        assert!(init.loopback.is_empty());

        let args = os(&["--relay"]);
        assert_eq!(parse_init(&args), Err(ArgsError::MissingValue(RELAY_FLAG)));
    }

    /// The Linux half spells the re-entry into the `connect` mode for ssh's
    /// `ProxyCommand`, and this is the reader of it: the two spellings are one.
    #[cfg(target_os = "linux")]
    #[test]
    fn the_connect_mode_is_spelled_as_the_parser_reads_it() {
        assert_eq!(
            crabpot_linux::net::ssh::CONNECT_REENTRY,
            format!("{HELPER_FLAG} {}", HelperMode::Connect.word())
        );
    }

    #[test]
    fn windows_uninstall_reads_its_flags() {
        assert_eq!(
            parse_subcommand(os(&[
                "windows-uninstall",
                "--keep-user",
                "--sublayer-guid=G"
            ])),
            Some(Ok(Subcommand::WindowsUninstall(UninstallOptions {
                sublayer_guid: Some("G".into()),
                keep_user: true,
            })))
        );
    }

    #[test]
    fn a_windows_subcommand_refuses_what_it_does_not_know() {
        assert_eq!(
            parse_subcommand(os(&["windows-install", "--keep-user"])),
            Some(Err(ArgsError::UnknownOption("--keep-user".into())))
        );
        assert_eq!(
            parse_subcommand(os(&["windows-uninstall", "--allow-loopback"])),
            Some(Err(ArgsError::UnknownOption("--allow-loopback".into())))
        );
        assert_eq!(
            parse_subcommand(os(&["windows-install", "--sandbox-user"])),
            Some(Err(ArgsError::MissingValue("--sandbox-user")))
        );
        assert_eq!(
            parse_subcommand(os(&["windows-install", "--allow-loopback=yes"])),
            Some(Err(ArgsError::UnknownOption("--allow-loopback=yes".into())))
        );
    }

    #[test]
    fn a_windows_subcommand_answers_help() {
        for name in ["windows-install", "windows-uninstall"] {
            for flag in ["-h", "--help"] {
                assert_eq!(
                    parse_subcommand(os(&[name, flag])),
                    Some(Ok(Subcommand::Help)),
                    "{name} {flag}"
                );
            }
        }
        assert_eq!(
            parse_subcommand(os(&["windows-install", "--sandbox-user", "--help"])),
            Some(Ok(Subcommand::WindowsInstall(InstallOptions {
                sandbox_user: Some("--help".into()),
                ..InstallOptions::default()
            }))),
            "an option's value is not an option"
        );
    }

    #[test]
    fn a_subcommand_is_recognised_only_first() {
        assert_eq!(parse_subcommand(os(&["--", "windows-install"])), None);
        assert_eq!(parse_subcommand(os(&["ls", "windows-install"])), None);
        assert_eq!(parse_subcommand(os(&[])), None);
    }

    #[test]
    fn an_unknown_helper_mode_is_refused() {
        assert_eq!(
            parse_helper(os(&["--crabpot-helper", "nope"])),
            Some(Err(ArgsError::UnknownHelperMode("nope".into())))
        );
        assert_eq!(
            parse_helper(os(&["--crabpot-helper"])),
            Some(Err(ArgsError::MissingValue("--crabpot-helper")))
        );
    }
}