legit-hamming 0.1.4

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
//! The `deploy/` examples: the accept script run on snapshots the library writes, against the real
//! `legit-hamming verify`; the systemd units checked flag by flag against the program's help and
//! against each other; and the README and every example file checked to name nothing private or
//! secret, and to name each other.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

fn crate_dir() -> &'static Path {
    Path::new(env!("CARGO_MANIFEST_DIR"))
}

fn program() -> &'static str {
    env!("CARGO_BIN_EXE_legit-hamming")
}

/// The accept script run, and the tools it needs checked: built on Linux only, where the script
/// runs (bash, `flock`, GNU coreutils and GNU findutils).
#[cfg(target_os = "linux")]
mod accept {
    use std::fs;
    use std::os::unix::fs::PermissionsExt;
    use std::path::{Path, PathBuf};
    use std::process::{Command, Output, Stdio};
    use std::time::{Duration, Instant, SystemTime};

    use legit_hamming::{Records, Value, snapshot};
    use serde_json::Value as Json;

    use super::{crate_dir, program};
    use crate::support::TempDir;

    const SET: &str = "images-pdq";
    const ID: &str = "2026-12-02T12-00-00Z";

    fn script() -> PathBuf {
        crate_dir().join("deploy/legit-hamming-accept")
    }

    /// A root laid out as `/srv/hamming` is, one set's inbox and set directory made, and a settings
    /// file the accept script reads: this root, the built program, no verify user, the lock inside the
    /// root and no quiet time.
    struct Root(TempDir);

    impl Root {
        fn new() -> Self {
            let root = Self(TempDir::new());
            fs::create_dir_all(root.inbox()).expect("the inbox");
            fs::create_dir_all(root.set()).expect("the set directory");
            root.settings("");
            root
        }

        fn path(&self) -> &Path {
            &self.0.0
        }

        fn inbox(&self) -> PathBuf {
            self.path().join("inbox").join(SET)
        }

        fn set(&self) -> PathBuf {
            self.path().join("sets").join(SET)
        }

        fn staging(&self) -> PathBuf {
            self.path().join("staging").join(SET)
        }

        fn rejected(&self) -> PathBuf {
            self.path().join("rejected").join(SET)
        }

        fn conf(&self) -> PathBuf {
            self.path().join("accept.conf")
        }

        fn lock(&self) -> PathBuf {
            self.path().join("accept.lock")
        }

        /// The test settings, then `extra`, whose lines win as later shell assignments do.
        fn settings(&self, extra: &str) {
            let text = format!(
                "ROOT={}\nSETS=\"{SET}\"\nBIN={}\nVERIFY_USER=\"\"\nLOCK={}\nQUIET_SECONDS=0\n{extra}\n",
                self.path().display(),
                program(),
                self.lock().display()
            );
            fs::write(self.conf(), text).expect("the settings");
            fs::set_permissions(self.conf(), fs::Permissions::from_mode(0o644)).expect("mode 0644");
        }

        /// Run the accept script once.
        fn run(&self) -> Output {
            self.command().output().expect("bash runs the script")
        }

        /// The accept script as [`Root::run`] runs it, for a test to add to.
        fn command(&self) -> Command {
            let mut command = Command::new("bash");
            command
                .arg(script())
                .env("LEGIT_HAMMING_ACCEPT_CONF", self.conf())
                .stdin(Stdio::null());
            command
        }

        /// Run it, and expect exit status 0.
        fn accept(&self) -> String {
            succeeded(&self.run())
        }

        /// A snapshot of `records` uploaded as `name`, with its own `CURRENT` holding `current`.
        fn upload<V: Value>(&self, name: &str, records: &Records<V>, current: Option<&str>) -> PathBuf {
            let dir = self.inbox().join(name);
            snapshot::write(&dir, records, 100).expect("the snapshot is written");
            if let Some(current) = current {
                fs::write(dir.join("CURRENT"), format!("{current}\n")).expect("its CURRENT");
            }
            dir
        }

        fn status(&self) -> Json {
            let text =
                fs::read_to_string(self.path().join("status").join(format!("{SET}.json"))).expect("a status file");
            serde_json::from_str(&text).expect("the status file is JSON")
        }

        fn reason(&self, name: &str) -> Json {
            let text = fs::read_to_string(self.rejected().join(format!("{name}.reason.json"))).expect("a reason file");
            serde_json::from_str(&text).expect("the reason file is JSON")
        }

        /// What the set's `CURRENT` names, if it is there.
        fn current(&self) -> Option<String> {
            let path = self.set().join("CURRENT");
            assert!(!path.is_symlink(), "the set's CURRENT is never a link");
            fs::read_to_string(path).ok().map(|text| text.trim_end().to_owned())
        }
    }

    /// The standard output of a run of the script that exited 0.
    fn succeeded(output: &Output) -> String {
        let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
        assert_eq!(
            output.status.code(),
            Some(0),
            "the script exits 0: {stdout}{}",
            String::from_utf8_lossy(&output.stderr)
        );
        stdout
    }

    /// The names in `dir`, sorted; none when it is missing.
    fn names(dir: &Path) -> Vec<String> {
        let mut names: Vec<String> = fs::read_dir(dir)
            .map(|entries| {
                entries
                    .map(|entry| entry.expect("an entry").file_name().into_string().expect("UTF-8"))
                    .collect()
            })
            .unwrap_or_default();
        names.sort();
        names
    }

    /// 256-bit records with ids, distinct for each `seed`.
    fn wide(seed: u64) -> Records<[u64; 4]> {
        Records::from_records(
            (0..300u64).map(|i| (i * 3 + 1, [i ^ seed, i.wrapping_mul(0x9e37_79b9_7f4a_7c15), !i, seed])),
        )
        .expect("ids rise")
    }

    /// 64-bit records with ids, distinct for each `seed`.
    fn narrow(seed: u64) -> Records<u64> {
        Records::from_records((0..300u64).map(|i| (i * 2 + 1, i.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ seed)))
            .expect("ids rise")
    }

