safe-chains 0.243.2

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
use crate::parse::{Token, WordSet};
use crate::verdict::Verdict;

// `git remote`'s read-only allowlist moved to declarative subs in commands/vcs/git.toml (it was pure
// data, no logic). What stays here is the one piece the TOML shape can't express: the `-c
// <key>=<value>` gate. `git -c` can set ANY config for a single invocation, so this is a strict
// ALLOWLIST — only the settings enumerated below are permitted; every other `-c` (any key we have
// not vetted as harmless) is not allowed, and denies by omission. It is deliberately a positive list
// and not a list of blocked keys: an allowlist that omits a key is simply conservative, whereas a
// denylist would fail OPEN the day git adds another config that runs code. That the safe set has to
// be enumerated by hand, and grown as we vet more keys, is the cost of getting this right.

/// Exact `key=value` settings permitted after `-c`: display/UX toggles and safe protocol/init
/// settings that cannot run code, redirect trust, or reach a program path. Namespaces that are safe
/// for ANY value are handled by prefix in `is_allowed_git_c`.
///
/// Nothing here may switch off one of git's own safety checks. `safe.directory` exempts a
/// repository from the ownership check that keeps git from obeying the config, hooks and pager of a
/// repository someone else owns, and `http.sslVerify=false` drops certificate verification. Both
/// were once listed.
static GIT_C_ALLOWED_KV: WordSet = WordSet::new(&[
    "core.askPass=", "core.askPass=false", "core.askpass=", "core.askpass=false", "core.pager=cat", "core.pager=less",
    "credential.helper=", "http.sslVerify=true", "http.sslverify=true", "init.defaultBranch=main", "init.defaultBranch=master",
    "init.defaultBranch=trunk",
]);

/// Settings safe for ANY value, matched on the KEY alone — display and formatting knobs that only
/// change how a diff is rendered.
///
/// Enumerated as exact keys rather than a `diff.` prefix, because that namespace is NOT uniformly
/// safe: `diff.external` and `diff.textconv` run a program of the caller's choosing, `diff.tool`
/// and `diff.guitool` name one for difftool, and `diff.orderFile` reads an arbitrary file. A prefix
/// rule would hand over all five. Three-part driver keys (`diff.<driver>.command`,
/// `diff.<driver>.textconv`) also execute, and an exact two-part match excludes them by shape.
///
/// Keys are lowercased before lookup: git treats the section and variable names case-insensitively,
/// so `diff.noPrefix` and `diff.noprefix` are one setting. A subsection (the middle component of a
/// three-part name) IS case-sensitive, which costs nothing here — no three-part key is listed.
///
/// Verified against git-scm.com/docs/git-config (git 2.53) — none of these executes a program,
/// reads a file, or reaches the network.
static GIT_C_ALLOWED_KEYS: WordSet = WordSet::new(&[
    "diff.algorithm", "diff.colormoved", "diff.colormovedws", "diff.context", "diff.dstprefix", "diff.indentheuristic",
    "diff.interhunkcontext", "diff.mnemonicprefix", "diff.noprefix", "diff.relative", "diff.renames", "diff.srcprefix",
    "diff.statgraphwidth", "diff.submodule", "diff.wordregex", "diff.wserrorhighlight",
]);

/// Whether a `-c key=value` is on the allowlist. Positive by construction: an exact setting above,
/// a key safe for any value, or one of two namespaces safe for any value — `color.*` (output
/// styling) and `advice.*` (hint toggles). Anything else is not on the list.
fn is_allowed_git_c(kv: &str) -> bool {
    if GIT_C_ALLOWED_KV.contains(kv) {
        return true;
    }
    let Some((key, _)) = kv.split_once('=') else {
        return false;
    };
    let key = key.to_ascii_lowercase();
    GIT_C_ALLOWED_KEYS.contains(key.as_str()) || key.starts_with("advice.") || key.starts_with("color.")
}

pub fn is_safe_git(tokens: &[Token]) -> Verdict {
    let mut filtered: Vec<Token> = Vec::with_capacity(tokens.len());
    if let Some(t) = tokens.first() {
        filtered.push(t.clone());
    } else {
        return Verdict::Denied;
    }
    let mut i = 1;
    let mut saw_c = false;
    while i < tokens.len() {
        let t = &tokens[i];
        if t == "-c" {
            let Some(next) = tokens.get(i + 1) else {
                return Verdict::Denied;
            };
            if !is_allowed_git_c(next.as_str()) {
                return Verdict::Denied;
            }
            saw_c = true;
            i += 2;
            continue;
        }
        filtered.push(t.clone());
        i += 1;
    }
    if !saw_c {
        return crate::registry::toml_dispatch(tokens).unwrap_or(Verdict::Denied);
    }
    crate::registry::toml_dispatch(&filtered).unwrap_or(Verdict::Denied)
}

