mise-sigstore 2026.5.3

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

use async_trait::async_trait;
use base64::Engine;
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue, USER_AGENT};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use sigstore_verify::VerificationPolicy;
use sigstore_verify::trust_root::{SigstoreInstance, TrustedRoot};
use sigstore_verify::types::bundle::VerificationMaterialContent;
use sigstore_verify::types::{
    Artifact, Bundle, DerCertificate, DerPublicKey, HashAlgorithm, Sha256Hash, SignatureBytes,
    SignatureContent,
};
use thiserror::Error;
use tokio::io::AsyncReadExt;

const GITHUB_API_URL: &str = "https://api.github.com";
const USER_AGENT_VALUE: &str = "mise-sigstore/0.1.0";

#[derive(Debug, Error)]
pub enum AttestationError {
    #[error("API error: {0}")]
    Api(String),
    #[error("Verification failed: {0}")]
    Verification(String),
    #[error("SLSA subject mismatch: {0}")]
    SubjectMismatch(String),
    #[error("Unsupported attestation format: {0}")]
    UnsupportedFormat(String),
    #[error("No attestations found")]
    NoAttestations,
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("HTTP error: {0}")]
    Http(#[from] reqwest::Error),
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("Sigstore error: {0}")]
    Sigstore(String),
}

impl From<sigstore_verify::Error> for AttestationError {
    fn from(err: sigstore_verify::Error) -> Self {
        AttestationError::Sigstore(err.to_string())
    }
}

impl From<sigstore_verify::types::Error> for AttestationError {
    fn from(err: sigstore_verify::types::Error) -> Self {
        AttestationError::Sigstore(err.to_string())
    }
}

impl From<sigstore_verify::trust_root::Error> for AttestationError {
    fn from(err: sigstore_verify::trust_root::Error) -> Self {
        AttestationError::Sigstore(err.to_string())
    }
}

pub type Result<T> = std::result::Result<T, AttestationError>;

#[derive(Debug, Clone)]
pub struct SlsaArtifact {
    pub name: String,
    pub sha256: String,
}