    /// The modification time of `path` and everything in it set to `when`, as `rsync -a` copies an
    /// exporter's times: the contents first, the directory last.
    fn age(path: &Path, when: SystemTime) {
        if path.is_dir() {
            for entry in fs::read_dir(path).expect("a directory") {
                age(&entry.expect("an entry").path(), when);
            }
        }
        fs::File::open(path)
            .expect("opened")
            .set_modified(when)
            .expect("the time is set");
    }

    fn a_year_ago() -> SystemTime {
        SystemTime::now() - Duration::from_secs(365 * 24 * 3600)
    }

    #[test]
    fn the_tools_the_accept_script_needs_are_installed() {
        // Not a skip: a container without them can't check the script, and must say so.
        let check = Command::new("bash")
            .args([
                "-c",
                "command -v flock && command -v timeout && command -v stat && command -v find",
            ])
            .output()
            .expect("bash runs");
        assert!(
            check.status.success(),
            "bash, flock, timeout, stat and find are installed"
        );
        let version = Command::new("find").arg("--version").output().expect("find runs");
        assert!(
            String::from_utf8_lossy(&version.stdout).contains("GNU findutils"),
            "find is GNU find"
        );
        let scratch = TempDir::new();
        fs::create_dir_all(&scratch.0).expect("a directory");
        fs::write(scratch.0.join("new"), "").expect("a file");
        let newer = Command::new("find")
            .arg(&scratch.0)
            .args(["-newerct", "-60 seconds", "-name", "new"])
            .output()
            .expect("find runs");
        assert!(
            String::from_utf8_lossy(&newer.stdout).contains("new"),
            "find has -newerct"
        );
        let stat = Command::new("stat")
            .args(["-c", "%a %d"])
            .arg(&scratch.0)
            .output()
            .expect("stat runs");
        assert!(stat.status.success(), "stat takes -c");
    }

    #[test]
    fn the_accept_script_parses() {
        let output = Command::new("bash")
            .arg("-n")
            .arg(script())
            .output()
            .expect("bash runs");
        assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
        let mode = fs::metadata(script()).expect("the script").permissions().mode();
        assert_eq!(mode & 0o111, 0o111, "the script is executable");
    }

    #[test]
    fn a_finished_upload_is_verified_moved_and_named_in_current() {
        let root = Root::new();
        let records = wide(1);
        root.upload(ID, &records, Some(ID));
        let stdout = root.accept();
        assert!(stdout.contains(&format!("accepted {SET}/{ID}")), "{stdout}");

        let snapshot = root.set().join(ID);
        assert!(snapshot.join("MANIFEST.json").is_file(), "the snapshot is in the set");
        assert!(!snapshot.join("CURRENT").exists(), "its own CURRENT is gone");
        assert_eq!(root.current().as_deref(), Some(ID), "the set's CURRENT names it");
        assert!(!root.set().join("CURRENT.new").exists(), "no CURRENT.new is left");
        assert_eq!(names(&root.inbox()), Vec::<String>::new(), "the inbox is empty");
        assert_eq!(names(&root.staging()), Vec::<String>::new(), "staging is empty");
        let status = root.status();
        assert_eq!(
            (
                &status["set"],
                &status["current"],
                &status["accepted"],
                &status["rejected"],
                &status["pending"]
            ),
            (
                &Json::from(SET),
                &Json::from(ID),
                &Json::from(1),
                &Json::from(0),
                &Json::from(0)
            )
        );
        assert!(
            status["at"].as_str().is_some_and(|at| at.ends_with('Z')),
            "status has its time"
        );

        // What the worker would serve: the real program checks and searches it.
        let verify = Command::new(program())
            .arg("verify")
            .arg(&snapshot)
            .output()
            .expect("verify runs");
        assert_eq!(
            verify.status.code(),
            Some(0),
            "{}",
            String::from_utf8_lossy(&verify.stdout)
        );
        let value = records.value(5);
        let hex = (0..4).fold(String::new(), |hex, word| hex + &format!("{:016x}", value.word(word)));
        let request =
            format!("{{\"format\":1,\"index\":\"{SET}\",\"width\":256,\"radius\":0,\"values\":[\"{hex}\"]}}\n");
        let mut query = Command::new(program())
            .arg("query")
            .arg("--index")
            .arg(format!("{SET}={}", root.set().display()))
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .expect("query runs");
        std::io::Write::write_all(&mut query.stdin.take().expect("stdin"), request.as_bytes()).expect("written");
        let output = query.wait_with_output().expect("query ends");
        assert_eq!(output.status.code(), Some(0));
        let result: Json = serde_json::from_slice(&output.stdout).expect("a result line");
        assert_eq!(result["snapshot"], ID);
        let matches = result["queries"][0]["matches"].as_array().expect("matches");
        assert!(
            matches.iter().any(|found| found["id"] == records.id(5).expect("ids")),
            "the stored value is found: {result}"
        );
    }

    #[test]
    fn an_upload_without_current_or_still_changing_waits_in_the_inbox() {
        let root = Root::new();
        let dir = root.upload(ID, &wide(2), None);
        root.accept();
        assert!(
            dir.join("MANIFEST.json").is_file(),
            "an upload with no CURRENT is left alone"
        );
        assert_eq!(root.status()["pending"], 1);
        assert_eq!(root.current(), None);

        fs::write(dir.join("CURRENT"), format!("{ID}\n")).expect("CURRENT");
        root.settings("QUIET_SECONDS=3600");
        root.accept();
        assert!(
            dir.join("CURRENT").is_file(),
            "an upload changed within the quiet time is left alone"
        );
        assert_eq!(root.status()["pending"], 1);
        assert_eq!(names(&root.set()), Vec::<String>::new(), "nothing was taken");
    }

    #[test]
    fn an_unfinished_upload_with_nothing_new_is_dropped() {
        let root = Root::new();
        let dir = root.upload(ID, &wide(3), None);
        root.settings("STALE_MINUTES=0");
        let stdout = root.accept();
        assert!(!dir.exists(), "the unfinished upload is gone");
        assert!(stdout.contains("dropped"), "{stdout}");
        assert_eq!(root.status()["pending"], 0);
        assert_eq!(root.status()["rejected"], 0);
    }