/// Whether git runs in a folder outside the project, where the repository it finds carries
/// configuration no one reviewed: `core.fsmonitor` and `core.pager` name programs git runs. Only
/// `--version`, which reads no repository, is left to run anywhere. A folder that cannot be placed
/// counts as outside.
pub(crate) fn runs_in_a_repository_outside_the_project(tokens: &[Token]) -> bool {
    !only_asks_the_version(tokens) && lands_outside_the_project(crate::pathgate::chdir::landing("git", tokens))
}

/// Whether a tool that opens a repository and obeys its configuration opens one outside the
/// project: branchdiff and tig run git there, hg runs the hooks and extensions its `.hg/hgrc`
/// names, git-lfs and gitleaks call git in it, jj reads the repository's own config (which can name
/// a diff tool, a pager or a fix tool), and jjpr runs jj there. The repository is the folder the
/// tool runs in, or the one it is pointed at: branchdiff's operand, every `tig -C` in turn, each
/// `gitleaks --source`, each `jj -R`. Only asking a tool other than hg or jj for its version or
/// help is left to run anywhere, since hg loads the repository's extensions and jj its config
/// before either reads its options.
pub(crate) fn opens_a_repository_outside_the_project(cmd: &str, tokens: &[Token]) -> bool {
    if !matches!(cmd, "hg" | "jj")
        && tokens.len() == 2
        && matches!(tokens[1].as_str(), "--version" | "-V" | "-v" | "version" | "--help" | "-h")
    {
        return false;
    }
    let words: Vec<&str> = tokens.iter().skip(1).map(Token::as_str).collect();
    let here = crate::pathctx::cwd();
    match cmd {
        "branchdiff" => lands_outside_the_project(match words.iter().copied().find(|word| !word.starts_with('-')) {
            Some(dir) => crate::pathgate::chdir::moved_into(here, dir),
            None => here,
        }),
        "tig" => lands_outside_the_project(flag_values(&words, &["-C"]).into_iter().fold(here, crate::pathgate::chdir::moved_into)),
        "gitleaks" => any_lands_outside(here, &flag_values(&words, &["-s", "--source"])),
        "jj" => any_lands_outside(here, &flag_values(&words, &["-R", "--repository"])),
        _ => lands_outside_the_project(here),
    }
}

fn any_lands_outside(here: Option<String>, dirs: &[&str]) -> bool {
    if dirs.is_empty() {
        return lands_outside_the_project(here);
    }
    dirs.iter()
        .any(|dir| lands_outside_the_project(crate::pathgate::chdir::moved_into(here.clone(), dir)))
}

fn flag_values<'a>(words: &[&'a str], names: &[&str]) -> Vec<&'a str> {
    words
        .iter()
        .enumerate()
        .filter_map(|(at, word)| {
            names.iter().find_map(|name| match word.strip_prefix(name) {
                Some("") => words.get(at + 1).copied(),
                Some(rest) => rest.strip_prefix('=').or(if name.starts_with("--") { None } else { Some(rest) }),
                None => None,
            })
        })
        .collect()
}

fn lands_outside_the_project(dir: Option<String>) -> bool {
    let (Some(root), Some(dir)) = (crate::pathctx::root(), dir) else {
        return false;
    };
    if crate::pathctx::folder::is_unknown(&dir) {
        return false;
    }
    if dir == crate::pathctx::UNRESOLVED_CWD {
        return true;
    }
    let _here = crate::pathctx::enter_cwd(Some(dir));
    let placed = crate::pathctx::resolve(".");
    if placed.starts_with('/')
        && !placed.contains("__SAFE_CHAINS_")
        && (crate::pathctx::placed_in_root(&placed) || crate::engine::resolve::regions::granted_for_writing(&placed))
    {
        return false;
    }
    root.is_empty() || placed.starts_with(['/', '~']) || placed.contains("__SAFE_CHAINS_") || placed.split('/').any(|part| part == "..")
}

fn only_asks_the_version(tokens: &[Token]) -> bool {
    let mut asked = false;
    let mut words = tokens.iter().skip(1).map(Token::as_str);
    while let Some(word) = words.next() {
        match word {
            "-C" | "-c" => {
                words.next();
            }
            "--version" => asked = true,
            _ => return false,
        }
    }
    asked
}

