perf-sentinel 0.32.0

CLI for perf-sentinel: polyglot performance anti-pattern detector
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
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
//! `perf-sentinel verify-hash` subcommand.
//!
//! Chains up to four checks against a periodic disclosure report:
//! deterministic content hash recompute (pure Rust, always run), the
//! in-toto attestation naming that content hash (pure Rust, run when an
//! attestation is supplied), Sigstore cosign signature over the
//! attestation (delegated to the `cosign` binary), and SLSA build
//! provenance for the producing binary (verified via the
//! `gh attestation verify` GitHub CLI command, opt-in with
//! `--verify-binary <path>`). Exit codes:
//!
//! - `0` `TRUSTED` (content hash matched, the attestation names it, the
//!   signature over that attestation verified ok, and binary attestation
//!   not left unverified when the report carries attestation metadata)
//! - `1` `UNTRUSTED` (at least one check returned a hard failure: hash
//!   mismatch, attestation naming other figures, signature invalid,
//!   attestation invalid, identity mismatch)
//! - `2` `PARTIAL` (no hard failure but at least one check could not
//!   complete: cosign absent, `gh` CLI absent, signature metadata
//!   absent, sidecars missing). A scripted gate
//!   `verify-hash && deploy` still blocks on 2, but distinguishing
//!   `PARTIAL` from `UNTRUSTED` lets the operator tell a tamper
//!   attempt from a missing tool.
//! - `3` `INPUT_ERROR` (report file unreadable, JSON invalid, missing
//!   `--report` / `--url`)
//! - `4` `NETWORK_ERROR` (only `--url` mode: fetch of report or sidecar
//!   failed)

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

use sentinel_core::report::periodic::schema::{IntegrityLevel, PeriodicReport, SignatureMetadata};
use sentinel_core::report::periodic::{
    AttestationBinding, InTotoStatement, SchemaVersionError, check_attestation_binding,
    check_schema_version, compute_content_hash,
};

use crate::limits::{CappedRead, MAX_LOCAL_REPORT_BYTES, read_capped};

/// Hard cap on remote payloads pulled by `--url`. 10 MB is well above any
/// realistic report file size and guards against pathological responses.
#[cfg(any(feature = "daemon", feature = "tempo", feature = "jaeger-query"))]
const MAX_REMOTE_BYTES: usize = 10 * 1024 * 1024;

/// Cap on the attestation read. A statement is a few KB.
const MAX_ATTESTATION_BYTES: u64 = 1024 * 1024;

/// Per-request timeout for `--url` fetches.
#[cfg(any(feature = "daemon", feature = "tempo", feature = "jaeger-query"))]
const REMOTE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// Exit code: every verification check returned Ok.
pub const EXIT_TRUSTED: i32 = 0;
/// Exit code: at least one check returned a hard failure (hash mismatch,
/// signature invalid, attestation invalid, identity mismatch).
pub const EXIT_UNTRUSTED: i32 = 1;
/// Exit code: no hard failure but at least one check could not complete
/// (cosign absent, `gh` CLI absent, signature metadata absent,
/// sidecars missing).
pub const EXIT_PARTIAL: i32 = 2;
/// Exit code: report file unreadable, JSON invalid, or required flag
/// missing.
pub const EXIT_INPUT_ERROR: i32 = 3;
/// Exit code: `--url` fetch failed (HTTP error, scheme rejected, body
/// over the size cap).
pub const EXIT_NETWORK_ERROR: i32 = 4;
/// Exit code: the report's schema is newer than this engine reads.
pub const EXIT_UNSUPPORTED: i32 = 5;

#[derive(Clone, Copy, clap::ValueEnum)]
pub enum VerifyHashFormat {
    Text,
    Json,
}

#[derive(Debug)]
enum Status {
    Ok(String),
    Fail(String),
    Skip(String),
    NotProvided,
}

impl Status {
    fn is_failure(&self) -> bool {
        matches!(self, Status::Fail(_))
    }
}

struct Outcome {
    report_path: String,
    report: PeriodicReport,
    content_hash: Status,
    core_patterns: Status,
    attestation_binding: Status,
    signature: Status,
    binary_attestation: Status,
    /// The report came out of a PDF: its printed pages were not checked.
    from_pdf: bool,
}

/// A report as read, with the bytes it was parsed from: an attestation
/// written before content-hash subjects is checked against them.
struct LoadedReport {
    report: PeriodicReport,
    bytes: Vec<u8>,
    display: String,
    fetched: FetchedPaths,
    from_pdf: bool,
}

/// Signer identity expectation, fed by the CLI flags
/// `--expected-identity`, `--expected-issuer`, `--no-identity-check`.
/// A consumer who does not assert one of these cannot tell a legitimate
/// signature from a forged one (a Sigstore bundle without identity
/// constraint can be issued by any GitHub or Google account holder).
#[derive(Default, Debug, Clone)]
pub struct IdentityOptions {
    pub expected_identity: Option<String>,
    pub expected_issuer: Option<String>,
    pub no_identity_check: bool,
}

/// Entry point invoked from `main.rs` dispatch.
pub async fn cmd_verify_hash(
    report_path: Option<&Path>,
    url: Option<&str>,
    attestation_path: Option<&Path>,
    bundle_path: Option<&Path>,
    verify_binary: Option<&Path>,
    format: VerifyHashFormat,
    identity: &IdentityOptions,
) -> i32 {
    let LoadedReport {
        report,
        bytes,
        display,
        fetched,
        from_pdf,
    } = match load_report(report_path, url).await {
        Ok(v) => v,
        Err(code) => return code,
    };

    // An explicit flag wins over a file found beside the report.
    let attestation = attestation_path.or(fetched.attestation.as_deref());
    let content_hash = verify_content_hash(&report);
    let core_patterns = verify_core_patterns(&report);
    let attestation_binding = verify_attestation_binding(&report, &bytes, attestation);
    let signature = verify_signature(
        &report,
        attestation,
        bundle_path.or(fetched.bundle.as_deref()),
        identity,
    );
    let binary_attestation = verify_binary_attestation(&report, verify_binary);

    let outcome = Outcome {
        report_path: display,
        report,
        content_hash,
        core_patterns,
        attestation_binding,
        signature,
        binary_attestation,
        from_pdf,
    };

    match format {
        VerifyHashFormat::Text => print_text(&outcome),
        VerifyHashFormat::Json => print_json(&outcome),
    }

    exit_code(&outcome)
}

/// The attestation and bundle that came with the report, written for the
/// checks that read paths into a private directory removed on drop.
struct FetchedPaths {
    attestation: Option<PathBuf>,
    bundle: Option<PathBuf>,
    _dir: Option<tempfile::TempDir>,
}

impl FetchedPaths {
    const NONE: Self = Self {
        attestation: None,
        bundle: None,
        _dir: None,
    };