impl SlsaArtifact {
    pub fn from_bytes(name: String, bytes: &[u8]) -> Self {
        Self {
            name,
            sha256: hex::encode(Sha256::digest(bytes)),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ArtifactRef {
    digest: String,
}

impl ArtifactRef {
    pub fn from_digest(digest: &str) -> Self {
        if digest.contains(':') {
            Self {
                digest: digest.to_string(),
            }
        } else {
            Self {
                digest: format!("sha256:{digest}"),
            }
        }
    }
}

#[async_trait]
pub trait AttestationSource {
    async fn fetch_attestations(&self, artifact: &ArtifactRef) -> Result<Vec<Attestation>>;
}

pub mod sources {
    pub use crate::{ArtifactRef, AttestationSource};

    pub mod github {
        pub use crate::GitHubSource;
    }
}

#[derive(Debug, Clone)]
pub struct GitHubSource {
    client: AttestationClient,
    owner: String,
    repo: String,
}

impl GitHubSource {
    pub fn new(owner: &str, repo: &str, token: Option<&str>) -> Result<Self> {
        let mut builder = AttestationClient::builder();
        if let Some(token) = token {
            builder = builder.github_token(token);
        }
        Ok(Self {
            client: builder.build()?,
            owner: owner.to_string(),
            repo: repo.to_string(),
        })
    }

    pub fn with_base_url(
        owner: &str,
        repo: &str,
        token: Option<&str>,
        base_url: &str,
    ) -> Result<Self> {
        let mut builder = AttestationClient::builder().base_url(base_url);
        if let Some(token) = token {
            builder = builder.github_token(token);
        }
        Ok(Self {
            client: builder.build()?,
            owner: owner.to_string(),
            repo: repo.to_string(),
        })
    }
}

#[async_trait]
impl AttestationSource for GitHubSource {
    async fn fetch_attestations(&self, artifact: &ArtifactRef) -> Result<Vec<Attestation>> {
        self.client
            .fetch_attestations(FetchParams {
                owner: self.owner.clone(),
                repo: Some(format!("{}/{}", self.owner, self.repo)),
                digest: artifact.digest.clone(),
                limit: 30,
                predicate_type: None,
            })
            .await
    }
}

#[derive(Debug, Clone)]
pub struct AttestationClient {
    client: reqwest::Client,
    base_url: String,
    github_token: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct AttestationClientBuilder {
    base_url: Option<String>,
    github_token: Option<String>,
}

impl AttestationClientBuilder {
    pub fn base_url(mut self, url: &str) -> Self {
        self.base_url = Some(url.trim_end_matches('/').to_string());
        self
    }

    pub fn github_token(mut self, token: &str) -> Self {
        self.github_token = Some(token.to_string());
        self
    }

    pub fn build(self) -> Result<AttestationClient> {
        let mut headers = HeaderMap::new();
        headers.insert(USER_AGENT, HeaderValue::from_static(USER_AGENT_VALUE));
        let client = reqwest::Client::builder()
            .default_headers(headers)
            .build()?;

        Ok(AttestationClient {
            client,
            base_url: self.base_url.unwrap_or_else(|| GITHUB_API_URL.to_string()),
            github_token: self.github_token,
        })
    }
}

#[derive(Debug, Serialize)]
pub struct FetchParams {
    pub owner: String,
    pub repo: Option<String>,
    pub digest: String,
    pub limit: usize,
    pub predicate_type: Option<String>,
}

#[derive(Debug, Deserialize)]
struct AttestationsResponse {
    attestations: Vec<Attestation>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Attestation {
    bundle: Option<serde_json::Value>,
    bundle_url: Option<String>,
}

impl AttestationClient {
    pub fn builder() -> AttestationClientBuilder {
        AttestationClientBuilder::default()
    }

    fn github_headers(&self, url: &str) -> Result<HeaderMap> {
        let mut headers = HeaderMap::new();
        let base_with_slash = format!("{}/", self.base_url);
        if url == self.base_url || url.starts_with(&base_with_slash) {
            if let Some(token) = &self.github_token {
                headers.insert(
                    AUTHORIZATION,
                    HeaderValue::from_str(&format!("Bearer {token}"))
                        .map_err(|e| AttestationError::Api(e.to_string()))?,
                );
            }
            headers.insert(
                "x-github-api-version",
                HeaderValue::from_static("2022-11-28"),
            );
        }
        Ok(headers)
    }

    pub async fn fetch_attestations(&self, params: FetchParams) -> Result<Vec<Attestation>> {
        let url = if let Some(repo) = &params.repo {
            format!(
                "{}/repos/{repo}/attestations/{}",
                self.base_url, params.digest
            )
        } else {
            format!(
                "{}/orgs/{}/attestations/{}",
                self.base_url, params.owner, params.digest
            )
        };

        let mut query_params = vec![("per_page", params.limit.to_string())];
        if let Some(predicate_type) = &params.predicate_type {
            query_params.push(("predicate_type", predicate_type.clone()));
        }
        let url = reqwest::Url::parse_with_params(&url, query_params)
            .map_err(|e| AttestationError::Api(format!("Invalid GitHub attestations URL: {e}")))?;

        let response = self
            .client
            .get(url.clone())
            .headers(self.github_headers(url.as_str())?)
            .send()
            .await?;

        if response.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(vec![]);
        }
        if !response.status().is_success() {
            let status = response.status();
            let body = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(AttestationError::Api(format!(
                "GitHub API returned {status}: {body}"
            )));
        }

        let response: AttestationsResponse = response.json().await?;
        let mut attestations = Vec::new();
        for attestation in response.attestations {
            if attestation.bundle.is_some() {
                attestations.push(attestation);
            } else if let Some(bundle_url) = &attestation.bundle_url {
                let bundle = self.fetch_bundle_url(bundle_url).await?;
                attestations.push(Attestation {
                    bundle: Some(bundle),
                    bundle_url: Some(bundle_url.clone()),
                });
            }
        }
        Ok(attestations)
    }

    async fn fetch_bundle_url(&self, bundle_url: &str) -> Result<serde_json::Value> {
        let response = self
            .client
            .get(bundle_url)
            .headers(self.github_headers(bundle_url)?)
            .send()
            .await?;
        if !response.status().is_success() {
            return Err(AttestationError::Api(format!(
                "bundle URL returned {}",
                response.status()
            )));
        }
        if is_snappy_content_type(&response) {
            let bytes = response.bytes().await?;
            let decompressed = snap::raw::Decoder::new()
                .decompress_vec(&bytes)
                .map_err(|e| AttestationError::Api(format!("Snappy decompression failed: {e}")))?;
            serde_json::from_slice(&decompressed).map_err(AttestationError::Json)
        } else {
            response.json().await.map_err(AttestationError::Http)
        }
    }
}

pub async fn verify_github_attestation(
    artifact_path: &Path,
    owner: &str,
    repo: &str,
    token: Option<&str>,
    signer_workflow: Option<&str>,
) -> Result<bool> {
    verify_github_attestation_inner(artifact_path, owner, repo, token, signer_workflow, None).await
}

pub async fn verify_github_attestation_with_base_url(
    artifact_path: &Path,
    owner: &str,
    repo: &str,
    token: Option<&str>,
    signer_workflow: Option<&str>,
    base_url: &str,
) -> Result<bool> {
    verify_github_attestation_inner(
        artifact_path,
        owner,
        repo,
        token,
        signer_workflow,
        Some(base_url),
    )
    .await
}

async fn verify_github_attestation_inner(
    artifact_path: &Path,
    owner: &str,
    repo: &str,
    token: Option<&str>,
    signer_workflow: Option<&str>,
    base_url: Option<&str>,
) -> Result<bool> {
    let mut builder = AttestationClient::builder();
    if let Some(token) = token {
        builder = builder.github_token(token);
    }
    if let Some(base_url) = base_url {
        builder = builder.base_url(base_url);
    }
    let client = builder.build()?;
    let digest = calculate_file_digest_async(artifact_path).await?;
    let attestations = client
        .fetch_attestations(FetchParams {
            owner: owner.to_string(),
            repo: Some(format!("{owner}/{repo}")),
            digest: format!("sha256:{digest}"),
            limit: 30,
            predicate_type: None,
        })
        .await?;

    if attestations.is_empty() {
        return Err(AttestationError::NoAttestations);
    }

    let artifact = tokio::fs::read(artifact_path).await?;
    let mut trust_roots = TrustRoots::default();
    verify_attestation_bundles(&attestations, &artifact, signer_workflow, &mut trust_roots).await
}

pub async fn verify_cosign_signature(
    artifact_path: &Path,
    sig_or_bundle_path: &Path,
) -> Result<bool> {
    let content = tokio::fs::read_to_string(sig_or_bundle_path).await?;
    let artifact = tokio::fs::read(artifact_path).await?;
    let mut trust_roots = TrustRoots::default();
    if let Ok(bundle) = Bundle::from_json(&content) {
        let trusted_root = trust_roots.for_bundle(&bundle).await?;
        verify_bundle(&artifact, &bundle, None, trusted_root)?;
        return Ok(true);
    }
    // Legacy cosign v1 bundle (`{base64Signature, cert, rekorBundle}`).
    // sigstore-verify only consumes the modern bundle shape, so we verify
    // these manually: chain-validate the embedded cert against Sigstore
    // Fulcio, then ECDSA-verify the signature over the artifact bytes.
    let trusted_root = trust_roots.sigstore_root().await?;
    verify_legacy_cosign_bundle(&artifact, &content, trusted_root)?;
    Ok(true)
}

pub async fn verify_cosign_signature_with_key(
    artifact_path: &Path,
    sig_or_bundle_path: &Path,
    public_key_path: &Path,
) -> Result<bool> {
    let key_pem = tokio::fs::read_to_string(public_key_path).await?;
    let public_key = DerPublicKey::from_pem(&key_pem)?;

    // Read the file once, propagating real I/O errors. Only a JSON-parse
    // failure means "this isn't a sigstore bundle, treat it as a raw `.sig`."
    let raw_bytes = tokio::fs::read(sig_or_bundle_path).await?;
    let bundle = std::str::from_utf8(&raw_bytes)
        .ok()
        .and_then(|content| Bundle::from_json(content).ok());
    if let Some(bundle) = bundle {
        if matches!(
            &bundle.verification_material.content,
            VerificationMaterialContent::PublicKey { .. }
        ) {
            let artifact = tokio::fs::read(artifact_path).await?;
            verify_public_key_bundle(&artifact, &bundle, &public_key)?;
            return Ok(true);
        }

        // Bundle path: needs the trust root for tlog (Rekor) verification.
        let trusted_root = production_trusted_root().await?;
        let artifact = tokio::fs::read(artifact_path).await?;
        let result = sigstore_verify::verify_with_key(
            artifact.as_slice(),
            &bundle,
            &public_key,
            &trusted_root,
        )?;
        if !result.success {
            return Err(AttestationError::Verification(
                "sigstore verification returned false".to_string(),
            ));
        }
        return Ok(true);
    }

    // Raw `.sig` path: only needs the local public key — no network access.
    let artifact = tokio::fs::read(artifact_path).await?;
    let signature = decode_cosign_signature(&raw_bytes);
    verify_raw_signature(&artifact, &signature, &public_key)?;
    Ok(true)
}

fn verify_public_key_bundle(
    artifact: &[u8],
    bundle: &Bundle,
    public_key: &DerPublicKey,
) -> Result<()> {
    use sigstore_verify::bundle::{ValidationOptions, validate_bundle_with_options};
    use sigstore_verify::crypto::{
        KeyType, SigningScheme, detect_key_type, verify_signature, verify_signature_prehashed,
    };

    validate_bundle_with_options(
        bundle,
        &ValidationOptions {
            require_inclusion_proof: true,
            require_timestamp: false,
        },
    )
    .map_err(|e| AttestationError::Verification(format!("bundle validation failed: {e}")))?;

    let scheme = match detect_key_type(public_key) {
        KeyType::Ed25519 => SigningScheme::Ed25519,
        KeyType::EcdsaP256 => SigningScheme::EcdsaP256Sha256,
        KeyType::Unknown => {
            return Err(AttestationError::Verification(
                "unsupported or unrecognized public key type".to_string(),
            ));
        }
    };

    match &bundle.content {
        SignatureContent::MessageSignature(msg_sig) => {
            let artifact_hash = Sha256Hash::try_from_slice(&Sha256::digest(artifact))?;
            if let Some(digest) = &msg_sig.message_digest {
                if digest.algorithm != HashAlgorithm::Sha2256 {
                    return Err(AttestationError::Verification(format!(
                        "unsupported message digest algorithm {}",
                        digest.algorithm
                    )));
                }
                if digest.digest != artifact_hash {
                    return Err(AttestationError::Verification(
                        "message digest in bundle does not match artifact hash".to_string(),
                    ));
                }
            }

            if scheme.uses_sha256() && scheme.supports_prehashed() {
                verify_signature_prehashed(public_key, &artifact_hash, &msg_sig.signature, scheme)
            } else {
                verify_signature(public_key, artifact, &msg_sig.signature, scheme)
            }
            .map_err(|e| {
                AttestationError::Verification(format!("signature verification failed: {e}"))
            })?;
        }
        SignatureContent::DsseEnvelope(envelope) => {
            let payload = envelope.decode_payload();
            let pae = sigstore_verify::types::pae(&envelope.payload_type, &payload);
            if !envelope
                .signatures
                .iter()
                .any(|sig| verify_signature(public_key, &pae, &sig.sig, scheme).is_ok())
            {
                return Err(AttestationError::Verification(
                    "DSSE signature verification failed: no valid signatures found".to_string(),
                ));
            }
        }
    }

    Ok(())
}

pub async fn verify_slsa_provenance(
    artifact_path: &Path,
    provenance_path: &Path,
    min_level: u8,
) -> Result<bool> {
    let artifact = tokio::fs::read(artifact_path).await?;
    verify_slsa_provenance_artifacts(
        provenance_path,
        &[SlsaArtifact::from_bytes(String::new(), &artifact)],
        min_level,
    )
    .await
}

pub async fn verify_slsa_provenance_artifacts(
    provenance_path: &Path,
    artifacts: &[SlsaArtifact],
    min_level: u8,
) -> Result<bool> {
    if artifacts.is_empty() {
        return Err(AttestationError::SubjectMismatch(
            "no artifacts supplied for SLSA subject verification".to_string(),
        ));
    }

    let content = tokio::fs::read_to_string(provenance_path).await?;
    let mut errors = Vec::new();
    let mut trust_roots = TrustRoots::default();

    let mut candidates: Vec<&str> = content
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .collect();
    let trimmed = content.trim();
    if !trimmed.is_empty() && !candidates.contains(&trimmed) {
        candidates.push(trimmed);
    }

    for candidate in candidates {
        // Bundle::from_json failure falls through to the DSSE envelope path.
        if let Ok(bundle) = Bundle::from_json(candidate) {
            let result = match trust_roots.for_bundle(&bundle).await {
                Ok(root) => verify_bundle_for_any_artifact(artifacts, &bundle, root)
                    .and_then(|_| verify_bundle_slsa_subjects(&bundle, artifacts, min_level)),
                Err(e) => Err(e),
            };
            match result {
                Ok(()) => return Ok(true),
                Err(e) => errors.push(e),
            }
            continue;
        }
        // slsa-github-generator and goreleaser write the provenance as a raw
        // DSSE envelope (`*.intoto.jsonl`) rather than a sigstore bundle —
        // there is no `verificationMaterial`, so `Bundle::from_json` rejects
        // it. Match the in-toto payload manually and check artifact digest +
        // SLSA predicate without going through sigstore-verify. Use the public
        // Sigstore trust root since slsa-github-generator certs are issued by
        // Sigstore Fulcio.
        let result = match trust_roots.sigstore_root().await {
            Ok(root) => verify_intoto_envelope_subjects(candidate, artifacts, min_level, root),
            Err(e) => Err(e),
        };
        match result {
            Ok(()) => return Ok(true),
            Err(e) => errors.push(e),
        }
    }

    collapse_slsa_errors(errors, || {
        "File does not contain valid attestations or SLSA provenance".to_string()
    })
}

#[cfg(test)]
fn verify_intoto_envelope(
    line: &str,
    artifact: &[u8],
    min_level: u8,
    trusted_root: &TrustedRoot,
) -> Result<()> {
    verify_intoto_envelope_subjects(
        line,
        &[SlsaArtifact::from_bytes(String::new(), artifact)],
        min_level,
        trusted_root,
    )
}

fn verify_intoto_envelope_subjects(
    line: &str,
    artifacts: &[SlsaArtifact],
    min_level: u8,
    trusted_root: &TrustedRoot,
) -> Result<()> {
    let envelope: serde_json::Value = serde_json::from_str(line).map_err(|e| {
        AttestationError::UnsupportedFormat(format!("not a JSON DSSE envelope: {e}"))
    })?;
    let payload_type = envelope
        .get("payloadType")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    if payload_type != "application/vnd.in-toto+json" {
        return Err(AttestationError::UnsupportedFormat(format!(
            "unsupported DSSE payloadType: {payload_type}"
        )));
    }
    let payload_b64 = envelope
        .get("payload")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            AttestationError::UnsupportedFormat("DSSE envelope missing payload".to_string())
        })?;
    let payload = base64::engine::general_purpose::STANDARD
        .decode(payload_b64.as_bytes())
        .map_err(|e| AttestationError::Verification(format!("invalid base64 payload: {e}")))?;

    // DSSE signature verification. The envelope's signatures sign the
    // Pre-Authentication Encoding of the payload, not the payload itself.
    // Without this check, anyone able to substitute the provenance file could
    // forge a passing attestation just by including the artifact's digest in
    // the in-toto subject list.
    //
    // Each signature embeds the Sigstore Fulcio leaf cert that signed it
    // (slsa-github-generator format). We chain-validate that cert against the
    // public Sigstore trust root, then verify the signature against the PAE
    // using the cert's public key. A self-signed forged cert would be
    // rejected at the chain step. Bundles in the modern sigstore format
    // (which carry tlog/TSA) take the strict `verify_bundle` path above.
    let signatures = envelope
        .get("signatures")
        .and_then(|v| v.as_array())
        .ok_or_else(|| {
            AttestationError::Verification("DSSE envelope missing signatures".to_string())
        })?;
    if signatures.is_empty() {
        return Err(AttestationError::Verification(
            "DSSE envelope has no signatures".to_string(),
        ));
    }
    let pae = sigstore_verify::types::pae(payload_type, &payload);
    let mut sig_errors = Vec::new();
    let mut verified = false;
    for sig in signatures {
        match verify_dsse_signature(sig, &pae, trusted_root) {
            Ok(()) => {
                verified = true;
                break;
            }
            Err(e) => sig_errors.push(e.to_string()),
        }
    }
    if !verified {
        return Err(AttestationError::Verification(format!(
            "no valid DSSE signature: {}",
            join_error_strings(sig_errors, || "no signatures could be verified".to_string())
        )));
    }

    verify_intoto_payload_subjects(&payload, artifacts, min_level)
}

/// Verify a legacy cosign v1 keyless bundle (`{base64Signature, cert, rekorBundle}`).
///
/// Cosign 2.x and earlier `cosign sign-blob --bundle` writes this format. The
/// modern sigstore Bundle (with `verificationMaterial`/`messageSignature`)
/// replaces it, but tools like goreleaser still produce v1 bundles in their
/// release artifacts. Verification mirrors what we do for raw DSSE envelopes:
/// decode the embedded Fulcio cert (PEM in `cert`), chain-validate it against
/// the public Sigstore trust root, then ECDSA-verify `base64Signature` over
/// the raw artifact bytes with the cert's public key.
///
/// The Rekor `SignedEntryTimestamp` and the artifact hash recorded in the
/// rekord entry aren't independently re-checked here — re-verifying them
/// would require a Rekor public key lookup and adds little: the cert+sig
/// step already cryptographically binds the signer to the artifact bytes,
/// which is what every downstream consumer cares about.
fn verify_legacy_cosign_bundle(
    artifact: &[u8],
    bundle_json: &str,
    trusted_root: &TrustedRoot,
) -> Result<()> {
    let value: serde_json::Value = serde_json::from_str(bundle_json).map_err(|e| {
        AttestationError::UnsupportedFormat(format!("not a sigstore or cosign bundle: {e}"))
    })?;
    let cert_b64 = value.get("cert").and_then(|v| v.as_str()).ok_or_else(|| {
        AttestationError::UnsupportedFormat("legacy cosign bundle missing cert".to_string())
    })?;
    let sig_b64 = value
        .get("base64Signature")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            AttestationError::UnsupportedFormat(
                "legacy cosign bundle missing base64Signature".to_string(),
            )
        })?;