#[cfg(test)]
mod tests {
    use crate::is_safe_command;

    fn check(cmd: &str) -> bool {
        is_safe_command(cmd)
    }

    safe! {
        git_log: "git log --oneline -5",
        git_log_graph: "git log --graph --all --oneline",
        git_log_author: "git log --author=foo --since=2024-01-01",
        git_log_format: "git log --format='%H %s' -n 10",
        git_log_stat: "git log --stat --no-merges",
        git_log_grep_i: "git log --all --oneline --grep=pattern -i",
        git_log_bare: "git log",
        git_diff: "git diff --stat",
        git_diff_cached: "git diff --cached --name-only",
        git_diff_algorithm: "git diff --diff-algorithm=patience",
        git_show: "git show HEAD:some/file.rb",
        git_show_stat: "git show --stat HEAD",
        git_status: "git status --porcelain",
        git_status_short: "git status -sb",
        git_fetch: "git fetch origin master",
        git_fetch_all: "git fetch --all --prune",
        git_ls_tree: "git ls-tree HEAD",
        git_ls_tree_r: "git ls-tree -r --name-only HEAD",
        git_grep: "git grep pattern",
        git_grep_flags: "git grep -n -i --count pattern",
        git_rev_parse: "git rev-parse HEAD",
        git_rev_parse_toplevel: "git rev-parse --show-toplevel",
        git_merge_base: "git merge-base master HEAD",
        git_merge_tree: "git merge-tree HEAD~1 HEAD master",
        git_version: "git --version",
        git_help: "git help log",
        git_shortlog: "git shortlog -s",
        git_shortlog_ne: "git shortlog -sne",
        git_describe: "git describe --tags",
        git_describe_always: "git describe --always --abbrev=7",
        git_blame: "git blame file.rb",
        git_blame_flags: "git blame -L 10,20 -w file.rb",
        git_reflog: "git reflog",
        git_reflog_n: "git reflog -n 10",
        git_ls_files: "git ls-files",
        git_ls_files_others: "git ls-files --others --exclude-standard",
        git_ls_remote: "git ls-remote origin",
        git_ls_remote_tags: "git ls-remote --tags origin",
        git_diff_tree: "git diff-tree --no-commit-id -r HEAD",
        git_cat_file: "git cat-file -p HEAD",
        git_cat_file_t: "git cat-file -t HEAD",
        git_check_ignore: "git check-ignore .jj/",
        git_check_ignore_v: "git check-ignore -v .gitignore",
        git_name_rev: "git name-rev HEAD",
        git_for_each_ref: "git for-each-ref refs/heads",
        git_for_each_ref_format: "git for-each-ref --format='%(refname)' --sort=-committerdate",
        git_count_objects: "git count-objects -v",
        git_verify_commit: "git verify-commit HEAD",
        git_verify_tag: "git verify-tag v1.0",
        git_merge_base_all: "git merge-base --all HEAD main",
        git_c_flag: "git -C /some/repo diff --stat",
        git_c_nested: "git -C /some/repo -C nested log",
        git_config_askpass_disable: "git -c core.askPass=false ls-remote https://github.com/foo/bar",
        git_config_askpass_empty: "git -c core.askPass= ls-remote https://github.com/foo/bar",
        git_config_askpass_lower: "git -c core.askpass=false fetch origin",
        git_config_credential_helper_empty: "git -c credential.helper= ls-remote origin",
        git_config_advice: "git -c advice.detachedHead=false log HEAD",
        git_config_color_ui: "git -c color.ui=never status",
        git_config_pager_cat: "git -c core.pager=cat log",
        git_config_sslverify_true: "git -c http.sslVerify=true fetch origin",
        git_config_init_default_branch: "git -c init.defaultBranch=main ls-remote origin",
        git_config_multiple_c: "git -c core.askPass=false -c credential.helper= ls-remote origin",
        git_config_lower_c_with_upper_c: "git -C /repo -c core.askPass=false log",
        git_c_diff_mnemonic_prefix: "git -c diff.mnemonicPrefix=false diff main -- src/x.rs",
        git_c_diff_noprefix: "git -c diff.noprefix=false diff main",
        git_c_diff_both_prefixes: "git -c diff.mnemonicPrefix=false -c diff.noprefix=false diff main -- src/x.rs",
        git_c_diff_key_case_insensitive: "git -c DIFF.NOPREFIX=true diff",
        git_c_diff_algorithm: "git -c diff.algorithm=histogram diff",
        git_c_diff_context: "git -c diff.context=10 diff",
        git_c_diff_color_moved: "git -c diff.colorMoved=zebra diff",
        git_c_diff_src_prefix: "git -c diff.srcPrefix=old/ -c diff.dstPrefix=new/ diff",
        git_c_diff_relative: "git -c diff.relative=true diff",
        git_c_diff_renames: "git -c diff.renames=copies diff",
        git_c_diff_indent_heuristic: "git -c diff.indentHeuristic=true diff",
        git_c_diff_word_regex: "git -c diff.wordRegex=. diff --word-diff",
        git_c_diff_submodule: "git -c diff.submodule=log diff",
        git_c_diff_ws_error_highlight: "git -c diff.wsErrorHighlight=all diff",
        git_remote_bare: "git remote",
        git_remote_v: "git remote -v",
        git_remote_get_url: "git remote get-url origin",
        git_remote_show: "git remote show origin",
        git_branch_list: "git branch",
        git_branch_list_all: "git branch -a",
        git_branch_list_verbose: "git branch -v",
        git_branch_contains: "git branch --contains abc123",
        git_stash_list: "git stash list",
        git_stash_show: "git stash show -p",
        git_tag_list: "git tag",
        git_tag_list_pattern: "git tag -l 'v1.*'",
        git_tag_list_long: "git tag --list",
        git_config_list: "git config --list",
        git_config_get: "git config --get user.name",
        git_config_get_all: "git config --get-all remote.origin.url",
        git_config_get_regexp: "git config --get-regexp 'remote.*'",
        git_config_l: "git config -l",
        git_config_local_list: "git config --local --list",
        git_config_global_list: "git config --global --list",
        git_config_system_l: "git config --system -l",
        git_config_local_get: "git config --local --get user.name",
        git_config_file_list: "git config --file .gitconfig --list",
        git_config_f_list: "git config -f .gitconfig -l",
        git_config_show_origin_list: "git config --show-origin --list",
        git_config_show_scope_local_list: "git config --show-scope --local --list",
        git_config_name_only_list: "git config --name-only --list",
        git_config_worktree_list: "git config --worktree -l",
        git_config_blob_get: "git config --blob HEAD:.gitmodules --get submodule.foo.url",
        git_config_local_help: "git config --local --help",
        git_worktree_list: "git worktree list",
        git_worktree_list_porcelain: "git worktree list --porcelain",
        git_worktree_list_verbose: "git worktree list -v",
        git_notes_show: "git notes show HEAD",
        git_notes_list: "git notes list",
        git_worktree_help: "git worktree --help",
        git_worktree_help_h: "git worktree -h",
        git_rebase_help: "git rebase --help",
    }