    fn spill(attestation: Option<&[u8]>, bundle: Option<&[u8]>) -> std::io::Result<Self> {
        if attestation.is_none() && bundle.is_none() {
            return Ok(Self::NONE);
        }
        let dir = tempfile::Builder::new()
            .prefix("perf-sentinel-verify-")
            .tempdir()?;
        let write = |data: Option<&[u8]>, name: &str| {
            data.map(|data| {
                let path = dir.path().join(name);
                std::fs::write(&path, data).map(|()| path)
            })
            .transpose()
        };
        Ok(Self {
            attestation: write(attestation, "attestation.intoto.jsonl")?,
            bundle: write(bundle, "bundle.sig")?,
            _dir: Some(dir),
        })
    }
}

fn spill_or_exit(attestation: Option<&[u8]>, bundle: Option<&[u8]>) -> Result<FetchedPaths, i32> {
    FetchedPaths::spill(attestation, bundle).map_err(|e| {
        eprintln!("Error: write the attestation and bundle to a temporary directory: {e}");
        EXIT_INPUT_ERROR
    })
}

async fn load_report(report_path: Option<&Path>, url: Option<&str>) -> Result<LoadedReport, i32> {
    if let Some(path) = report_path {
        return load_local_report(path);
    }
    if let Some(url) = url {
        return fetch_from_url(url).await;
    }
    eprintln!("Error: one of --report or --url is required");
    Err(EXIT_INPUT_ERROR)
}

/// Read and parse a report from disk. Synchronous on purpose: a single small
/// file, read before any network work, has nothing to gain from async I/O.
fn load_local_report(path: &Path) -> Result<LoadedReport, i32> {
    let bytes = match read_capped(path, MAX_LOCAL_REPORT_BYTES) {
        Ok(CappedRead::Bytes(bytes)) => bytes,
        Ok(CappedRead::TooLarge(len)) => {
            eprintln!(
                "Error: report at {} is {len} bytes, exceeds the {}-byte cap.",
                sanitise_for_terminal(&path.display().to_string()),
                MAX_LOCAL_REPORT_BYTES
            );
            return Err(EXIT_INPUT_ERROR);
        }
        Err(e) => {
            eprintln!(
                "Error: read {}: {e}",
                sanitise_for_terminal(&path.display().to_string())
            );
            return Err(EXIT_INPUT_ERROR);
        }
    };
    let display = path.display().to_string();
    if bytes.starts_with(PDF_MAGIC) {
        return load_pdf(&bytes, display);
    }
    let report = parse_gated(&bytes, &display)?;
    Ok(LoadedReport {
        report,
        bytes,
        display,
        fetched: FetchedPaths::NONE,
        from_pdf: false,
    })
}

const PDF_MAGIC: &[u8] = b"%PDF-";

/// A disclosure PDF attaches its report, attestation and bundle, so
/// nothing else is read next to it.
fn load_pdf(pdf: &[u8], display: String) -> Result<LoadedReport, i32> {
    let (bytes, fetched) = unpack_pdf(pdf, &display)?;
    let report = parse_gated(&bytes, &display)?;
    Ok(LoadedReport {
        report,
        bytes,
        display,
        fetched,
        from_pdf: true,
    })
}

/// The report a disclosure PDF attaches, with its attestation and bundle.
#[cfg(feature = "pdf")]
fn unpack_pdf(pdf: &[u8], display: &str) -> Result<(Vec<u8>, FetchedPaths), i32> {
    let files = sentinel_core::report::periodic::pdf::extract_attachments(
        pdf,
        MAX_LOCAL_REPORT_BYTES,
        MAX_ATTESTATION_BYTES,
    )
    .map_err(|e| {
        eprintln!("Error: {}: {e}", sanitise_for_terminal(display));
        EXIT_INPUT_ERROR
    })?;
    let fetched = spill_or_exit(files.attestation.as_deref(), files.bundle.as_deref())?;
    Ok((files.report, fetched))
}

#[cfg(not(feature = "pdf"))]
fn unpack_pdf(_pdf: &[u8], display: &str) -> Result<(Vec<u8>, FetchedPaths), i32> {
    eprintln!(
        "Error: {}: this build cannot read PDF disclosures, use the attached report.json",
        sanitise_for_terminal(display)
    );
    Err(EXIT_INPUT_ERROR)
}

fn parse_report(bytes: &[u8]) -> Result<PeriodicReport, serde_json::Error> {
    serde_json::from_slice(bytes)
}

/// Refuse a schema this engine does not read before parsing: a newer
/// report would lose its new fields and fail the hash for the wrong reason.
fn parse_gated(bytes: &[u8], source: &str) -> Result<PeriodicReport, i32> {
    let source = sanitise_for_terminal(source);
    match check_schema_version(bytes) {
        Err(e @ SchemaVersionError::Unsupported(_)) => {
            eprintln!("Error: {source}: {}", sanitise_for_terminal(&e.to_string()));
            return Err(EXIT_UNSUPPORTED);
        }
        Err(e @ SchemaVersionError::Unknown(_)) => {
            eprintln!("Error: {source}: {}", sanitise_for_terminal(&e.to_string()));
            return Err(EXIT_INPUT_ERROR);
        }
        _ => {}
    }
    parse_report(bytes).map_err(|e| {
        eprintln!("Error: parse {source}: {e}");
        EXIT_INPUT_ERROR
    })
}

async fn fetch_from_url(url: &str) -> Result<LoadedReport, i32> {
    load_remote(url, |u| async move { http_get(&u).await }).await
}

/// `get` stands in for the HTTP client, so tests can serve the bytes.
async fn load_remote<F, Fut>(url: &str, get: F) -> Result<LoadedReport, i32>
where
    F: Fn(String) -> Fut,
    Fut: Future<Output = Result<Vec<u8>, String>>,
{
    let bytes = get(url.to_string()).await.map_err(|e| {
        eprintln!("Error: fetch {url}: {e}");
        EXIT_NETWORK_ERROR
    })?;
    if bytes.starts_with(PDF_MAGIC) {
        return load_pdf(&bytes, url.to_string());
    }
    let report = parse_gated(&bytes, url)?;
    let attestation_url = derive_sidecar_url(url, "attestation.intoto.jsonl");
    let bundle_url = derive_sidecar_url(url, "bundle.sig");
    let mut attestation = None;
    if let Some(a_url) = attestation_url {
        match get(a_url).await {
            Ok(data) => attestation = Some(data),
            Err(e) => eprintln!("Note: could not fetch attestation sidecar: {e}"),
        }
    }
    let mut bundle = None;
    if let Some(b_url) = bundle_url {
        match get(b_url).await {
            Ok(data) => bundle = Some(data),
            Err(e) => eprintln!("Note: could not fetch signature bundle: {e}"),
        }
    }
    let fetched = spill_or_exit(attestation.as_deref(), bundle.as_deref())?;
    Ok(LoadedReport {
        report,
        bytes,
        display: url.to_string(),
        fetched,
        from_pdf: false,
    })
}

