c2pa 0.91.10

Rust SDK for C2PA (Coalition for Content Provenance and Authenticity) implementors
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
// Copyright 2022 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

use std::{borrow::Cow, io::Write};

use asn1_rs::FromDer;
use async_generic::async_generic;
use c2pa_raw_crypto::{
    ec_utils::parse_ec_der_sig, validator_for_signing_alg, RawSignatureValidationError, SigningAlg,
};
use coset::CoseSign1;
use x509_parser::{
    der_parser::oid, oid_registry::Oid, prelude::X509Certificate, x509::AlgorithmIdentifier,
};

use crate::{
    crypto::{
        asn1::rfc3161::TstInfo,
        base64::encode,
        cose::{
            cert_chain_from_sign1, check_end_entity_certificate_profile, parse_cose_sign1,
            signing_alg_from_sign1, CertificateInfo, CertificateTrustError, CertificateTrustPolicy,
            CoseError, TrustAnchorType,
        },
    },
    log_item,
    status_tracker::StatusTracker,
    validation_results::validation_codes::{
        ALGORITHM_UNSUPPORTED, CLAIM_SIGNATURE_OUTSIDE_VALIDITY, SIGNING_CREDENTIAL_INVALID,
        SIGNING_CREDENTIAL_TRUSTED, SIGNING_CREDENTIAL_UNTRUSTED,
    },
};