    let cert_pem_bytes = base64::engine::general_purpose::STANDARD
        .decode(cert_b64.as_bytes())
        .map_err(|e| {
            AttestationError::Verification(format!("invalid base64 cert in legacy bundle: {e}"))
        })?;
    let cert_pem = std::str::from_utf8(&cert_pem_bytes).map_err(|e| {
        AttestationError::Verification(format!("legacy cosign cert is not UTF-8 PEM: {e}"))
    })?;
    let cert = DerCertificate::from_pem(cert_pem)?;
    verify_cert_chain(cert.as_bytes(), trusted_root)?;

    let sig_bytes = base64::engine::general_purpose::STANDARD
        .decode(sig_b64.as_bytes())
        .map_err(|e| AttestationError::Verification(format!("invalid base64 signature: {e}")))?;
    let spki_der = extract_spki_der(cert.as_bytes())?;
    let public_key = DerPublicKey::new(spki_der);
    verify_raw_signature(artifact, &sig_bytes, &public_key)
}

fn verify_dsse_signature(
    sig: &serde_json::Value,
    pae: &[u8],
    trusted_root: &TrustedRoot,
) -> Result<()> {
    let cert_pem = sig.get("cert").and_then(|v| v.as_str()).ok_or_else(|| {
        AttestationError::Verification("DSSE signature missing cert field".to_string())
    })?;
    let sig_b64 = sig.get("sig").and_then(|v| v.as_str()).ok_or_else(|| {
        AttestationError::Verification("DSSE signature missing sig field".to_string())
    })?;
    let sig_bytes = base64::engine::general_purpose::STANDARD
        .decode(sig_b64.as_bytes())
        .map_err(|e| AttestationError::Verification(format!("invalid base64 signature: {e}")))?;
    let cert = DerCertificate::from_pem(cert_pem)?;
    // Chain-validate the embedded cert before trusting its public key.
    verify_cert_chain(cert.as_bytes(), trusted_root)?;
    let spki_der = extract_spki_der(cert.as_bytes())?;
    let public_key = DerPublicKey::new(spki_der);
    verify_raw_signature(pae, &sig_bytes, &public_key)
}