/// Fetch an `https://` URL through the shared core client, so the report
/// download follows the same proxy and trust rules as every other outbound
/// call (`HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`, `SSL_CERT_FILE`).
///
/// The client follows no redirect: a 3xx comes back as an error, so a
/// redirect cannot rebind the fetch to `http://internal` or
/// `https://localhost:4317` and turn it into an SSRF probe. Operators who
/// need redirect-following should re-resolve the canonical URL first.
#[cfg(any(feature = "daemon", feature = "tempo", feature = "jaeger-query"))]
async fn http_get(url: &str) -> Result<Vec<u8>, String> {
    use sentinel_core::http_client::{self, FetchError, Uri};

    if !url.starts_with("https://") {
        return Err("only https:// URLs are accepted".to_string());
    }
    let uri: Uri = url.parse().map_err(|e| format!("invalid url: {e}"))?;
    let client = http_client::build_client();
    // The inner timeout covers the response head, this one the whole
    // transfer, so a body that trickles in cannot hold the command.
    let fetch = http_client::fetch_get_limited(
        &client,
        &uri,
        concat!("perf-sentinel/", env!("CARGO_PKG_VERSION")),
        REMOTE_TIMEOUT,
        None,
        MAX_REMOTE_BYTES,
    );
    match tokio::time::timeout(REMOTE_TIMEOUT, fetch).await {
        Ok(Ok(body)) => Ok(body.to_vec()),
        Ok(Err(FetchError::HttpStatus(code))) => Err(format!("http status {code}")),
        Ok(Err(FetchError::BodyTooLarge(_))) => Err(format!(
            "response exceeds {MAX_REMOTE_BYTES} byte cap, refusing to load"
        )),
        Ok(Err(e)) => Err(error_chain(&e)),
        Err(_) => Err("http: request timed out".to_string()),
    }
}

/// `http: <error>: <cause>: ...`, so a proxy or TLS failure names its cause.
#[cfg(any(feature = "daemon", feature = "tempo", feature = "jaeger-query"))]
fn error_chain(e: &dyn std::error::Error) -> String {
    use std::fmt::Write as _;
    let mut out = format!("http: {e}");
    let mut source = e.source();
    while let Some(cause) = source {
        let _ = write!(out, ": {cause}");
        source = cause.source();
    }
    out
}

/// A build without the `daemon`, `tempo` or `jaeger-query` feature has no
/// HTTP client, so `--url` cannot fetch anything.
#[cfg(not(any(feature = "daemon", feature = "tempo", feature = "jaeger-query")))]
fn http_get(_url: &str) -> std::future::Ready<Result<Vec<u8>, String>> {
    std::future::ready(Err(
        "this build has no HTTP client, use --report with a local file".to_string(),
    ))
}

/// Conventional sidecar URL: same directory as the report, fixed
/// tail. Matches the operator workflow in `docs/REPORTING.md` which
/// instructs publishing `attestation.intoto.jsonl` and `bundle.sig`
/// alongside the report regardless of the report's exact filename.
fn derive_sidecar_url(report_url: &str, tail: &str) -> Option<String> {
    let (prefix, _last) = report_url.rsplit_once('/')?;
    Some(format!("{prefix}/{tail}"))
}

fn verify_content_hash(report: &PeriodicReport) -> Status {
    let claimed = report.integrity.content_hash.clone();
    if claimed.is_empty() {
        return Status::Fail("integrity.content_hash is empty".to_string());
    }
    match compute_content_hash(report) {
        Ok(recomputed) if recomputed == claimed => {
            Status::Ok(format!("matches integrity.content_hash ({claimed})"))
        }
        Ok(recomputed) => Status::Fail(format!(
            "mismatch: recomputed {recomputed} vs claimed {claimed}"
        )),
        Err(e) => Status::Fail(format!("recompute failed: {e}")),
    }
}

/// Cross-check `methodology.core_patterns_required` against the
/// canonical set baked into the verifying binary. Detects core-pattern
/// substitution that the validator would have rejected at signing
/// time only if the signer was honest. A divergence means either the
/// report was tampered with (substitution) or the verifying binary
/// is a different perf-sentinel version with a different canonical
/// core (rare, surfaced as a hint).
fn verify_core_patterns(report: &PeriodicReport) -> Status {
    use sentinel_core::report::periodic::hash_core_patterns;
    use sentinel_core::report::periodic::schema::core_patterns_required as canonical_set;

    let declared = &report.methodology.core_patterns_required;
    let local_canonical = canonical_set();
    let declared_hash = hash_core_patterns(declared);
    let canonical_hash = hash_core_patterns(&local_canonical);

    if declared_hash == canonical_hash {
        return Status::Ok(format!(
            "matches canonical core set for local perf-sentinel ({} patterns)",
            local_canonical.len()
        ));
    }

    fn set_difference<'a>(a: &'a [String], b: &[String]) -> Vec<&'a str> {
        a.iter()
            .filter(|x| !b.iter().any(|y| y == *x))
            .map(String::as_str)
            .collect()
    }
    let only_in_declared = set_difference(declared, &local_canonical);
    let only_in_canonical = set_difference(&local_canonical, declared);
    // Cite the report-declared producing binary so an auditor on a
    // mismatched version knows exactly which perf-sentinel to download
    // and re-run against. Falls back to perf_sentinel_version when
    // binary_version is empty on pre-0.7.0 reports.
    let producing_version = if report.report_metadata.binary_version.is_empty() {
        report.report_metadata.perf_sentinel_version.as_str()
    } else {
        report.report_metadata.binary_version.as_str()
    };
    Status::Fail(format!(
        "core_patterns_required diverges from local canonical set: \
         declared-only={only_in_declared:?}, canonical-only={only_in_canonical:?}. \
         Possible substitution at sign time, or verifying binary is a different version. \
         Report was produced by perf-sentinel {producing_version}, consider re-running \
         verify-hash with that exact version before flagging the report as untrusted."
    ))
}

