devsandbox 0.11.1

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! The one way the host runs git on a sandbox's repo.
//!
//! A sandbox bind-mounts the repo (and, for worktree instances, the base
//! repo's `.git`) read-write, so anything in the container can write
//! `.git/config` and `.git/hooks`. Host git reads both: a planted hook, or a
//! config key such as `core.fsmonitor`, `core.sshCommand`, a filter driver or
//! `include.path`, would run as the host user during `worktree add`, `fetch`,
//! `worktree remove`, … — and dispatchers let a container trigger those calls
//! itself. [`host_git`] therefore disables hooks and fsmonitor on the command
//! line and refuses repos whose local config holds anything outside a small
//! allowlist of keys known not to run commands. The config is read as files,
//! never via `git config`, which would follow includes.
//!
//! The same container can also *point* host git elsewhere: a `gitdir:` file
//! or `commondir` naming another host repo, or a symlink in the git dir
//! (`refs/heads`, `objects`, `index`, …) redirecting its reads and writes.
//! So a `.git` symlink is refused, a `gitdir:` file only accepted when it is
//! a linked worktree git itself made (`<common>/worktrees/<name>` whose
//! `gitdir` back-pointer names this checkout), `commondir` only in such an
//! admin dir, and no symlink may sit in the git dirs where git looks
//! ([`symlink_refusal`]).
//!
//! A sandbox also writes the checkout's `.gitattributes`: `filter=<name>`
//! there makes a host checkout (`worktree add`, `reset --hard`, …) run a
//! filter driver the *user's* global or system config defines, git-lfs
//! included (which then fetches with the user's credentials from a URL the
//! sandbox's `.lfsconfig` names). The repo's own `filter.*` keys are refused
//! above; for the rest every host git gets `GIT_LFS_SKIP_SMUDGE=1` and, per
//! driver name in those configs ([`filter_args`]), overrides that make it
//! pass content through unchanged.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::OnceLock;

use anyhow::{bail, Context, Result};

/// A `git` command for `repo`: its local config checked first (see the module
/// docs), hooks and fsmonitor off, no stdin and no credential prompts.
pub(crate) fn host_git(repo: &Path) -> Result<Command> {
    check_repo(repo)?;
    Ok(git_command(repo))
}

/// A `git` command for the bare repo `dir` (a repo devsandbox keeps for
/// itself, as the fleet's repo cache): `dir` is the git dir, its `config`
/// and alternates checked as [`check_repo`] checks a checkout's, symlinks and
/// `commondir` refused as in a checkout's main git dir, hooks and fsmonitor
/// off as [`host_git`]'s.
pub(crate) fn host_git_bare(dir: &Path) -> Result<Command> {
    check_dirs(dir, dir, dir)?;
    let mut cmd = Command::new("git");
    cmd.args(SAFE_ARGS).args(filter_args()).arg("--git-dir").arg(dir);
    Ok(safe_env(cmd))
}

/// A `git` command in `dir`, which holds no repo yet (for `git init`): with
/// no `.git` there is no repo config to check. Refused when `dir` has a
/// `.git` (use [`host_git`]) or isn't a dir.
pub(crate) fn host_git_new(dir: &Path) -> Result<Command> {
    if !dir.is_dir() {
        bail!("refusing to run git in {}: not a directory", dir.display());
    }
    if dir.join(".git").symlink_metadata().is_ok() {
        bail!("refusing to run git in {}: it holds a .git already", dir.display());
    }
    Ok(git_command(dir))
}

/// What every host git gets on its command line: hooks and fsmonitor off.
const SAFE_ARGS: [&str; 4] = ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"];

fn git_command(repo: &Path) -> Command {
    let mut cmd = Command::new("git");
    cmd.args(SAFE_ARGS).args(filter_args()).arg("-C").arg(repo);
    safe_env(cmd)
}

/// No stdin, no credential prompts, no LFS downloads, no env pointing git at
/// another repo; the values [`neutral_filter_args`] reads.
fn safe_env(mut cmd: Command) -> Command {
    cmd.stdin(Stdio::null())
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_LFS_SKIP_SMUDGE", "1")
        .envs(FILTER_VALUES);
    // These would make git use another repo than the one `check_repo` read.
    for var in ["GIT_DIR", "GIT_COMMON_DIR", "GIT_WORK_TREE"] {
        cmd.env_remove(var);
    }
    cmd
}

/// The [`neutral_filter_args`] of the user's global and system filter
/// drivers, read once per process.
fn filter_args() -> &'static [String] {
    static ARGS: OnceLock<Vec<String>> = OnceLock::new();
    ARGS.get_or_init(|| neutral_filter_args(&user_filter_names(&[])))
}

/// `--config-env` values: `-c` splits at the first `=`, and a filter name may
/// hold one; `--config-env` splits at the last.
const FILTER_VALUES: [(&str, &str); 3] =
    [("DEVSANDBOX_GIT_EMPTY", ""), ("DEVSANDBOX_GIT_CAT", "cat"), ("DEVSANDBOX_GIT_FALSE", "false")];

/// Overrides that make each filter driver in `names` inert. An empty
/// `process` is what disables it: git (convert.c `apply_filter`) skips
/// `smudge`/`clean` whenever `process` is set, then applies nothing when it
/// is empty, spawning no command; `required=false` makes that a pass-through
/// instead of an error. `smudge`/`clean` = `cat` keep it inert were an empty
/// `process` ever read as unset.
fn neutral_filter_args(names: &BTreeSet<String>) -> Vec<String> {
    let [(empty, _), (cat, _), (no, _)] = FILTER_VALUES;
    names
        .iter()
        .flat_map(|name| {
            [("smudge", cat), ("clean", cat), ("process", empty), ("required", no)]
                .map(|(key, var)| format!("--config-env=filter.{name}.{key}={var}"))
        })
        .collect()
}

/// The filter driver names the user's global and system config define
/// (includes followed), with `env` added to git's: never a repo's config,
/// which names none ([`refusal`]). A scope with no filters, or no file, has
/// none.
fn user_filter_names(env: &[(&str, &std::ffi::OsStr)]) -> BTreeSet<String> {
    let mut names = BTreeSet::new();
    for scope in ["--global", "--system"] {
        let mut cmd = safe_env(Command::new("git"));
        cmd.args(["config", scope, "--includes", "-z", "--name-only", "--get-regexp", r"^filter\."])
            .current_dir("/")
            .envs(env.iter().copied())
            .stderr(Stdio::null());
        if let Some(out) = cmd.output().ok().filter(|out| out.status.success()) {
            names.extend(parse_filter_names(&out.stdout));
        }
    }
    names
}

/// The `<name>` of each NUL-terminated `filter.<name>.<key>`; `<name>` may
/// hold dots.
fn parse_filter_names(out: &[u8]) -> BTreeSet<String> {
    out.split(|b| *b == 0)
        .filter_map(|key| String::from_utf8_lossy(key).strip_prefix("filter.")?.rsplit_once('.').map(|(name, _)| name.to_string()))
        .filter(|name| !name.is_empty())
        .collect()
}