fn verify_intoto_payload_subjects(
    payload: &[u8],
    artifacts: &[SlsaArtifact],
    min_level: u8,
) -> Result<()> {
    let statement: serde_json::Value = serde_json::from_slice(payload).map_err(|e| {
        AttestationError::Verification(format!("Failed to parse SLSA payload: {e}"))
    })?;
    let predicate_type = statement
        .get("predicateType")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    if !predicate_type.starts_with("https://slsa.dev/provenance/") {
        return Err(AttestationError::UnsupportedFormat(format!(
            "Not an SLSA provenance predicate: {predicate_type}"
        )));
    }
    if min_level > 1 {
        return Err(AttestationError::Verification(format!(
            "SLSA level {min_level} verification is not supported by the native adapter"
        )));
    }
    let subjects = statement
        .get("subject")
        .and_then(|v| v.as_array())
        .ok_or_else(|| {
            AttestationError::Verification("SLSA statement missing subject array".to_string())
        })?;

    let subject_digests = subjects
        .iter()
        .filter_map(|subject| {
            subject
                .get("digest")
                .and_then(|d| d.get("sha256"))
                .and_then(|v| v.as_str())
                .map(|sha| sha.to_ascii_lowercase())
        })
        .collect::<std::collections::HashSet<_>>();
    let named_subjects = subjects
        .iter()
        .filter_map(|subject| {
            let name = subject.get("name")?.as_str()?;
            let sha = subject
                .get("digest")
                .and_then(|d| d.get("sha256"))
                .and_then(|v| v.as_str())?;
            Some((name.to_string(), sha.to_ascii_lowercase()))
        })
        .collect::<std::collections::HashSet<_>>();

    let mut missing = Vec::new();
    for artifact in artifacts {
        let artifact_digest = artifact.sha256.to_ascii_lowercase();
        let matches_subject = if artifact.name.is_empty() {
            subject_digests.contains(&artifact_digest)
        } else {
            named_subjects.contains(&(artifact.name.clone(), artifact_digest.clone()))
        };
        if !matches_subject {
            if artifact.name.is_empty() {
                missing.push(artifact_digest);
            } else {
                missing.push(format!("{} ({artifact_digest})", artifact.name));
            }
        }
    }
    if !missing.is_empty() {
        return Err(AttestationError::SubjectMismatch(format!(
            "artifact subjects not found in SLSA statement subjects: {}",
            missing.join(", ")
        )));
    }
    Ok(())
}