    #[test]
    fn a_current_naming_another_directory_is_rejected() {
        let root = Root::new();
        root.upload("served", &wide(4), Some("served"));
        root.accept();
        root.upload(ID, &wide(5), Some("another"));
        let stdout = root.accept();
        assert!(stdout.contains(&format!("rejected {SET}/{ID}")), "{stdout}");
        assert!(
            root.rejected().join(ID).join("MANIFEST.json").is_file(),
            "it is kept among the rejected"
        );
        let reason = root.reason(ID);
        assert_eq!(reason["name"], ID);
        assert_eq!(reason["reason"], "CURRENT does not name its own directory");
        assert!(reason["at"].as_str().is_some_and(|at| at.ends_with('Z')));
        assert_eq!(
            root.current().as_deref(),
            Some("served"),
            "the set's CURRENT is unchanged"
        );
        assert!(!root.set().join(ID).exists());
        let status = root.status();
        assert_eq!(
            (&status["accepted"], &status["rejected"]),
            (&Json::from(1), &Json::from(1))
        );
        assert_eq!(status["last_rejected"], ID);
    }

    #[test]
    fn a_snapshot_verify_refuses_is_rejected_with_its_message_in_valid_json() {
        let root = Root::new();
        let dir = root.upload(ID, &wide(6), Some(ID));
        let part = dir.join("part-00001.bin");
        let mut bytes = fs::read(&part).expect("a part");
        bytes[17] ^= 0x40;
        fs::write(&part, bytes).expect("damaged");
        root.accept();
        assert!(root.rejected().join(ID).is_dir(), "it is rejected");
        let reason = root.reason(ID);
        let text = reason["reason"].as_str().expect("a reason");
        assert!(text.starts_with("verify failed:"), "{text}");
        // verify prints JSON, so its quotes were escaped into the reason file, which still parsed.
        assert!(text.contains('"'), "verify's own message is quoted: {text}");
        assert_eq!(root.current(), None, "nothing is served");
        assert_eq!(names(&root.set()), Vec::<String>::new());
    }

    #[test]
    fn links_files_and_directories_where_only_plain_files_belong_are_refused() {
        let root = Root::new();
        let outside = root.path().join("outside");
        fs::create_dir_all(&outside).expect("a directory outside the inbox");
        fs::write(outside.join("kept"), "not the uploader's").expect("a file outside");

        // A part replaced by a link.
        let linked = root.upload("part-linked", &wide(7), Some("part-linked"));
        fs::rename(linked.join("part-00000.bin"), outside.join("part-00000.bin")).expect("moved away");
        std::os::unix::fs::symlink(outside.join("part-00000.bin"), linked.join("part-00000.bin")).expect("a link");
        // A link beside the parts.
        let beside = root.upload("link-beside", &wide(8), Some("link-beside"));
        std::os::unix::fs::symlink(outside.join("kept"), beside.join("extra")).expect("a link");
        // A directory inside.
        let nested = root.upload("nested", &wide(9), Some("nested"));
        fs::create_dir(nested.join("deeper")).expect("a subdirectory");
        // At the top of the inbox: a link to a directory, and a plain file.
        std::os::unix::fs::symlink(&outside, root.inbox().join("top-link")).expect("a link");
        fs::write(root.inbox().join("top-file"), "a file").expect("a file");

        root.settings("KEEP_REJECTED=5");
        root.accept();
        for name in ["part-linked", "link-beside", "nested"] {
            let reason = root.reason(name);
            assert_eq!(
                reason["reason"], "it holds something that is not a plain file",
                "{name}"
            );
        }
        assert_eq!(
            names(&root.inbox()),
            Vec::<String>::new(),
            "the top-level link and file are removed"
        );
        assert_eq!(
            fs::read_to_string(outside.join("kept")).expect("kept"),
            "not the uploader's"
        );
        assert!(
            outside.join("part-00000.bin").is_file(),
            "a link's target is never touched"
        );
        assert_eq!(root.current(), None);
        assert_eq!(root.status()["rejected"], 3);
    }

    #[test]
    fn a_name_already_accepted_is_rejected_and_the_served_one_kept() {
        let root = Root::new();
        root.upload(ID, &wide(10), Some(ID));
        root.accept();
        let manifest = fs::read(root.set().join(ID).join("MANIFEST.json")).expect("the manifest");

        root.upload(ID, &wide(11), Some(ID));
        root.accept();
        assert_eq!(
            root.reason(ID)["reason"],
            "a snapshot of that name was already accepted"
        );
        assert_eq!(
            fs::read(root.set().join(ID).join("MANIFEST.json")).expect("the manifest"),
            manifest
        );
        assert_eq!(root.current().as_deref(), Some(ID));
        let status = root.status();
        assert_eq!(
            (&status["accepted"], &status["rejected"]),
            (&Json::from(1), &Json::from(1))
        );
    }

    #[test]
    fn bad_and_reserved_names_are_rejected() {
        let root = Root::new();
        root.upload(ID, &wide(12), Some(ID));
        root.accept();
        for name in [".hidden", "CURRENT", "x.reason.json"] {
            root.upload(name, &wide(13), Some(name));
        }
        root.settings("KEEP_REJECTED=5");
        root.accept();
        assert_eq!(names(&root.inbox()), Vec::<String>::new());
        assert!(root.set().join("CURRENT").is_file(), "the set's CURRENT stays a file");
        assert_eq!(root.current().as_deref(), Some(ID));
        assert_eq!(names(&root.set()), [ID, "CURRENT"]);
        let rejected: Vec<String> = names(&root.rejected())
            .into_iter()
            .filter(|name| !name.ends_with(".json"))
            .collect();
        assert_eq!(rejected.len(), 3, "{rejected:?}");
        for name in rejected {
            assert!(
                name.starts_with("bad-name-"),
                "a bad name is never used as a path: {name}"
            );
            assert_eq!(
                root.reason(&name)["reason"],
                "the directory name is not a valid snapshot name"
            );
        }
        assert_eq!(root.status()["rejected"], 3);
    }