/// Check that the attestation beside the report names these figures. The
/// signature covers the attestation, not the report, so without this a
/// valid signature would vouch for any report carrying the right hash.
fn verify_attestation_binding(
    report: &PeriodicReport,
    report_bytes: &[u8],
    attestation_path: Option<&Path>,
) -> Status {
    let Some(path) = attestation_path else {
        return Status::NotProvided;
    };
    let statement = match read_statement(path) {
        Ok(s) => s,
        Err(reason) => return Status::Fail(reason),
    };
    match check_attestation_binding(report, report_bytes, &statement) {
        Ok(AttestationBinding::ContentHash) => {
            Status::Ok("the attestation names this content hash".to_string())
        }
        Ok(AttestationBinding::FileBytes) => Status::Ok(
            "the attestation pins these exact report bytes (written before content-hash subjects)"
                .to_string(),
        ),
        Ok(AttestationBinding::Unbindable) => Status::Skip(format!(
            "the attestation predates content-hash subjects and pins report bytes that changed \
             since, usually when integrity.signature was patched in. Nothing ties it to these \
             figures. Emit it again with perf-sentinel {} or later and sign it again.",
            env!("CARGO_PKG_VERSION")
        )),
        Ok(AttestationBinding::Mismatch(reason)) => Status::Fail(sanitise_for_terminal(&reason)),
        Ok(_) => Status::Fail("unrecognised attestation binding".to_string()),
        Err(e) => Status::Fail(format!("recompute failed: {e}")),
    }
}

fn read_statement(path: &Path) -> Result<InTotoStatement, String> {
    let shown = sanitise_for_terminal(&path.display().to_string());
    let meta = std::fs::metadata(path).map_err(|e| format!("stat {shown}: {e}"))?;
    if meta.len() > MAX_ATTESTATION_BYTES {
        return Err(format!(
            "attestation at {shown} is {} bytes, over the {MAX_ATTESTATION_BYTES}-byte cap",
            meta.len()
        ));
    }
    let text = std::fs::read_to_string(path).map_err(|e| format!("read {shown}: {e}"))?;
    serde_json::from_str(text.trim())
        .map_err(|e| format!("attestation at {shown} is not one in-toto statement: {e}"))
}

/// What identity constraint cosign should enforce. Constrain enforces
/// the operator-supplied identity (the safe default for a third-party
/// auditor). Skip runs cosign without identity flags (cryptographic
/// integrity only, signer not verified).
enum IdentityCheck {
    Constrain { identity: String, issuer: String },
    Skip,
}

fn verify_signature(
    report: &PeriodicReport,
    attestation_path: Option<&Path>,
    bundle_path: Option<&Path>,
    identity: &IdentityOptions,
) -> Status {
    let Some(sig) = report.integrity.signature.as_ref() else {
        return Status::NotProvided;
    };
    let check = match resolve_identity_check(identity) {
        Ok(c) => c,
        Err(s) => return s,
    };
    let Some(att_path) = attestation_path else {
        return Status::Skip(
            "signature metadata present, pass --attestation <path> to verify".to_string(),
        );
    };
    let Some(b_path) = bundle_path else {
        return Status::Skip(
            "signature metadata present, pass --bundle <path> to verify".to_string(),
        );
    };
    if let Some(s) = reject_unsafe_cosign_flag("signer_identity", &sig.signer_identity) {
        return s;
    }
    if let Some(s) = reject_unsafe_cosign_flag("signer_issuer", &sig.signer_issuer) {
        return s;
    }
    if !command_exists("cosign") {
        return Status::Skip(
            "cosign not found in PATH (install from https://docs.sigstore.dev/system_config/installation)".to_string(),
        );
    }
    run_cosign_verify(sig, att_path, b_path, &check)
}

/// Translate user-facing flags into an identity-check decision. The
/// "no flag at all" branch returns Fail with an explicit message so a
/// scripted gate does not silently treat an unverified signer as
/// trusted. Both flags must be present together: a partial pair is a
/// configuration error rather than a security failure, but it still
/// blocks verification because cosign cannot run with only one of the
/// pair.
fn resolve_identity_check(identity: &IdentityOptions) -> Result<IdentityCheck, Status> {
    if identity.no_identity_check {
        return Ok(IdentityCheck::Skip);
    }
    match (&identity.expected_identity, &identity.expected_issuer) {
        (Some(id), Some(issuer)) => {
            if let Some(s) = reject_unsafe_cosign_flag("--expected-identity", id) {
                return Err(s);
            }
            if let Some(s) = reject_unsafe_cosign_flag("--expected-issuer", issuer) {
                return Err(s);
            }
            Ok(IdentityCheck::Constrain {
                identity: id.clone(),
                issuer: issuer.clone(),
            })
        }
        (Some(_), None) | (None, Some(_)) => Err(Status::Fail(
            "both --expected-identity and --expected-issuer must be passed together".to_string(),
        )),
        (None, None) => Err(Status::Fail(
            "cannot verify without expected identity. Pass --expected-identity \
             and --expected-issuer to constrain the signer, or --no-identity-check \
             to verify cryptographic integrity only. A Sigstore bundle without an \
             identity constraint can be forged by any GitHub or Google account holder."
                .to_string(),
        )),
    }
}

fn run_cosign_verify(
    sig: &SignatureMetadata,
    attestation_path: &Path,
    bundle_path: &Path,
    check: &IdentityCheck,
) -> Status {
    // The disclose pipeline emits a complete in-toto v1 Statement
    // (see attestation.rs). Operators sign it with `cosign sign-blob
    // <statement> --bundle <bundle.sig> --new-bundle-format`, so the
    // bundle pins the statement file itself, not the report. The
    // matching verify command is `cosign verify-blob`, with the
    // statement as the positional. Using `verify-blob-attestation`
    // here, or `attest-blob --predicate <statement>` on the sign
    // side, would wrap the statement in another statement and
    // produce a permanent double-wrapped entry in Rekor.
    let mut cmd = Command::new("cosign");
    cmd.arg("verify-blob")
        .arg("--bundle")
        .arg(bundle_path)
        .arg("--new-bundle-format");
    if let IdentityCheck::Constrain { identity, issuer } = check {
        cmd.arg("--certificate-identity")
            .arg(identity)
            .arg("--certificate-oidc-issuer")
            .arg(issuer);
    }
    cmd.arg(attestation_path);
    let output = cmd.output();
    match output {
        Ok(out) if out.status.success() => match check {
            IdentityCheck::Constrain { identity, issuer } => Status::Ok(format!(
                "valid (signed by {} via {})",
                sanitise_for_terminal(identity),
                sanitise_for_terminal(issuer)
            )),
            IdentityCheck::Skip => Status::Skip(format!(
                "identity check skipped via --no-identity-check, cryptographic integrity OK \
                 but signer ({} via {}) not verified",
                sanitise_for_terminal(&sig.signer_identity),
                sanitise_for_terminal(&sig.signer_issuer)
            )),
        },
        Ok(out) => Status::Fail(format!(
            "cosign rejected: {}",
            last_stderr_line(&out.stderr)
        )),
        Err(e) => Status::Fail(format!("cosign spawn failed: {e}")),
    }
}