fn collapse_slsa_errors(
    errors: Vec<AttestationError>,
    default: impl FnOnce() -> String,
) -> Result<bool> {
    let unsupported_format = errors
        .iter()
        .all(|error| matches!(error, AttestationError::UnsupportedFormat(_)));
    let subject_mismatch = errors.iter().any(is_slsa_subject_mismatch);
    let message = join_error_strings(
        errors.into_iter().map(|error| error.to_string()).collect(),
        default,
    );
    Err(if unsupported_format {
        AttestationError::UnsupportedFormat(message)
    } else if subject_mismatch {
        AttestationError::SubjectMismatch(message)
    } else {
        AttestationError::Verification(message)
    })
}

pub fn is_slsa_subject_mismatch(error: &AttestationError) -> bool {
    match error {
        AttestationError::SubjectMismatch(_) => true,
        AttestationError::Verification(msg) | AttestationError::Sigstore(msg) => {
            is_subject_mismatch_message(msg)
        }
        _ => false,
    }
}

fn is_subject_mismatch_message(message: &str) -> bool {
    message.contains("artifact hash does not match any subject in attestation")
        || message.contains("not found in SLSA statement subjects")
        || message.contains("artifact subjects not found in SLSA statement subjects")
}

fn join_error_strings(errors: Vec<String>, default: impl FnOnce() -> String) -> String {
    let mut errors = errors
        .into_iter()
        .filter(|error| !error.trim().is_empty())
        .collect::<Vec<_>>();
    errors.dedup();
    if errors.is_empty() {
        default()
    } else {
        errors.join("; ")
    }
}

async fn verify_attestation_bundles(
    attestations: &[Attestation],
    artifact: &[u8],
    signer_workflow: Option<&str>,
    trust_roots: &mut TrustRoots,
) -> Result<bool> {
    let mut errors = Vec::new();
    for attestation in attestations {
        let Some(bundle_value) = &attestation.bundle else {
            continue;
        };
        let bundle = match serde_json::from_value::<Bundle>(bundle_value.clone()) {
            Ok(bundle) => bundle,
            Err(e) => {
                errors.push(e.to_string());
                continue;
            }
        };
        let trusted_root = match trust_roots.for_bundle(&bundle).await {
            Ok(root) => root,
            Err(e) => {
                errors.push(e.to_string());
                continue;
            }
        };
        match verify_bundle(artifact, &bundle, signer_workflow, trusted_root) {
            Ok(()) => return Ok(true),
            Err(e) => errors.push(e.to_string()),
        }
    }

    Err(AttestationError::Verification(join_error_strings(
        errors,
        || "No valid attestations found".to_string(),
    )))
}

fn is_snappy_content_type(response: &reqwest::Response) -> bool {
    response
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .and_then(|content_type| content_type.split(';').next())
        .is_some_and(|content_type| content_type.trim() == "application/x-snappy")
}

fn verify_bundle<'a>(
    artifact: impl Into<Artifact<'a>>,
    bundle: &Bundle,
    signer_workflow: Option<&str>,
    trusted_root: &TrustedRoot,
) -> Result<()> {
    let mut policy = VerificationPolicy::default();
    // sigstore-verify's default policy *requires* an inclusion proof when
    // `verify_tlog` is on. GitHub artifact attestations and TSA-only bundles
    // never carry one, so we'd reject them outright. Skip tlog only when the
    // bundle has no inclusion proof — public-Sigstore cosign bundles, which do
    // ship a Rekor inclusion proof, still get full tlog verification (Rekor
    // checkpoint signature, SET, inclusion-proof Merkle path).
    if !bundle.has_inclusion_proof() {
        policy = policy.skip_tlog();
    }
    // GitHub-internal leaf certs don't carry an SCT extension (GitHub's CA
    // doesn't log to public CT). `skip_sct` keeps full certificate-chain
    // validation against the GitHub trust root's Fulcio certs but turns off
    // the SCT check, which is exactly what GitHub artifact attestations need.
    if is_github_internal_certificate(bundle) {
        policy = policy.skip_sct();
    }
    let result = sigstore_verify::verify(artifact, bundle, &policy, trusted_root)?;
    if !result.success {
        return Err(AttestationError::Verification(
            "sigstore verification returned false".to_string(),
        ));
    }

    verify_signer_workflow_identity(result.identity.as_deref(), signer_workflow)?;

    Ok(())
}