    #[test]
    fn pruning_keeps_the_newest_two_accepted_and_rejected() {
        let root = Root::new();
        for name in ["s1", "s2", "s3"] {
            root.upload(
                name,
                &narrow(name.len() as u64 + u64::from(name.as_bytes()[1])),
                Some(name),
            );
            root.accept();
        }
        assert_eq!(names(&root.set()), ["CURRENT", "s2", "s3"]);
        assert_eq!(root.current().as_deref(), Some("s3"));

        for name in ["r1", "r2", "r3"] {
            root.upload(name, &narrow(7), Some("elsewhere"));
            root.accept();
        }
        assert_eq!(
            names(&root.rejected()),
            ["r2", "r2.reason.json", "r3", "r3.reason.json"],
            "the oldest rejection and its reason file are gone"
        );
        let status = root.status();
        assert_eq!(
            (&status["accepted"], &status["rejected"]),
            (&Json::from(3), &Json::from(3))
        );
    }

    #[test]
    fn pruning_counts_from_acceptance_not_from_upload_times() {
        // Accepted: B and C carry times a year older than A's, as `rsync -a` copies them.
        let root = Root::new();
        root.upload("a", &narrow(1), Some("a"));
        root.accept();
        let b = root.upload("b", &narrow(2), Some("b"));
        age(&b, a_year_ago());
        root.accept();
        let c = root.upload("c", &narrow(3), Some("c"));
        age(&c, a_year_ago());
        root.accept();
        assert_eq!(root.current().as_deref(), Some("c"));
        assert_eq!(
            names(&root.set()),
            ["CURRENT", "b", "c"],
            "A, accepted first, is the one removed"
        );

        // Rejected: the same, for rejections, whose directories nothing else touches.
        let first = root.upload("r1", &narrow(4), Some("elsewhere"));
        drop(first);
        root.accept();
        for name in ["r2", "r3"] {
            let dir = root.upload(name, &narrow(5), Some("elsewhere"));
            age(&dir, a_year_ago());
            root.accept();
        }
        assert_eq!(
            names(&root.rejected()),
            ["r2", "r2.reason.json", "r3", "r3.reason.json"],
            "R1, rejected first, is the one removed"
        );
    }

    #[test]
    fn pruning_never_removes_the_snapshot_served() {
        let root = Root::new();
        // A directory put in the set by hand, with a time in the future: newest by its time.
        let by_hand = root.set().join("by-hand");
        fs::create_dir(&by_hand).expect("a directory");
        fs::File::open(&by_hand)
            .expect("opened")
            .set_modified(SystemTime::now() + Duration::from_secs(3600))
            .expect("the time is set");
        root.upload(ID, &narrow(6), Some(ID));
        root.settings("KEEP_ACCEPTED=1");
        root.accept();
        assert_eq!(root.current().as_deref(), Some(ID));
        assert_eq!(
            names(&root.set()),
            [ID, "CURRENT"],
            "the one served is kept, whatever the times"
        );
    }

    #[test]
    fn a_current_that_cannot_be_replaced_keeps_what_it_named_and_prunes_nothing() {
        let root = Root::new();
        root.upload("a", &narrow(7), Some("a"));
        root.accept();
        // A directory in the way of CURRENT.new: the write fails, as it would on a full disk.
        fs::create_dir(root.set().join("CURRENT.new")).expect("a directory");
        root.upload("b", &narrow(8), Some("b"));
        root.settings("KEEP_ACCEPTED=1");
        let stdout = root.accept();
        assert!(!stdout.contains("accepted"), "{stdout}");
        assert_eq!(
            root.current().as_deref(),
            Some("a"),
            "CURRENT still names what it named"
        );
        assert!(
            root.set().join("a/MANIFEST.json").is_file(),
            "the snapshot served is not pruned"
        );
        assert!(!root.set().join("b").exists(), "the unnamed snapshot left the set");
        assert_eq!(
            root.reason("b")["reason"],
            "the set's CURRENT could not be replaced; what it named is still served"
        );
        let status = root.status();
        assert_eq!(
            (&status["current"], &status["accepted"], &status["rejected"]),
            (&Json::from("a"), &Json::from(1), &Json::from(1))
        );

        // Once the way is clear, the same name is accepted.
        fs::remove_dir(root.set().join("CURRENT.new")).expect("removed");
        root.upload("b", &narrow(8), Some("b"));
        root.accept();
        assert_eq!(root.current().as_deref(), Some("b"));
        assert_eq!(names(&root.set()), ["CURRENT", "b"]);
    }

    #[test]
    fn a_current_that_is_a_directory_is_never_entered() {
        let root = Root::new();
        fs::create_dir(root.set().join("CURRENT")).expect("a directory");
        root.upload(ID, &narrow(9), Some(ID));
        root.accept();
        assert_eq!(
            names(&root.set().join("CURRENT")),
            Vec::<String>::new(),
            "nothing was moved into it"
        );
        assert!(!root.set().join("CURRENT.new").exists(), "no CURRENT.new is left");
        assert!(!root.set().join(ID).exists());
        assert_eq!(
            root.reason(ID)["reason"],
            "the set's CURRENT could not be replaced; what it named is still served"
        );
    }