fn verify_binary_attestation(report: &PeriodicReport, verify_binary: Option<&Path>) -> Status {
    // An explicit --verify-binary always runs the check: gh verifies the
    // binary's own GitHub provenance. When the report records a commit, it is
    // cross-checked so a validly attested build of another commit cannot pass
    // as this report's.
    if let Some(binary) = verify_binary {
        let expected_commit = report
            .integrity
            .binary_attestation
            .as_ref()
            .map(|a| a.git_commit.as_str());
        return run_gh_attestation_verify(binary, expected_commit);
    }
    match report.integrity.binary_attestation.as_ref() {
        None => Status::NotProvided,
        // Metadata present but no binary to check against: report the hint
        // without claiming verification, so overall_label stays below TRUSTED.
        Some(att) => Status::Skip(format!(
            "binary attestation metadata present (built from {} at {}, builder {}, attestation indexed at {}). Pass --verify-binary <path> to verify with `gh attestation verify`.",
            sanitise_for_terminal(&att.git_tag),
            sanitise_for_terminal(&att.git_commit),
            sanitise_for_terminal(&att.builder_id),
            sanitise_for_terminal(&att.attestation_url),
        )),
    }
}

/// Last line of a subprocess's stderr, terminal-sanitised. The bytes can echo
/// remote-derived content (attestation subjects, registry errors), so ANSI and
/// control chars must be stripped before they reach the operator's terminal.
fn last_stderr_line(stderr: &[u8]) -> String {
    let text = String::from_utf8_lossy(stderr);
    sanitise_for_terminal(text.lines().last().unwrap_or("(no stderr)"))
}

/// Whether `commit` appears in `output` at the start of a hex run, so a short
/// (7-char) commit cannot false-match inside an unrelated longer SHA/digest.
fn output_references_commit(output: &str, commit: &str) -> bool {
    output
        .match_indices(commit)
        .any(|(i, _)| i == 0 || !output.as_bytes()[i - 1].is_ascii_hexdigit())
}

/// Where GitHub keeps a release's provenance. Releases built since the
/// repository moved to the Institut du Numérique Responsable are attested in
/// its repository. Earlier ones stayed under the original account, which only
/// answers by owner, pinned to the original repository as signer.
const ATTESTATION_SCOPES: [&[&str]; 2] = [
    &["--repo", "Institut-du-Numerique-Responsable/perf-sentinel"],
    &[
        "--owner",
        "robintra",
        "--signer-repo",
        "robintra/perf-sentinel",
    ],
];

/// Runs `verify` against each scope in turn and returns the stdout of the
/// first one that verifies. A rejection moves on to the next scope, a spawn
/// failure stops at once.
fn first_verified_scope(
    mut verify: impl FnMut(&[&str]) -> std::io::Result<std::process::Output>,
) -> Result<Vec<u8>, Status> {
    let mut rejection = String::from("(no stderr)");
    for scope in ATTESTATION_SCOPES {
        match verify(scope) {
            Ok(out) if out.status.success() => return Ok(out.stdout),
            Ok(out) => rejection = last_stderr_line(&out.stderr),
            Err(e) => return Err(Status::Fail(format!("gh spawn failed: {e}"))),
        }
    }
    Err(Status::Fail(format!(
        "gh attestation verify rejected: {rejection}"
    )))
}

/// Verify a binary's GitHub build provenance via `gh attestation verify`.
///
/// The scopes are compile-time constants and `binary` is an
/// operator-supplied path (never report-derived), so no argument
/// sanitisation is needed on the command itself. When `expected_commit` is set
/// (the report records one), the verified attestation must reference that commit
/// so a validly attested build of a different version cannot pass as this
/// report's.
fn run_gh_attestation_verify(binary: &Path, expected_commit: Option<&str>) -> Status {
    if !command_exists("gh") {
        return Status::Skip(
            "gh CLI not found on PATH, cannot verify binary attestation".to_string(),
        );
    }
    let verified = first_verified_scope(|scope| {
        Command::new("gh")
            .arg("attestation")
            .arg("verify")
            .arg(binary)
            .args(scope)
            .arg("--format")
            .arg("json")
            .output()
    });
    match verified {
        Ok(stdout) => {
            if let Some(commit) = expected_commit {
                let commit = commit.trim();
                // A cross-check is only meaningful against a real git SHA. An
                // empty or 1-2 char commit would make `.contains` vacuously
                // true, so refuse rather than award a false provenance match.
                if commit.len() < 7 || !commit.chars().all(|c| c.is_ascii_hexdigit()) {
                    return Status::Fail(format!(
                        "cannot cross-check binary: report records no usable git_commit ({})",
                        sanitise_for_terminal(commit)
                    ));
                }
                if !output_references_commit(&String::from_utf8_lossy(&stdout), commit) {
                    return Status::Fail(format!(
                        "binary attestation verified, but it does not reference the report's recorded commit {}",
                        sanitise_for_terminal(commit)
                    ));
                }
            }
            Status::Ok(format!(
                "verified via gh attestation verify ({})",
                sanitise_for_terminal(&binary.display().to_string())
            ))
        }
        Err(status) => status,
    }
}

fn command_exists(name: &str) -> bool {
    let path = std::env::var_os("PATH").unwrap_or_default();
    std::env::split_paths(&path).any(|d| {
        if d.join(name).is_file() {
            return true;
        }
        #[cfg(windows)]
        {
            for ext in ["exe", "cmd", "bat", "com"] {
                if d.join(format!("{name}.{ext}")).is_file() {
                    return true;
                }
            }
        }
        false
    })
}

/// Reject values that would let an adversarial report pivot cosign's
/// CLI flags (anything starting with `-`) or smuggle control chars
/// past terminal sanitisation. `Command::arg()` does not invoke a
/// shell so quoting / `;` / `$(...)` are inert, but flag values are
/// still parsed by cosign itself.
#[must_use]
fn is_safe_cosign_argument(s: &str) -> bool {
    !s.is_empty() && !s.starts_with('-') && !s.chars().any(|c| c.is_control() || c == '\0')
}

/// Wraps `is_safe_cosign_argument` with the canonical rejection
/// message, returning `None` when the value is safe and `Some(Fail)`
/// otherwise. Centralises the message so signer fields and operator
/// flags surface the same wording.
fn reject_unsafe_cosign_flag(label: &str, value: &str) -> Option<Status> {
    if is_safe_cosign_argument(value) {
        None
    } else {
        Some(Status::Fail(format!(
            "{label} rejected: starts with '-' or contains control chars"
        )))
    }
}

fn sanitise_for_terminal(s: &str) -> String {
    sentinel_core::text_safety::sanitize_for_terminal(s).into_owned()
}

fn exit_code(outcome: &Outcome) -> i32 {
    match overall_label(outcome) {
        "TRUSTED" => EXIT_TRUSTED,
        "UNTRUSTED" => EXIT_UNTRUSTED,
        _ => EXIT_PARTIAL,
    }
}