fn is_github_internal_certificate(bundle: &Bundle) -> bool {
    bundle
        .signing_certificate()
        .map(|cert| cert_issuer_organization(cert.as_bytes()).as_deref() == Some("GitHub, Inc."))
        .unwrap_or(false)
}

/// Verify that a leaf certificate chains to one of the trust root's CA certs.
///
/// Used for raw DSSE envelopes (`*.intoto.jsonl` from slsa-github-generator),
/// which don't have the bundle structure sigstore-verify expects, so we can't
/// delegate to `sigstore_verify::verify`. GitHub-internal bundles go through
/// sigstore-verify directly with `skip_sct`.
///
/// webpki performs the same chain-building, ECDSA/RSA signature checks, and
/// CODE_SIGNING EKU enforcement as sigstore-verify, just without the SCT step.
///
/// Validation time is the leaf cert's `notAfter`. Fulcio leaves are
/// short-lived (~10 min) so by `now()` they're already expired and we have no
/// independently verified time source here. Using `notAfter` rather than
/// `notBefore` is the stricter choice: it catches any intermediate CA whose
/// own validity ends before the leaf's, which would otherwise slip through.
fn verify_cert_chain(leaf_der: &[u8], trusted_root: &TrustedRoot) -> Result<()> {
    use rustls_pki_types::{CertificateDer, UnixTime};
    use webpki::{ALL_VERIFICATION_ALGS, EndEntityCert, KeyUsage, anchor_from_trusted_cert};
    use x509_cert::Certificate;
    use x509_cert::der::Decode;

    let leaf = Certificate::from_der(leaf_der).map_err(|e| {
        AttestationError::Verification(format!("failed to parse leaf certificate: {e}"))
    })?;
    let not_after = leaf
        .tbs_certificate
        .validity
        .not_after
        .to_unix_duration()
        .as_secs();
    let validation_time = UnixTime::since_unix_epoch(std::time::Duration::from_secs(not_after));

    let all_certs = trusted_root.fulcio_certs().map_err(|e| {
        AttestationError::Verification(format!("failed to load CA certs from trust root: {e}"))
    })?;
    if all_certs.is_empty() {
        return Err(AttestationError::Verification(
            "trust root contains no CA certificates".to_string(),
        ));
    }
    // Use every CA cert in the trust root as both a trust anchor and as a
    // possible intermediate. `anchor_from_trusted_cert` accepts any parseable
    // cert (not just self-signed roots), and that's intentional: we trust the
    // whole CA bundle the trust root ships, so it's fine for chain validation
    // to terminate at an intermediate rather than walk all the way up to the
    // self-signed root. This matches what sigstore-verify does internally.
    // The chain itself is still cryptographically verified end-to-end.
    let trust_anchors: Vec<_> = all_certs
        .iter()
        .filter_map(|der| {
            anchor_from_trusted_cert(&CertificateDer::from(der.as_ref()))
                .map(|a| a.to_owned())
                .ok()
        })
        .collect();
    if trust_anchors.is_empty() {
        return Err(AttestationError::Verification(
            "trust root CA certs are unparseable".to_string(),
        ));
    }
    let intermediate_certs: Vec<CertificateDer<'static>> = all_certs
        .iter()
        .map(|der| CertificateDer::from(der.as_ref()).into_owned())
        .collect();

    let leaf_der_ref = CertificateDer::from(leaf_der);
    let leaf_cert = EndEntityCert::try_from(&leaf_der_ref).map_err(|e| {
        AttestationError::Verification(format!("failed to parse leaf for chain check: {e}"))
    })?;

    // 1.3.6.1.5.5.7.3.3 — id-kp-codeSigning, raw OID bytes (no DER tag/length).
    const ID_KP_CODE_SIGNING: &[u8] = &[0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x03];

    leaf_cert
        .verify_for_usage(
            ALL_VERIFICATION_ALGS,
            &trust_anchors,
            &intermediate_certs,
            validation_time,
            KeyUsage::required(ID_KP_CODE_SIGNING),
            None,
            None,
        )
        .map_err(|e| {
            AttestationError::Verification(format!("certificate chain validation failed: {e}"))
        })?;
    Ok(())
}

/// Return the X.509 Issuer's `O` (organizationName) attribute, if present.
///
/// Used to dispatch verification policy: certs issued by GitHub's internal
/// Fulcio (`O=GitHub, Inc.`) need a separate trust root and a relaxed policy.
/// Parses the cert with x509-cert rather than byte-searching the DER, so we
/// only match the actual issuer organization field — not arbitrary substrings
/// elsewhere in the certificate.
fn cert_issuer_organization(cert_der: &[u8]) -> Option<String> {
    use x509_cert::Certificate;
    use x509_cert::der::Decode;
    let cert = Certificate::from_der(cert_der).ok()?;
    for rdn in cert.tbs_certificate.issuer.0.iter() {
        for atv in rdn.0.iter() {
            // 2.5.4.10 = id-at-organizationName
            if atv.oid.to_string() == "2.5.4.10" {
                if let Ok(s) = atv.value.decode_as::<String>() {
                    return Some(s);
                }
                if let Ok(s) = atv
                    .value
                    .decode_as::<x509_cert::der::asn1::PrintableStringRef>()
                {
                    return Some(s.as_str().to_string());
                }
                if let Ok(s) = atv.value.decode_as::<x509_cert::der::asn1::Utf8StringRef>() {
                    return Some(s.as_str().to_string());
                }
            }
        }
    }
    None
}

/// Extract the SubjectPublicKeyInfo bytes (DER) from an X.509 certificate.
fn extract_spki_der(cert_der: &[u8]) -> Result<Vec<u8>> {
    use x509_cert::Certificate;
    use x509_cert::der::{Decode, Encode};
    let cert = Certificate::from_der(cert_der)
        .map_err(|e| AttestationError::Verification(format!("failed to parse certificate: {e}")))?;
    cert.tbs_certificate
        .subject_public_key_info
        .to_der()
        .map_err(|e| {
            AttestationError::Verification(format!("failed to encode SubjectPublicKeyInfo: {e}"))
        })
}