    denied! {
        git_grep_open_files_in_pager_denied: "git grep -Otouch pat",
        git_grep_open_files_in_pager_spaced_denied: "git grep -O touch pat",
        git_grep_open_files_in_pager_long_denied: "git grep --open-files-in-pager=touch pat",
        git_grep_no_index_denied: "git grep --no-index x /etc/passwd",
        git_grep_no_index_dash_c_denied: "git -C /tmp grep --no-index x",
        // The `diff.` namespace is NOT uniformly safe, which is why the display keys are listed
        // exactly rather than by prefix. Each of these runs a program or reads a file, and each
        // would be reachable the moment `diff.*` became a prefix rule.
        git_c_diff_external_denied: "git -c diff.external=/tmp/evil.sh diff",
        git_c_diff_textconv_denied: "git -c diff.textconv=/tmp/evil.sh diff",
        git_c_diff_tool_denied: "git -c diff.tool=evil difftool",
        git_c_diff_guitool_denied: "git -c diff.guitool=evil difftool",
        git_c_diff_order_file_denied: "git -c diff.orderFile=/etc/shadow diff",
        // A three-part driver key executes too, and must not be reached by the two-part match.
        git_c_diff_driver_command_denied: "git -c diff.mydriver.command=/tmp/evil.sh diff",
        git_c_diff_driver_textconv_denied: "git -c diff.myDriver.textconv=/tmp/evil.sh diff",
        // Vetting display keys must not have widened `-c` generally.
        git_c_core_ssh_command_denied: "git -c core.sshCommand=/tmp/evil.sh diff",
        git_c_alias_shell_denied: "git -c alias.x=!/tmp/evil.sh diff",
        git_c_core_editor_denied: "git -c core.editor=/tmp/evil.sh diff",
        git_c_unvetted_diff_key_denied: "git -c diff.notARealKey=1 diff",
        // (`git rebase --help` moved to the safe set when rebase gained a facet profile — it is a
        // supported sub now, so its help form is an ordinary read.)
        git_push_help_denied: "git push --help",
        git_fetch_upload_pack_denied: "git fetch --upload-pack=malicious origin",
        git_ls_remote_upload_pack_denied: "git ls-remote --upload-pack malicious origin",
        git_tag_delete_denied: "git tag -d v1.0",
        git_tag_annotate_denied: "git tag -a v1.0 -m 'release'",
        git_tag_sign_denied: "git tag -s v1.0",
        git_tag_force_denied: "git tag -f v1.0",
        git_config_set_denied: "git config user.name foo",
        git_config_unset_denied: "git config --unset user.name",
        git_config_local_set_denied: "git config --local user.name foo",
        git_config_local_unset_denied: "git config --local --unset user.name",
        git_config_local_evil_list_denied: "git config --local --evil --list",
        git_config_list_trailing_flag_denied: "git config --list --evil",
        git_config_get_trailing_flag_denied: "git config --get user.name --evil",
        git_worktree_add_denied: "git worktree add ../new-branch",
        git_worktree_list_trailing_denied: "git worktree list --evil",
        git_notes_list_trailing_flag_denied: "git notes list --evil",
        git_branch_d_denied: "git branch -D feature",
        git_branch_delete_denied: "git branch --delete feature",
        git_branch_move_denied: "git branch -m old new",
        git_branch_copy_denied: "git branch -c old new",
        git_branch_set_upstream_denied: "git branch --set-upstream-to=origin/main",
        git_remote_add_denied: "git remote add upstream https://github.com/foo/bar",
        git_remote_remove_denied: "git remote remove upstream",
        git_remote_rename_denied: "git remote rename origin upstream",
        // Allowlist conversion closes the fail-open holes the old denylist had:
        git_remote_rm_alias_denied: "git remote rm upstream",   // alias of `remove`, was allowed
        git_remote_set_head_denied: "git remote set-head origin -a",
        git_remote_set_url_denied: "git remote set-url origin https://x",
        git_remote_prune_denied: "git remote prune origin",
        git_remote_update_denied: "git remote update",
        git_remote_unknown_sub_denied: "git remote frobnicate",
        git_config_flag_denied: "git -c user.name=foo log",
        git_config_editor_denied: "git -c core.editor=vim commit",
        git_config_ssh_command_denied: "git -c core.sshCommand=evil ls-remote origin",
        git_config_alias_denied: "git -c alias.evil=push log",
        git_config_hooks_path_denied: "git -c core.hooksPath=/tmp log",
        git_config_pager_arbitrary_denied: "git -c core.pager=evil log",
        git_config_no_value_denied: "git -c log",
        git_config_safe_directory_denied: "git -c safe.directory=/repo status",
        git_config_safe_directory_star_denied: "git -c safe.directory=* log",
        git_config_sslverify_false_denied: "git -c http.sslVerify=false fetch origin",
        git_config_parameters_env_denied: "GIT_CONFIG_PARAMETERS=\"'safe.directory'='*'\" git log",
        git_help_bypass_denied: "git push -- --help",
    }
}