/// A `Verifier` reads a COSE signature and reports on its validity.
///
/// It can provide different levels of verification depending on the enum value
/// chosen.
#[derive(Debug)]
#[non_exhaustive]
pub enum Verifier<'a> {
    /// Use a [`CertificateTrustPolicy`] to validate the signing certificate's
    /// profile against C2PA requirements _and_ validate the certificate's
    /// membership against a trust configuration.
    VerifyTrustPolicy(Cow<'a, CertificateTrustPolicy>),

    /// Validate the certificate's membership against a trust configuration, but
    /// do not against any trust list. The [`CertificateTrustPolicy`] is used to
    /// enforce EKU (Extended Key Usage) policy only.
    VerifyCertificateProfileOnly(Cow<'a, CertificateTrustPolicy>),

    /// Ignore both trust configuration and trust lists.
    IgnoreProfileAndTrustPolicy,
}

const EC_PUBLICKEY_OID: Oid<'static> = oid!(1.2.840 .10045 .2 .1);
const RSA_OID: Oid<'static> = oid!(1.2.840 .113549 .1 .1 .1);
const RSASSA_PSS_OID: Oid<'static> = oid!(1.2.840 .113549 .1 .1 .10);
const ED25519_OID: Oid<'static> = oid!(1.3.101 .112);
const PRIME256V1_OID: Oid<'static> = oid!(1.2.840 .10045 .3 .1 .7);
const SECP384R1_OID: Oid<'static> = oid!(1.3.132 .0 .34);
const SECP521R1_OID: Oid<'static> = oid!(1.3.132 .0 .35);

// Does the certificate's key match the algorithm -- and, for EC, the curve --
// implied by the COSE `SigningAlg` (RFC 8152: Es256/384/512 are P-256/384/521)?
// Fails closed: an unmapped future `SigningAlg` is rejected so this map must be
// updated when a new algorithm is added.
fn spki_matches_signing_alg(alg: SigningAlg, spki: &AlgorithmIdentifier) -> bool {
    let key_alg = &spki.algorithm;
    let ec_named_curve_is = |curve: &Oid| {
        *key_alg == EC_PUBLICKEY_OID
            && spki
                .parameters
                .as_ref()
                .and_then(|p| p.as_oid().ok())
                .is_some_and(|c| c == *curve)
    };
    match alg {
        SigningAlg::Es256 => ec_named_curve_is(&PRIME256V1_OID),
        SigningAlg::Es384 => ec_named_curve_is(&SECP384R1_OID),
        SigningAlg::Es512 => ec_named_curve_is(&SECP521R1_OID),
        SigningAlg::Ps256 | SigningAlg::Ps384 | SigningAlg::Ps512 => {
            *key_alg == RSA_OID || *key_alg == RSASSA_PSS_OID
        }
        SigningAlg::Ed25519 => *key_alg == ED25519_OID,
        _ => false,
    }
}

impl Verifier<'_> {
    /// Verify a COSE signature according to the configured policies.
    #[async_generic]
    pub fn verify_signature(
        &self,
        cose_sign1: &[u8],
        data: &[u8],
        additional_data: &[u8],
        tst_info: Option<&TstInfo>,
        validation_log: &mut StatusTracker,
    ) -> Result<CertificateInfo, CoseError> {
        let mut sign1 = parse_cose_sign1(cose_sign1, data, validation_log)?;

        let Ok(alg) = signing_alg_from_sign1(&sign1) else {
            log_item!(
                "Cose_Sign1",
                "unsupported or missing Cose algorithm",
                "verify_cose"
            )
            .validation_status(ALGORITHM_UNSUPPORTED)
            .failure_no_throw(validation_log, CoseError::UnsupportedSigningAlgorithm);

            return Err(CoseError::UnsupportedSigningAlgorithm);
        };

        if let (SigningAlg::Es256 | SigningAlg::Es384 | SigningAlg::Es512, true) =
            (alg, parse_ec_der_sig(&sign1.signature).is_some())
        {
            // Should have been in P1363 format, not DER.
            log_item!(
                "Cose_Sign1",
                "unsupported signature format (EC signature should be in P1363 r|s format)",
                "verify_cose"
            )
            .validation_status(SIGNING_CREDENTIAL_INVALID)
            .failure_no_throw(validation_log, CoseError::InvalidEcdsaSignature);

            return Err(CoseError::InvalidEcdsaSignature);
        }

        // check the trust for this item
        let trust_log_start = validation_log.logged_items().len();
        let result = if _sync {
            self.verify_trust(&sign1, tst_info, validation_log)
        } else {
            self.verify_trust_async(&sign1, tst_info, validation_log)
                .await
        }; // Ignore errors here - they have already been logged.

        // see if this trusted anchor set had custom EKU overrides
        let override_ekus = match result {
            // only case where we have named trust sets
            Ok((trust_type, Some(trust_uri))) => match self {
                Self::VerifyTrustPolicy(ref ctp) => {
                    if let Some(anchor) = ctp.get_anchor_set(trust_type, &trust_uri) {
                        anchor.trust_config.clone()
                    } else {
                        None
                    }
                }
                _ => None,
            },
            _ => None,
        };

        // check the profile of the cert
        let profile_log_start = validation_log.logged_items().len();
        let profile_failed = if _sync {
            self.verify_profile(&sign1, tst_info, override_ekus, validation_log)
        } else {
            self.verify_profile_async(&sign1, tst_info, override_ekus, validation_log)
                .await
        }
        .is_err(); // Errors have already been logged.

        // A certificate that fails the profile check is not a trusted signing
        // credential, even when it chains to a trust anchor.
        if profile_failed
            || validation_log.logged_items()[profile_log_start..]
                .iter()
                .any(|item| item.validation_status.as_deref() == Some(SIGNING_CREDENTIAL_INVALID))
        {
            validation_log.remove_status_since(trust_log_start, SIGNING_CREDENTIAL_TRUSTED);
        }

        // Reconstruct payload and additional data as it should have been at time of
        // signing.
        sign1.payload = Some(data.to_vec());
        let tbs = sign1.tbs_data(additional_data);

        let certs = cert_chain_from_sign1(&sign1)?;
        let end_entity_cert_der = &certs[0];

        let (_rem, sign_cert) = X509Certificate::from_der(end_entity_cert_der)
            .map_err(|_| CoseError::CborParsingError("invalid X509 certificate".to_string()))?;
        let pk = sign_cert.public_key();
        let pk_der = pk.raw;

        // Reject a certificate whose key algorithm does not match the declared
        // COSE signing algorithm (e.g. an Ed448 key under the Ed25519 selection).
        if !spki_matches_signing_alg(alg, &pk.algorithm) {
            log_item!(
                "Cose_Sign1",
                "certificate key algorithm does not match COSE signing algorithm",
                "verify_cose"
            )
            .validation_status(SIGNING_CREDENTIAL_INVALID)
            .failure_no_throw(
                validation_log,
                CoseError::RawSignatureValidationError(
                    RawSignatureValidationError::InvalidPublicKey,
                ),
            );

            return Err(RawSignatureValidationError::InvalidPublicKey.into());
        }

        // The built-in validators are pure-Rust and synchronous on every target
        // (including WASM), so the synchronous validator is used directly even on
        // the async path.
        let Some(validator) = validator_for_signing_alg(alg) else {
            return Err(CoseError::UnsupportedSigningAlgorithm);
        };

        validator.validate(&sign1.signature, &tbs, pk_der)?;

        let subject = sign_cert
            .subject()
            .iter_organization()
            .map(|attr| attr.as_str())
            .last()
            .and_then(|attr| attr.ok())
            .map(|a| a.to_string());

        let common_name = sign_cert
            .subject()
            .iter_common_name()
            .map(|attr| attr.as_str())
            .last()
            .and_then(|attr| attr.ok())
            .map(|a| a.to_string());

        Ok(CertificateInfo {
            alg: Some(alg),
            date: tst_info.map(|t| t.gen_time.clone().into()),
            cert_serial_number: Some(sign_cert.serial.clone()),
            issuer_org: subject,
            common_name,
            validated: true,
            cert_chain: dump_cert_chain(&certs)?,
            revocation_status: Some(true),
            ..Default::default()
        })
    }

    /// Verify certificate profile if so configured.
    #[async_generic]
    pub(crate) fn verify_profile(
        &self,
        sign1: &CoseSign1,
        tst_info: Option<&TstInfo>,
        additional_ekus: Option<String>,
        validation_log: &mut StatusTracker,
    ) -> Result<(), CoseError> {
        let ctp = match self {
            Self::VerifyTrustPolicy(ref ctp) => ctp,
            Self::VerifyCertificateProfileOnly(ref ctp) => ctp,
            Self::IgnoreProfileAndTrustPolicy => {
                return Ok(());
            }
        };

        let certs = cert_chain_from_sign1(sign1)?;
        let end_entity_cert_der = &certs[0];

        if let Some(ekus) = additional_ekus {
            let mut adjusted_ctp = ctp.clone();
            adjusted_ctp.to_mut().add_valid_ekus(ekus.as_bytes());

            Ok(check_end_entity_certificate_profile(
                end_entity_cert_der,
                adjusted_ctp.as_ref(),
                validation_log,
                tst_info,
            )?)
        } else {
            Ok(check_end_entity_certificate_profile(
                end_entity_cert_der,
                ctp.as_ref(),
                validation_log,
                tst_info,
            )?)
        }
    }

    /// Verify certificate trust if so configured.
    #[async_generic]
    pub(crate) fn verify_trust(
        &self,
        sign1: &CoseSign1,
        tst_info_res: Option<&TstInfo>,
        validation_log: &mut StatusTracker,
    ) -> Result<(TrustAnchorType, Option<String>), CoseError> {
        // should be used in conjunction with verify_profile in most cases

        let ctp = match self {
            Self::VerifyTrustPolicy(ref ctp) => ctp,

            Self::VerifyCertificateProfileOnly(ref _ctp) => {
                return Ok((TrustAnchorType::NoCheck, None));
            }

            Self::IgnoreProfileAndTrustPolicy => {
                return Ok((TrustAnchorType::NoCheck, None));
            }
        };

        let certs = cert_chain_from_sign1(sign1)?;
        let end_entity_cert_der = &certs[0];
        let chain_der = &certs[1..];

        let signing_time_epoch = tst_info_res.map(|tst_info| {
            let dt: chrono::DateTime<chrono::Utc> = tst_info.gen_time.clone().into();
            dt.timestamp()
        });

        let verify_result = if _sync {
            ctp.check_certificate_trust(chain_der, end_entity_cert_der, signing_time_epoch)
        } else {
            ctp.check_certificate_trust_async(chain_der, end_entity_cert_der, signing_time_epoch)
                .await
        };

        match verify_result {
            Ok((tat, trust_uri)) => {
                log_item!(
                    "",
                    format!(
                        "signing certificate trusted, found in [{}] trust anchors",
                        &trust_uri
                    ),
                    "verify_cose"
                )
                .validation_status(SIGNING_CREDENTIAL_TRUSTED)
                .set_trust_list_uri(&trust_uri)
                .success(validation_log);

                Ok((tat, Some(trust_uri)))
            }
            Err(e) => {
                // C2PA requires every CA certificate in the chain to be valid at
                // the validation time, and reports a failure as
                // claimSignature.outsideValidity.
                if e == CertificateTrustError::CaCertificateOutsideValidity {
                    log_item!(
                        "",
                        "certificate chain outside validity period",
                        "verify_cose"
                    )
                    .validation_status(CLAIM_SIGNATURE_OUTSIDE_VALIDITY)
                    .failure_no_throw(
                        validation_log,
                        CertificateTrustError::CaCertificateOutsideValidity,
                    );
                }

                Err(
                    log_item!("", "signing certificate untrusted", "verify_cose")
                        .validation_status(SIGNING_CREDENTIAL_UNTRUSTED)
                        .failure_as_err(validation_log, e.into()),
                )
            }
        }
    }
}

