rch 2.1.32

Remote Compilation Helper - PreToolUse hook CLI
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
//! Checksum and signature verification.

use super::types::UpdateError;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use which::which;

/// Result of verification.
#[derive(Debug)]
#[allow(dead_code)]
pub struct VerificationResult {
    pub checksum_valid: bool,
    pub signature_valid: Option<bool>,
}

/// Verify SHA256 checksum of a file.
pub async fn verify_checksum(
    file_path: &std::path::Path,
    expected: &str,
) -> Result<VerificationResult, UpdateError> {
    verify_checksum_and_signature(file_path, expected, None).await
}

/// Verify checksum and optional signature bundle of a file.
pub async fn verify_checksum_and_signature(
    file_path: &std::path::Path,
    expected: &str,
    signature_bundle: Option<&std::path::Path>,
) -> Result<VerificationResult, UpdateError> {
    let mut file = tokio::fs::File::open(file_path)
        .await
        .map_err(|e| UpdateError::InstallFailed(format!("Failed to open file: {}", e)))?;

    let mut hasher = blake3::Hasher::new();
    let mut buffer = vec![0u8; 64 * 1024]; // 64KB buffer

    loop {
        let bytes_read = file
            .read(&mut buffer)
            .await
            .map_err(|e| UpdateError::InstallFailed(format!("Failed to read file: {}", e)))?;

        if bytes_read == 0 {
            break;
        }

        hasher.update(&buffer[..bytes_read]);
    }

    let actual = hasher.finalize().to_hex().to_string();

    // Also try SHA256 if BLAKE3 doesn't match (GitHub uses SHA256)
    let sha256_actual = compute_sha256(file_path).await?;

    // Check both BLAKE3 and SHA256
    let checksum_valid =
        actual.eq_ignore_ascii_case(expected) || sha256_actual.eq_ignore_ascii_case(expected);

    if !checksum_valid {
        return Err(UpdateError::ChecksumMismatch {
            expected: expected.to_string(),
            actual: sha256_actual,
        });
    }

    let signature_valid = if let Some(bundle_path) = signature_bundle {
        Some(verify_signature(file_path, bundle_path).await?)
    } else {
        None
    };

    Ok(VerificationResult {
        checksum_valid: true,
        signature_valid,
    })
}

/// Compute SHA256 hash of a file.
async fn compute_sha256(file_path: &std::path::Path) -> Result<String, UpdateError> {
    use std::io::Read;

    // Use blocking I/O wrapped in spawn_blocking for SHA256
    let path = file_path.to_path_buf();
    tokio::task::spawn_blocking(move || {
        let mut file = std::fs::File::open(&path)
            .map_err(|e| UpdateError::InstallFailed(format!("Failed to open file: {}", e)))?;

        let mut hasher = sha2::Sha256::new();
        let mut buffer = vec![0u8; 64 * 1024];

        loop {
            let bytes_read = file
                .read(&mut buffer)
                .map_err(|e| UpdateError::InstallFailed(format!("Failed to read file: {}", e)))?;

            if bytes_read == 0 {
                break;
            }

            use sha2::Digest;
            hasher.update(&buffer[..bytes_read]);
        }

        use sha2::Digest;
        Ok(bytes_to_lower_hex(hasher.finalize()))
    })
    .await
    .map_err(|e| UpdateError::InstallFailed(format!("Task failed: {}", e)))?
}

fn bytes_to_lower_hex(bytes: impl AsRef<[u8]>) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let bytes = bytes.as_ref();
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(HEX[(byte >> 4) as usize] as char);
        output.push(HEX[(byte & 0x0f) as usize] as char);
    }
    output
}

/// Expected GitHub Actions OIDC issuer for sigstore verification.
const GITHUB_ACTIONS_OIDC_ISSUER: &str = "https://token.actions.githubusercontent.com";

/// Expected certificate identity pattern for official RCH releases.
/// This must match the GitHub Actions workflow that signs the releases.
///
/// # Anchoring
///
/// Cosign's `--certificate-identity-regexp` uses Go's `regexp.MatchString`
/// which performs *substring* matching. Without explicit `^` and `$`
/// anchors, a malicious certificate whose SAN merely contains our
/// workflow URL as a substring (for example, nested inside another URL)
/// would also satisfy the check. We anchor both ends and escape the `.`
/// metacharacters in `github.com` / `.github` / `.yml` so the pattern
/// matches the real identity shape only:
///
///     ^https://github\.com/Dicklesworthstone/remote_compilation_helper/\.github/workflows/release\.yml@refs/.*$
const RCH_RELEASE_IDENTITY_PATTERN: &str = r"^https://github\.com/Dicklesworthstone/remote_compilation_helper/\.github/workflows/release\.yml@refs/.*$";