/// Refuse `repo` when its local config (or an alternates file) could make
/// host git run commands or read objects from elsewhere, or when its git
/// dirs point host git at another repo or files (see the module docs).
pub(crate) fn check_repo(repo: &Path) -> Result<()> {
    let (gitdir, common) = git_dirs(repo)?;
    check_dirs(repo, &gitdir, &common)
}

/// The repo at `repo`'s identity for origin trust and the origin URL its
/// config holds now, after [`check_repo`]'s checks.
pub(crate) struct Origin {
    /// The canonical common dir: every checkout of one repo shares it.
    pub common: PathBuf,
    /// `None`: no `remote.origin.url`.
    pub url: Option<String>,
}

/// Read `repo`'s [`Origin`] from the common dir's `config` as a file, never
/// via `git config`.
pub(crate) fn read_origin(repo: &Path) -> Result<Origin> {
    let (gitdir, common) = git_dirs(repo)?;
    check_dirs(repo, &gitdir, &common)?;
    let config = common.join("config");
    let url = match std::fs::read(&config) {
        Ok(bytes) => {
            let entries = parse_config(&String::from_utf8_lossy(&bytes))
                .map_err(|why| anyhow::anyhow!("cannot parse {} ({why})", config.display()))?;
            origin_url(&entries)
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(e).with_context(|| format!("cannot read {}", config.display())),
    };
    let common = common.canonicalize().with_context(|| format!("cannot resolve {}", common.display()))?;
    Ok(Origin { common, url })
}

/// The biggest repo config [`read_remotes`] reads.
const MAX_CONFIG: u64 = 1 << 20;

/// Every `[remote "<name>"]` in `repo`'s common dir `config`, its `url` and
/// `pushurl` values kept where `keep` says, a remote left with none dropped.
/// Data only, for a checkout a sandbox may have written: the git dirs
/// resolved as [`check_repo`] resolves them, but no key refused, the file
/// opened without following a symlink, at most [`MAX_CONFIG`] bytes, and
/// `include.path`/`includeIf` never followed (git reads them; the record
/// doesn't). `Ok(empty)` when there's no `config`.
pub(crate) fn read_remotes(repo: &Path, keep: impl Fn(&str) -> bool) -> Result<Vec<crate::state::FolderRemote>> {
    let (_, common) = git_dirs(repo)?;
    let config = common.join("config");
    let bytes = match read_regular(&config) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e).with_context(|| format!("cannot read {}", config.display())),
    };
    let entries = parse_config(&String::from_utf8_lossy(&bytes))
        .map_err(|why| anyhow::anyhow!("cannot parse {} ({why})", config.display()))?;
    Ok(remotes_of(&entries, keep))
}

/// `path`'s bytes if it is a regular file, not a symlink (`ELOOP`), at most
/// [`MAX_CONFIG`] bytes. Non-blocking open: a FIFO planted there is
/// refused, not waited on.
fn read_regular(path: &Path) -> std::io::Result<Vec<u8>> {
    use std::io::{Error, ErrorKind, Read};
    let mut options = std::fs::File::options();
    options.read(true);
    #[cfg(unix)]
    std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_NOFOLLOW | libc::O_NONBLOCK);
    #[cfg(not(unix))]
    if std::fs::symlink_metadata(path)?.is_symlink() {
        return Err(Error::other("a symlink"));
    }
    let file = options.open(path)?;
    let meta = file.metadata()?;
    if !meta.is_file() {
        return Err(Error::other("not a regular file"));
    }
    if meta.len() > MAX_CONFIG {
        return Err(Error::new(ErrorKind::InvalidData, format!("bigger than {MAX_CONFIG} bytes")));
    }
    let mut bytes = Vec::new();
    file.take(MAX_CONFIG + 1).read_to_end(&mut bytes)?;
    if bytes.len() as u64 > MAX_CONFIG {
        return Err(Error::new(ErrorKind::InvalidData, format!("bigger than {MAX_CONFIG} bytes")));
    }
    Ok(bytes)
}

/// [`read_remotes`] over parsed entries: remotes in first-seen order, values
/// in file order, empty values (git's list reset) skipped.
fn remotes_of(entries: &[Entry], keep: impl Fn(&str) -> bool) -> Vec<crate::state::FolderRemote> {
    let mut out: Vec<crate::state::FolderRemote> = Vec::new();
    for e in entries.iter().filter(|e| e.section == "remote") {
        let (Some(name), Some(value)) = (&e.subsection, e.value.as_deref().filter(|v| !v.is_empty())) else {
            continue;
        };
        if !matches!(e.key.as_str(), "url" | "pushurl") || !keep(value) {
            continue;
        }
        let i = match out.iter().position(|r| &r.name == name) {
            Some(i) => i,
            None => {
                out.push(crate::state::FolderRemote { name: name.clone(), ..Default::default() });
                out.len() - 1
            }
        };
        let list = if e.key == "url" { &mut out[i].urls } else { &mut out[i].pushurls };
        list.push(value.to_string());
    }
    out
}

/// The URL `git fetch origin` would use: a remote's *first* `url` (more are
/// push-only targets), unlike most keys, where the last wins. The legacy
/// `[remote.Origin]` form names `origin` too: the parser lowercases it.
fn origin_url(entries: &[Entry]) -> Option<String> {
    entries
        .iter()
        .find(|e| e.section == "remote" && e.subsection.as_deref() == Some("origin") && e.key == "url")
        .and_then(|e| e.value.clone())
}

/// [`check_repo`] over a known git dir and common dir (`repo` names them in
/// messages).
fn check_dirs(repo: &Path, gitdir: &Path, common: &Path) -> Result<()> {
    let refuse = |what: String| -> anyhow::Error {
        anyhow::anyhow!("refusing to run git on {}: {what}", repo.display())
    };
    let shown = |p: &Path| p.strip_prefix(repo).unwrap_or(p).display().to_string();
    let commondir = gitdir.join("commondir");
    if gitdir == common && commondir.symlink_metadata().is_ok() {
        return Err(refuse(format!(
            "{} exists in a main git dir, which points host git at another repo; a sandbox may \
             have written it — review and remove it",
            shown(&commondir)
        )));
    }
    if let Some(link) = symlink_refusal(gitdir, common).map_err(|e| refuse(format!("{e:#}")))? {
        return Err(refuse(format!(
            "{} is a symlink, which points host git at files outside the repo; a sandbox may \
             have written it — review and remove it",
            shown(&link)
        )));
    }
    let alternates = common.join("objects/info/alternates");
    if alternates.symlink_metadata().is_ok() {
        return Err(refuse(format!(
            "{} exists, which points host git at another object store; a sandbox may have \
             written it — review and remove it",
            shown(&alternates)
        )));
    }
    for file in config_files(gitdir, common).map_err(|e| refuse(format!("{e:#}")))? {
        let bytes = match std::fs::read(&file) {
            Ok(b) => b,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => return Err(refuse(format!("cannot read {}: {e}", shown(&file)))),
        };
        let entries = parse_config(&String::from_utf8_lossy(&bytes)).map_err(|why| {
            refuse(format!("cannot parse {} ({why}); review and fix it by hand", shown(&file)))
        })?;
        if let Some(what) = entries.iter().find_map(refusal) {
            return Err(refuse(format!(
                "{} sets {what}, which can run commands on the host; a sandbox may have \
                 written it — review and remove it",
                shown(&file)
            )));
        }
    }
    Ok(())
}