async fn production_trusted_root() -> Result<TrustedRoot> {
    Ok(TrustedRoot::production().await?)
}

fn github_trusted_root() -> Result<TrustedRoot> {
    Ok(TrustedRoot::from_embedded(SigstoreInstance::GitHub)?)
}

/// Per-process cache so we only fetch the Sigstore TUF root or parse the
/// embedded GitHub trusted root once per `verify_*` invocation. Each is
/// loaded lazily — a verification flow that only ever sees GitHub bundles
/// never triggers a network call to the Sigstore TUF CDN, and vice versa.
#[derive(Default)]
struct TrustRoots {
    sigstore: Option<TrustedRoot>,
    github: Option<TrustedRoot>,
}

impl TrustRoots {
    async fn for_bundle(&mut self, bundle: &Bundle) -> Result<&TrustedRoot> {
        if is_github_internal_certificate(bundle) {
            self.github_root()
        } else {
            self.sigstore_root().await
        }
    }

    async fn sigstore_root(&mut self) -> Result<&TrustedRoot> {
        if self.sigstore.is_none() {
            self.sigstore = Some(production_trusted_root().await?);
        }
        Ok(self.sigstore.as_ref().unwrap())
    }

    fn github_root(&mut self) -> Result<&TrustedRoot> {
        if self.github.is_none() {
            self.github = Some(github_trusted_root()?);
        }
        Ok(self.github.as_ref().unwrap())
    }
}

fn verify_signer_workflow_identity(
    identity: Option<&str>,
    signer_workflow: Option<&str>,
) -> Result<()> {
    let Some(expected) = signer_workflow else {
        return Ok(());
    };
    let Some(identity) = identity.filter(|identity| !identity.is_empty()) else {
        return Err(AttestationError::Verification(format!(
            "Workflow verification failed: expected '{expected}', found no certificate identity"
        )));
    };
    if !identity.contains(expected) {
        return Err(AttestationError::Verification(format!(
            "Workflow verification failed: expected '{expected}', found certificate identity: {identity:?}"
        )));
    }
    Ok(())
}

/// SLSA-specific checks once `verify_bundle` has cryptographically verified
/// the bundle: the DSSE payload is an SLSA provenance statement, the policy
/// level is supported, and the artifact's SHA-256 appears in the statement's
/// `subject` array. The subject check is the load-bearing part — without it,
/// a valid SLSA bundle signed for *some* artifact would accept *any* artifact.
fn verify_bundle_for_any_artifact(
    artifacts: &[SlsaArtifact],
    bundle: &Bundle,
    root: &TrustedRoot,
) -> Result<()> {
    let artifact = artifacts.first().ok_or_else(|| {
        AttestationError::SubjectMismatch(
            "no artifacts supplied for SLSA subject verification".to_string(),
        )
    })?;
    let digest = Sha256Hash::from_hex(&artifact.sha256).map_err(|e| {
        AttestationError::Verification(format!("invalid artifact sha256 digest: {e}"))
    })?;
    match verify_bundle(Artifact::from_digest(digest), bundle, None, root) {
        Ok(()) => Ok(()),
        Err(e) if is_slsa_subject_mismatch(&e) => {
            Err(AttestationError::SubjectMismatch(e.to_string()))
        }
        Err(e) => Err(e),
    }
}

fn verify_bundle_slsa_subjects(
    bundle: &Bundle,
    artifacts: &[SlsaArtifact],
    min_level: u8,
) -> Result<()> {
    let payload = match &bundle.content {
        sigstore_verify::types::SignatureContent::DsseEnvelope(envelope) => {
            envelope.decode_payload()
        }
        _ => {
            return Err(AttestationError::UnsupportedFormat(
                "SLSA provenance must be a DSSE envelope".to_string(),
            ));
        }
    };
    verify_intoto_payload_subjects(&payload, artifacts, min_level)
}

fn decode_cosign_signature(bytes: &[u8]) -> Vec<u8> {
    let trimmed = String::from_utf8_lossy(bytes).trim().to_string();
    if let Some(decoded) = base64::engine::general_purpose::STANDARD
        .decode(trimmed.as_bytes())
        .ok()
        .filter(|_| !trimmed.is_empty())
    {
        return decoded;
    }
    bytes.to_vec()
}

fn verify_raw_signature(
    artifact: &[u8],
    signature: &[u8],
    public_key: &DerPublicKey,
) -> Result<()> {
    use sigstore_verify::crypto::{KeyType, SigningScheme, detect_key_type, verify_signature};

    let scheme = match detect_key_type(public_key) {
        KeyType::Ed25519 => SigningScheme::Ed25519,
        KeyType::EcdsaP256 => SigningScheme::EcdsaP256Sha256,
        KeyType::Unknown => {
            return Err(AttestationError::Verification(
                "unsupported or unrecognized public key type".to_string(),
            ));
        }
    };
    let signature = SignatureBytes::from_bytes(signature);
    verify_signature(public_key, artifact, &signature, scheme)
        .map_err(|e| AttestationError::Verification(format!("signature verification failed: {e}")))
}