/// Verify Sigstore/cosign signature bundle for a file.
///
/// # Security
///
/// This verifies that binaries were signed by the official RCH GitHub Actions
/// release workflow. It checks:
/// - OIDC issuer is GitHub Actions (`https://token.actions.githubusercontent.com`)
/// - Certificate identity matches the release workflow URL pattern
///
/// Wildcard patterns (`.*`) are intentionally NOT used as they would accept
/// any sigstore signature, defeating supply chain security.
pub(crate) async fn verify_signature(
    file_path: &std::path::Path,
    bundle_path: &std::path::Path,
) -> Result<bool, UpdateError> {
    let executable = which("cosign").map_err(|_| {
        UpdateError::SignatureVerificationFailed("cosign not found in PATH".to_string())
    })?;

    let command = cosign_command(&executable, file_path, bundle_path);
    let output =
        capture_verifier_output(command, std::time::Duration::from_secs(120), 1024 * 1024).await?;

    if output.status.success() {
        Ok(true)
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        Err(UpdateError::SignatureVerificationFailed(format!(
            "cosign verify-blob failed: {}{}",
            stderr.trim(),
            if stdout.trim().is_empty() {
                String::new()
            } else {
                format!(" | {}", stdout.trim())
            }
        )))
    }
}

fn cosign_command(
    executable: &std::path::Path,
    file_path: &std::path::Path,
    bundle_path: &std::path::Path,
) -> Command {
    // Resolve PATH exactly once. Paths and policy are separate arguments,
    // never a shell command or options obtained from the signature bundle.
    let mut command = Command::new(executable);
    command
        .arg("verify-blob")
        .arg("--bundle")
        .arg(bundle_path)
        .arg("--certificate-identity-regexp")
        .arg(RCH_RELEASE_IDENTITY_PATTERN)
        .arg("--certificate-oidc-issuer")
        .arg(GITHUB_ACTIONS_OIDC_ISSUER)
        .arg(file_path);
    command
}

async fn read_verifier_output(
    mut reader: impl tokio::io::AsyncRead + Unpin,
    limit: usize,
) -> std::io::Result<Vec<u8>> {
    let mut output = Vec::new();
    let mut buffer = [0u8; 8192];
    loop {
        let length = match reader.read(&mut buffer).await {
            Ok(0) => return Ok(output),
            Ok(length) => length,
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(error) => return Err(error),
        };
        if length > limit.saturating_sub(output.len()) {
            return Err(std::io::Error::other(
                "signature verifier output limit exceeded",
            ));
        }
        output.extend_from_slice(&buffer[..length]);
    }
}

/// Own the local verifier for its entire exchange, not merely until it exits.
/// A zero status without complete stdout/stderr is not successful verification.
/// The deadline covers pipe EOF as well as the process; overflow and read errors
/// fail closed instead of accepting a valid-looking prefix. On cancellation,
/// kill_on_drop terminates the owned local child. This is not a process-tree or
/// cgroup containment guarantee for helpers launched by an external verifier.
async fn capture_verifier_output(
    mut command: Command,
    budget: std::time::Duration,
    output_limit: usize,
) -> Result<std::process::Output, UpdateError> {
    use std::process::Stdio;

    let mut child = command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .spawn()
        .map_err(|e| {
            UpdateError::SignatureVerificationFailed(format!("Failed to execute cosign: {}", e))
        })?;
    let stdout = child.stdout.take().ok_or_else(|| {
        UpdateError::SignatureVerificationFailed("missing verifier stdout pipe".to_owned())
    })?;
    let stderr = child.stderr.take().ok_or_else(|| {
        UpdateError::SignatureVerificationFailed("missing verifier stderr pipe".to_owned())
    })?;

    let result = tokio::time::timeout(budget, async {
        let (stdout, stderr, status) = tokio::try_join!(
            read_verifier_output(stdout, output_limit),
            read_verifier_output(stderr, output_limit),
            child.wait(),
        )?;
        Ok::<_, std::io::Error>(std::process::Output {
            status,
            stdout,
            stderr,
        })
    })
    .await;
    let mut failure = match result {
        Ok(Ok(output)) => return Ok(output),
        Ok(Err(error)) => format!("cosign output collection failed: {error}"),
        Err(_) => format!("cosign verification timed out after {budget:?}"),
    };

    // The exchange future has dropped its pipe readers and child borrow.
    // Reap the local child explicitly on failure, with a separate small bound;
    // never turn failure to kill or reap into successful verification.
    match tokio::time::timeout(std::time::Duration::from_secs(2), child.kill()).await {
        Ok(Ok(())) => {}
        Ok(Err(error)) => failure.push_str(&format!("; verifier teardown failed: {error}")),
        Err(_) => failure.push_str("; verifier teardown timed out"),
    }
    Err(UpdateError::SignatureVerificationFailed(failure))
}

/// Public key dsr signs every rch release archive with (minisign key id
/// 69B3955C8D2E62A8). A checksum from the same release only detects
/// corruption; this signature is what makes an update authentic (bd-oxxnk).
pub(crate) const RELEASE_MINISIGN_PUBLIC_KEY: &str =
    "RWSoYi6NXJWzaRs1mJmOwwXrZfPWcq6MXnQlNMLBYKzlIQTLwuVQG6uO";

/// Verify `archive` against a `.minisig` document with the pinned release key.
pub(crate) fn verify_minisign(
    archive: &std::path::Path,
    signature_text: &str,
) -> Result<(), UpdateError> {
    verify_minisign_with_key(archive, signature_text, RELEASE_MINISIGN_PUBLIC_KEY)
}