fn print_text(outcome: &Outcome) {
    println!("perf-sentinel verify-hash {}", env!("CARGO_PKG_VERSION"));
    println!();
    println!("Report: {}", outcome.report_path);
    if outcome.from_pdf {
        println!(
            "  Verified: the attached report.json, not its printed pages. Compare the printed figures with it."
        );
    }
    println!(
        "  Period: {} to {}",
        outcome.report.period.from_date, outcome.report.period.to_date
    );
    println!(
        "  Organisation: {} ({})",
        sanitise_for_terminal(&outcome.report.organisation.name),
        sanitise_for_terminal(&outcome.report.organisation.country)
    );
    println!(
        "  Intent: {}, integrity_level: {}",
        intent_label(outcome.report.report_metadata.intent),
        integrity_level_label(outcome.report.report_metadata.integrity_level)
    );
    println!();
    println!("Verifications:");
    println!("  {}", format_status("Content hash", &outcome.content_hash));
    println!(
        "  {}",
        format_status("Core patterns", &outcome.core_patterns)
    );
    println!(
        "  {}",
        format_status("Attestation binding", &outcome.attestation_binding)
    );
    println!("  {}", format_status("Signature", &outcome.signature));
    println!(
        "  {}",
        format_status("Binary attestation", &outcome.binary_attestation)
    );
    println!();
    println!("Overall: {}", overall_label(outcome));
}

fn format_status(label: &str, s: &Status) -> String {
    match s {
        Status::Ok(detail) => format!("[OK] {label}: {detail}"),
        Status::Fail(detail) => format!("[FAIL] {label}: {detail}"),
        Status::Skip(detail) => format!("[SKIP] {label}: {detail}"),
        Status::NotProvided => format!("[--] {label}: not provided"),
    }
}

fn print_json(outcome: &Outcome) {
    let mut body = serde_json::json!({
        "report_path": outcome.report_path,
        "report_metadata": {
            "intent": intent_label(outcome.report.report_metadata.intent),
            "integrity_level": integrity_level_label(outcome.report.report_metadata.integrity_level),
            "perf_sentinel_version": outcome.report.report_metadata.perf_sentinel_version,
            "report_uuid": outcome.report.report_metadata.report_uuid,
        },
        "period": {
            "from_date": outcome.report.period.from_date.to_string(),
            "to_date": outcome.report.period.to_date.to_string(),
        },
        "verifications": {
            "content_hash": status_to_json(&outcome.content_hash),
            "core_patterns": status_to_json(&outcome.core_patterns),
            "attestation_binding": status_to_json(&outcome.attestation_binding),
            "signature": status_to_json(&outcome.signature),
            "binary_attestation": status_to_json(&outcome.binary_attestation),
        },
        "overall": overall_label(outcome),
    });
    if outcome.from_pdf {
        body["verified_from"] = "pdf_attachment".into();
    }
    println!(
        "{}",
        serde_json::to_string_pretty(&body).unwrap_or_default()
    );
}

fn status_to_json(s: &Status) -> serde_json::Value {
    match s {
        Status::Ok(d) => serde_json::json!({"status": "ok", "detail": d}),
        Status::Fail(d) => serde_json::json!({"status": "fail", "detail": d}),
        Status::Skip(d) => serde_json::json!({"status": "skip", "detail": d}),
        Status::NotProvided => serde_json::json!({"status": "not_provided"}),
    }
}

fn overall_label(outcome: &Outcome) -> &'static str {
    if outcome.content_hash.is_failure()
        || outcome.core_patterns.is_failure()
        || outcome.attestation_binding.is_failure()
        || outcome.signature.is_failure()
        || outcome.binary_attestation.is_failure()
    {
        "UNTRUSTED"
    } else if matches!(outcome.content_hash, Status::Ok(_))
        && matches!(outcome.attestation_binding, Status::Ok(_))
        && matches!(outcome.signature, Status::Ok(_))
        && !matches!(outcome.binary_attestation, Status::Skip(_))
    {
        // The signature covers the attestation, so it vouches for these
        // figures only when the attestation names them.
        // A Skip on binary_attestation means the report carries attestation
        // metadata that was not verified (no --verify-binary, or gh absent).
        // Do not award TRUSTED on that: it would be a false provenance
        // signal. NotProvided (no metadata at all) still allows TRUSTED.
        "TRUSTED"
    } else {
        "PARTIAL"
    }
}

fn intent_label(intent: sentinel_core::report::periodic::schema::ReportIntent) -> &'static str {
    use sentinel_core::report::periodic::schema::ReportIntent;
    match intent {
        ReportIntent::Internal => "internal",
        ReportIntent::Official => "official",
        ReportIntent::Audited => "audited",
    }
}