    #[test]
    fn an_upload_swapped_for_a_link_just_before_the_move_is_removed_and_its_target_untouched() {
        let root = Root::new();
        root.upload("served", &wide(18), Some("served"));
        root.accept();

        // A directory the uploader must never reach, and an upload that passes every first check.
        let victim = root.path().join("victim");
        fs::create_dir(&victim).expect("the victim directory");
        fs::write(victim.join("secret"), "root's").expect("its file");
        fs::set_permissions(victim.join("secret"), fs::Permissions::from_mode(0o600)).expect("mode 0600");
        fs::set_permissions(&victim, fs::Permissions::from_mode(0o700)).expect("mode 0700");
        let upload = root.upload(ID, &wide(19), Some(ID));

        // An `mv` first in PATH that, asked to move this upload into staging, first replaces it with a
        // link to the victim, as an uploader could at that moment; then it runs the real `mv`.
        let real = Command::new("bash")
            .args(["-c", "command -v mv"])
            .output()
            .expect("bash runs");
        let real = String::from_utf8(real.stdout).expect("UTF-8").trim().to_owned();
        assert!(real.starts_with('/'), "the real mv is found: {real}");
        let bin = root.path().join("bin");
        fs::create_dir(&bin).expect("a directory for the wrapper");
        let wrapper = bin.join("mv");
        fs::write(
            &wrapper,
            format!(
                "#!/bin/bash\nif [ \"$2\" = '{upload}' ] && [ \"$3\" = '{staged}' ]; then\n  \
                 rm -rf -- \"$2\" && ln -s -- '{victim}' \"$2\" || exit 99\nfi\nexec '{real}' \"$@\"\n",
                upload = upload.display(),
                staged = root.staging().join(ID).display(),
                victim = victim.display(),
            ),
        )
        .expect("the wrapper");
        fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).expect("executable");
        let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default());

        let stdout = succeeded(&root.command().env("PATH", path).output().expect("bash runs the script"));
        let mode = |path: &Path| fs::symlink_metadata(path).expect("there").permissions().mode() & 0o7777;
        assert_eq!(
            format!("{:o}", mode(&victim)),
            "700",
            "the victim directory's mode is unchanged"
        );
        assert_eq!(
            format!("{:o}", mode(&victim.join("secret"))),
            "600",
            "its file's mode is unchanged"
        );
        assert_eq!(
            fs::read_to_string(victim.join("secret")).expect("still there"),
            "root's"
        );
        assert!(
            stdout.contains(&format!("removed {SET}/{ID}: not a directory")),
            "{stdout}"
        );
        assert!(!stdout.contains("accepted"), "{stdout}");
        assert_eq!(
            root.current().as_deref(),
            Some("served"),
            "the set's CURRENT is as it was"
        );
        assert_eq!(names(&root.set()), ["CURRENT", "served"], "nothing was accepted");
        assert_eq!(names(&root.staging()), Vec::<String>::new(), "staging is empty");
        assert_eq!(names(&root.inbox()), Vec::<String>::new(), "the link left the inbox");
        let status = root.status();
        assert_eq!(
            (&status["accepted"], &status["rejected"]),
            (&Json::from(1), &Json::from(0))
        );
    }

    #[test]
    fn a_link_left_in_staging_is_removed_never_rejected_and_its_target_untouched() {
        let root = Root::new();
        let target = root.path().join("target");
        fs::create_dir(&target).expect("a directory outside");
        fs::write(target.join("kept"), "not the script's").expect("a file");
        age(&target, a_year_ago());
        fs::set_permissions(&target, fs::Permissions::from_mode(0o700)).expect("mode 0700");
        let before = fs::metadata(&target).expect("the target").modified().expect("a time");
        fs::create_dir_all(root.staging()).expect("staging");
        std::os::unix::fs::symlink(&target, root.staging().join(ID)).expect("a link in staging");

        let stdout = root.accept();
        let after = fs::metadata(&target).expect("the target");
        assert_eq!(
            after.modified().expect("a time"),
            before,
            "the target's time is unchanged"
        );
        assert_eq!(
            format!("{:o}", after.permissions().mode() & 0o7777),
            "700",
            "the target's mode is unchanged"
        );
        assert_eq!(
            fs::read_to_string(target.join("kept")).expect("still there"),
            "not the script's"
        );
        assert!(
            stdout.contains(&format!("removed {SET}/{ID}: a symbolic link, not rejected")),
            "{stdout}"
        );
        assert_eq!(names(&root.staging()), Vec::<String>::new(), "staging is empty");
        assert_eq!(names(&root.rejected()), Vec::<String>::new(), "nothing was rejected");
        assert_eq!(root.status()["rejected"], 0);
    }

    #[test]
    fn a_snapshot_left_in_staging_is_rejected() {
        let root = Root::new();
        let left = root.staging().join(ID);
        fs::create_dir_all(&left).expect("a directory in staging");
        fs::write(left.join("part-00000.bin"), [0u8; 16]).expect("a part");
        let stdout = root.accept();
        assert!(stdout.contains("interrupted"), "{stdout}");
        assert_eq!(root.reason(ID)["reason"], "interrupted while it was being checked");
        assert_eq!(names(&root.staging()), Vec::<String>::new());
        assert_eq!(root.current(), None, "it is never served");
    }

    #[test]
    fn settings_that_others_can_write_or_that_are_wrong_stop_the_script() {
        let root = Root::new();
        let dir = root.upload(ID, &wide(14), Some(ID));
        fs::set_permissions(root.conf(), fs::Permissions::from_mode(0o666)).expect("mode 0666");
        let output = root.run();
        assert_eq!(output.status.code(), Some(2));
        assert!(String::from_utf8_lossy(&output.stderr).contains("writable"));
        assert!(dir.join("CURRENT").is_file(), "nothing moved");
        assert!(!root.path().join("status").exists(), "nothing written");

        for (setting, message) in [
            ("QUIET_SECONDS=soon", "must be a number"),
            ("KEEP_ACCEPTED=0", "at least 1"),
            ("BIN=/nonexistent/legit-hamming", "no program"),
            ("ROOT=relative", "ROOT must be"),
        ] {
            root.settings(setting);
            let output = root.run();
            assert_eq!(output.status.code(), Some(2), "{setting}");
            assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{setting}");
            assert!(dir.join("CURRENT").is_file(), "nothing moved with {setting}");
        }

        fs::remove_file(root.conf()).expect("removed");
        assert_eq!(root.run().status.code(), Some(2), "no settings file");
    }

    #[test]
    fn a_set_name_that_is_not_an_index_name_is_skipped() {
        let root = Root::new();
        root.upload(ID, &wide(15), Some(ID));
        root.settings(&format!("SETS=\"Bad Name * {SET}\""));
        let stdout = root.accept();
        assert!(stdout.contains("skipped set Bad: not an index name"), "{stdout}");
        assert!(stdout.contains("skipped set Name: not an index name"), "{stdout}");
        assert!(
            stdout.contains("skipped set *: not an index name"),
            "never expanded as a pattern: {stdout}"
        );
        assert_eq!(root.current().as_deref(), Some(ID), "the valid set is still served");
    }

    #[test]
    fn a_set_whose_inbox_is_missing_is_skipped() {
        let root = Root::new();
        root.settings(&format!("SETS=\"missing {SET}\""));
        root.upload(ID, &wide(16), Some(ID));
        let stdout = root.accept();
        assert!(stdout.contains("skipped set missing"), "{stdout}");
        assert_eq!(root.current().as_deref(), Some(ID));
    }

    #[test]
    fn a_run_while_another_holds_the_lock_does_nothing() {
        let root = Root::new();
        let dir = root.upload(ID, &wide(17), Some(ID));
        let mut holder = Command::new("flock")
            .arg(root.lock())
            .args(["sleep", "5"])
            .spawn()
            .expect("flock runs");
        // Wait until the lock is held: a non-blocking try fails then.
        let deadline = Instant::now() + Duration::from_secs(5);
        while Command::new("flock")
            .arg("-n")
            .arg(root.lock())
            .arg("true")
            .status()
            .expect("flock runs")
            .success()
        {
            assert!(Instant::now() < deadline, "the lock is taken");
            std::thread::sleep(Duration::from_millis(20));
        }
        let output = root.run();
        let _ = holder.kill();
        let _ = holder.wait();
        assert_eq!(output.status.code(), Some(0));
        assert!(dir.join("CURRENT").is_file(), "the upload stays in the inbox");
        assert_eq!(root.current(), None);
    }

    #[test]
    fn a_lock_that_is_a_link_stops_the_script_and_its_target_is_untouched() {
        let root = Root::new();
        let dir = root.upload(ID, &wide(20), Some(ID));
        let target = root.path().join("not-a-lock");
        fs::write(&target, "kept").expect("a file");
        std::os::unix::fs::symlink(&target, root.lock()).expect("a link where the lock goes");
        let output = root.run();
        assert_eq!(output.status.code(), Some(2));
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("is a symbolic link"), "{stderr}");
        assert_eq!(
            fs::read_to_string(&target).expect("still there"),
            "kept",
            "never truncated"
        );
        assert!(root.lock().is_symlink(), "the link is left as it was");
        assert!(dir.join("CURRENT").is_file(), "nothing moved");
        assert!(!root.path().join("status").exists(), "nothing written");
    }
}