fn verify_minisign_with_key(
    archive: &std::path::Path,
    signature_text: &str,
    public_key: &str,
) -> Result<(), UpdateError> {
    let fail = |detail: String| UpdateError::SignatureVerificationFailed(detail);
    let key = minisign_verify::PublicKey::from_base64(public_key)
        .map_err(|e| fail(format!("invalid pinned minisign key: {e}")))?;
    let signature = minisign_verify::Signature::decode(signature_text)
        .map_err(|e| fail(format!("malformed .minisig: {e}")))?;
    let mut file = std::fs::File::open(archive)
        .map_err(|e| fail(format!("cannot read {}: {e}", archive.display())))?;
    verify_minisign_reader(&mut file, &key, &signature)
}

const VERIFICATION_CHUNK_BYTES: usize = 64 * 1024;

/// Verify the entire archive without allocating an archive-sized buffer.
/// Streaming retains the existing prehashed-only policy, checks the key ID,
/// and verifies BOTH the payload signature and authenticated comment. A read
/// error, including one after the last payload byte, is never an EOF verdict.
fn verify_minisign_reader(
    reader: &mut impl std::io::Read,
    key: &minisign_verify::PublicKey,
    signature: &minisign_verify::Signature,
) -> Result<(), UpdateError> {
    let fail = |detail: String| UpdateError::SignatureVerificationFailed(detail);
    let mut verifier = key
        .verify_stream(signature)
        .map_err(|e| fail(format!("minisign verification failed: {e}")))?;
    let mut buffer = vec![0u8; VERIFICATION_CHUNK_BYTES];
    loop {
        match reader.read(&mut buffer) {
            Ok(0) => break,
            Ok(length) => verifier.update(&buffer[..length]),
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(error) => return Err(fail(format!("cannot read signed archive: {error}"))),
        }
    }
    verifier
        .finalize()
        .map_err(|e| fail(format!("minisign verification failed: {e}")))
}