impl Default for Verifier<'_> {
    fn default() -> Self {
        Self::VerifyTrustPolicy(Cow::Owned(CertificateTrustPolicy::default()))
    }
}

fn dump_cert_chain(certs: &[Vec<u8>]) -> Result<Vec<u8>, CoseError> {
    let mut writer = Vec::new();

    let line_len = 64;
    let cert_begin = "-----BEGIN CERTIFICATE-----";
    let cert_end = "-----END CERTIFICATE-----";

    for der_bytes in certs {
        let cert_base_str = encode(der_bytes);

        // Break line into fixed-length lines.
        let cert_lines = cert_base_str
            .chars()
            .collect::<Vec<char>>()
            .chunks(line_len)
            .map(|chunk| chunk.iter().collect::<String>())
            .collect::<Vec<_>>();

        writer
            .write_fmt(format_args!("{cert_begin}\n"))
            .map_err(|_e| CoseError::InternalError("could not write PEM".to_string()))?;

        for l in cert_lines {
            writer
                .write_fmt(format_args!("{l}\n"))
                .map_err(|_e| CoseError::InternalError("could not write PEM".to_string()))?;
        }

        writer
            .write_fmt(format_args!("{cert_end}\n"))
            .map_err(|_e| CoseError::InternalError("could not write PEM".to_string()))?;
    }

    Ok(writer)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use c2pa_raw_crypto::SigningAlg;
    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
    use wasm_bindgen_test::wasm_bindgen_test;
    use x509_parser::prelude::{FromDer, Pem, X509Certificate};

    use super::spki_matches_signing_alg;

    const ES256: &[u8] = include_bytes!("../../../tests/fixtures/crypto/raw_signature/es256.pub");
    const ES384: &[u8] = include_bytes!("../../../tests/fixtures/crypto/raw_signature/es384.pub");
    const ES512: &[u8] = include_bytes!("../../../tests/fixtures/crypto/raw_signature/es512.pub");
    const PS256: &[u8] = include_bytes!("../../../tests/fixtures/crypto/raw_signature/ps256.pub");
    const PS384: &[u8] = include_bytes!("../../../tests/fixtures/crypto/raw_signature/ps384.pub");
    const ED25519: &[u8] = include_bytes!("../../../tests/fixtures/certs/ed25519.pub");
    const ED448: &[u8] = include_bytes!("../../../tests/fixtures/crypto/raw_signature/ed448.pub");

    fn key_matches(cert_pem: &[u8], alg: SigningAlg) -> bool {
        let pem = Pem::iter_from_buffer(cert_pem).next().unwrap().unwrap();
        let (_, cert) = X509Certificate::from_der(&pem.contents).unwrap();
        spki_matches_signing_alg(alg, &cert.public_key().algorithm)
    }

    #[test]
    fn matching_keys_accepted() {
        assert!(key_matches(ED25519, SigningAlg::Ed25519));
        assert!(key_matches(ES256, SigningAlg::Es256));
        assert!(key_matches(ES384, SigningAlg::Es384));
        assert!(key_matches(ES512, SigningAlg::Es512));
        assert!(key_matches(PS256, SigningAlg::Ps256));
        assert!(key_matches(PS384, SigningAlg::Ps384));
    }

    #[test]
    fn wrong_key_type_rejected() {
        // The reported bypass: an Ed448 key must not match Ed25519.
        assert!(!key_matches(ED448, SigningAlg::Ed25519));
        // EC vs RSA vs Ed in either direction.
        assert!(!key_matches(ES256, SigningAlg::Ed25519));
        assert!(!key_matches(ED25519, SigningAlg::Es256));
        assert!(!key_matches(PS256, SigningAlg::Es256));
        assert!(!key_matches(ES256, SigningAlg::Ps256));
        assert!(!key_matches(PS256, SigningAlg::Ed25519));
    }

    #[test]
    fn wrong_ec_curve_rejected() {
        // Right key type (EC) but the wrong curve for the declared alg.
        assert!(!key_matches(ES256, SigningAlg::Es384));
        assert!(!key_matches(ES256, SigningAlg::Es512));
        assert!(!key_matches(ES384, SigningAlg::Es256));
        assert!(!key_matches(ES512, SigningAlg::Es256));
    }

    /// CA validity failures reject trust and report the C2PA 2.5 section 14.8.2 code.
    #[c2pa_macros::c2pa_test_async]
    async fn ca_outside_validity_reports_both_failure_codes() {
        use std::borrow::Cow;

        use coset::cbor::value::Value;

        use super::*;
        use crate::crypto::{
            asn1::{rfc3161::MessageImprint, AlgorithmIdentifier, GeneralizedTime},
            cert_chain_pem_to_der,
        };

        let tst_info = TstInfo {
            version: 1.into(),
            policy: "1.2.3".parse().unwrap(),
            message_imprint: MessageImprint {
                hash_algorithm: AlgorithmIdentifier {
                    algorithm: "2.16.840.1.101.3.4.2.1".parse().unwrap(),
                },
                hashed_message: bcder::OctetString::new(bytes::Bytes::from_static(&[0; 32])),
            },
            serial_number: 1.into(),
            gen_time: GeneralizedTime::from_der_bytes(b"\x18\x0f20260901000000Z").unwrap(),
            accuracy: None,
            ordering: None,
            nonce: None,
            tsa: None,
            extensions: None,
        };

        for (chain_pem, root_pem, outside_validity) in [
            (
                include_bytes!(
                    "../../../tests/fixtures/crypto/cose/chain_trust_expired_intermediate.pub"
                )
                .as_slice(),
                include_bytes!("../../../tests/fixtures/crypto/cose/chain_trust_root.pub")
                    .as_slice(),
                true,
            ),
            (
                include_bytes!(
                    "../../../tests/fixtures/crypto/cose/chain_trust_future_intermediate.pub"
                )
                .as_slice(),
                include_bytes!("../../../tests/fixtures/crypto/cose/chain_trust_future_root.pub")
                    .as_slice(),
                true,
            ),
            (
                include_bytes!("../../../tests/fixtures/crypto/cose/chain_trust_valid.pub")
                    .as_slice(),
                include_bytes!("../../../tests/fixtures/crypto/cose/chain_trust_root.pub")
                    .as_slice(),
                false,
            ),
        ] {
            let certs = cert_chain_pem_to_der(chain_pem).unwrap();
            let mut sign1 = CoseSign1::default();
            sign1.protected.header.rest.push((
                coset::Label::Int(coset::iana::HeaderParameter::X5Chain as i64),
                Value::Array(certs.into_iter().map(Value::Bytes).collect()),
            ));
            let mut policy = CertificateTrustPolicy::new();
            policy
                .add_trust_anchors(
                    root_pem,
                    "http://some_trust_list",
                    TrustAnchorType::Manifest,
                    None,
                )
                .unwrap();
            let verifier = Verifier::VerifyTrustPolicy(Cow::Borrowed(&policy));

            for is_async in [false, true] {
                let mut log = StatusTracker::default();
                let result = if is_async {
                    verifier
                        .verify_trust_async(&sign1, Some(&tst_info), &mut log)
                        .await
                } else {
                    verifier.verify_trust(&sign1, Some(&tst_info), &mut log)
                };
                if outside_validity {
                    assert!(matches!(
                        result,
                        Err(CoseError::CertificateTrustError(
                            CertificateTrustError::CaCertificateOutsideValidity
                        ))
                    ));
                    assert!(log.has_status(CLAIM_SIGNATURE_OUTSIDE_VALIDITY));
                    assert!(log.has_status(SIGNING_CREDENTIAL_UNTRUSTED));
                    assert!(!log.has_status(SIGNING_CREDENTIAL_TRUSTED));
                    assert_eq!(log.logged_items().len(), 2);
                } else {
                    assert_eq!(
                        result.unwrap(),
                        (
                            TrustAnchorType::Manifest,
                            Some("http://some_trust_list".into())
                        )
                    );
                    assert!(log.has_status(SIGNING_CREDENTIAL_TRUSTED));
                    assert!(!log.has_any_error());
                    assert!(!log.has_status(CLAIM_SIGNATURE_OUTSIDE_VALIDITY));
                    assert!(!log.has_status(SIGNING_CREDENTIAL_UNTRUSTED));
                }
            }
        }
    }

    /// A certificate that fails the certificate profile check is not a trusted
    /// signing credential, even when it chains to a trust anchor.
    #[c2pa_macros::c2pa_test_async]
    async fn profile_failure_is_not_trusted() {
        use std::borrow::Cow;

        use c2pa_raw_crypto::signer_from_private_key;

        use super::Verifier;
        use crate::{
            crypto::{
                cert_chain_pem_to_der,
                cose::{CertificateTrustPolicy, TrustAnchorType},
            },
            settings::Settings,
            signer::RawSignerWrapper,
            status_tracker::StatusTracker,
            validation_results::validation_codes::{
                SIGNING_CREDENTIAL_INVALID, SIGNING_CREDENTIAL_TRUSTED,
            },
        };

        // The leaf chains to the root, but its only EKU is id-kp-documentSigning,
        // which this trust policy does not allow, so it fails the certificate profile.
        let cert_chain = include_bytes!("../../../tests/fixtures/crypto/cose/disallowed_eku.pub");
        let private_key = include_bytes!("../../../tests/fixtures/crypto/cose/disallowed_eku.priv");
        let root = include_bytes!("../../../tests/fixtures/crypto/cose/key_usage_root.pub");

        let signer = RawSignerWrapper::new(
            signer_from_private_key(private_key, SigningAlg::Es256).unwrap(),
            cert_chain_pem_to_der(cert_chain).unwrap(),
            None,
        );

        let mut claim = crate::claim::Claim::new("profile_test", Some("contentauth"), 1);
        claim.build().unwrap();
        let claim_bytes = claim.data().unwrap();

        let mut settings = Settings::default();
        settings.verify.verify_trust = false;
        let cose_bytes =
            crate::cose_sign::sign_claim(&claim_bytes, &signer, 10000, &settings).unwrap();

        let sign1 =
            super::parse_cose_sign1(&cose_bytes, &claim_bytes, &mut StatusTracker::default())
                .unwrap();
        for (allow_eku, require_missing_eku) in [(false, false), (true, true), (true, false)] {
            let mut ctp = CertificateTrustPolicy::new();
            ctp.add_trust_anchors(
                root,
                "http://some_trust_list",
                TrustAnchorType::Manifest,
                None,
            )
            .unwrap();
            if allow_eku {
                ctp.add_valid_ekus(b"1.3.6.1.5.5.7.3.36");
            }
            if require_missing_eku {
                ctp.add_mandatory_ekus(b"1.3.6.1.5.5.7.3.8");
            }
            let verifier = Verifier::VerifyTrustPolicy(Cow::Owned(ctp));
            let invalid = !allow_eku || require_missing_eku;
            for use_async in [false, true] {
                let mut profile_log = StatusTracker::default();
                let profile = if use_async {
                    verifier
                        .verify_profile_async(&sign1, None, None, &mut profile_log)
                        .await
                } else {
                    verifier.verify_profile(&sign1, None, None, &mut profile_log)
                };
                assert_eq!(profile.is_err(), !allow_eku);
                assert_eq!(profile_log.has_status(SIGNING_CREDENTIAL_INVALID), invalid);

                let mut log = StatusTracker::default();
                crate::log_item!(
                    "previous claim",
                    "trusted",
                    "profile_failure_is_not_trusted"
                )
                .validation_status(SIGNING_CREDENTIAL_TRUSTED)
                .success(&mut log);
                crate::log_item!(
                    "previous claim",
                    "invalid",
                    "profile_failure_is_not_trusted"
                )
                .validation_status(SIGNING_CREDENTIAL_INVALID)
                .failure_no_throw(&mut log, super::CoseError::UnsupportedSigningAlgorithm);
                let verification_log_start = log.logged_items().len();
                let result = if use_async {
                    verifier
                        .verify_signature_async(&cose_bytes, &claim_bytes, b"", None, &mut log)
                        .await
                } else {
                    verifier.verify_signature(&cose_bytes, &claim_bytes, b"", None, &mut log)
                };
                assert!(result.unwrap().validated);
                assert_eq!(
                    log.logged_items()[verification_log_start..]
                        .iter()
                        .any(|item| item.validation_status.as_deref()
                            == Some(SIGNING_CREDENTIAL_INVALID)),
                    invalid
                );
                assert_eq!(
                    log.logged_items()
                        .iter()
                        .filter(|item| item.validation_status.as_deref()
                            == Some(SIGNING_CREDENTIAL_TRUSTED))
                        .count(),
                    if invalid { 1 } else { 2 }
                );
                assert_eq!(log.logged_items()[0].label, "previous claim");
            }
        }
    }

    /// A certificate that chains to a trust anchor but fails a rule only the certificate
    /// profile enforces is not a trusted signing credential.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn profile_failure_without_key_usage_is_not_trusted() {
        use std::borrow::Cow;

        use c2pa_raw_crypto::signer_from_private_key;

        use super::Verifier;
        use crate::{
            crypto::cose::{
                cose_signer::RawSignerCoseSigner, sign, CertificateTrustPolicy, TimeStampStorage,
                TrustAnchorType,
            },
            status_tracker::StatusTracker,
            utils::ephemeral_cert::generate_ephemeral_chain_with_ee_skip,
            validation_results::validation_codes::{
                SIGNING_CREDENTIAL_INVALID, SIGNING_CREDENTIAL_TRUSTED,
            },
        };

        // The leaf chains to the CA, which is a trust anchor, so the trust check passes
        // and logs signingCredential.trusted. Without a key usage extension it then fails
        // the certificate profile, which only that check enforces. (The rust_native
        // backend trusts this chain; OpenSSL already rejects it at the trust check.)
        let chain =
            generate_ephemeral_chain_with_ee_skip("profile-test.example.com", &["key_usage"])
                .unwrap();
        let raw_signer =
            signer_from_private_key(chain.ee_private_key_pem.as_bytes(), SigningAlg::Ed25519)
                .unwrap();
        let cert_chain = vec![chain.ee_der.clone(), chain.ca_der.clone()];
        // Sign below the layer that checks the certificate profile, which would refuse it.
        let signer = RawSignerCoseSigner::new(raw_signer.as_ref(), &cert_chain);
        let claim_bytes = b"claim";
        let cose_bytes =
            sign(&signer, claim_bytes, None, TimeStampStorage::V2_sigTst2_CTT).unwrap();

        let mut ctp = CertificateTrustPolicy::default();
        ctp.add_trust_anchors(
            format!(
                "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n",
                crate::crypto::base64::encode(&chain.ca_der)
            )
            .as_bytes(),
            "http://some_trust_list",
            TrustAnchorType::Manifest,
            None,
        )
        .unwrap();

        let mut log = StatusTracker::default();
        let _ = Verifier::VerifyTrustPolicy(Cow::Owned(ctp)).verify_signature(
            &cose_bytes,
            claim_bytes,
            b"",
            None,
            &mut log,
        );

        assert!(log.has_status(SIGNING_CREDENTIAL_INVALID));
        assert!(!log.has_status(SIGNING_CREDENTIAL_TRUSTED));
    }
}