// The units.

/// The `key=value` lines of a unit file, comments and section headers left out.
fn unit(path: &Path) -> Vec<(String, String)> {
    fs::read_to_string(path)
        .expect("a unit file")
        .lines()
        .map(str::trim)
        .filter(|line| !(line.is_empty() || line.starts_with('#') || line.starts_with(';') || line.starts_with('[')))
        .map(|line| {
            let (key, value) = line.split_once('=').expect("a key=value line");
            (key.trim().to_owned(), value.trim().to_owned())
        })
        .collect()
}

fn values<'a>(unit: &'a [(String, String)], key: &str) -> Vec<&'a str> {
    unit.iter()
        .filter(|(name, _)| name == key)
        .map(|(_, value)| value.as_str())
        .collect()
}

fn one<'a>(unit: &'a [(String, String)], key: &str) -> &'a str {
    let found = values(unit, key);
    assert_eq!(found.len(), 1, "one {key}=");
    found[0]
}

/// The value after `flag` in `command`'s words.
fn flag_value<'a>(command: &'a str, flag: &str) -> Option<&'a str> {
    let words: Vec<&str> = command.split_whitespace().collect();
    words
        .iter()
        .position(|word| *word == flag)
        .and_then(|at| words.get(at + 1).copied())
}

/// Whether `help` holds `flag` as a whole flag, not inside a longer one.
fn names_flag(help: &str, flag: &str) -> bool {
    help.match_indices(flag).any(|(at, _)| {
        let whole = |c: Option<char>| c.is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '-'));
        whole(help[..at].chars().next_back()) && whole(help[at + flag.len()..].chars().next())
    })
}

fn unit_files() -> Vec<PathBuf> {
    let mut files = Vec::new();
    let mut directories = vec![crate_dir().join("deploy/systemd")];
    while let Some(directory) = directories.pop() {
        for entry in fs::read_dir(&directory).expect("a directory") {
            let path = entry.expect("an entry").path();
            if path.is_dir() {
                directories.push(path);
            } else {
                files.push(path);
            }
        }
    }
    files.sort();
    files
}

#[test]
fn every_unit_runs_the_program_with_flags_it_knows() {
    let help = Command::new(program())
        .args(["serve", "--help"])
        .output()
        .expect("the help");
    assert_eq!(help.status.code(), Some(0));
    let help = String::from_utf8(help.stdout).expect("UTF-8");
    let byte_flags = [
        "--max-result-bytes",
        "--max-options-bytes",
        "--max-log-bytes",
        "--max-fetch-bytes",
        "--max-text-bytes",
        "--max-pixels",
    ];
    let files = unit_files();
    assert_eq!(files.len(), 4, "{files:?}");
    let mut serving = 0;
    for path in &files {
        let unit = unit(path);
        let name = path.file_name().expect("a name").to_string_lossy();
        for command in values(&unit, "ExecStart")
            .into_iter()
            .filter(|command| !command.is_empty())
        {
            if name == "legit-hamming-accept.service" {
                assert_eq!(command, "/usr/local/sbin/legit-hamming-accept");
                continue;
            }
            serving += 1;
            assert!(
                command.starts_with("/usr/local/bin/legit-hamming serve "),
                "{name}: {command}"
            );
            let words: Vec<&str> = command.split_whitespace().collect();
            for (at, word) in words.iter().enumerate().filter(|(_, word)| word.starts_with("--")) {
                let flag = word.split('=').next().expect("a flag");
                assert!(names_flag(&help, flag), "{name}: `{flag}` is not a flag of serve");
                if byte_flags.contains(&flag) {
                    let value = word
                        .split_once('=')
                        .map_or_else(|| words.get(at + 1).copied().unwrap_or(""), |(_, value)| value);
                    assert!(
                        !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
                        "{name}: {flag} {value} in plain digits"
                    );
                }
            }
            let stop: u64 = one(&unit, "TimeoutStopSec").parse().expect("seconds");
            assert!(
                stop >= 30 + 10,
                "{name}: TimeoutStopSec covers the 30 s shutdown grace and a margin"
            );
            let runtime = one(&unit, "RuntimeDirectory");
            let stats = flag_value(command, "--stats-file").expect("a stats file");
            assert!(
                stats.starts_with(&format!("/run/{runtime}/")),
                "{name}: the stats file is in the runtime directory"
            );
        }
    }
    assert_eq!(serving, 2, "two worker units");
}