fn integrity_level_label(level: IntegrityLevel) -> &'static str {
    match level {
        IntegrityLevel::None => "none",
        IntegrityLevel::HashOnly => "hash-only",
        IntegrityLevel::Signed => "signed",
        IntegrityLevel::SignedWithAttestation => "signed-with-attestation",
        IntegrityLevel::Audited => "audited",
    }
}

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

    use sentinel_core::report::periodic::schema::BinaryAttestationMetadata;
    use std::path::PathBuf;

    fn example_g2() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("..")
            .join("docs/schemas/examples/example-official-public-G2.json")
    }

    #[test]
    fn content_hash_check_passes_on_valid_recompute() {
        let bytes = std::fs::read(example_g2()).unwrap();
        let mut report: PeriodicReport = serde_json::from_slice(&bytes).unwrap();
        let hash = compute_content_hash(&report).unwrap();
        report.integrity.content_hash = hash;
        let s = verify_content_hash(&report);
        assert_matches!(s, Status::Ok(_), "expected OK, got display");
    }

    #[test]
    fn content_hash_check_fails_on_mismatch() {
        let mut report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        report.integrity.content_hash = format!("sha256:{}", "0".repeat(64));
        let s = verify_content_hash(&report);
        assert_matches!(s, Status::Fail(_));
    }

    #[test]
    fn core_patterns_check_passes_on_canonical_set() {
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        let s = verify_core_patterns(&report);
        assert!(
            matches!(s, Status::Ok(_)),
            "G2 ships the canonical core set"
        );
    }

    #[test]
    fn core_patterns_check_fails_on_substitution() {
        let mut report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        // Substitute one of the four canonical core patterns with a
        // non-canonical one. Counts stay at 4 but the canonical hash
        // differs, which is the audit case the cross-check exists to catch.
        let to_replace = report.methodology.core_patterns_required[0].clone();
        for slot in &mut report.methodology.core_patterns_required {
            if *slot == to_replace {
                *slot = "slow_sql".to_string();
                break;
            }
        }
        let s = verify_core_patterns(&report);
        match s {
            Status::Fail(detail) => {
                assert!(detail.contains("slow_sql"), "{detail}");
                assert!(detail.contains(&to_replace), "{detail}");
            }
            _ => panic!("expected Fail"),
        }
    }

    #[test]
    fn core_patterns_check_fails_on_shrinkage() {
        let mut report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        let dropped = report.methodology.core_patterns_required.pop().unwrap();
        let s = verify_core_patterns(&report);
        match s {
            Status::Fail(detail) => assert!(detail.contains(&dropped), "{detail}"),
            _ => panic!("expected Fail on shrinkage"),
        }
    }

    #[test]
    fn core_patterns_check_fails_on_growth() {
        let mut report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        report
            .methodology
            .core_patterns_required
            .push("slow_sql".to_string());
        let s = verify_core_patterns(&report);
        match s {
            Status::Fail(detail) => assert!(detail.contains("slow_sql"), "{detail}"),
            _ => panic!("expected Fail on growth"),
        }
    }

    #[test]
    fn signature_check_returns_not_provided_when_absent() {
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        let s = verify_signature(&report, None, None, &IdentityOptions::default());
        assert_matches!(s, Status::NotProvided);
    }

    fn report_with_signature() -> PeriodicReport {
        let mut report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        report.integrity.signature = Some(SignatureMetadata {
            format: "sigstore-cosign-intoto-v1".to_string(),
            bundle_url: "https://example.fr/x.sig".to_string(),
            signer_identity: "user@example.fr".to_string(),
            signer_issuer: "https://accounts.google.com".to_string(),
            rekor_url: "https://rekor.sigstore.dev".to_string(),
            rekor_log_index: 1,
            signed_at: "2026-01-01T00:00:00Z".to_string(),
        });
        report
    }

    #[test]
    fn signature_check_fails_without_identity_flags() {
        // Autosigning case: a third-party auditor running verify-hash without
        // --expected-identity (the default) must not see TRUSTED on a
        // bundle whose identity comes only from the report itself.
        let report = report_with_signature();
        let s = verify_signature(&report, None, None, &IdentityOptions::default());
        match s {
            Status::Fail(detail) => assert!(detail.contains("expected identity"), "{detail}"),
            _ => panic!("expected Fail without identity flags, got display"),
        }
    }

    #[test]
    fn signature_check_fails_when_only_one_identity_flag_set() {
        let report = report_with_signature();
        let s = verify_signature(
            &report,
            None,
            None,
            &IdentityOptions {
                expected_identity: Some("user@example.fr".to_string()),
                expected_issuer: None,
                no_identity_check: false,
            },
        );
        match s {
            Status::Fail(detail) => {
                assert!(detail.contains("must be passed together"), "{detail}");
            }
            _ => panic!("expected Fail on half-pair, got display"),
        }
    }

    #[test]
    fn signature_check_skips_with_no_identity_check_and_paths_absent() {
        // Operator opts out explicitly. The check still reaches the
        // paths-absent branch and returns Skip there (cryptographic
        // integrity only, signer not verified).
        let report = report_with_signature();
        let s = verify_signature(
            &report,
            None,
            None,
            &IdentityOptions {
                expected_identity: None,
                expected_issuer: None,
                no_identity_check: true,
            },
        );
        match s {
            Status::Skip(detail) => assert!(detail.contains("pass --attestation"), "{detail}"),
            _ => panic!("expected Skip on missing paths under --no-identity-check"),
        }
    }

    #[test]
    fn signature_check_rejects_dash_prefix_in_expected_identity() {
        let report = report_with_signature();
        let s = verify_signature(
            &report,
            None,
            None,
            &IdentityOptions {
                expected_identity: Some("--certificate-github-workflow-ref=evil".to_string()),
                expected_issuer: Some("https://attacker".to_string()),
                no_identity_check: false,
            },
        );
        match s {
            Status::Fail(detail) => {
                assert!(detail.contains("expected-identity rejected"), "{detail}");
            }
            _ => panic!("expected Fail on dash-prefixed identity, got display"),
        }
    }

    #[cfg(unix)]
    fn gh_output(code: i32, stdout: &str, stderr: &str) -> std::process::Output {
        use std::os::unix::process::ExitStatusExt;
        std::process::Output {
            status: std::process::ExitStatus::from_raw(code << 8),
            stdout: stdout.as_bytes().to_vec(),
            stderr: stderr.as_bytes().to_vec(),
        }
    }

    #[cfg(unix)]
    #[test]
    fn attestation_falls_back_to_the_pre_transfer_account() {
        let mut seen = Vec::new();
        let got = first_verified_scope(|scope| {
            seen.push(scope.join(" "));
            Ok(if seen.len() == 1 {
                gh_output(1, "", "HTTP 404: Not Found")
            } else {
                gh_output(0, "86b3223", "")
            })
        });
        assert!(matches!(got.as_deref(), Ok(b"86b3223")));
        assert_eq!(
            seen,
            [
                "--repo Institut-du-Numerique-Responsable/perf-sentinel",
                "--owner robintra --signer-repo robintra/perf-sentinel",
            ]
        );
    }

    #[cfg(unix)]
    #[test]
    fn attestation_stops_at_the_first_verified_scope() {
        let mut calls = 0;
        let got = first_verified_scope(|_| {
            calls += 1;
            Ok(gh_output(0, "ok", ""))
        });
        assert!(got.is_ok());
        assert_eq!(calls, 1);
    }

    #[cfg(unix)]
    #[test]
    fn attestation_reports_the_last_rejection() {
        let got = first_verified_scope(|_| Ok(gh_output(1, "", "no attestations found")));
        assert!(matches!(got, Err(Status::Fail(m)) if m.ends_with("no attestations found")));
    }

    #[test]
    fn binary_attestation_skipped_with_metadata_hint() {
        let mut report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        report.integrity.binary_attestation = Some(BinaryAttestationMetadata {
            format: "slsa-provenance-v1".to_string(),
            attestation_url: "https://gh/p.intoto.jsonl".to_string(),
            builder_id: "https://github.com/actions/runner".to_string(),
            git_tag: "v0.7.0".to_string(),
            git_commit: "a47be9d".to_string(),
            slsa_level: "L3".to_string(),
        });
        // No --verify-binary: metadata present is reported as an unverified
        // Skip with the hint, never Ok.
        let s = verify_binary_attestation(&report, None);
        match s {
            Status::Skip(d) => assert!(d.contains("gh attestation")),
            other => panic!(
                "expected Skip, got {}",
                match other {
                    Status::Ok(_) => "Ok",
                    Status::Fail(_) => "Fail",
                    Status::NotProvided => "NotProvided",
                    Status::Skip(_) => unreachable!(),
                }
            ),
        }
    }

    #[test]
    fn verify_binary_flag_runs_even_without_report_metadata() {
        // An explicit --verify-binary must not be silently ignored when the
        // report has no attestation block: the check runs (Skip if gh is
        // absent, Fail on a bogus binary), never the NotProvided short-circuit.
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        assert!(report.integrity.binary_attestation.is_none());
        let s = verify_binary_attestation(&report, Some(Path::new("/nonexistent/binary")));
        assert!(
            !matches!(s, Status::NotProvided),
            "explicit --verify-binary must trigger a real check, got NotProvided"
        );
    }

    #[test]
    fn unverified_attestation_metadata_blocks_trusted() {
        // hash + signature Ok but attestation metadata present-yet-unverified
        // (Skip) must not reach TRUSTED, because it would be a false
        // provenance signal.
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        let outcome = Outcome {
            report_path: "test".to_string(),
            report,
            content_hash: Status::Ok("match".to_string()),
            core_patterns: Status::Ok("match".to_string()),
            attestation_binding: Status::Ok("names".to_string()),
            signature: Status::Ok("valid".to_string()),
            binary_attestation: Status::Skip("metadata present, unverified".to_string()),
            from_pdf: false,
        };
        assert_eq!(overall_label(&outcome), "PARTIAL");
    }

    #[test]
    fn no_attestation_metadata_still_reaches_trusted() {
        // NotProvided (no metadata at all) must not block TRUSTED. That is
        // the common case for reports without SLSA provenance.
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        let outcome = Outcome {
            report_path: "test".to_string(),
            report,
            content_hash: Status::Ok("match".to_string()),
            core_patterns: Status::Ok("match".to_string()),
            attestation_binding: Status::Ok("names".to_string()),
            signature: Status::Ok("valid".to_string()),
            binary_attestation: Status::NotProvided,
            from_pdf: false,
        };
        assert_eq!(overall_label(&outcome), "TRUSTED");
    }

    fn signed_outcome(attestation_binding: Status) -> Outcome {
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        Outcome {
            report_path: "test".to_string(),
            report,
            content_hash: Status::Ok("match".to_string()),
            core_patterns: Status::Ok("match".to_string()),
            attestation_binding,
            signature: Status::Ok("valid".to_string()),
            binary_attestation: Status::NotProvided,
            from_pdf: false,
        }
    }

    #[test]
    fn a_valid_signature_over_other_figures_is_untrusted() {
        let outcome = signed_outcome(Status::Fail("names other figures".to_string()));
        assert_eq!(overall_label(&outcome), "UNTRUSTED");
    }

    #[test]
    fn a_valid_signature_over_an_unbindable_attestation_stays_partial() {
        let outcome = signed_outcome(Status::Skip("predates content-hash subjects".to_string()));
        assert_eq!(overall_label(&outcome), "PARTIAL");
    }

    #[test]
    fn attestation_binding_is_not_provided_without_an_attestation() {
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        let s = verify_attestation_binding(&report, b"", None);
        assert_matches!(s, Status::NotProvided);
    }

    #[test]
    fn attestation_binding_fails_on_a_file_that_is_not_a_statement() {
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("attestation.intoto.jsonl");
        std::fs::write(&path, "{\"not\": \"a statement\"}\n").unwrap();
        let s = verify_attestation_binding(&report, b"", Some(&path));
        assert!(
            matches!(&s, Status::Fail(d) if d.contains("not one in-toto statement")),
            "{s:?}"
        );
    }

    #[test]
    fn attestation_binding_fails_on_a_missing_file() {
        let report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        let s = verify_attestation_binding(&report, b"", Some(Path::new("/nonexistent/att.jsonl")));
        assert_matches!(s, Status::Fail(_));
    }

    #[test]
    fn output_references_commit_requires_hex_boundary() {
        // A 7-hex prefix of a 40-hex SHA at a boundary matches.
        assert!(output_references_commit(
            "\"digest\": \"a47be9d1122334455667788990011223344556677\"",
            "a47be9d"
        ));
        // The same 7 hex sitting inside a longer SHA must not match.
        assert!(!output_references_commit(
            "\"digest\": \"ffffa47be9d0000000000000000000000000000000\"",
            "a47be9d"
        ));
    }

    #[test]
    fn derive_sidecar_url_uses_same_directory() {
        assert_eq!(
            derive_sidecar_url(
                "https://example.fr/perf-sentinel-report.json",
                "attestation.intoto.jsonl"
            ),
            Some("https://example.fr/attestation.intoto.jsonl".to_string())
        );
        assert_eq!(
            derive_sidecar_url("https://example.fr/report.json", "bundle.sig"),
            Some("https://example.fr/bundle.sig".to_string())
        );
    }

    #[test]
    fn derive_sidecar_url_returns_none_when_url_has_no_slash() {
        assert!(derive_sidecar_url("report.json", "bundle.sig").is_none());
    }

    #[test]
    fn cosign_argument_rejects_flag_injection() {
        assert!(!is_safe_cosign_argument(
            "--certificate-github-workflow-ref=evil"
        ));
        assert!(!is_safe_cosign_argument("-x"));
        assert!(!is_safe_cosign_argument(""));
        assert!(!is_safe_cosign_argument("user@example.fr\nmalicious"));
        assert!(is_safe_cosign_argument("user@example.fr"));
        assert!(is_safe_cosign_argument(
            "https://token.actions.githubusercontent.com"
        ));
    }

    /// A disclosure PDF served at a URL carries its own attestation and
    /// bundle, so no sidecar is fetched next to it.
    #[cfg(feature = "pdf")]
    #[tokio::test]
    async fn a_url_serving_a_pdf_reads_the_report_it_attaches() {
        use sentinel_core::report::periodic::pdf::{PdfInputs, render_disclosure_pdf};
        use std::sync::Mutex;

        let mut report: PeriodicReport =
            serde_json::from_slice(&std::fs::read(example_g2()).unwrap()).unwrap();
        report.integrity.content_hash = compute_content_hash(&report).unwrap();
        let report_bytes = serde_json::to_vec(&report).unwrap();
        let pdf = render_disclosure_pdf(&PdfInputs {
            report_bytes: &report_bytes,
            attestation: None,
            bundle: None,
            expected_identity: None,
            expected_issuer: None,
        })
        .unwrap();
        let url = "https://example.fr/disclosure/report.pdf";
        let asked = Mutex::new(Vec::new());
        let loaded = load_remote(url, |u| {
            asked.lock().unwrap().push(u.clone());
            let body = (u == url).then(|| pdf.clone());
            async move { body.ok_or_else(|| "http status 404".to_string()) }
        })
        .await
        .unwrap_or_else(|code| panic!("exit {code}"));

        assert!(loaded.from_pdf);
        assert_eq!(report_bytes, loaded.bytes);
        assert_eq!(
            report.integrity.content_hash,
            loaded.report.integrity.content_hash
        );
        assert_eq!(vec![url.to_string()], *asked.lock().unwrap());
    }
}