GITv
master
ssh.rs939 lines, 44.7 KB
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
//! `gitv serve` (what a key runs over SSH) and the administrator commands, exercised with real
//! git pushes and clones through a stand-in for ssh.

mod common;

use std::fs;

use common::{Host, ed25519_key, git, scratch, stderr, stdout};

/// A working copy with one commit on `branch`.
fn work(name: &str, branch: &str) -> std::path::PathBuf {
    let dir = scratch(name);
    git(&dir, &["init", "-q", "-b", branch]);
    fs::write(dir.join("hello.txt"), "hello\n").unwrap();
    git(&dir, &["add", "."]);
    git(&dir, &["commit", "-qm", "First"]);
    dir
}

#[test]
fn help_lists_the_commands() {
    let host = Host::new("ssh-help");
    for command in ["", "help"] {
        let out = host.ssh("ada", command);
        assert!(out.status.success());
        assert!(stdout(&out).contains("create <name>"), "{}", stdout(&out));
    }
}

#[test]
fn unknown_and_unreadable_commands_are_refused() {
    let host = Host::new("ssh-unknown");
    for command in ["rm -rf /", "list extra", "create", "git-upload-pack", "create 'unterminated"] {
        let out = host.ssh("ada", command);
        assert!(!out.status.success(), "{command} should fail");
        assert!(stderr(&out).starts_with("gitv: "), "{command}: {}", stderr(&out));
    }
}

#[test]
fn create_list_and_delete() {
    let host = Host::new("ssh-crud");
    let out = host.ssh("ada", "create notes");
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stdout(&out).trim(), "git@git.example.test:ada/notes.git");
    assert!(host.repo("ada", "notes").join("HEAD").is_file());

    assert!(!host.ssh("ada", "create notes").status.success(), "duplicates are refused");
    host.ssh("ada", "create alpha");
    assert_eq!(
        stdout(&host.ssh("ada", "list")),
        "git@git.example.test:ada/alpha.git\ngit@git.example.test:ada/notes.git\n"
    );
    assert_eq!(stdout(&host.ssh("bob", "list")), "", "owners only see their own repositories");

    let out = host.ssh("ada", "delete notes");
    assert!(!out.status.success());
    assert!(stderr(&out).contains("delete notes --yes"), "{}", stderr(&out));
    assert!(host.repo("ada", "notes").exists(), "nothing is deleted without --yes");

    let out = host.ssh("ada", "delete notes --yes");
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stdout(&out).contains("trash"), "{}", stdout(&out));
    assert!(!host.repo("ada", "notes").exists());
    assert_eq!(trash(&host, "ada").len(), 1, "the repository waits in the trash");
    assert!(host.logged().contains("ada/notes.git moved to the trash"), "{}", host.logged());
    assert!(!host.ssh("ada", "delete notes --yes").status.success(), "a missing repository can't be deleted");
    assert_eq!(stdout(&host.ssh("ada", "list")), "git@git.example.test:ada/alpha.git\n", "the trash isn't listed");
}

/// The names in an owner's trash.
fn trash(host: &Host, owner: &str) -> Vec<String> {
    let mut names: Vec<String> = fs::read_dir(host.repos.join(owner).join(".trash"))
        .map(|dir| dir.map(|e| e.unwrap().file_name().into_string().unwrap()).collect())
        .unwrap_or_default();
    names.sort();
    names
}

#[test]
fn names_are_validated() {
    let host = Host::new("ssh-names");
    for name in ["Upper", "-dash", "has.dot", "a/b", "..", &"x".repeat(64)] {
        let out = host.ssh("ada", &format!("create '{name}'"));
        assert!(!out.status.success(), "{name} should be refused");
    }
    assert!(fs::read_dir(&host.repos).unwrap().next().is_none(), "nothing was created");
    assert!(host.ssh("ada", "create ok_name-2").status.success());
}