#[cfg(test)]
mod properties {
    use super::{GIT_C_ALLOWED_KEYS, GIT_C_ALLOWED_KV, is_allowed_git_c};
    use crate::is_safe_command;
    use proptest::prelude::*;

    /// git settings that switch off one of git's own safety checks, with values that do it. The
    /// middle component of a three-part key is a subsection, which git matches case-sensitively, so
    /// only the section and the variable are re-cased below.
    const SAFETY_SWITCHES: &[(&str, &[&str])] = &[
        ("safe.directory", &["*", "/repo", ".", "/tmp/x", "%(prefix)/repo"]),
        ("safe.bareRepository", &["all"]),
        ("http.sslVerify", &["false", "0", "no", "off"]),
        ("http.https://example.com.sslVerify", &["false"]),
        ("http.sslCAInfo", &["/tmp/ca.pem"]),
        ("protocol.allow", &["always"]),
        ("protocol.ext.allow", &["always"]),
        ("protocol.file.allow", &["always"]),
        ("core.fsmonitor", &["/tmp/x", "true"]),
        ("core.hooksPath", &["/tmp/hooks"]),
        ("core.protectNTFS", &["false"]),
        ("core.protectHFS", &["false"]),
        ("transfer.fsckObjects", &["false"]),
        ("fetch.fsckObjects", &["false"]),
        ("receive.fsckObjects", &["false"]),
    ];