/// `(gitdir, common dir)` of the checkout at `repo`, found the way git does
/// for `git -C repo` without running it: `<repo>/.git` is the git dir (its
/// own common dir), or a `gitdir: <path>` file pointing at a linked
/// worktree's admin dir `<common>/worktrees/<name>`, accepted only when that
/// dir's `gitdir` back-pointer names this `.git` and its `commondir` names
/// `<common>`. Anything else (no `.git`, a `.git` symlink, a bare repo, a
/// `gitdir:` file git didn't write for this checkout) is refused rather than
/// guessed at. A linked worktree's dirs come back canonical.
fn git_dirs(repo: &Path) -> Result<(PathBuf, PathBuf)> {
    let refuse = |what: String| anyhow::anyhow!("refusing to run git on {}: {what}", repo.display());
    let dotgit = repo.join(".git");
    let meta = std::fs::symlink_metadata(&dotgit).map_err(|_| refuse("no .git found".into()))?;
    if meta.is_symlink() {
        return Err(refuse(
            ".git is a symlink, which points host git at another repo; a sandbox may have written \
             it — review and remove it"
                .into(),
        ));
    }
    if meta.is_dir() {
        return Ok((dotgit.clone(), dotgit));
    }
    let text = std::fs::read_to_string(&dotgit).with_context(|| format!("cannot read {}", dotgit.display()))?;
    let Some(path) = text.strip_prefix("gitdir:").map(str::trim) else {
        bail!("refusing to run git on {}: .git is not a `gitdir:` file", repo.display());
    };
    let unlinked = |why: &str| {
        refuse(format!(
            ".git points at {path}, {why}; a sandbox may have written it — review and remove it"
        ))
    };
    let gitdir = repo
        .join(path)
        .canonicalize()
        .map_err(|e| unlinked(&format!("which cannot be resolved ({e})")))?;
    let common = match gitdir.parent() {
        Some(worktrees) if worktrees.file_name().is_some_and(|n| n == "worktrees") => worktrees.parent(),
        _ => None,
    }
    .ok_or_else(|| unlinked("which is not a linked worktree's `<repo>/worktrees/<name>` dir"))?
    .to_path_buf();
    let resolves_to = |file: &str, want: &Path| -> bool {
        std::fs::read_to_string(gitdir.join(file))
            .ok()
            .and_then(|text| gitdir.join(text.trim()).canonicalize().ok())
            .is_some_and(|p| p == want)
    };
    let this = dotgit.canonicalize().with_context(|| format!("cannot resolve {}", dotgit.display()))?;
    if !resolves_to("gitdir", &this) {
        return Err(unlinked("whose `gitdir` back-pointer does not name this checkout"));
    }
    if !resolves_to("commondir", &common) {
        return Err(unlinked(&format!("whose `commondir` does not name {}", common.display())));
    }
    Ok((gitdir, common))
}

/// The first symlink where git would follow it into another file: a direct
/// entry of `gitdir` or `common`, anything under their `refs/`, or a direct
/// entry of `objects/`, `objects/info/`, `objects/pack/`. Loose objects
/// aren't walked: too many, and a redirected one only fails to inflate.
fn symlink_refusal(gitdir: &Path, common: &Path) -> Result<Option<PathBuf>> {
    // Breadth first: a dir is listed only after its parent's entry was seen
    // not to be a symlink.
    let mut dirs = std::collections::VecDeque::from([(gitdir.to_path_buf(), false)]);
    if common != gitdir {
        dirs.push_back((common.to_path_buf(), false));
    }
    for sub in ["objects", "objects/info", "objects/pack"] {
        dirs.push_back((common.join(sub), false));
    }
    // A symlinked reflog makes host git append to any host file.
    for sub in ["refs", "logs"] {
        dirs.push_back((gitdir.join(sub), true));
        if common != gitdir {
            dirs.push_back((common.join(sub), true));
        }
    }
    while let Some((dir, recurse)) = dirs.pop_front() {
        let entries = match std::fs::read_dir(&dir) {
            Ok(entries) => entries,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => return Err(e).with_context(|| format!("cannot list {}", dir.display())),
        };
        for entry in entries {
            let entry = entry.with_context(|| format!("cannot list {}", dir.display()))?;
            let kind = entry.file_type().with_context(|| format!("cannot stat {}", entry.path().display()))?;
            if kind.is_symlink() {
                return Ok(Some(entry.path()));
            }
            if recurse && kind.is_dir() {
                dirs.push_back((entry.path(), true));
            }
        }
    }
    Ok(None)
}