#[test]
fn push_creates_the_repository_and_clone_reads_it() {
    let host = Host::new("ssh-push");
    let dir = work("ssh-push-work", "main");
    let out = host.git(&dir, &["push", "-q", "ada@x:ada/project.git", "main"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stderr(&out).contains("gitv: created ada/project.git"), "{}", stderr(&out));

    let clone = scratch("ssh-push-clone");
    let out = host.git(&clone, &["clone", "-q", "ada@x:ada/project.git", "copy"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(fs::read_to_string(clone.join("copy/hello.txt")).unwrap(), "hello\n");
    // The address without `.git` names the same repository.
    let out = host.git(&clone, &["clone", "-q", "ada@x:ada/project", "bare-name"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(clone.join("bare-name/hello.txt").is_file());

    // A second push updates the same repository.
    fs::write(dir.join("hello.txt"), "hello again\n").unwrap();
    git(&dir, &["commit", "-qam", "Second"]);
    assert!(host.git(&dir, &["push", "-q", "ada@x:ada/project.git", "main"]).status.success());
    let log = git(&host.repo("ada", "project"), &["log", "--format=%s", "main"]);
    assert_eq!(log, "Second\nFirst");
}

#[test]
fn fetching_a_missing_repository_fails_without_creating_it() {
    let host = Host::new("ssh-missing");
    let clone = scratch("ssh-missing-clone");
    let out = host.git(&clone, &["clone", "-q", "ada@x:ada/nothing.git"]);
    assert!(!out.status.success());
    assert!(!host.repo("ada", "nothing").exists());
}

#[test]
fn keys_only_reach_their_owners_repositories() {
    let host = Host::new("ssh-owner");
    let dir = work("ssh-owner-work", "main");
    assert!(host.git(&dir, &["push", "-q", "bob@x:bob/private.git", "main"]).status.success());

    let clone = scratch("ssh-owner-clone");
    let out = host.git(&clone, &["clone", "-q", "ada@x:bob/private.git"]);
    assert!(!out.status.success(), "ada read bob's repository");
    let out = host.git(&dir, &["push", "-q", "ada@x:bob/other.git", "main"]);
    assert!(!out.status.success(), "ada created a repository for bob");
    assert!(!host.repo("bob", "other").exists());

    for path in ["'../bob/private.git'", "'ada/../bob/private.git'", "'/etc/passwd'", "'ada/x'"] {
        let out = host.ssh("ada", &format!("git-upload-pack {path}"));
        assert!(!out.status.success(), "{path} was served");
        assert!(stderr(&out).contains("repository unavailable"), "{path}: {}", stderr(&out));
    }
}

#[test]
fn pushing_master_alone_makes_it_the_default_branch() {
    let host = Host::new("ssh-head");
    let dir = work("ssh-head-work", "master");
    let out = host.git(&dir, &["push", "-q", "ada@x:ada/legacy.git", "master"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stderr(&out).contains("default branch is now master"), "{}", stderr(&out));
    assert_eq!(git(&host.repo("ada", "legacy"), &["symbolic-ref", "HEAD"]), "refs/heads/master");

    // A clone now checks out master without being told to.
    let clone = scratch("ssh-head-clone");
    assert!(host.git(&clone, &["clone", "-q", "ada@x:ada/legacy.git", "copy"]).status.success());
    assert_eq!(git(&clone.join("copy"), &["branch", "--show-current"]), "master");
}

#[test]
fn admin_create_and_delete() {
    let host = Host::new("admin-crud");
    let out = host.admin(&["create", "ada", "tools"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stdout(&out).trim(), "git@git.example.test:ada/tools.git");
    assert_eq!(git(&host.repo("ada", "tools"), &["symbolic-ref", "HEAD"]), "refs/heads/main");

    let out = host.admin(&["delete", "ada", "tools"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("--yes"), "{}", stderr(&out));
    assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success());
    assert!(!host.repo("ada", "tools").exists());

    assert!(!host.admin(&["create", "Ada", "tools"]).status.success(), "owner names are validated");
}

#[test]
fn deleted_repositories_can_be_restored_until_purged() {
    let host = Host::new("admin-trash");
    let dir = work("admin-trash-work", "main");
    assert!(host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]).status.success());
    assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success());
    let [entry] = <[String; 1]>::try_from(trash(&host, "ada")).unwrap();
    assert!(entry.starts_with("tools."), "{entry}");
    let listed = stdout(&host.admin(&["trash"]));
    assert!(listed.contains(&format!("ada {entry}")) && listed.contains("deleted 0 days ago"), "{listed}");

    // Restoring never replaces what is at the name now.
    assert!(host.admin(&["create", "ada", "tools"]).status.success());
    let out = host.admin(&["restore", "ada", &entry]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("--as"), "{}", stderr(&out));
    let out = host.admin(&["restore", "ada", &entry, "--as", "tools-old"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(git(&host.repo("ada", "tools-old"), &["log", "--format=%s", "main"]), "First");
    assert!(trash(&host, "ada").is_empty());
    assert!(!host.admin(&["restore", "ada", &entry]).status.success(), "an entry restores once");
    assert!(!host.admin(&["restore", "ada", "../../etc"]).status.success(), "entries are validated");

    // A purge keeps recent entries and removes old enough ones.
    assert!(host.admin(&["delete", "ada", "tools", "--yes"]).status.success());
    assert!(host.admin(&["purge"]).status.success());
    assert_eq!(trash(&host, "ada").len(), 1, "a fresh entry survives the default purge");
    let out = host.admin(&["purge", "--older-than-days", "0"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stdout(&out).contains("purged ada/.trash/tools."), "{}", stdout(&out));
    assert!(trash(&host, "ada").is_empty());
}

#[test]
fn overwritten_and_deleted_branches_stay_recoverable() {
    let host = Host::new("ssh-recovery");
    let dir = work("ssh-recovery-work", "main");
    let remote = "ada@x:ada/history.git";
    assert!(host.git(&dir, &["push", "-q", remote, "main", "main:topic"]).status.success());
    let first = git(&dir, &["rev-parse", "HEAD"]);

    // Rewrite main and force it over the old commit, then delete topic.
    git(&dir, &["commit", "-q", "--amend", "-m", "Rewritten"]);
    let rewritten = git(&dir, &["rev-parse", "HEAD"]);
    assert!(host.git(&dir, &["push", "-qf", remote, "main"]).status.success());
    assert!(host.git(&dir, &["push", "-q", remote, ":topic"]).status.success());

    let repo = host.repo("ada", "history");
    assert_eq!(git(&repo, &["rev-parse", "main@{1}"]), first, "the reflog keeps the overwritten commit");
    let log = fs::read_to_string(repo.join("gitv-push.log")).unwrap();
    let lines: Vec<Vec<&str>> = log.lines().map(|l| l.split(' ').skip(1).collect()).collect();
    assert_eq!(
        lines,
        [
            vec!["-", first.as_str(), "refs/heads/main"],
            vec!["-", first.as_str(), "refs/heads/topic"],
            vec![first.as_str(), rewritten.as_str(), "refs/heads/main"],
            vec![first.as_str(), "-", "refs/heads/topic"],
        ],
        "{log}"
    );
    assert_eq!(git(&repo, &["cat-file", "-t", &first]), "commit", "the deleted branch's commit is still there");
}

#[test]
fn the_configuration_file_sets_the_host_and_the_forced_command() {
    let host = Host::new("ssh-config");
    let config = host.dir.join("gitv.conf");
    fs::write(&config, "# this server\nhost = Code.Example.org\ncommand = /opt/gitv/bin/gitv\n").unwrap();
    let admin = |args: &[&str]| {
        std::process::Command::new(&*common::GITV)
            .args(args)
            .env("GITV_CONFIG", &config)
            .env("GITV_REPOS", &host.repos)
            .env("GITV_KEYS", &host.keys)
            .output()
            .unwrap()
    };
    let out = admin(&["create", "ada", "tools"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stdout(&out).trim(), "git@code.example.org:ada/tools.git");
    let key = host.dir.join("ada.pub");
    fs::write(&key, ed25519_key(3)).unwrap();
    assert!(admin(&["add-key", "ada", key.to_str().unwrap()]).status.success());
    assert!(fs::read_to_string(&host.keys).unwrap().starts_with("restrict,command=\"/opt/gitv/bin/gitv serve ada\""));

    // A mistake stops every command, and a key holder isn't shown the server's paths.
    fs::write(&config, "hostname = code.example.org\n").unwrap();
    let out = admin(&["create", "ada", "other"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("unknown setting `hostname`"), "{}", stderr(&out));
    let out = std::process::Command::new(&*common::GITV)
        .args(["serve", "ada"])
        .env("SSH_ORIGINAL_COMMAND", "list")
        .env("GITV_CONFIG", &config)
        .env("GITV_REPOS", &host.repos)
        .env("GITV_LOG", host.log())
        .output()
        .unwrap();
    assert!(!out.status.success());
    assert!(stderr(&out).contains("misconfigured") && !stderr(&out).contains("gitv.conf"), "{}", stderr(&out));
    assert!(host.logged().contains("unknown setting `hostname`"), "{}", host.logged());
}

#[test]
fn admin_add_key() {
    let host = Host::new("admin-keys");
    let key = host.dir.join("ada.pub");
    fs::write(&key, ed25519_key(7)).unwrap();
    let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]);
    assert!(out.status.success(), "{}", stderr(&out));
    let keys = fs::read_to_string(&host.keys).unwrap();
    assert!(keys.starts_with("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 AAAA"), "{keys}");
    assert!(!keys.contains("test@example"), "the key's comment is dropped");
    assert!(host.repos.join("ada").is_dir(), "the owner's directory exists");

    let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("already registered"), "{}", stderr(&out));

    let second = host.dir.join("bob.pub");
    fs::write(&second, ed25519_key(9)).unwrap();
    assert!(host.admin(&["add-key", "bob", second.to_str().unwrap()]).status.success());
    assert_eq!(fs::read_to_string(&host.keys).unwrap().lines().count(), 2, "both keys are kept");
}

#[test]
fn admin_add_key_rejects_bad_keys() {
    let host = Host::new("admin-badkeys");
    let cases = [
        ("rsa", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ test\n".to_string()),
        ("garbage", "not a key\n".to_string()),
        ("bad-base64", "ssh-ed25519 !!!!\n".to_string()),
        ("short", "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5\n".to_string()),
        ("options", format!("command=\"sh\" {}", ed25519_key(1))),
    ];
    for (name, text) in cases {
        let file = host.dir.join(format!("{name}.pub"));
        fs::write(&file, text).unwrap();
        let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]);
        assert!(!out.status.success(), "{name} was accepted");
    }
    assert!(!host.keys.exists(), "no key was written");
}

#[test]
fn admin_needs_root_outside_a_local_tree() {
    if nix::unistd::geteuid().is_root() {
        return;
    }
    let out = std::process::Command::new(&*common::GITV)
        .args(["create", "ada", "tools"])
        .env_remove("GITV_REPOS")
        .output()
        .unwrap();
    assert!(!out.status.success());
    assert!(stderr(&out).contains("as root"), "{}", stderr(&out));
}

#[test]
fn symlinked_repositories_are_refused() {
    let host = Host::new("ssh-symlink-repo");
    let dir = work("ssh-symlink-repo-work", "main");
    assert!(host.git(&dir, &["push", "-q", "bob@x:bob/real.git", "main"]).status.success());
    // ada/link.git points at bob's repository: following it would cross the owner boundary.
    fs::create_dir_all(host.repos.join("ada")).unwrap();
    std::os::unix::fs::symlink(host.repo("bob", "real"), host.repo("ada", "link")).unwrap();

    let clone = scratch("ssh-symlink-repo-clone");
    assert!(!host.git(&clone, &["clone", "-q", "ada@x:ada/link.git"]).status.success(), "read through a symlink");
    let out = host.git(&dir, &["push", "-q", "ada@x:ada/link.git", "main:other"]);
    assert!(!out.status.success(), "wrote through a symlink");
    assert!(git(&host.repo("bob", "real"), &["branch", "--list", "other"]).is_empty());
    assert_eq!(stdout(&host.ssh("ada", "list")), "", "symlinks aren't listed");
    assert!(!host.ssh("ada", "delete link --yes").status.success());
    assert!(host.repo("bob", "real").join("HEAD").is_file(), "the target survives");
}

#[test]
fn symlinked_owner_directories_are_refused() {
    let host = Host::new("ssh-symlink-owner");
    let outside = scratch("ssh-symlink-owner-outside");
    std::os::unix::fs::symlink(&outside, host.repos.join("ada")).unwrap();
    let dir = work("ssh-symlink-owner-work", "main");
    let out = host.git(&dir, &["push", "-q", "ada@x:ada/new.git", "main"]);
    assert!(!out.status.success(), "created a repository through a symlinked owner directory");
    assert!(!host.ssh("ada", "create other").status.success());
    assert!(fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the tree");
}

#[test]
fn simultaneous_first_pushes_all_succeed() {
    let host = std::sync::Arc::new(Host::new("ssh-race"));
    let dir = work("ssh-race-work", "main");
    // Each push sends its own branch: racing to create one *branch* is git's business, but
    // racing to create the *repository* must not fail anyone.
    let pushes: Vec<_> = (0..6)
        .map(|n| {
            let (host, dir) = (host.clone(), dir.clone());
            std::thread::spawn(move || host.git(&dir, &["push", "-q", "ada@x:ada/raced.git", &format!("main:b{n}")]))
        })
        .collect();
    for push in pushes {
        let out = push.join().unwrap();
        assert!(out.status.success(), "{}", stderr(&out));
    }
    let leftovers: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect();
    assert_eq!(leftovers, [std::ffi::OsString::from("raced.git")], "no staging directories left behind");
    assert_eq!(git(&host.repo("ada", "raced"), &["for-each-ref", "--format=%(refname:lstrip=2)"]).lines().count(), 6);
    assert_eq!(host.logged(), "", "losing a creation race is ordinary and isn't logged");
}

#[test]
fn add_key_failure_installs_nothing() {
    let host = Host::new("admin-keys-atomic");
    // A file where the owner's directory should go makes preparing the owner fail.
    fs::write(host.repos.join("ada"), "not a directory").unwrap();
    let key = host.dir.join("ada.pub");
    fs::write(&key, ed25519_key(3)).unwrap();
    let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]);
    assert!(!out.status.success());
    assert!(!host.keys.exists(), "the key was installed although the command failed");

    // Once the problem is fixed, a retry succeeds rather than finding the key already there.
    fs::remove_file(host.repos.join("ada")).unwrap();
    let out = host.admin(&["add-key", "ada", key.to_str().unwrap()]);
    assert!(out.status.success(), "{}", stderr(&out));
}

#[test]
fn a_failed_key_write_leaves_no_temporary_file() {
    use std::os::unix::process::CommandExt;
    let host = Host::new("admin-keys-cleanup");
    let key = host.dir.join("ada.pub");
    fs::write(&key, ed25519_key(4)).unwrap();
    let mut command = std::process::Command::new(&*common::GITV);
    command
        .args(["add-key", "ada", key.to_str().unwrap()])
        .env("GITV_HOST", common::TEST_HOST)
        .env("GITV_CONFIG", common::NO_CONFIG)
        .env("GITV_REPOS", &host.repos)
        .env("GITV_KEYS", &host.keys);
    // Files may grow to 16 bytes, so writing the new keys file fails part way. With SIGXFSZ
    // ignored the write returns an error instead of killing the process.
    // SAFETY: signal and setrlimit are async-signal-safe and the closure does nothing else.
    unsafe {
        command.pre_exec(|| {
            nix::libc::signal(nix::libc::SIGXFSZ, nix::libc::SIG_IGN);
            nix::sys::resource::setrlimit(nix::sys::resource::Resource::RLIMIT_FSIZE, 16, 16)
                .map_err(std::io::Error::from)
        });
    }
    let out = command.output().unwrap();
    assert!(!out.status.success(), "the write should have failed");
    assert!(stderr(&out).contains("File too large"), "it failed while writing: {}", stderr(&out));
    assert!(!host.keys.exists(), "no keys file was published");
    let left: Vec<_> = fs::read_dir(&host.dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().into_string().unwrap())
        .filter(|n| n.starts_with(".authorized_keys"))
        .collect();
    assert!(left.is_empty(), "temporary files left behind: {left:?}");
}

#[test]
fn add_key_respects_existing_lines() {
    let host = Host::new("admin-keys-existing");
    let blob = ed25519_key(5);
    let blob = blob.split_whitespace().nth(1).unwrap();
    // Written by hand: options in front, a comment after, and no final newline.
    fs::write(&host.keys, format!("restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob} laptop"))
        .unwrap();

    let same = host.dir.join("same.pub");
    fs::write(&same, ed25519_key(5)).unwrap();
    let out = host.admin(&["add-key", "bob", same.to_str().unwrap()]);
    assert!(!out.status.success(), "the same key was registered twice");
    assert!(stderr(&out).contains("already registered"), "{}", stderr(&out));

    let other = host.dir.join("other.pub");
    fs::write(&other, ed25519_key(6)).unwrap();
    assert!(host.admin(&["add-key", "bob", other.to_str().unwrap()]).status.success());
    let keys = fs::read_to_string(&host.keys).unwrap();
    let lines: Vec<&str> = keys.lines().collect();
    assert_eq!(lines.len(), 2, "{keys}");
    assert!(
        lines[0].ends_with(" laptop") && lines[1].starts_with("restrict,command=\"/usr/local/bin/gitv serve bob\"")
    );
}

#[test]
fn the_readme_fake_ssh_script_works() {
    let host = Host::new("ssh-script");
    let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/fake-ssh");
    let dir = work("ssh-script-work", "main");
    let out = common::git_cmd(&dir)
        .env("GIT_SSH_COMMAND", &script)
        .env("GITV_REPOS", &host.repos)
        .args(["push", "-q", "um9i@local:um9i/demo.git", "main"])
        .output()
        .unwrap();
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(host.repo("um9i", "demo").join("HEAD").is_file());
}

#[test]
fn default_branch_repair_keeps_branch_names_exact() {
    use std::os::unix::ffi::OsStrExt;
    // Names that whitespace splitting or UTF-8 conversion would mangle.
    let names: [&[u8]; 2] = ["trunk\u{a0}line".as_bytes(), b"caf\xe9"];
    for (n, name) in names.iter().enumerate() {
        let host = Host::new(&format!("ssh-head-bytes-{n}"));
        let dir = work(&format!("ssh-head-bytes-{n}-work"), "main");
        let target = [b"main:refs/heads/".as_slice(), name].concat();
        let out = common::git_cmd(&dir)
            .env("GIT_SSH_COMMAND", host.ssh_script())
            .args([std::ffi::OsStr::new("push"), "-q".as_ref(), "ada@x:ada/odd.git".as_ref()])
            .arg(std::ffi::OsStr::from_bytes(&target))
            .output()
            .unwrap();
        assert!(out.status.success(), "{}", stderr(&out));
        let head = common::git_cmd(&host.repo("ada", "odd")).args(["symbolic-ref", "HEAD"]).output().unwrap();
        assert_eq!(
            head.stdout,
            [b"refs/heads/".as_slice(), name, b"\n"].concat(),
            "HEAD names the pushed branch exactly"
        );

        let clone = scratch(&format!("ssh-head-bytes-{n}-clone"));
        let out = host.git(&clone, &["clone", "-q", "ada@x:ada/odd.git", "copy"]);
        assert!(out.status.success(), "{}", stderr(&out));
        assert!(clone.join("copy/hello.txt").is_file(), "the clone checked out the default branch");
    }
}

#[test]
fn commented_keys_do_not_block_registration() {
    let host = Host::new("admin-keys-comments");
    let key = ed25519_key(8);
    let blob = key.split_whitespace().nth(1).unwrap();
    // The key is retired (commented out) and also mentioned in another key's comment.
    let other = ed25519_key(9);
    let other_blob = other.split_whitespace().nth(1).unwrap();
    fs::write(
        &host.keys,
        format!(
            "# restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {blob}\n\
             # ssh-ed25519 {blob} old laptop\n\
             command=\"/usr/local/bin/gitv serve bob\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {other_blob} replaces ssh-ed25519 {blob}\n"
        ),
    )
    .unwrap();
    let file = host.dir.join("ada.pub");
    fs::write(&file, &key).unwrap();
    let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]);
    assert!(out.status.success(), "{}", stderr(&out));

    // A real duplicate behind quoted options with spaces is still caught.
    let again = host.dir.join("bob.pub");
    fs::write(&again, &other).unwrap();
    let out = host.admin(&["add-key", "carol", again.to_str().unwrap()]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("already registered"), "{}", stderr(&out));
}

#[test]
fn tab_separated_keys_are_recognised() {
    let host = Host::new("admin-keys-tabs");
    let key = ed25519_key(11);
    let blob = key.split_whitespace().nth(1).unwrap();
    // An active key written with tabs between its fields, with and without options.
    fs::write(
        &host.keys,
        format!("ssh-ed25519\t{blob}\tlaptop\nrestrict\tssh-ed25519\t{}\n", {
            let other = ed25519_key(12);
            other.split_whitespace().nth(1).unwrap().to_string()
        }),
    )
    .unwrap();
    for (seed, owner) in [(11, "bob"), (12, "carol")] {
        let file = host.dir.join(format!("{owner}.pub"));
        fs::write(&file, ed25519_key(seed)).unwrap();
        let out = host.admin(&["add-key", owner, file.to_str().unwrap()]);
        assert!(!out.status.success(), "key {seed} was registered a second time");
        assert!(stderr(&out).contains("already registered"), "{}", stderr(&out));
    }
}

#[test]
fn creation_never_replaces_what_is_at_the_name() {
    let host = Host::new("admin-create-noreplace");
    // An empty directory (which a plain rename would silently replace) and a symlink.
    fs::create_dir_all(host.repo("ada", "empty")).unwrap();
    let elsewhere = scratch("admin-create-noreplace-elsewhere");
    std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "link")).unwrap();
    for name in ["empty", "link"] {
        let out = host.admin(&["create", "ada", name]);
        assert!(!out.status.success(), "{name} was created over");
        assert!(stderr(&out).contains("already exists"), "{name}: {}", stderr(&out));
    }
    assert!(fs::read_dir(host.repo("ada", "empty")).unwrap().next().is_none(), "the directory is untouched");
    assert!(fs::read_dir(&elsewhere).unwrap().next().is_none(), "nothing was written through the symlink");
    let names: Vec<_> = fs::read_dir(host.repos.join("ada")).unwrap().flatten().map(|e| e.file_name()).collect();
    assert_eq!(names.len(), 2, "no staging directory left behind: {names:?}");
}