async fn calculate_file_digest_async(path: &Path) -> Result<String> {
    let mut file = tokio::fs::File::open(path).await?;
    let mut hasher = Sha256::new();
    let mut buffer = [0; 8192];
    loop {
        let read = file.read(&mut buffer).await?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(hex::encode(hasher.finalize()))
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn signer_workflow_requires_identity() {
        let err = verify_signer_workflow_identity(None, Some(".github/workflows/release.yml"))
            .unwrap_err()
            .to_string();

        assert!(err.contains("found no certificate identity"));
    }

    #[test]
    fn signer_workflow_rejects_mismatch() {
        let err = verify_signer_workflow_identity(
            Some("https://github.com/jdx/mise/.github/workflows/ci.yml@refs/tags/v1.0.0"),
            Some(".github/workflows/release.yml"),
        )
        .unwrap_err()
        .to_string();

        assert!(err.contains("Workflow verification failed"));
    }

    #[test]
    fn signer_workflow_accepts_match() {
        verify_signer_workflow_identity(
            Some("https://github.com/jdx/mise/.github/workflows/release.yml@refs/tags/v1.0.0"),
            Some(".github/workflows/release.yml"),
        )
        .unwrap();
    }

    #[test]
    fn signer_workflow_rejects_expected_containing_identity() {
        let err = verify_signer_workflow_identity(
            Some(".github/workflows/release.yml"),
            Some("https://github.com/jdx/mise/.github/workflows/release.yml@refs/tags/v1.0.0"),
        )
        .unwrap_err()
        .to_string();

        assert!(err.contains("Workflow verification failed"));
    }

    /// A genuine `*.intoto.jsonl` produced by slsa-github-generator (sops
    /// v3.9.0 release). Signed by Sigstore Fulcio. Tests that don't need a
    /// matching artifact can run against this fixture alone.
    const GENUINE_INTOTO_ENVELOPE: &str =
        include_str!("../tests/fixtures/sops_v3_9_0.intoto.jsonl");

    fn embedded_sigstore_root() -> TrustedRoot {
        TrustedRoot::from_json(sigstore_verify::trust_root::SIGSTORE_PRODUCTION_TRUSTED_ROOT)
            .expect("embedded production trusted_root.json parses")
    }

    fn slsa_statement(subjects: serde_json::Value) -> Vec<u8> {
        serde_json::json!({
            "predicateType": "https://slsa.dev/provenance/v1",
            "subject": subjects,
        })
        .to_string()
        .into_bytes()
    }

    #[test]
    fn intoto_payload_accepts_complete_content_subjects() {
        let artifact = SlsaArtifact::from_bytes("pixi".to_string(), b"binary");
        let payload = slsa_statement(serde_json::json!([
            {"name": "pixi", "digest": {"sha256": artifact.sha256.clone()}},
        ]));

        verify_intoto_payload_subjects(&payload, &[artifact], 1).unwrap();
    }

    #[test]
    fn intoto_payload_rejects_partial_content_subjects() {
        let covered = SlsaArtifact::from_bytes("bin/tool".to_string(), b"tool");
        let uncovered = SlsaArtifact::from_bytes("README.md".to_string(), b"docs");
        let payload = slsa_statement(serde_json::json!([
            {"name": "bin/tool", "digest": {"sha256": covered.sha256.clone()}},
        ]));

        let err = verify_intoto_payload_subjects(&payload, &[covered, uncovered], 1)
            .unwrap_err()
            .to_string();
        assert!(err.contains("README.md"));
        assert!(err.contains("not found in SLSA statement subjects"));
    }

    #[test]
    fn intoto_envelope_rejects_tampered_signature() {
        let root = embedded_sigstore_root();
        let mut env: serde_json::Value =
            serde_json::from_str(GENUINE_INTOTO_ENVELOPE.trim()).unwrap();
        env["signatures"][0]["sig"] =
            serde_json::Value::String(base64::engine::general_purpose::STANDARD.encode(b"forged"));
        let tampered = serde_json::to_string(&env).unwrap();

        // Signature verification happens before the subject digest check, so a
        // forged sig fails regardless of which artifact bytes we pass.
        let err = verify_intoto_envelope(&tampered, b"any artifact bytes", 1, &root)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("DSSE signature") || err.contains("signature verification failed"),
            "expected signature failure, got {err}"
        );
    }

    #[test]
    fn intoto_envelope_rejects_missing_signatures() {
        let root = embedded_sigstore_root();
        let mut env: serde_json::Value =
            serde_json::from_str(GENUINE_INTOTO_ENVELOPE.trim()).unwrap();
        env["signatures"] = serde_json::json!([]);
        let stripped = serde_json::to_string(&env).unwrap();
        let err = verify_intoto_envelope(&stripped, b"any artifact bytes", 1, &root)
            .unwrap_err()
            .to_string();
        assert!(err.contains("no signatures"), "got {err}");
    }

    #[test]
    fn intoto_envelope_rejects_unknown_artifact() {
        // Genuine signature verifies, but a foreign artifact is not in subjects.
        let root = embedded_sigstore_root();
        let err = verify_intoto_envelope(
            GENUINE_INTOTO_ENVELOPE.trim(),
            b"different artifact contents",
            1,
            &root,
        )
        .unwrap_err()
        .to_string();
        assert!(
            err.contains("not found in SLSA statement subjects"),
            "expected subject mismatch, got {err}"
        );
    }

    #[test]
    fn intoto_envelope_rejects_self_signed_cert() {
        // Replace the embedded Fulcio cert with an unrelated self-signed cert
        // and a recomputed signature. Chain validation must reject it.
        let root = embedded_sigstore_root();
        let mut env: serde_json::Value =
            serde_json::from_str(GENUINE_INTOTO_ENVELOPE.trim()).unwrap();
        // A self-signed P-256 cert (any will do — the issuer doesn't chain to
        // the Sigstore trust root).
        const SELF_SIGNED: &str = "-----BEGIN CERTIFICATE-----\n\
MIIBhTCCASugAwIBAgIUExample0AAAAAAAAAAAAAAAAAAAAwCgYIKoZIzj0EAwIw\n\
EzERMA8GA1UEAwwIc2VsZi1jYTAeFw0yNTAxMDEwMDAwMDBaFw0zNTAxMDEwMDAw\n\
MDBaMBMxETAPBgNVBAMMCHNlbGYtY2EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC\n\
AAQX9YJlbpFy0FmCXn7gC8m/qAh3wZw9w0CIxample/Random/dataABCDEFGHIJ\n\
KLMNOPQRSTUVWXYZabcdefghijklmnopo1MwUTAdBgNVHQ4EFgQUExampleHandle\n\
00000000000000000000003wHwYDVR0jBBgwFoAUExampleHandle00000000000\n\
00000000003wDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNJADBGAiEAExam\n\
pleSignature1234567890123456789012345678901234567890CIQDExampleS\n\
ignature1234567890123456789012345678901234567890Aa==\n\
-----END CERTIFICATE-----\n";
        env["signatures"][0]["cert"] = serde_json::Value::String(SELF_SIGNED.to_string());
        let forged = serde_json::to_string(&env).unwrap();
        let err = verify_intoto_envelope(&forged, b"any artifact bytes", 1, &root)
            .unwrap_err()
            .to_string();
        assert!(
            err.to_lowercase().contains("chain")
                || err.to_lowercase().contains("trust")
                || err.to_lowercase().contains("invalid"),
            "expected chain validation failure, got {err}"
        );
    }
}