/// Verify a byte slice against expected checksum.
#[allow(dead_code)]
pub fn verify_sha256_bytes(content: &[u8], expected: &str) -> Result<(), UpdateError> {
    use sha2::Digest;

    let mut hasher = sha2::Sha256::new();
    hasher.update(content);
    let actual = bytes_to_lower_hex(hasher.finalize());

    if actual.eq_ignore_ascii_case(expected) {
        Ok(())
    } else {
        Err(UpdateError::ChecksumMismatch {
            expected: expected.to_string(),
            actual,
        })
    }
}

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

    // Fixture made once with `minisign -G -W` + `minisign -S` (throwaway key).
    const TEST_KEY: &str = "RWTZPaZ0gaEhqMa/pPZEdaALWkxxAm/EtQzB6egPldD4Uh1cCRlw/b0w";
    const PAYLOAD: &[u8] = b"rch minisign test payload v1\n";
    const SIGNATURE: &str = "untrusted comment: signature from minisign secret key\n\
RUTZPaZ0gaEhqDSXunnChY49+8G9WeMdP7wwnCG9s382LwYf7h09hfwypAG0pKwYrhcX+N1Ujyzv1r4ZpRClO4To6jTL1DR1ewo=\n\
trusted comment: rch test fixture\n\
xfmvGjlaWGXfdNKtFwBNm45V0V6VPZ3lLFhIzfLmQ7xUjPzacD1iHPC0MO2oczUBCt2gAZtoGnuQMxpswMpMCw==\n";

    fn archive(bytes: &[u8]) -> tempfile::NamedTempFile {
        let file = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(file.path(), bytes).unwrap();
        file
    }

    #[test]
    fn genuine_signature_verifies() {
        let file = archive(PAYLOAD);
        verify_minisign_with_key(file.path(), SIGNATURE, TEST_KEY).unwrap();
    }

    #[test]
    fn tampered_archive_is_refused_even_though_it_hashes_cleanly() {
        // An attacker who replaces the archive can also replace the .sha256;
        // the signature is what they cannot forge.
        let file = archive(b"rch minisign test payload v2\n");
        let error = verify_minisign_with_key(file.path(), SIGNATURE, TEST_KEY).unwrap_err();
        assert!(
            error.to_string().contains("minisign verification failed"),
            "{error}"
        );
    }

    #[test]
    fn signature_from_another_key_is_refused() {
        let file = archive(PAYLOAD);
        assert!(verify_minisign(file.path(), SIGNATURE).is_err());
    }

    #[test]
    fn malformed_signature_is_refused() {
        let file = archive(PAYLOAD);
        let error = verify_minisign_with_key(file.path(), "not a minisig", TEST_KEY).unwrap_err();
        assert!(error.to_string().contains("malformed .minisig"), "{error}");
    }

    #[test]
    fn pinned_release_key_parses() {
        minisign_verify::PublicKey::from_base64(RELEASE_MINISIGN_PUBLIC_KEY).unwrap();
    }

    struct Chunked<'a> {
        remaining: &'a [u8],
        chunk: usize,
        interrupt: bool,
        fail_at_eof: bool,
        reads: usize,
    }

    impl std::io::Read for Chunked<'_> {
        fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
            assert!(buffer.len() <= VERIFICATION_CHUNK_BYTES);
            self.reads += 1;
            if self.interrupt {
                self.interrupt = false;
                return Err(std::io::ErrorKind::Interrupted.into());
            }
            if self.remaining.is_empty() && self.fail_at_eof {
                return Err(std::io::Error::other("injected read failure"));
            }
            let length = self.remaining.len().min(self.chunk).min(buffer.len());
            buffer[..length].copy_from_slice(&self.remaining[..length]);
            self.remaining = &self.remaining[length..];
            Ok(length)
        }
    }

    #[test]
    fn minisign_stream_accepts_short_reads_and_interrupted_io() {
        let key = minisign_verify::PublicKey::from_base64(TEST_KEY).unwrap();
        let signature = minisign_verify::Signature::decode(SIGNATURE).unwrap();
        for chunk in 1..=PAYLOAD.len() + 1 {
            let mut reader = Chunked {
                remaining: PAYLOAD,
                chunk,
                interrupt: true,
                fail_at_eof: false,
                reads: 0,
            };
            verify_minisign_reader(&mut reader, &key, &signature).unwrap();
            assert!(reader.remaining.is_empty());
            assert!(
                reader.reads >= 3,
                "interruption, payload and EOF are all required"
            );
        }
    }

    #[test]
    fn minisign_stream_never_turns_read_failure_into_verified_eof() {
        let key = minisign_verify::PublicKey::from_base64(TEST_KEY).unwrap();
        let signature = minisign_verify::Signature::decode(SIGNATURE).unwrap();
        for data in [&PAYLOAD[..0], &PAYLOAD[..5], PAYLOAD] {
            let mut reader = Chunked {
                remaining: data,
                chunk: 3,
                interrupt: false,
                fail_at_eof: true,
                reads: 0,
            };
            let error = verify_minisign_reader(&mut reader, &key, &signature).unwrap_err();
            assert!(
                error.to_string().contains("injected read failure"),
                "{error}"
            );
        }
    }

    #[test]
    fn minisign_stream_checks_truncation_appended_bytes_and_trusted_comment() {
        let key = minisign_verify::PublicKey::from_base64(TEST_KEY).unwrap();
        let signature = minisign_verify::Signature::decode(SIGNATURE).unwrap();
        assert!(
            verify_minisign_reader(&mut &PAYLOAD[..PAYLOAD.len() - 1], &key, &signature).is_err()
        );
        let mut appended = PAYLOAD.to_vec();
        appended.push(0);
        assert!(verify_minisign_reader(&mut appended.as_slice(), &key, &signature).is_err());

        let changed = SIGNATURE.replace(
            "trusted comment: rch test fixture",
            "trusted comment: forged",
        );
        let changed = minisign_verify::Signature::decode(&changed).unwrap();
        assert!(verify_minisign_reader(&mut &PAYLOAD[..], &key, &changed).is_err());
    }

    #[test]
    fn minisign_stream_rejects_a_foreign_key_before_reading_payload() {
        let key = minisign_verify::PublicKey::from_base64(RELEASE_MINISIGN_PUBLIC_KEY).unwrap();
        let signature = minisign_verify::Signature::decode(SIGNATURE).unwrap();
        let mut reader = Chunked {
            remaining: PAYLOAD,
            chunk: 1,
            interrupt: false,
            fail_at_eof: true,
            reads: 0,
        };
        assert!(verify_minisign_reader(&mut reader, &key, &signature).is_err());
        assert_eq!(reader.reads, 0);
    }

    #[test]
    fn minisign_stream_rejects_legacy_mode_without_reading_payload() {
        // Changing only the algorithm preserves a well-formed signature
        // container, not its validity. Legacy mode must be refused upfront.
        let legacy = SIGNATURE.replace("\nRUTZ", "\nRWTZ");
        let signature = minisign_verify::Signature::decode(&legacy).unwrap();
        let key = minisign_verify::PublicKey::from_base64(TEST_KEY).unwrap();
        let mut reader = Chunked {
            remaining: PAYLOAD,
            chunk: 1,
            interrupt: false,
            fail_at_eof: true,
            reads: 0,
        };
        assert!(verify_minisign_reader(&mut reader, &key, &signature).is_err());
        assert_eq!(reader.reads, 0);
    }

    #[test]
    fn minisign_stream_authenticates_bytes_beyond_the_first_buffer() {
        // Throwaway Ed25519 key, independently signed over BLAKE2b-512 of
        // 1 MiB + 7 zero bytes. No production secret or signer is required.
        const KEY: &str = "RWRSQ0h0ZXN0MmBwaHoVCw4YFi8NW0uVH5/PWQ4eAfqB4KheU+mLK3vO";
        const SIG: &str = "untrusted comment: rch stream test\n\
RURSQ0h0ZXN0Mi8mprmagbFizyF2eUefaE/5/jwR84KN9Yyf3OO1y5NwJP1Oe2voxuVRAyhv8L89lerNzNkvMbAIcENd/nq7KA0=\n\
trusted comment: rch bounded verification fixture\n\
Vcz52SNOvweQ+rHxeLsHlafJK6iWhND+nbrEl2yDfYyQfv/z3NEBaNwcXNt5QN5NQX3dPBymXHGFiMas/eJGCg==\n";
        let key = minisign_verify::PublicKey::from_base64(KEY).unwrap();
        let signature = minisign_verify::Signature::decode(SIG).unwrap();
        let mut bytes = vec![0u8; 1024 * 1024 + 7];
        let mut reader = Chunked {
            remaining: &bytes,
            chunk: usize::MAX,
            interrupt: false,
            fail_at_eof: false,
            reads: 0,
        };
        verify_minisign_reader(&mut reader, &key, &signature).unwrap();
        assert!(reader.reads > 16);
        bytes[VERIFICATION_CHUNK_BYTES + 1] = 1;
        assert!(verify_minisign_reader(&mut bytes.as_slice(), &key, &signature).is_err());
    }
}

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

    #[test]
    fn test_verify_sha256_bytes() {
        let content = b"test content";
        // SHA256 of "test content"
        let expected = "6ae8a75555209fd6c44157c0aed8016e763ff435a19cf186f76863140143ff72";

        assert!(verify_sha256_bytes(content, expected).is_ok());
    }

    #[test]
    fn test_verify_sha256_bytes_mismatch() {
        let content = b"test content";
        let wrong = "0000000000000000000000000000000000000000000000000000000000000000";

        let result = verify_sha256_bytes(content, wrong);
        assert!(matches!(result, Err(UpdateError::ChecksumMismatch { .. })));
    }

    #[tokio::test]
    async fn test_compute_sha256() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.txt");

        std::fs::write(&file_path, "test content").unwrap();

        let hash = compute_sha256(&file_path.to_path_buf()).await.unwrap();
        assert_eq!(
            hash,
            "6ae8a75555209fd6c44157c0aed8016e763ff435a19cf186f76863140143ff72"
        );
    }

    #[test]
    fn test_verify_sha256_bytes_case_insensitive() {
        let content = b"test content";
        // SHA256 in uppercase
        let expected_upper = "6AE8A75555209FD6C44157C0AED8016E763FF435A19CF186F76863140143FF72";

        assert!(verify_sha256_bytes(content, expected_upper).is_ok());
    }

    #[test]
    fn test_verify_sha256_bytes_empty_content() {
        let content = b"";
        // SHA256 of empty string
        let expected = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

        assert!(verify_sha256_bytes(content, expected).is_ok());
    }

    #[tokio::test]
    async fn test_compute_sha256_large_file() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("large.bin");

        // Create a larger file (1MB of zeros)
        let content = vec![0u8; 1024 * 1024];
        std::fs::write(&file_path, &content).unwrap();

        let hash = compute_sha256(&file_path.to_path_buf()).await.unwrap();
        // SHA256 of 1MB of zeros
        assert_eq!(
            hash,
            "30e14955ebf1352266dc2ff8067e68104607e750abb9d3b36582b8af909fcb58"
        );
    }

    #[tokio::test]
    async fn test_verify_checksum_sha256() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.txt");

        std::fs::write(&file_path, "test content").unwrap();

        // Verify using SHA256
        let expected = "6ae8a75555209fd6c44157c0aed8016e763ff435a19cf186f76863140143ff72";
        let result = verify_checksum(&file_path, expected).await.unwrap();

        assert!(result.checksum_valid);
    }

    #[tokio::test]
    async fn test_verify_checksum_mismatch() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("test.txt");

        std::fs::write(&file_path, "test content").unwrap();

        // Wrong checksum
        let wrong = "0000000000000000000000000000000000000000000000000000000000000000";
        let result = verify_checksum(&file_path, wrong).await;

        assert!(matches!(result, Err(UpdateError::ChecksumMismatch { .. })));
    }

    #[test]
    fn test_verify_sha256_bytes_binary_content() {
        // Test with binary (non-UTF8) content
        let content: &[u8] = &[0x00, 0x01, 0x02, 0xFF, 0xFE, 0xFD];
        // SHA256 of the above bytes
        let expected = "feb1aba6fea741741b1bbcc974f74fed337b535b8eec7223b6dd15d7108f08e3";

        assert!(verify_sha256_bytes(content, expected).is_ok());
    }

    #[tokio::test]
    async fn test_verify_checksum_file_not_found() {
        let temp = TempDir::new().unwrap();
        let nonexistent = temp.path().join("does_not_exist.bin");

        let result = verify_checksum(&nonexistent, "0".repeat(64).as_str()).await;
        assert!(matches!(
            result,
            Err(UpdateError::InstallFailed(msg)) if msg.contains("Failed to open file")
        ));
    }

    #[tokio::test]
    async fn test_compute_sha256_file_not_found() {
        let temp = TempDir::new().unwrap();
        let nonexistent = temp.path().join("nonexistent.txt");

        let result = compute_sha256(&nonexistent).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_verify_checksum_blake3() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("blake3_test.txt");

        std::fs::write(&file_path, "test content").unwrap();

        // Compute BLAKE3 hash of "test content"
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"test content");
        let blake3_hash = hasher.finalize().to_hex().to_string();

        // verify_checksum should accept BLAKE3 hash
        let result = verify_checksum(&file_path, &blake3_hash).await.unwrap();
        assert!(result.checksum_valid);
    }

    #[test]
    fn test_verification_result_fields() {
        let result = VerificationResult {
            checksum_valid: true,
            signature_valid: Some(true),
        };
        assert!(result.checksum_valid);
        assert_eq!(result.signature_valid, Some(true));

        let result_no_sig = VerificationResult {
            checksum_valid: false,
            signature_valid: None,
        };
        assert!(!result_no_sig.checksum_valid);
        assert!(result_no_sig.signature_valid.is_none());
    }

    #[test]
    fn test_verify_sha256_bytes_invalid_hex_length() {
        let content = b"test";
        // Too short to be a valid SHA256 hash
        let short_hash = "abc123";

        // Should fail because actual hash won't match this short string
        let result = verify_sha256_bytes(content, short_hash);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_verify_checksum_with_mixed_case_hex() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("mixedcase.txt");

        std::fs::write(&file_path, "test content").unwrap();

        // Mixed case SHA256 hash
        let expected = "6Ae8A75555209fD6C44157c0AED8016E763Ff435a19cF186F76863140143Ff72";
        let result = verify_checksum(&file_path, expected).await.unwrap();

        assert!(result.checksum_valid);
    }

    #[tokio::test]
    async fn test_compute_sha256_empty_file() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("empty.txt");

        std::fs::write(&file_path, "").unwrap();

        let hash = compute_sha256(&file_path).await.unwrap();
        // SHA256 of empty file
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    // ============================================================
    // Signature verification tests (post-hoc gap-fill for bd-2bwc)
    //
    // The bead's original AC enumerated 4 sub-criteria:
    //   1. Test valid signature acceptance       -> covered by integration
    //      test (`integration_signature_verifies_with_real_cosign`,
    //      gated on RCH_TEST_REAL_SIG=1 + cosign in PATH).
    //   2. Test invalid signature rejection      -> test_signature_invalid_bundle_returns_err
    //   3. Test missing signature handling       -> test_signature_missing_bundle_yields_none
    //   4. Test key rotation scenarios           -> covered by the
    //      identity-pattern unit tests below; key rotation in cosign
    //      maps to changes in the certificate-identity regex anchor.
    //
    // The bead originally suggested ed25519 fixtures, but the real
    // implementation is cosign + sigstore + GitHub OIDC. End-to-end
    // verification requires real cosign + a real GitHub-signed binary,
    // so the e2e check lives in the integration tier. The unit tier
    // exercises the security-critical surfaces we own: the identity
    // anchor regex and the error-paths through `verify_signature`.
    // ============================================================

    /// Sub-criterion 3: missing signature handling.
    /// `verify_checksum_and_signature(_, _, None)` returns `signature_valid: None`.
    #[tokio::test]
    async fn test_signature_missing_bundle_yields_none() {
        // TEST START: missing signature bundle yields signature_valid=None
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("artifact.bin");
        std::fs::write(&file_path, b"hello world").unwrap();
        let mut hasher = sha2::Sha256::new();
        use sha2::Digest;
        hasher.update(b"hello world");
        let expected = bytes_to_lower_hex(hasher.finalize());

        let result = verify_checksum_and_signature(&file_path, &expected, None)
            .await
            .unwrap();

        assert!(result.checksum_valid);
        assert!(
            result.signature_valid.is_none(),
            "missing signature bundle must yield signature_valid=None, got {:?}",
            result.signature_valid
        );
        // TEST PASS: missing bundle handled
    }

    /// Sub-criterion 2: invalid signature rejection.
    /// A malformed/empty bundle causes cosign (when present) to fail; the
    /// implementation translates that into `SignatureVerificationFailed`.
    /// Skipped when cosign is not installed (CI-friendly).
    #[tokio::test]
    async fn test_signature_invalid_bundle_returns_err() {
        // TEST START: invalid signature bundle is rejected
        if which::which("cosign").is_err() {
            eprintln!("SKIP test_signature_invalid_bundle_returns_err: cosign not installed");
            return;
        }
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("artifact.bin");
        let bundle_path = temp.path().join("artifact.sig");
        std::fs::write(&file_path, b"hello world").unwrap();
        // A malformed bundle: cosign cannot parse this as a valid signature.
        std::fs::write(&bundle_path, b"\x00\x01\x02 totally not a real bundle").unwrap();

        let result = verify_signature(&file_path, &bundle_path).await;
        assert!(matches!(
            result,
            Err(UpdateError::SignatureVerificationFailed(_)) | Ok(false)
        ));
        // TEST PASS: invalid bundle rejected
    }

    /// Sub-criterion 4 (security-anchor portion): the certificate-identity
    /// regex must be anchored at both ends so that substring attacks are
    /// rejected. Without `^`/`$`, a CA-signed certificate whose SAN merely
    /// contained our workflow URL as a substring would satisfy cosign's
    /// regex check (since Go's `regexp.MatchString` is substring-based).
    #[test]
    fn test_rch_release_identity_pattern_is_anchored() {
        // TEST START: certificate-identity regex must use ^...$ anchors
        assert!(
            RCH_RELEASE_IDENTITY_PATTERN.starts_with('^'),
            "identity pattern must start with ^"
        );
        assert!(
            RCH_RELEASE_IDENTITY_PATTERN.ends_with("$"),
            "identity pattern must end with $"
        );
        // Escaped dots (so `.` doesn't act as wildcard).
        assert!(
            RCH_RELEASE_IDENTITY_PATTERN.contains(r"github\.com"),
            "github.com dot must be escaped"
        );
        assert!(
            RCH_RELEASE_IDENTITY_PATTERN.contains(r"\.github/"),
            ".github dot must be escaped"
        );
        assert!(
            RCH_RELEASE_IDENTITY_PATTERN.contains(r"release\.yml"),
            "release.yml dot must be escaped"
        );
        // TEST PASS: anchored + escaped
    }

    /// Sub-criterion 4: legitimate canonical URL is accepted by the regex.
    #[test]
    fn test_rch_release_identity_pattern_accepts_canonical_url() {
        // TEST START: canonical RCH release identity URL matches
        let re = regex::Regex::new(RCH_RELEASE_IDENTITY_PATTERN).unwrap();
        let canonical = "https://github.com/Dicklesworthstone/remote_compilation_helper/.github/workflows/release.yml@refs/tags/v1.0.0";
        assert!(
            re.is_match(canonical),
            "canonical release URL should match: {}",
            canonical
        );
        // Also branch refs:
        let branch_ref = "https://github.com/Dicklesworthstone/remote_compilation_helper/.github/workflows/release.yml@refs/heads/main";
        assert!(re.is_match(branch_ref), "branch ref form should match");
        // TEST PASS: canonical URL accepted
    }

    /// Sub-criterion 4: substring attack URLs MUST NOT match the regex.
    /// This is the security property — if a malicious cert's SAN merely
    /// contains our URL as a substring, anchoring rejects it.
    #[test]
    fn test_rch_release_identity_pattern_rejects_substring_attacks() {
        // TEST START: substring/lookalike URLs must NOT match
        let re = regex::Regex::new(RCH_RELEASE_IDENTITY_PATTERN).unwrap();

        // Different repo (similar prefix attack)
        let attack1 = "https://github.com/Attacker/remote_compilation_helper/.github/workflows/release.yml@refs/tags/v1.0.0";
        assert!(
            !re.is_match(attack1),
            "different-owner URL must not match: {}",
            attack1
        );

        // Subdomain trick
        let attack2 = "https://github.com.evil.example/Dicklesworthstone/remote_compilation_helper/.github/workflows/release.yml@refs/tags/v1.0.0";
        assert!(
            !re.is_match(attack2),
            "subdomain-prefix attack must not match: {}",
            attack2
        );

        // Wrong workflow file
        let attack3 = "https://github.com/Dicklesworthstone/remote_compilation_helper/.github/workflows/sneaky.yml@refs/tags/v1.0.0";
        assert!(
            !re.is_match(attack3),
            "different-workflow URL must not match: {}",
            attack3
        );

        // Wrong protocol — must NOT match (the `^https://` anchor prefix
        // rejects http://).
        let attack4 = "http://github.com/Dicklesworthstone/remote_compilation_helper/.github/workflows/release.yml@refs/tags/v1.0.0";
        assert!(
            !re.is_match(attack4),
            "http (not https) must not match: {}",
            attack4
        );

        // Lookalike-URL prefix attack — the `^` anchor prevents a longer
        // hostname from being treated as a match by substring rule.
        let attack5 = "evilhttps://github.com/Dicklesworthstone/remote_compilation_helper/.github/workflows/release.yml@refs/tags/v1.0.0";
        assert!(
            !re.is_match(attack5),
            "lookalike-host prefix must not match: {}",
            attack5
        );

        // Path-traversal attempt — `.` is escaped in the pattern, so a
        // literal `.github` is required (no wildcard substitution).
        let attack6 = "https://github.com/Dicklesworthstone/remote_compilation_helper/Xgithub/workflows/release.yml@refs/tags/v1.0.0";
        assert!(
            !re.is_match(attack6),
            "missing .github literal must not match: {}",
            attack6
        );
        // TEST PASS: substring attacks rejected
    }

    /// Sub-criterion 1: signature verification with a real cosign bundle.
    /// Gated on RCH_TEST_REAL_SIG=1 AND `cosign` in PATH AND
    /// fixtures present. Skipped silently otherwise.
    #[tokio::test]
    async fn integration_signature_verifies_with_real_cosign() {
        // TEST START: end-to-end signature verification (gated)
        if std::env::var("RCH_TEST_REAL_SIG").is_err() {
            eprintln!(
                "SKIP integration_signature_verifies_with_real_cosign: RCH_TEST_REAL_SIG not set"
            );
            return;
        }
        if which::which("cosign").is_err() {
            eprintln!("SKIP integration_signature_verifies_with_real_cosign: cosign not in PATH");
            return;
        }

        // Fixture paths: the actual binary + .sig bundle from a real RCH release.
        // Place under rch/tests/fixtures/update/. If absent, skip with a clear message.
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let bin = manifest_dir.join("tests/fixtures/update/rch_release_sample.bin");
        let sig = manifest_dir.join("tests/fixtures/update/rch_release_sample.sig");
        if !bin.exists() || !sig.exists() {
            eprintln!(
                "SKIP integration_signature_verifies_with_real_cosign: fixtures missing at {} and/or {}",
                bin.display(),
                sig.display()
            );
            return;
        }

        let result = verify_signature(&bin, &sig).await;
        assert!(
            result.is_ok() && result.unwrap(),
            "real cosign-signed binary should verify"
        );
        // TEST PASS: real signature verified end-to-end
    }
}