/// Every config file git may read for any checkout of this repo: the shared
/// `config`, the main worktree's `config.worktree`, each linked worktree's
/// `config.worktree`, and the current git dir's own if it lives elsewhere.
/// Missing ones are skipped by the reader.
fn config_files(gitdir: &Path, common: &Path) -> Result<Vec<PathBuf>> {
    let mut files = std::collections::BTreeSet::new();
    files.insert(common.join("config"));
    files.insert(common.join("config.worktree"));
    files.insert(gitdir.join("config.worktree"));
    let worktrees = common.join("worktrees");
    match std::fs::read_dir(&worktrees) {
        Ok(dir) => {
            for entry in dir {
                let entry = entry.with_context(|| format!("cannot list {}", worktrees.display()))?;
                files.insert(entry.path().join("config.worktree"));
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(e).with_context(|| format!("cannot list {}", worktrees.display())),
    }
    Ok(files.into_iter().collect())
}

/// One `key [= value]` line of a git config file. Section and key are
/// lowercased (git compares them case-insensitively); the subsection keeps
/// its case, except in the legacy `[section.sub]` form, which git lowercases.
#[derive(Debug, PartialEq)]
struct Entry {
    section: String,
    subsection: Option<String>,
    key: String,
    /// `None` for a bare `key` (boolean true).
    value: Option<String>,
}

impl Entry {
    fn name(&self) -> String {
        match &self.subsection {
            Some(sub) => format!("{}.{sub}.{}", self.section, self.key),
            None => format!("{}.{}", self.section, self.key),
        }
    }
}

/// Why `e` makes the repo unsafe for host git, or `None` when it is on the
/// allowlist (docs/decisions/0003-host-git-never-runs-repo-controlled-code.md).
/// Anything unknown is refused.
fn refusal(e: &Entry) -> Option<String> {
    let key = e.key.as_str();
    let value = e.value.as_deref().unwrap_or("").trim_start();
    let ext_url = || value.to_ascii_lowercase().starts_with("ext::");
    let allowed = match (e.section.as_str(), e.subsection.as_deref()) {
        ("core", None) => matches!(
            key,
            "repositoryformatversion"
                | "filemode"
                | "bare"
                | "logallrefupdates"
                | "ignorecase"
                | "precomposeunicode"
                | "symlinks"
                | "autocrlf"
                | "eol"
                | "safecrlf"
        ),
        ("extensions" | "worktree" | "rerere" | "color" | "advice", _) => true,
        ("remote", Some(_)) => match key {
            "url" | "pushurl" if ext_url() => return Some(format!("{} to an ext:: URL", e.name())),
            "url" | "pushurl" | "fetch" | "tagopt" | "prune" | "mirror" => true,
            _ => false,
        },
        // `vscode-merge-base` is written by VS Code's git extension, the
        // `github-pr-*` data keys by its GitHub Pull Requests extension.
        ("branch", Some(_)) => {
            matches!(
                key,
                "remote" | "merge" | "rebase" | "pushremote" | "description" | "vscode-merge-base"
            ) || key.starts_with("github-pr-")
        }
        ("user", None) => matches!(key, "name" | "email"),
        ("init", None) => key == "defaultbranch",
        ("pull", None) => matches!(key, "rebase" | "ff"),
        ("push", None) => matches!(key, "default" | "autosetupremote"),
        ("fetch", None) => key == "prune",
        ("gc", _) => !key.contains("hook"),
        // git-lfs runs custom transfer agents and extensions from its config
        // (`lfs.customtransfer.<name>.path`, `lfs.extension.<name>.clean`).
        ("lfs", sub) => {
            let sub = sub.unwrap_or("").to_ascii_lowercase();
            !(key == "standalonetransferagent"
                || sub.starts_with("customtransfer")
                || sub.starts_with("extension"))
        }
        ("submodule", Some(_)) => match key {
            "url" if ext_url() => return Some(format!("{} to an ext:: URL", e.name())),
            "update" if value.starts_with('!') => {
                return Some(format!("{} to a `!command`", e.name()))
            }
            "url" | "active" | "update" => true,
            _ => false,
        },
        _ => false,
    };
    (!allowed).then(|| e.name())
}

/// Parse git config syntax into its entries. Errors (`line N: why`) are
/// meant to fail closed: whatever git might read differently is refused.
fn parse_config(text: &str) -> std::result::Result<Vec<Entry>, String> {
    let s: Vec<char> = text.strip_prefix('\u{feff}').unwrap_or(text).chars().collect();
    let mut p = Parser { s: &s, i: 0, line: 1 };
    let mut section: Option<(String, Option<String>)> = None;
    let mut entries = Vec::new();
    while let Some(c) = p.peek() {
        match c {
            c if c.is_whitespace() => p.bump(),
            '#' | ';' => p.skip_comment(),
            '[' => {
                p.bump();
                section = Some(p.header()?);
            }
            c if c.is_ascii_alphabetic() => {
                let Some((sec, sub)) = &section else {
                    return Err(p.err("key before any [section]"));
                };
                let key = p.key();
                p.skip_blanks();
                let value = match p.peek() {
                    Some('=') => {
                        p.bump();
                        Some(p.value()?)
                    }
                    None | Some('\n' | '\r' | '#' | ';') => None,
                    Some(c) => return Err(p.err(&format!("unexpected `{c}` after key `{key}`"))),
                };
                entries.push(Entry { section: sec.clone(), subsection: sub.clone(), key, value });
            }
            c => return Err(p.err(&format!("unexpected `{c}`"))),
        }
    }
    Ok(entries)
}

struct Parser<'a> {
    s: &'a [char],
    i: usize,
    line: usize,
}

impl Parser<'_> {
    fn peek(&self) -> Option<char> {
        self.s.get(self.i).copied()
    }

    fn bump(&mut self) {
        if self.peek() == Some('\n') {
            self.line += 1;
        }
        self.i += 1;
    }

    fn err(&self, why: &str) -> String {
        format!("line {}: {why}", self.line)
    }

    fn skip_comment(&mut self) {
        while self.peek().is_some_and(|c| c != '\n') {
            self.bump();
        }
    }

    fn skip_blanks(&mut self) {
        while matches!(self.peek(), Some(' ' | '\t')) {
            self.bump();
        }
    }

    /// After `[`: `name]`, `name "sub"]`, or legacy `name.sub]`.
    fn header(&mut self) -> std::result::Result<(String, Option<String>), String> {
        let mut name = String::new();
        while let Some(c) = self.peek().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.')) {
            name.push(c.to_ascii_lowercase());
            self.bump();
        }
        if name.is_empty() {
            return Err(self.err("empty section name"));
        }
        match self.peek() {
            Some(']') => {
                self.bump();
                Ok(match name.split_once('.') {
                    Some((sec, sub)) => (sec.to_string(), Some(sub.to_string())),
                    None => (name, None),
                })
            }
            Some(' ' | '\t') => {
                self.skip_blanks();
                if self.peek() != Some('"') {
                    return Err(self.err("expected `\"` in section header"));
                }
                self.bump();
                let mut sub = String::new();
                loop {
                    match self.peek() {
                        None | Some('\n') => return Err(self.err("unterminated subsection")),
                        Some('"') => break,
                        Some('\\') => {
                            self.bump();
                            match self.peek() {
                                None | Some('\n') => return Err(self.err("unterminated subsection")),
                                Some(c) => sub.push(c),
                            }
                        }
                        Some(c) => sub.push(c),
                    }
                    self.bump();
                }
                self.bump();
                if self.peek() != Some(']') {
                    return Err(self.err("expected `]` after subsection"));
                }
                self.bump();
                Ok((name, Some(sub)))
            }
            _ => Err(self.err("malformed section header")),
        }
    }

    fn key(&mut self) -> String {
        let mut key = String::new();
        while let Some(c) = self.peek().filter(|c| c.is_ascii_alphanumeric() || *c == '-') {
            key.push(c.to_ascii_lowercase());
            self.bump();
        }
        key
    }

    /// After `=`: leading and unquoted trailing blanks dropped, quotes
    /// stripped, `\n \t \b \\ \"` unescaped, `\` + newline continues the
    /// value, unquoted `#`/`;` start a comment.
    fn value(&mut self) -> std::result::Result<String, String> {
        self.skip_blanks();
        let (mut v, mut keep, mut quoted) = (String::new(), 0, false);
        loop {
            match self.peek() {
                None | Some('\n') if quoted => return Err(self.err("unterminated quote")),
                None | Some('\n') => break,
                Some('#' | ';') if !quoted => {
                    self.skip_comment();
                    break;
                }
                Some('"') => quoted = !quoted,
                Some('\\') => {
                    self.bump();
                    match self.peek() {
                        Some('\n') => {}
                        Some('\r') if self.s.get(self.i + 1) == Some(&'\n') => self.bump(),
                        Some(c @ ('n' | 't' | 'b' | '\\' | '"')) => {
                            v.push(match c {
                                'n' => '\n',
                                't' => '\t',
                                'b' => '\u{8}',
                                c => c,
                            });
                            keep = v.len();
                        }
                        _ => return Err(self.err("invalid escape in value")),
                    }
                }
                Some(c @ (' ' | '\t' | '\r')) if !quoted => v.push(c),
                Some(c) => {
                    v.push(c);
                    keep = v.len();
                }
            }
            self.bump();
        }
        v.truncate(keep);
        Ok(v)
    }
}

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

    fn entry(section: &str, sub: Option<&str>, key: &str, value: Option<&str>) -> Entry {
        Entry {
            section: section.into(),
            subsection: sub.map(Into::into),
            key: key.into(),
            value: value.map(Into::into),
        }
    }

    #[test]
    fn parses_git_config_syntax() {
        let text = "\u{feff}# comment\n\
            [Core]\n\
            \trepositoryFormatVersion = 0\n\
            \tBare\n\
            ; another\n\
            [remote \"Or\\\"ig\\\\in\"]\n\
            \turl = git@h:o/r.git   # trailing comment\n\
            \tfetch = \"+refs/heads/*:refs/remotes/origin/*\" \n\
            [branch.Main] remote = origin\n\
            [user]\n\
            \tname = \"a ; b\" c\\\n\
            d\n\
            \temail=x\\t@y\r\n";
        let got = parse_config(text).unwrap();
        assert_eq!(
            got,
            [
                entry("core", None, "repositoryformatversion", Some("0")),
                entry("core", None, "bare", None),
                entry("remote", Some("Or\"ig\\in"), "url", Some("git@h:o/r.git")),
                entry("remote", Some("Or\"ig\\in"), "fetch", Some("+refs/heads/*:refs/remotes/origin/*")),
                entry("branch", Some("main"), "remote", Some("origin")),
                entry("user", None, "name", Some("a ; b cd")),
                entry("user", None, "email", Some("x\t@y")),
            ]
        );
    }

    #[test]
    fn unparseable_config_errors() {
        for bad in [
            "bare = true\n",
            "[core\n",
            "[]\n",
            "[remote \"x]\n",
            "[remote x]\n",
            "[core]\n\tname = \"open\n",
            "[core]\n\tname = bad\\q\n",
            "[core]\n\t!key = 1\n",
            "[core]\n\tkey value\n",
        ] {
            assert!(parse_config(bad).is_err(), "{bad:?}");
        }
        assert_eq!(parse_config("[core]\n\tx = \"a\n").unwrap_err(), "line 2: unterminated quote");
    }

    /// `(config, refused key or None)`.
    #[test]
    fn allowlist_accepts_and_refuses() {
        let cases: &[(&str, Option<&str>)] = &[
            ("[core]\nrepositoryformatversion = 0\nfilemode\nbare = false\nlogallrefupdates = true", None),
            ("[Core]\nIgnoreCase = true\nsymlinks = false\nautocrlf = input\neol = lf", None),
            ("[extensions]\nworktreeConfig = true\nobjectFormat = sha256", None),
            ("[remote \"origin\"]\nurl = git@github.com:o/r.git\nfetch = +refs/heads/*:refs/remotes/origin/*\nprune = true", None),
            ("[branch \"main\"]\nremote = origin\nmerge = refs/heads/main\nvscode-merge-base = origin/main\ngithub-pr-owner-number = o#r#1", None),
            ("[user]\nname = a\nemail = b", None),
            ("[init]\ndefaultBranch = main\n[pull]\nrebase = true\n[push]\nautoSetupRemote = true\n[fetch]\nprune = true", None),
            ("[gc]\nauto = 0\n[gc \"refs/x\"]\nreflogExpire = never", None),
            ("[lfs]\nrepositoryformatversion = 0\n[lfs \"https://h/r.git/info/lfs\"]\naccess = basic", None),
            ("[submodule \"s\"]\nurl = ../s.git\nactive = true\nupdate = rebase", None),
            ("[worktree]\nguessRemote = true\n[rerere]\nenabled = true\n[color]\nui = auto\n[advice]\ndetachedHead = false", None),
            ("[core]\nfsmonitor = /tmp/x", Some("core.fsmonitor")),
            ("[CORE]\nFsMonitor = true", Some("core.fsmonitor")),
            ("[core]\nsshCommand = sh", Some("core.sshcommand")),
            ("[core]\nhooksPath = /tmp", Some("core.hookspath")),
            ("[core]\nalternateRefsCommand = x", Some("core.alternaterefscommand")),
            ("[core \"x\"]\nbare = false", Some("core.x.bare")),
            ("[include]\npath = /tmp/evil", Some("include.path")),
            ("[includeIf \"gitdir:x\"]\npath = /tmp/evil", Some("includeif.gitdir:x.path")),
            ("[filter \"lfs\"]\nprocess = git-lfs filter-process", Some("filter.lfs.process")),
            ("[diff \"x\"]\ntextconv = sh", Some("diff.x.textconv")),
            ("[credential]\nhelper = !sh", Some("credential.helper")),
            ("[url \"ext::sh\"]\ninsteadOf = https://", Some("url.ext::sh.insteadof")),
            ("[remote \"origin\"]\nurl = ext::sh -c x", Some("remote.origin.url to an ext:: URL")),
            ("[remote \"origin\"]\npushurl = EXT::sh", Some("remote.origin.pushurl to an ext:: URL")),
            ("[remote \"origin\"]\nuploadpack = sh", Some("remote.origin.uploadpack")),
            ("[remote]\npushDefault = origin", Some("remote.pushdefault")),
            ("[branch \"main\"]\nsomething = x", Some("branch.main.something")),
            ("[gc]\npreAutoHook = x", Some("gc.preautohook")),
            ("[lfs \"customtransfer.x\"]\npath = sh", Some("lfs.customtransfer.x.path")),
            ("[lfs \"extension.x\"]\nclean = sh", Some("lfs.extension.x.clean")),
            ("[lfs]\nstandalonetransferagent = x", Some("lfs.standalonetransferagent")),
            ("[submodule \"s\"]\nupdate = !sh -c x", Some("submodule.s.update to a `!command`")),
            ("[submodule \"s\"]\nurl = ext::sh", Some("submodule.s.url to an ext:: URL")),
            ("[http]\nproxy = x", Some("http.proxy")),
        ];
        for (text, want) in cases {
            let entries = parse_config(text).unwrap();
            assert_eq!(entries.iter().find_map(refusal).as_deref(), *want, "{text}");
        }
    }

    #[test]
    fn origin_url_is_the_first_url_of_remote_origin() {
        let url = |text: &str| origin_url(&parse_config(text).unwrap());
        assert_eq!(url("[core]\nbare = false"), None);
        assert_eq!(url("[remote \"upstream\"]\nurl = /u\n[remote \"Origin\"]\nurl = /x"), None);
        assert_eq!(url("[remote \"origin\"]\nfetch = x\nURL = /a\nurl = /b\n[remote \"origin\"]\nurl = /c"), Some("/a".into()));
        assert_eq!(url("[remote.ORIGIN]\nurl = /legacy\n[remote \"origin\"]\nurl = /b"), Some("/legacy".into()));
    }

    #[test]
    fn read_origin_keys_checkouts_by_canonical_common_dir() {
        let root = temp("origin");
        let (base, wt) = base_and_worktree(&root);
        let none = read_origin(&base).unwrap();
        assert_eq!((none.common, none.url), (base.join(".git").canonicalize().unwrap(), None));
        git_in(&base, &["remote", "add", "origin", "/srv/repo.git"]);
        for repo in [&base, &wt] {
            let o = read_origin(repo).unwrap();
            assert_eq!((o.common, o.url.as_deref()), (base.join(".git").canonicalize().unwrap(), Some("/srv/repo.git")));
        }
        std::fs::write(base.join(".git/config.worktree"), "[core]\n\tfsmonitor = x\n").unwrap();
        assert!(read_origin(&base).is_err(), "refused like check_repo");
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn wrapper_disables_hooks_fsmonitor_filters_and_prompts() {
        let cmd = git_command(Path::new("/r"));
        assert_eq!(cmd.get_program(), "git");
        let args: Vec<_> = cmd.get_args().map(|a| a.to_str().unwrap()).collect();
        let mut want = vec!["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"];
        want.extend(filter_args().iter().map(String::as_str));
        want.extend(["-C", "/r"]);
        assert_eq!(args, want);
        let envs: Vec<_> = cmd.get_envs().collect();
        assert!(envs.contains(&("GIT_TERMINAL_PROMPT".as_ref(), Some("0".as_ref()))));
        assert!(envs.contains(&("GIT_LFS_SKIP_SMUDGE".as_ref(), Some("1".as_ref()))));
        assert!(envs.contains(&("DEVSANDBOX_GIT_EMPTY".as_ref(), Some("".as_ref()))));
        assert!(envs.contains(&("GIT_DIR".as_ref(), None)));
    }

    #[test]
    fn filter_names_and_overrides() {
        let names = parse_filter_names(b"filter.lfs.process\0filter.lfs.smudge\0filter.a.b.clean\0filter.x=y.required\0filter..smudge\0core.x\0");
        assert_eq!(names.iter().map(String::as_str).collect::<Vec<_>>(), ["a.b", "lfs", "x=y"]);
        let args = neutral_filter_args(&BTreeSet::from(["x=y".to_string()]));
        assert_eq!(
            args,
            [
                "--config-env=filter.x=y.smudge=DEVSANDBOX_GIT_CAT",
                "--config-env=filter.x=y.clean=DEVSANDBOX_GIT_CAT",
                "--config-env=filter.x=y.process=DEVSANDBOX_GIT_EMPTY",
                "--config-env=filter.x=y.required=DEVSANDBOX_GIT_FALSE",
            ]
        );
    }

    const LFS_POINTER: &str = "version https://git-lfs.github.com/spec/v1\n\
        oid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 12345\n";

    /// A global config (`<root>/global`) whose filters `lfs`, `my.dot` (via
    /// an include) and `x=y` each touch `<root>/marker` from `smudge`,
    /// `clean` and `process`, and a repo at `<root>/base` whose committed
    /// `.gitattributes` uses them, committed without them.
    #[cfg(unix)]
    fn repo_with_user_filters(root: &Path) -> (PathBuf, PathBuf) {
        use std::os::unix::fs::PermissionsExt;
        let script = root.join("filter.sh");
        std::fs::write(&script, format!("#!/bin/sh\ntouch {}/marker\ncat\n", root.display())).unwrap();
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
        let section = |name: &str| {
            let s = script.display();
            format!("[filter \"{name}\"]\n\tsmudge = {s}\n\tclean = {s}\n\tprocess = {s}\n\trequired = true\n")
        };
        std::fs::write(root.join("included"), section("my.dot")).unwrap();
        let global = root.join("global");
        let include = format!("[include]\n\tpath = {}\n", root.join("included").display());
        std::fs::write(&global, section("lfs") + &section("x=y") + &include).unwrap();

        let base = root.join("base");
        std::fs::create_dir_all(&base).unwrap();
        git_in(&base, &["init", "-q", "-b", "main"]);
        std::fs::write(base.join(".gitattributes"), "*.bin filter=lfs\n*.txt filter=my.dot\n*.dat filter=x=y\n").unwrap();
        std::fs::write(base.join("big.bin"), LFS_POINTER).unwrap();
        std::fs::write(base.join("a.txt"), "a\n").unwrap();
        std::fs::write(base.join("b.dat"), "b\n").unwrap();
        git_in(&base, &["add", "."]);
        git_in(&base, &["commit", "-q", "-m", "x"]);
        (base, global)
    }

    #[cfg(unix)]
    #[test]
    fn host_checkouts_never_run_user_filters() {
        let root = temp("filters");
        let (base, global) = repo_with_user_filters(&root);
        let env = [("GIT_CONFIG_GLOBAL", global.as_os_str())];
        let names = user_filter_names(&env);
        for name in ["lfs", "my.dot", "x=y"] {
            assert!(names.contains(name), "{name}: {names:?}");
        }
        let marker = root.join("marker");
        // `host_git` with the overrides `filter_args` would hold under `global`.
        let git = |repo: &Path, args: &[&str]| {
            let ok = host_git(repo)
                .unwrap()
                .args(neutral_filter_args(&names))
                .envs(env)
                .args(args)
                .status()
                .unwrap()
                .success();
            assert!(ok, "git {args:?}");
        };
        let checked_out = |dir: &Path| {
            assert!(!marker.exists(), "a filter ran");
            assert_eq!(std::fs::read_to_string(dir.join("big.bin")).unwrap(), LFS_POINTER);
            assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "a\n");
            assert_eq!(std::fs::read_to_string(dir.join("b.dat")).unwrap(), "b\n");
        };

        let wt = root.join("wt");
        git(&base, &["worktree", "add", "-q", wt.to_str().unwrap()]);
        checked_out(&wt);
        for f in ["big.bin", "a.txt", "b.dat"] {
            std::fs::remove_file(wt.join(f)).unwrap();
        }
        git(&wt, &["reset", "-q", "--hard"]);
        checked_out(&wt);
        git(&wt, &["status", "--porcelain"]);
        assert!(!marker.exists(), "a filter ran");

        // Without the overrides the same checkout runs them.
        std::fs::remove_file(wt.join("a.txt")).unwrap();
        let ran = Command::new("git").arg("-C").arg(&wt).args(["reset", "-q", "--hard"]).envs(env).status().unwrap();
        assert!(marker.exists(), "control: filter not run ({ran})");
        std::fs::remove_dir_all(&root).unwrap();
    }

    fn temp(tag: &str) -> PathBuf {
        let root = std::env::temp_dir().join(format!("devsandbox-git-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        root
    }

    fn git_in(dir: &Path, args: &[&str]) {
        let ok = Command::new("git")
            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
            .arg("-C")
            .arg(dir)
            .args(args)
            .status()
            .unwrap()
            .success();
        assert!(ok, "git {args:?}");
    }

    /// A repo at `<root>/base` with one commit and git's own linked worktree
    /// of it at `<root>/wt`.
    fn base_and_worktree(root: &Path) -> (PathBuf, PathBuf) {
        let (base, wt) = (root.join("base"), root.join("wt"));
        std::fs::create_dir_all(&base).unwrap();
        git_in(&base, &["init", "-q", "-b", "main"]);
        std::fs::write(base.join("f"), "x\n").unwrap();
        git_in(&base, &["add", "f"]);
        git_in(&base, &["commit", "-q", "-m", "x"]);
        git_in(&base, &["worktree", "add", "-q", "-b", "wt", wt.to_str().unwrap()]);
        (base, wt)
    }

    fn refusal_of(repo: &Path) -> String {
        format!("{:#}", check_repo(repo).unwrap_err())
    }

    #[test]
    fn git_dirs_for_checkout_and_linked_worktree() {
        let root = temp("dirs");
        let (base, wt) = base_and_worktree(&root);
        let common = base.join(".git").canonicalize().unwrap();

        assert_eq!(git_dirs(&base).unwrap(), (base.join(".git"), base.join(".git")));
        assert_eq!(git_dirs(&wt).unwrap(), (common.join("worktrees/wt"), common.clone()));
        check_repo(&wt).unwrap();
        // git's relative form (`worktree.useRelativePaths`) resolves the same.
        std::fs::write(wt.join(".git"), "gitdir: ../base/.git/worktrees/wt\n").unwrap();
        std::fs::write(common.join("worktrees/wt/gitdir"), "../../../../wt/.git\n").unwrap();
        assert_eq!(git_dirs(&wt).unwrap().0, common.join("worktrees/wt"));
        assert!(git_dirs(&root).is_err(), "no .git");
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn redirected_gitdir_and_commondir_refuse() {
        let root = temp("redirect");
        let (base, wt) = base_and_worktree(&root);
        let other = root.join("other");
        std::fs::create_dir_all(&other).unwrap();
        git_in(&other, &["init", "-q"]);

        // A planted `gitdir:` at another repo's git dir.
        let checkout = root.join("checkout");
        std::fs::create_dir_all(&checkout).unwrap();
        std::fs::write(checkout.join(".git"), format!("gitdir: {}\n", other.join(".git").display())).unwrap();
        let err = refusal_of(&checkout);
        assert!(err.contains("not a linked worktree's"), "{err}");

        // A planted `gitdir:` at a real worktree's admin dir: its back-pointer
        // names `wt`, not this checkout.
        let admin = base.join(".git/worktrees/wt");
        std::fs::write(checkout.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap();
        let err = refusal_of(&checkout);
        assert!(err.contains("back-pointer does not name this checkout"), "{err}");

        // A forged admin dir under `other` whose back-pointer names another
        // checkout, then one that names this checkout but has no `commondir`.
        let fake = other.join(".git/worktrees/x");
        std::fs::create_dir_all(&fake).unwrap();
        std::fs::write(fake.join("commondir"), "../..\n").unwrap();
        std::fs::write(fake.join("gitdir"), format!("{}\n", wt.join(".git").display())).unwrap();
        std::fs::write(checkout.join(".git"), format!("gitdir: {}\n", fake.display())).unwrap();
        let err = refusal_of(&checkout);
        assert!(err.contains("back-pointer does not name this checkout"), "{err}");
        std::fs::write(fake.join("gitdir"), format!("{}\n", checkout.join(".git").display())).unwrap();
        std::fs::remove_file(fake.join("commondir")).unwrap();
        let err = refusal_of(&checkout);
        assert!(err.contains("`commondir` does not name"), "{err}");

        // A worktree's `commondir` pointing at another repo.
        std::fs::write(admin.join("commondir"), format!("{}\n", other.join(".git").display())).unwrap();
        let err = refusal_of(&wt);
        assert!(err.contains("`commondir` does not name"), "{err}");
        std::fs::write(admin.join("commondir"), "../..\n").unwrap();
        check_repo(&wt).unwrap();

        std::fs::write(base.join(".git/commondir"), format!("{}\n", other.join(".git").display())).unwrap();
        let err = refusal_of(&base);
        assert!(err.contains(".git/commondir exists in a main git dir"), "{err}");
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn symlinks_in_git_dirs_refuse() {
        use std::os::unix::fs::symlink;
        let root = temp("symlinks");
        let (base, wt) = base_and_worktree(&root);
        let elsewhere = root.join("elsewhere");
        std::fs::create_dir_all(&elsewhere).unwrap();
        let git = base.join(".git");

        // `(path in the base's .git, whether it's a dir)`: each swapped for a
        // symlink must refuse, from the base and from the linked worktree.
        for (rel, is_dir) in [("refs/heads", true), ("objects", true), ("index", false), ("refs/heads/main", false), ("objects/pack", true), ("logs/HEAD", false)] {
            let p = git.join(rel);
            let saved = root.join("saved");
            std::fs::rename(&p, &saved).unwrap();
            let target = if is_dir { elsewhere.clone() } else { elsewhere.join("f") };
            symlink(&target, &p).unwrap();
            for repo in [&base, &wt] {
                let err = refusal_of(repo);
                assert!(err.contains(&format!("{rel} is a symlink")), "{rel}: {err}");
            }
            std::fs::remove_file(&p).unwrap();
            std::fs::rename(&saved, &p).unwrap();
            check_repo(&base).unwrap();
        }

        // In the worktree's own admin dir.
        symlink(elsewhere.join("f"), git.join("worktrees/wt/index.lock")).unwrap();
        let err = refusal_of(&wt);
        assert!(err.contains("worktrees/wt/index.lock is a symlink"), "{err}");
        std::fs::remove_file(git.join("worktrees/wt/index.lock")).unwrap();

        // `.git` itself, as a dir symlink or a symlinked `gitdir:` file.
        let checkout = root.join("checkout");
        std::fs::create_dir_all(&checkout).unwrap();
        symlink(&git, checkout.join(".git")).unwrap();
        let err = refusal_of(&checkout);
        assert!(err.contains(".git is a symlink"), "{err}");
        std::fs::remove_file(checkout.join(".git")).unwrap();
        symlink(wt.join(".git"), checkout.join(".git")).unwrap();
        let err = refusal_of(&checkout);
        assert!(err.contains(".git is a symlink"), "{err}");

        // A symlinked parent path to the repo is fine.
        let via = root.join("via");
        symlink(&root, &via).unwrap();
        check_repo(&via.join("base")).unwrap();
        check_repo(&via.join("wt")).unwrap();
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn bare_repo_refuses_symlinks_and_commondir() {
        use std::os::unix::fs::symlink;
        let root = temp("bare");
        let cache = root.join("c.git");
        std::fs::create_dir_all(&cache).unwrap();
        git_in(&cache, &["init", "-q", "--bare"]);
        host_git_bare(&cache).unwrap();
        symlink(root.join("x"), cache.join("refs/heads/main")).unwrap();
        let err = format!("{:#}", host_git_bare(&cache).unwrap_err());
        assert!(err.contains("refs/heads/main is a symlink"), "{err}");
        std::fs::remove_file(cache.join("refs/heads/main")).unwrap();
        std::fs::write(cache.join("commondir"), "/elsewhere\n").unwrap();
        let err = format!("{:#}", host_git_bare(&cache).unwrap_err());
        assert!(err.contains("commondir exists in a main git dir"), "{err}");
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn check_repo_reads_every_config_and_alternates() {
        let root = temp("check");
        let git = |args: &[&str]| {
            let ok = Command::new("git").arg("-C").arg(&root).args(args).status().unwrap().success();
            assert!(ok, "git {args:?}");
        };
        git(&["init", "-q", "-b", "main"]);
        check_repo(&root).unwrap();

        let wtconf = root.join(".git/worktrees/x/config.worktree");
        std::fs::create_dir_all(wtconf.parent().unwrap()).unwrap();
        std::fs::write(&wtconf, "[core]\n\tfsmonitor = /tmp/pwn\n").unwrap();
        let err = check_repo(&root).unwrap_err().to_string();
        assert!(err.contains(".git/worktrees/x/config.worktree sets core.fsmonitor"), "{err}");
        std::fs::remove_file(&wtconf).unwrap();

        std::fs::write(root.join(".git/config.worktree"), "[core\n").unwrap();
        let err = check_repo(&root).unwrap_err().to_string();
        assert!(err.contains("cannot parse .git/config.worktree (line 1:"), "{err}");
        std::fs::remove_file(root.join(".git/config.worktree")).unwrap();

        std::fs::write(root.join(".git/objects/info/alternates"), "/elsewhere\n").unwrap();
        let err = check_repo(&root).unwrap_err().to_string();
        assert!(err.contains(".git/objects/info/alternates exists"), "{err}");
        std::fs::remove_dir_all(&root).unwrap();
    }

    /// Read-only sanity check against this checkout's real config:
    /// `cargo test -- --ignored real_repo_passes`.
    #[test]
    #[ignore]
    fn real_repo_passes() {
        check_repo(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
    }

    fn remote(name: &str, urls: &[&str], pushurls: &[&str]) -> crate::state::FolderRemote {
        crate::state::FolderRemote {
            name: name.into(),
            urls: urls.iter().map(|u| u.to_string()).collect(),
            pushurls: pushurls.iter().map(|u| u.to_string()).collect(),
        }
    }

    #[test]
    fn reads_every_remote_url_and_pushurl() {
        let text = "[remote \"origin\"]\n\
            \turl = \"git@github.com:o/r.git\" ; quoted\n\
            \tpushurl = https://github.com/o/r\n\
            \turl = /home/u/mirror\n\
            \tfetch = +refs/heads/*:refs/remotes/origin/*\n\
            [include]\n\tpath = /etc/evil\n\
            [includeIf \"gitdir:/\"]\n\tpath = x\n\
            [branch \"main\"]\n\tremote = https://github.com/planted/x\n\
            [remote \"Up\\\"stream\"]\n\turl =\n\turl = https://github.com/u/r\n\tpushurl = file:///x\n\
            [remote \"local\"]\n\turl = ../other\n\
            [remote.Legacy]\n\turl = https://gitlab.com/l/r\n\
            [remote \"origin\"]\n\tpushurl = git@gitlab.com:o/r\n";
        let entries = parse_config(text).unwrap();
        let keep = |u: &str| crate::credentials::fence::parse(u).is_some();
        assert_eq!(
            remotes_of(&entries, keep),
            [
                remote("origin", &["git@github.com:o/r.git"], &["https://github.com/o/r", "git@gitlab.com:o/r"]),
                remote("Up\"stream", &["https://github.com/u/r"], &[]),
                remote("legacy", &["https://gitlab.com/l/r"], &[]),
            ]
        );
    }

    #[test]
    fn read_remotes_refuses_a_symlinked_or_huge_config() {
        let root = temp("remotes");
        let repo = root.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        git_in(&repo, &["init", "-q"]);
        git_in(&repo, &["remote", "add", "origin", "https://github.com/o/r"]);
        let all = |_: &str| true;
        assert_eq!(read_remotes(&repo, all).unwrap(), [remote("origin", &["https://github.com/o/r"], &[])]);

        let config = repo.join(".git/config");
        let elsewhere = root.join("elsewhere");
        std::fs::write(&elsewhere, "[remote \"x\"]\n\turl = https://github.com/x/y\n").unwrap();
        std::fs::remove_file(&config).unwrap();
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&elsewhere, &config).unwrap();
            let err = read_remotes(&repo, all).unwrap_err();
            assert!(format!("{err:#}").contains("cannot read"), "{err:#}");
            std::fs::remove_file(&config).unwrap();
            let ok = Command::new("mkfifo").arg(&config).status().unwrap().success();
            assert!(ok);
            assert!(read_remotes(&repo, all).is_err(), "a FIFO is refused, not waited on");
            std::fs::remove_file(&config).unwrap();
        }
        assert!(read_remotes(&repo, all).unwrap().is_empty(), "no config: no remotes");
        std::fs::write(&config, format!("[core]\n#{}\n", "x".repeat(MAX_CONFIG as usize))).unwrap();
        assert!(read_remotes(&repo, all).is_err());

        // A linked worktree reads the common dir's config.
        std::fs::write(&config, "[remote \"origin\"]\n\turl = https://github.com/o/r\n").unwrap();
        let (base, wt) = base_and_worktree(&root.join("wt"));
        git_in(&base, &["remote", "add", "origin", "git@github.com:b/r"]);
        assert_eq!(read_remotes(&wt, all).unwrap(), [remote("origin", &["git@github.com:b/r"], &[])]);
        std::fs::remove_dir_all(&root).unwrap();
    }
}