#[test]
fn the_fixed_and_dynamic_user_units_differ_only_in_the_user_and_the_state_directory() {
    let systemd = crate_dir().join("deploy/systemd");
    let fixed = unit(&systemd.join("legit-hamming.service"));
    let dynamic = unit(&systemd.join("legit-hamming.dynamic-user.service"));
    assert_eq!(values(&dynamic, "DynamicUser"), ["yes"]);
    assert!(values(&dynamic, "User").is_empty());
    assert_eq!(values(&fixed, "User"), ["legit-hamming"]);
    assert!(values(&fixed, "DynamicUser").is_empty());

    let state = one(&fixed, "StateDirectory");
    assert_eq!(one(&dynamic, "StateDirectory"), state);
    let fixed_start = one(&fixed, "ExecStart");
    let dynamic_start = one(&dynamic, "ExecStart");
    assert_eq!(
        flag_value(fixed_start, "--state-dir"),
        Some(format!("/var/lib/{state}").as_str())
    );
    assert_eq!(
        flag_value(dynamic_start, "--state-dir"),
        Some(format!("/var/lib/private/{state}").as_str())
    );
    fn other(command: &str) -> Vec<&str> {
        let words: Vec<&str> = command.split_whitespace().collect();
        let at = words
            .iter()
            .position(|word| *word == "--state-dir")
            .expect("--state-dir");
        [&words[..=at], &words[at + 2..]].concat()
    }
    assert_eq!(
        other(fixed_start),
        other(dynamic_start),
        "every other word of ExecStart= is the same"
    );

    // Every other line is the same too, apart from the user.
    let without = |unit: &[(String, String)]| -> Vec<(String, String)> {
        unit.iter()
            .filter(|(key, _)| !["User", "Group", "DynamicUser", "ExecStart"].contains(&key.as_str()))
            .cloned()
            .collect()
    };
    assert_eq!(without(&fixed), without(&dynamic));
}

// What the README and the examples name.

/// Every file under `deploy/`.
fn deploy_files() -> Vec<PathBuf> {
    let mut files = Vec::new();
    let mut directories = vec![crate_dir().join("deploy")];
    while let Some(directory) = directories.pop() {
        for entry in fs::read_dir(&directory).expect("a directory") {
            let path = entry.expect("an entry").path();
            if path.is_dir() {
                directories.push(path);
            } else {
                files.push(path);
            }
        }
    }
    files.sort();
    files
}

/// Whether `word` appears in `text` as a whole word, of letters, digits, `_` and `-`.
fn whole_word(text: &str, word: &str) -> bool {
    text.match_indices(word).any(|(at, _)| {
        let boundary = |c: Option<char>| c.is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '-'));
        boundary(text[..at].chars().next_back()) && boundary(text[at + word.len()..].chars().next())
    })
}

/// Each dotted quad of `text` in a private range, unless written as the range's own block.
fn private_addresses(text: &str) -> Vec<String> {
    let blocks = [
        [["10", "0", "0", "0"].join("."), "/8".to_owned()].concat(),
        [["172", "16", "0", "0"].join("."), "/12".to_owned()].concat(),
        [["192", "168", "0", "0"].join("."), "/16".to_owned()].concat(),
        [["100", "64", "0", "0"].join("."), "/10".to_owned()].concat(),
    ];
    let bytes = text.as_bytes();
    let mut found = Vec::new();
    let mut at = 0;
    while at < bytes.len() {
        if !bytes[at].is_ascii_digit() || (at > 0 && (bytes[at - 1].is_ascii_digit() || bytes[at - 1] == b'.')) {
            at += 1;
            continue;
        }
        let end = at
            + bytes[at..]
                .iter()
                .take_while(|b| b.is_ascii_digit() || **b == b'.')
                .count();
        let run = text[at..end].trim_end_matches('.');
        let octets: Vec<u32> = run.split('.').map_while(|octet| octet.parse().ok()).collect();
        if run.split('.').count() == 4 && octets.len() == 4 && octets.iter().all(|octet| *octet <= 255) {
            let [a, b, ..] = [octets[0], octets[1], octets[2], octets[3]];
            let private = a == 10
                || (a == 172 && (16..=31).contains(&b))
                || (a == 192 && b == 168)
                || (a == 100 && (64..=127).contains(&b));
            if private && !blocks.iter().any(|block| text[at..].starts_with(block.as_str())) {
                found.push(run.to_owned());
            }
        }
        at = end.max(at + 1);
    }
    found
}