    /// Every way a caller can hand git one setting for one invocation.
    const ROUTES: &[&str] = &[
        "git -c {kv} {sub}",
        "git -c '{kv}' {sub}",
        "git -C . -c {kv} {sub}",
        "git -c color.ui=never -c {kv} {sub}",
        "git --config-env={k}=SC_V {sub}",
        "git --config-env {k}=SC_V {sub}",
        "SC_V='{v}' git --config-env={k}=SC_V {sub}",
        "GIT_CONFIG_PARAMETERS=\"'{k}'='{v}'\" git {sub}",
        "export GIT_CONFIG_PARAMETERS=\"'{k}'='{v}'\"; git {sub}",
        "env GIT_CONFIG_PARAMETERS=\"'{k}'='{v}'\" git {sub}",
        "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0={k} GIT_CONFIG_VALUE_0='{v}' git {sub}",
        "export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0={k} GIT_CONFIG_VALUE_0='{v}'; git {sub}",
    ];

    const SUBS: &[&str] = &["log", "status", "diff", "show HEAD", "fetch origin", "ls-remote origin", "rev-parse HEAD"];

    fn recase(key: &str, flips: &[bool]) -> String {
        let parts: Vec<&str> = key.split('.').collect();
        let last = parts.len() - 1;
        let mut flip = flips.iter().cycle();
        let mut out: Vec<String> = Vec::with_capacity(parts.len());
        for (i, part) in parts.iter().enumerate() {
            if i == 0 || i == last {
                out.push(
                    part.chars()
                        .map(|c| if *flip.next().unwrap_or(&false) { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() })
                        .collect(),
                );
            } else {
                out.push((*part).to_string());
            }
        }
        out.join(".")
    }

    proptest! {
        /// No spelling of a setting that switches off a git safety check is approved, whatever its
        /// case, its value, the route that carries it or the subcommand it rides on.
        #[test]
        fn no_route_to_git_config_switches_off_a_safety_check(
            switch in proptest::sample::select(SAFETY_SWITCHES.to_vec()),
            value_pick in any::<proptest::sample::Index>(),
            flips in proptest::collection::vec(any::<bool>(), 1..24),
            route in proptest::sample::select(ROUTES.to_vec()),
            sub in proptest::sample::select(SUBS.to_vec()),
        ) {
            let (key, values) = switch;
            let k = recase(key, &flips);
            let v = values[value_pick.index(values.len())];
            let kv = format!("{k}={v}");
            let line = route.replace("{kv}", &kv).replace("{k}", &k).replace("{v}", v).replace("{sub}", sub);
            prop_assert!(!is_allowed_git_c(&kv), "`-c {}` is on the -c allowlist", kv);
            prop_assert!(!is_safe_command(&line), "a git safety check can be switched off: `{}`", line);
        }
    }

    /// The allowlist itself, entry by entry, so a later addition cannot name a safety switch the
    /// table above does not know: no listed setting turns off a check by name (`*verify*`,
    /// `*fsck*`, `*protect*`) or touches the `safe.` and `protocol.` sections that hold them.
    #[test]
    fn the_c_allowlist_names_no_safety_switch() {
        let disabling = ["false", "0", "no", "off"];
        for kv in GIT_C_ALLOWED_KV.iter() {
            let (key, value) = kv.split_once('=').unwrap_or((kv, ""));
            let key = key.to_ascii_lowercase();
            let checks = key.contains("verify") || key.contains("fsck") || key.contains("protect");
            assert!(!(checks && disabling.contains(&value)), "`{kv}` switches off a check");
            assert!(!key.starts_with("safe.") && !key.starts_with("protocol."), "`{kv}` is in a safety section");
        }
        for key in GIT_C_ALLOWED_KEYS.iter() {
            assert!(
                !["verify", "fsck", "protect", "safe.", "protocol.", "fsmonitor", "hookspath"]
                    .iter()
                    .any(|n| key.contains(n)),
                "`{key}` is allowed for any value and names a safety switch"
            );
        }
        for (key, _) in SAFETY_SWITCHES {
            assert!(!is_allowed_git_c(&format!("{key}=x")), "`{key}` is allowed for any value");
        }
    }
}