#[cfg(test)]
mod bounded_verifier_tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn cosign_preserves_exact_executable_paths_and_trust_policy_arguments() {
        let executable = std::path::Path::new("/verifiers/cosign with spaces");
        let archive = std::path::Path::new("/download/é ' archive.tar.gz");
        let bundle = std::path::Path::new("/download/bundle;not-a-command.json");
        let command = cosign_command(executable, archive, bundle);
        assert_eq!(command.as_std().get_program(), executable.as_os_str());
        let expected = [
            std::ffi::OsStr::new("verify-blob"),
            std::ffi::OsStr::new("--bundle"),
            bundle.as_os_str(),
            std::ffi::OsStr::new("--certificate-identity-regexp"),
            std::ffi::OsStr::new(RCH_RELEASE_IDENTITY_PATTERN),
            std::ffi::OsStr::new("--certificate-oidc-issuer"),
            std::ffi::OsStr::new(GITHUB_ACTIONS_OIDC_ISSUER),
            archive.as_os_str(),
        ];
        assert_eq!(command.as_std().get_args().collect::<Vec<_>>(), expected);
    }

    #[tokio::test]
    async fn verifier_output_accepts_exact_bound_and_refuses_one_extra_byte() {
        for length in [0, 1, 8191, 8192, 8193, 65536] {
            let bytes = vec![0xf0; length];
            assert_eq!(
                read_verifier_output(bytes.as_slice(), length)
                    .await
                    .unwrap(),
                bytes,
            );
            if length > 0 {
                assert!(
                    read_verifier_output(bytes.as_slice(), length - 1)
                        .await
                        .is_err()
                );
            }
        }
    }

    #[cfg(unix)]
    fn shell(script: &str) -> Command {
        let mut command = Command::new("/bin/sh");
        command.arg("-c").arg(script);
        command
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn verifier_collects_both_streams_and_preserves_nonzero_status() {
        let output = capture_verifier_output(
            shell("printf out; printf err >&2; exit 7"),
            Duration::from_secs(5),
            64,
        )
        .await
        .unwrap();
        assert_eq!(output.status.code(), Some(7));
        assert_eq!(output.stdout, b"out");
        assert_eq!(output.stderr, b"err");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn verifier_has_no_interactive_stdin_and_requires_successful_exit() {
        let output = capture_verifier_output(
            shell("if read -r input; then exit 9; fi; printf verified"),
            Duration::from_secs(5),
            64,
        )
        .await
        .unwrap();
        assert!(output.status.success());
        assert_eq!(output.stdout, b"verified");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn verifier_bounds_each_output_stream_and_never_accepts_a_prefix() {
        for script in [
            "i=0; while [ $i -lt 100 ]; do printf 0123456789; i=$((i+1)); done",
            "i=0; while [ $i -lt 100 ]; do printf 0123456789 >&2; i=$((i+1)); done",
        ] {
            let error = capture_verifier_output(shell(script), Duration::from_secs(5), 64)
                .await
                .unwrap_err();
            assert!(
                error.to_string().contains("output limit exceeded"),
                "{error}"
            );
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn verifier_deadline_covers_a_silent_running_process() {
        let error = capture_verifier_output(shell("exec sleep 30"), Duration::from_millis(30), 64)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("timed out"), "{error}");
        assert!(!error.to_string().contains("teardown"), "{error}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn verifier_zero_exit_without_pipe_eof_is_not_verification_success() {
        // The short-lived helper deliberately retains both pipes. This tests
        // the exchange deadline, NOT process-tree termination authority.
        let error =
            capture_verifier_output(shell("sleep 0.3 & exit 0"), Duration::from_millis(30), 64)
                .await
                .unwrap_err();
        assert!(error.to_string().contains("timed out"), "{error}");
    }

    #[tokio::test]
    async fn missing_verifier_is_an_error_not_a_successful_empty_exchange() {
        let root = tempfile::tempdir().unwrap();
        let error = capture_verifier_output(
            Command::new(root.path().join("absent-verifier")),
            Duration::from_secs(5),
            64,
        )
        .await
        .unwrap_err();
        assert!(
            error.to_string().contains("Failed to execute cosign"),
            "{error}"
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn cancelling_verification_terminates_the_owned_local_child() {
        let root = tempfile::tempdir().unwrap();
        let pid_file = root.path().join("child.pid");
        let mut command = shell("printf '%s' \"$$\" > \"$1\"; exec sleep 30");
        command.arg("verifier-test").arg(&pid_file);
        let task = tokio::spawn(capture_verifier_output(
            command,
            Duration::from_secs(30),
            64,
        ));
        let pid = tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                if let Ok(text) = tokio::fs::read_to_string(&pid_file).await
                    && let Ok(pid) = text.parse::<u32>()
                {
                    break pid;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("test child did not become ready");
        let stat_path = format!("/proc/{pid}/stat");
        let initial = tokio::fs::read_to_string(&stat_path).await.unwrap();
        let (_, fields) = initial.rsplit_once(") ").unwrap();
        let start = fields.split_whitespace().nth(19).unwrap().to_owned();
        task.abort();
        assert!(task.await.unwrap_err().is_cancelled());
        tokio::time::timeout(Duration::from_secs(3), async {
            loop {
                match tokio::fs::read_to_string(&stat_path).await {
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
                    Err(error) => panic!("cannot inspect owned test child: {error}"),
                    Ok(stat) => {
                        let (_, fields) = stat.rsplit_once(") ").unwrap();
                        let fields = fields.split_whitespace().collect::<Vec<_>>();
                        // Reaping is separate from termination; a zombie no
                        // longer executes. A reused PID is not this child.
                        if matches!(fields[0], "Z" | "X") || fields[19] != start {
                            break;
                        }
                    }
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("cancelled verification left its local child running");
    }
}