/// What a file the package ships must not hold.
fn leaks(text: &str, in_deploy: bool) -> Vec<String> {
    let mut found: Vec<String> = private_addresses(text)
        .into_iter()
        .map(|address| format!("the address {address}"))
        .collect();
    let lower = text.to_lowercase();
    if lower.contains(&[".ts", ".net"].concat()) {
        found.push("a tailnet name".to_owned());
    }
    for home in [["/Us", "ers/"].concat(), ["/ho", "me/"].concat()] {
        if text
            .match_indices(&home)
            .any(|(at, _)| text[at + home.len()..].starts_with(|c: char| c.is_ascii_alphanumeric()))
        {
            found.push(format!("a path under {home}"));
        }
    }
    let body = ["AA", "AA"].concat();
    for prefix in [
        ["ssh-", "ed25519"].concat(),
        ["ssh-", "rsa"].concat(),
        ["ecdsa-", "sha2"].concat(),
    ] {
        for (at, _) in text.match_indices(&prefix) {
            let rest = &text[at + prefix.len()..];
            let key = rest
                .split_whitespace()
                .find(|word| !word.starts_with('-') || word.len() > 30)
                .unwrap_or("");
            if key.starts_with(&body)
                || rest
                    .split_whitespace()
                    .next()
                    .is_some_and(|word| word.starts_with(&body))
            {
                found.push(format!("a {prefix} key"));
            }
        }
    }
    let fingerprint = ["SHA", "256:"].concat();
    for (at, _) in text.match_indices(&fingerprint) {
        let run = text[at + fingerprint.len()..]
            .bytes()
            .take_while(|b| b.is_ascii_alphanumeric() || b"+/=".contains(b))
            .count();
        if run >= 20 {
            found.push("a key fingerprint".to_owned());
        }
    }
    for (at, _) in text.match_indices('@') {
        let local = text[..at]
            .chars()
            .rev()
            .take_while(|c| c.is_ascii_alphanumeric() || "._%+-".contains(*c))
            .count();
        let domain: String = text[at + 1..]
            .chars()
            .take_while(|c| c.is_ascii_alphanumeric() || ".-".contains(*c))
            .collect();
        let domain = domain.trim_end_matches(['.', '-']).to_lowercase();
        let tld = domain.rsplit('.').next().unwrap_or("");
        let address =
            local > 0 && domain.contains('.') && tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic());
        if address && domain != "example.com" && !domain.ends_with(".example.com") {
            found.push(format!("an e-mail address at {domain}"));
        }
    }
    for word in [
        ["med", "ia"].concat(),
        ["ban", "ned"].concat(),
        ["known", "-bad"].concat(),
    ] {
        if whole_word(&lower, &word) {
            found.push(format!("the word {word}"));
        }
    }
    for word in [["TO", "DO"].concat(), ["FIX", "ME"].concat()] {
        if whole_word(text, &word) {
            found.push(format!("a {word} marker"));
        }
    }
    if in_deploy {
        let mut run = 0;
        for byte in text.bytes() {
            run = if byte.is_ascii_hexdigit() { run + 1 } else { 0 };
            if run == 32 {
                found.push("32 or more hexadecimal digits in a row".to_owned());
            }
        }
    }
    found
}

#[test]
fn the_leak_check_finds_what_it_looks_for() {
    let address = ["192", "168", "1", "20"].join(".");
    assert_eq!(
        leaks(&format!("bind {address}"), false),
        [format!("the address {address}")]
    );
    let block = [["10", "0", "0", "0"].join("."), "/8".to_owned()].concat();
    assert!(leaks(&format!("refuses {block}, and 192.0.2.10 and 1.10.0.1.2"), false).is_empty());
    assert_eq!(
        leaks(
            &format!("ssh-ed25519 {}C3NzaC1lZDI1NTE5 someone", ["AA", "AA"].concat()),
            false
        )
        .len(),
        1
    );
    assert!(
        leaks(
            "ssh-ed25519 REPLACE_WITH_THE_EXPORTER_PUBLIC_KEY images-pdq-exporter",
            false
        )
        .is_empty()
    );
    assert_eq!(
        leaks(
            &format!("{}ABCDEFGHIJKLMNOPQRSTUVWXYZ012", ["SHA", "256:"].concat()),
            false
        )
        .len(),
        1
    );
    assert_eq!(leaks(&["someone@", "mail.test.org"].concat(), false).len(), 1);
    assert!(leaks("someone@images.example.com and redis://:x@127.0.0.1:6390", false).is_empty());
    assert_eq!(leaks(&["/ho", "me/someone/x"].concat(), false).len(), 1);
    assert_eq!(leaks(&["the ", "med", "ia server"].concat(), false).len(), 1);
    assert!(leaks("the median", false).is_empty());
    let hex = "0123456789abcdef".repeat(2);
    assert_eq!(leaks(&hex, true).len(), 1);
    assert!(leaks(&hex, false).is_empty());
}

#[test]
fn the_readme_and_the_examples_name_nothing_private_or_secret() {
    let readme = fs::read_to_string(crate_dir().join("README.md")).expect("the README");
    assert_eq!(leaks(&readme, false), Vec::<String>::new(), "README.md");
    let files = deploy_files();
    assert_eq!(files.len(), 10, "{files:?}");
    for path in files {
        let text = fs::read_to_string(&path).expect("a UTF-8 file");
        assert_eq!(leaks(&text, true), Vec::<String>::new(), "{}", path.display());
        let first = text.lines().nth(usize::from(text.starts_with("#!"))).unwrap_or("");
        assert!(first.starts_with('#'), "{} starts with a comment", path.display());
        assert!(
            text.contains("See Deploying in the crate's README"),
            "{} points to Deploying",
            path.display()
        );
    }
}

#[test]
fn the_readme_and_the_examples_name_each_other() {
    let readme = fs::read_to_string(crate_dir().join("README.md")).expect("the README");
    let named: Vec<&str> = readme
        .match_indices("deploy/")
        .filter(|(at, _)| {
            readme[..*at]
                .chars()
                .next_back()
                .is_none_or(|c| !(c.is_ascii_alphanumeric() || "_-./".contains(c)))
        })
        .map(|(at, _)| {
            let length = readme[at..]
                .bytes()
                .take_while(|b| b.is_ascii_alphanumeric() || b"._/-".contains(b))
                .count();
            readme[at..at + length].trim_end_matches('.')
        })
        .collect();
    assert!(!named.is_empty(), "the README names the examples");
    for path in &named {
        assert!(
            crate_dir().join(path).exists(),
            "the README names {path}, which isn't there"
        );
    }
    for path in deploy_files() {
        let relative = path
            .strip_prefix(crate_dir())
            .expect("in the crate")
            .to_string_lossy()
            .into_owned();
        assert!(named.contains(&relative.as_str()), "the README doesn't name {relative}");
    }
}