#[test]
fn purging_removes_links_inside_a_repository_without_following_them() {
    let host = Host::new("admin-delete-links");
    assert!(host.admin(&["create", "ada", "tools"]).status.success());
    let outside = scratch("admin-delete-links-outside");
    fs::write(outside.join("precious.txt"), "keep").unwrap();
    std::os::unix::fs::symlink(&outside, host.repo("ada", "tools").join("escape")).unwrap();
    let out = host.admin(&["delete", "ada", "tools", "--yes"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(!host.repo("ada", "tools").exists());
    let out = host.admin(&["purge", "--older-than-days", "0"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(fs::read_to_string(outside.join("precious.txt")).unwrap(), "keep");
    assert!(trash(&host, "ada").is_empty(), "the trash is emptied");
    assert_eq!(fs::read_dir(host.repos.join("ada")).unwrap().count(), 1, "only the trash itself is left");
}

#[test]
fn a_failed_first_push_tells_the_operator_why() {
    let host = Host::new("ssh-first-push-log");
    let elsewhere = scratch("ssh-first-push-log-elsewhere");
    fs::create_dir_all(host.repos.join("ada")).unwrap();
    std::os::unix::fs::symlink(&elsewhere, host.repo("ada", "taken")).unwrap();
    let dir = work("ssh-first-push-log-work", "main");
    let out = host.git(&dir, &["push", "-q", "ada@x:ada/taken.git", "main"]);
    assert!(!out.status.success());
    // The client gets the generic answer, without server details.
    assert!(stderr(&out).contains("gitv: repository unavailable"), "{}", stderr(&out));
    assert!(!stderr(&out).contains("already exists"), "{}", stderr(&out));
    // The operator gets the cause.
    let log = host.logged();
    assert!(log.contains("first push to ada/taken.git couldn't create it: repository already exists"), "{log}");
}

#[test]
fn ssh_create_keeps_server_details_for_the_operator() {
    let host = Host::new("ssh-create-private");
    // A file where the owner's directory should be: creation fails on the server's side.
    fs::write(host.repos.join("ada"), "not a directory").unwrap();
    let out = host.ssh("ada", "create notes");
    assert!(!out.status.success());
    let said = stderr(&out);
    assert!(said.contains("couldn't create the repository; the server's operator can see why"), "{said}");
    assert!(!said.contains(host.repos.to_str().unwrap()), "a server path reached the client: {said}");
    let log = host.logged();
    assert!(log.contains("ssh create of ada/notes.git failed:") && log.contains("is not a directory"), "{log}");

    // An administrator running the same thing sees the details directly.
    let out = host.admin(&["create", "ada", "notes"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("is not a directory"), "{}", stderr(&out));

    // "Already exists" is safe to tell anyone.
    fs::remove_file(host.repos.join("ada")).unwrap();
    assert!(host.ssh("ada", "create notes").status.success());
    let out = host.ssh("ada", "create notes");
    assert!(stderr(&out).contains("gitv: repository already exists"), "{}", stderr(&out));
}

/// The owner sshd would run `gitv serve` for when `key` connects: the forced command of the
/// first active line holding that key, as sshd reads authorized_keys. `None` means sshd
/// refuses the key.
fn sshd_owner(keys: &std::path::Path, key: &str) -> Option<String> {
    let blob = key.split_whitespace().nth(1).unwrap();
    let text = fs::read_to_string(keys).unwrap_or_default();
    let line = text
        .lines()
        .filter(|l| !l.trim_start().starts_with('#'))
        .find(|l| l.split([' ', '\t']).any(|field| field == blob))?;
    let command = line.split("serve ").nth(1)?;
    Some(command.split('"').next()?.to_string())
}

/// The fingerprint `ssh-keygen -l` prints for a key file.
fn ssh_keygen_fingerprint(file: &std::path::Path) -> String {
    let out = std::process::Command::new("ssh-keygen").arg("-lf").arg(file).output().unwrap();
    assert!(out.status.success(), "{}", stderr(&out));
    stdout(&out).split_whitespace().nth(1).unwrap().to_string()
}

#[test]
fn keys_are_listed_and_revoked_one_at_a_time() {
    let host = Host::new("admin-keys-revoke");
    let add = |owner: &str, seed: u8, label: &str| {
        let file = host.dir.join(format!("{owner}-{seed}.pub"));
        fs::write(&file, ed25519_key(seed)).unwrap();
        let out = host.admin(&["add-key", owner, file.to_str().unwrap(), "--label", label]);
        assert!(out.status.success(), "{}", stderr(&out));
        file
    };
    let laptop = add("ada", 21, "ada's laptop");
    add("ada", 22, "desktop");
    add("bob", 23, "bob's phone");
    let out = host.admin(&["create", "ada", "tools"]);
    assert!(out.status.success(), "{}", stderr(&out));

    let listed = stdout(&host.admin(&["keys"]));
    let rows: Vec<&str> = listed.lines().collect();
    assert_eq!(rows.len(), 3, "{listed}");
    let laptop_print = ssh_keygen_fingerprint(&laptop);
    assert!(rows[0].starts_with("ada ") && rows[0].contains(&laptop_print), "{listed}");
    assert!(rows[0].ends_with("  ada's laptop"), "the label is kept whole: {listed}");
    assert!(rows[2].starts_with("bob ") && rows[2].ends_with("bob's phone"), "{listed}");
    let only_ada = stdout(&host.admin(&["keys", "ada"]));
    assert_eq!(only_ada.lines().count(), 2, "{only_ada}");
    assert!(!only_ada.contains("bob"), "{only_ada}");

    // A fingerprint that matches nothing changes nothing.
    let before = fs::read(&host.keys).unwrap();
    let out = host.admin(&["remove-key", "SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("no key has the fingerprint"), "{}", stderr(&out));
    assert_eq!(fs::read(&host.keys).unwrap(), before);

    // Revoking the laptop (prefix optional) leaves the desktop working.
    let bare = laptop_print.strip_prefix("SHA256:").unwrap();
    let out = host.admin(&["remove-key", bare]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stdout(&out).contains("ada ada's laptop"), "{}", stdout(&out));
    assert_eq!(sshd_owner(&host.keys, &ed25519_key(21)), None, "the revoked key no longer gets in");
    let owner = sshd_owner(&host.keys, &ed25519_key(22)).expect("the other key still gets in");
    let out = host.ssh(&owner, "list");
    assert!(out.status.success() && stdout(&out).contains("ada/tools.git"), "{}", stderr(&out));
    assert_eq!(sshd_owner(&host.keys, &ed25519_key(23)).as_deref(), Some("bob"));
    assert!(!stdout(&host.admin(&["keys"])).contains(&laptop_print));
}

#[test]
fn removing_a_key_keeps_every_other_line_exactly() {
    let host = Host::new("admin-keys-remove-exact");
    let blob = |seed| ed25519_key(seed).split_whitespace().nth(1).unwrap().to_string();
    // Hand-written: a comment, options with quoted spaces, tabs, a non-GITv key, and the key
    // to remove last with no final newline.
    let kept = format!(
        "# retired: ssh-ed25519 {}\n\
         command=\"/usr/local/bin/gitv serve bob\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {} work\n\
         ssh-ed25519\t{}\tbackup box\n",
        blob(31),
        blob(32),
        blob(33)
    );
    fs::write(&host.keys, format!("{kept}restrict,command=\"/usr/local/bin/gitv serve ada\" ssh-ed25519 {}", blob(31)))
        .unwrap();
    let listed = stdout(&host.admin(&["keys"]));
    assert_eq!(listed.lines().count(), 3, "the commented-out key isn't listed: {listed}");
    assert!(listed.contains("bob ") && listed.contains("-  ") && listed.contains("backup box"), "{listed}");

    let file = host.dir.join("ada.pub");
    fs::write(&file, ed25519_key(31)).unwrap();
    let out = host.admin(&["remove-key", &ssh_keygen_fingerprint(&file)]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(fs::read_to_string(&host.keys).unwrap(), kept, "only the active line went");
}

#[test]
fn key_labels_stay_on_one_line() {
    let host = Host::new("admin-keys-labels");
    let file = host.dir.join("ada.pub");
    fs::write(&file, ed25519_key(41)).unwrap();
    for label in ["", "  ", "two\nlines", "\u{1b}[31mred", &"x".repeat(65)] {
        let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", label]);
        assert!(!out.status.success(), "{label:?} was accepted");
    }
    assert!(!host.keys.exists(), "no key was written");
}

#[test]
fn descriptions_are_set_shown_and_removed() {
    let host = Host::new("ssh-description");
    assert!(host.ssh("ada", "create tools").status.success());
    // `git init` writes a placeholder, which doesn't count as a description.
    let out = host.ssh("ada", "description tools");
    assert!(out.status.success() && stdout(&out).is_empty(), "{}", stdout(&out));

    assert!(host.ssh("ada", "description tools A small toolbox").status.success());
    assert_eq!(stdout(&host.ssh("ada", "description tools")), "A small toolbox\n");
    assert_eq!(fs::read_to_string(host.repo("ada", "tools").join("description")).unwrap(), "A small toolbox\n");
    // Quoted, as one argument, from the admin command too.
    let out = host.admin(&["description", "ada", "tools", "  Tools for ada  "]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stdout(&host.ssh("ada", "description tools")), "Tools for ada\n");

    for bad in ["description tools 'two\nlines'", &format!("description tools {}", "x".repeat(161))] {
        let out = host.ssh("ada", bad);
        assert!(!out.status.success(), "{bad} was accepted");
        assert!(stderr(&out).contains("one line of at most 160"), "{}", stderr(&out));
    }
    assert_eq!(stdout(&host.ssh("ada", "description tools")), "Tools for ada\n", "a refusal changes nothing");

    assert!(host.ssh("ada", "description tools ''").status.success());
    assert!(!host.repo("ada", "tools").join("description").exists());
    // Only the owner's own repositories.
    assert!(!host.ssh("bob", "description tools Mine now").status.success());
    let leftovers: Vec<_> = fs::read_dir(host.repo("ada", "tools"))
        .unwrap()
        .map(|e| e.unwrap().file_name().into_string().unwrap())
        .filter(|n| n.starts_with(".description"))
        .collect();
    assert!(leftovers.is_empty(), "{leftovers:?}");
}

#[test]
fn the_default_branch_can_be_chosen_among_existing_branches() {
    let host = Host::new("ssh-default-branch");
    let dir = work("ssh-default-branch-work", "main");
    git(&dir, &["branch", "release"]);
    let out = host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main", "release"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "main\n");

    let out = host.ssh("ada", "default-branch tools release");
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "release\n");
    let head = common::git_cmd(&host.repo("ada", "tools")).args(["symbolic-ref", "HEAD"]).output().unwrap();
    assert_eq!(head.stdout, b"refs/heads/release\n");

    // Names that aren't existing branches, or aren't branch names at all, change nothing.
    for bad in ["missing", "-x", "../main", "HEAD", "refs/heads/main", "main^"] {
        let out = host.ssh("ada", &format!("default-branch tools '{bad}'"));
        assert!(!out.status.success(), "{bad} was accepted");
        assert!(stderr(&out).contains("no branch named"), "{bad}: {}", stderr(&out));
    }
    assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "release\n");
    let out = host.admin(&["default-branch", "ada", "tools", "main"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stdout(&host.ssh("ada", "default-branch tools")), "main\n");
    assert!(!host.ssh("bob", "default-branch tools release").status.success());
}

#[test]
fn adding_a_key_again_with_a_label_renames_it() {
    let host = Host::new("admin-keys-relabel");
    let file = host.dir.join("ada.pub");
    fs::write(&file, ed25519_key(51)).unwrap();
    let blob = ed25519_key(52).split_whitespace().nth(1).unwrap().to_string();
    // Another key, written by hand: options with quoted spaces, an old comment, no final newline.
    let handwritten =
        format!("command=\"/usr/local/bin/gitv serve ada\",from=\"10.0.0.1, 10.0.0.2\" ssh-ed25519 {blob}");
    fs::write(&host.keys, format!("# keep me\n{handwritten} old laptop")).unwrap();
    assert!(host.admin(&["add-key", "ada", file.to_str().unwrap()]).status.success());

    // Again without a label is still a mistake.
    let out = host.admin(&["add-key", "ada", file.to_str().unwrap()]);
    assert!(!out.status.success() && stderr(&out).contains("already registered"), "{}", stderr(&out));
    // With one, the key is renamed in place.
    let before = fs::read_to_string(&host.keys).unwrap();
    let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", "omarchy"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stdout(&out).starts_with("relabelled SHA256:") && stdout(&out).trim_end().ends_with(" omarchy"));
    let after = fs::read_to_string(&host.keys).unwrap();
    assert_eq!(after.lines().count(), before.lines().count(), "no line was added");
    assert_eq!(after.lines().nth(2).unwrap(), format!("{} omarchy", before.lines().nth(2).unwrap()));
    let out = host.admin(&["add-key", "ada", file.to_str().unwrap(), "--label", "work laptop"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(
        fs::read_to_string(&host.keys)
            .unwrap()
            .lines()
            .nth(2)
            .unwrap()
            .ends_with(&format!("{} work laptop", ed25519_key(51).split_whitespace().nth(1).unwrap()))
    );

    // A hand-written line keeps its options; only the comment changes, and the ending stays.
    let other = host.dir.join("other.pub");
    fs::write(&other, ed25519_key(52)).unwrap();
    let out = host.admin(&["add-key", "ada", other.to_str().unwrap(), "--label", "desk"]);
    assert!(out.status.success(), "{}", stderr(&out));
    let text = fs::read_to_string(&host.keys).unwrap();
    assert!(text.starts_with(&format!("# keep me\n{handwritten} desk\n")), "{text}");
    assert!(stdout(&host.admin(&["keys", "ada"])).contains("  desk\n"));

    // A key never moves to another owner, and a refusal changes nothing.
    let before = fs::read(&host.keys).unwrap();
    let out = host.admin(&["add-key", "bob", file.to_str().unwrap(), "--label", "mine"]);
    assert!(!out.status.success() && stderr(&out).contains("another owner"), "{}", stderr(&out));
    assert_eq!(fs::read(&host.keys).unwrap(), before);
}

#[test]
fn a_protected_repository_refuses_rewrites_and_deletions() {
    let host = Host::new("ssh-protect");
    let dir = work("ssh-protect-work", "main");
    git(&dir, &["branch", "feature"]);
    let push = |args: &[&str]| host.git(&dir, &[&["push", "ada@x:ada/tools.git"][..], args].concat());
    assert!(push(&["main", "feature"]).status.success());
    assert_eq!(stdout(&host.ssh("ada", "protect tools")), "off\n");
    let out = host.ssh("ada", "protect tools on");
    assert!(out.status.success(), "{}", stderr(&out));
    assert_eq!(stdout(&host.ssh("ada", "protect tools")), "on\n");
    let repo = host.repo("ada", "tools");
    let tip = |branch: &str| git(&repo, &["rev-parse", branch]);

    // Moving forwards, and new branches and tags, still work.
    fs::write(dir.join("hello.txt"), "more\n").unwrap();
    git(&dir, &["commit", "-qam", "Second"]);
    git(&dir, &["tag", "v1"]);
    let out = push(&["main", "v1", "main:refs/heads/new"]);
    assert!(out.status.success(), "{}", stderr(&out));
    let second = tip("main");

    // A rewrite of any branch, and any deletion, is refused and changes nothing.
    git(&dir, &["commit", "-q", "--amend", "-m", "Rewritten"]);
    let out = push(&["--force", "main"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("non-fast-forward"), "{}", stderr(&out));
    assert_eq!(tip("main"), second);
    // Every branch, not just the default: `new` is at Second, and First would rewind it.
    let out = push(&["--force", "HEAD~1:new"]);
    assert!(!out.status.success(), "other branches are protected too");
    assert_eq!(tip("new"), second);
    let out = push(&[":feature"]);
    assert!(!out.status.success(), "a branch was deleted");
    assert!(stderr(&out).contains("deletion prohibited"), "{}", stderr(&out));
    assert!(git(&repo, &["show-ref"]).contains("refs/heads/feature"));
    // Git applies both settings to branches only. A deleted tag is still in the push log, so
    // it can be put back.
    assert!(push(&[":refs/tags/v1"]).status.success(), "git now protects tags too: update the docs");
    let log = fs::read_to_string(repo.join("gitv-push.log")).unwrap();
    assert!(log.lines().last().unwrap().ends_with(&format!(" {second} - refs/tags/v1")), "{log}");
    // Kept by gitv, not in the repository's own config, where a later tool might drop it.
    assert!(!fs::read_to_string(repo.join("config")).unwrap().contains("receive."));
    // Recovery still records every change that did happen, and only those.
    assert_eq!(log.lines().count(), 6, "{log}");

    // Only the owner's key, and only on or off.
    assert!(!host.ssh("bob", "protect tools off").status.success());
    assert!(!host.ssh("ada", "protect tools maybe").status.success());
    assert_eq!(stdout(&host.ssh("ada", "protect tools")), "on\n");
    // Turned off, as root here, a rewrite goes through.
    assert!(host.admin(&["protect", "ada", "tools", "off"]).status.success());
    let out = push(&["--force", "main"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert_ne!(tip("main"), second);
}

#[test]
fn hooks_in_a_repository_never_run() {
    use std::os::unix::fs::PermissionsExt;
    let host = Host::new("ssh-no-hooks");
    let dir = work("ssh-no-hooks-work", "main");
    assert!(host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]).status.success());
    // A hook planted in the repository, as one copied in with a restored folder could be.
    let ran = host.dir.join("hook-ran");
    let hooks = host.repo("ada", "tools").join("hooks");
    fs::create_dir_all(&hooks).unwrap();
    for hook in ["pre-receive", "post-receive", "update"] {
        let path = hooks.join(hook);
        fs::write(&path, format!("#!/bin/sh\ntouch '{}'\n", ran.display())).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
    }
    fs::write(dir.join("hello.txt"), "again\n").unwrap();
    git(&dir, &["commit", "-qam", "Second"]);
    let out = host.git(&dir, &["push", "-q", "ada@x:ada/tools.git", "main"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(!ran.exists(), "a hook ran");
}