c2pa 0.91.7

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
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
// Copyright 2024 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::sync::Arc;

use c2pa_raw_crypto::{signer_from_private_key, RawSigner, RawSignerError, SigningAlg};
use http::Request;
use serde::{Deserialize, Serialize};

use crate::{
    create_signer,
    crypto::cert_chain_pem_to_der,
    dynamic_assertion::DynamicAssertion,
    http::{SyncGenericResolver, SyncHttpResolver},
    identity::{
        builder::{CredentialHolder, IdentityAssertionBuilder, IdentityBuilderError},
        x509::X509CredentialHolder,
        SignerPayload,
    },
    settings::{Settings, SettingsValidate},
    signer::OwnedSignerWrapper,
    BoxedSigner, Error, Result, Signer,
};

/// Settings for configuring a local or remote [`Signer`].
///
/// A [`Signer`] can be obtained by calling the [`signer()`] function.
///
/// [`Signer`]: crate::Signer
/// [`signer()`]: crate::settings::Settings::signer
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SignerSettings {
    /// A signer configured locally.
    Local {
        /// Algorithm to use for signing.
        #[cfg_attr(feature = "json_schema", schemars(with = "crate::SigningAlgSchema"))]
        alg: SigningAlg,
        /// Certificate used for signing (PEM format).
        sign_cert: String,
        /// Private key used for signing (PEM format).
        private_key: String,
        /// Time stamp authority URL for signing.
        tsa_url: Option<String>,
        /// Referenced assertions for CAWG identity signing (optional).
        referenced_assertions: Option<Vec<String>>,
        /// Roles for CAWG identity signing (optional).
        roles: Option<Vec<String>>,
    },
    /// A signer configured remotely.
    Remote {
        /// URL that the signer will use for signing.
        /// A POST request with a byte-stream will be sent to this URL.
        url: String,
        /// Algorithm to use for signing.
        #[cfg_attr(feature = "json_schema", schemars(with = "crate::SigningAlgSchema"))]
        alg: SigningAlg,
        /// Certificate used for signing (PEM format).
        sign_cert: String,
        /// Time stamp authority URL for signing.
        tsa_url: Option<String>,
        /// Referenced assertions for CAWG identity signing (optional).
        referenced_assertions: Option<Vec<String>>,
        /// Roles for CAWG identity signing (optional).
        roles: Option<Vec<String>>,
    },
}

impl SignerSettings {
    // TODO: add async signer
    /// Returns the constructed signer from the thread-local `signer` settings field.
    ///
    /// If the signer settings aren't specified, this function will return [Error::MissingSignerSettings].
    ///
    /// Configure the signer via a [`Context`](crate::Context) passed explicitly to
    /// [`Builder::from_context`](crate::Builder::from_context) instead.
    #[deprecated(
        note = "Configure the signer via `Context` and pass it to `Builder::from_context` instead of using thread-local signer settings. Will be removed in 0.92.0 (scheduled for mid-November 2026)."
    )]
    pub fn signer() -> Result<BoxedSigner> {
        let signer_info = match Settings::get_thread_local_value::<Option<SignerSettings>>("signer")
        {
            Ok(Some(signer_info)) => signer_info,
            #[cfg(test)]
            _ => {
                return Ok(crate::utils::test_signer::test_signer(SigningAlg::Ps256));
            }
            #[cfg(not(test))]
            _ => {
                return Err(Error::MissingSignerSettings);
            }
        };

        let c2pa_signer = Self::c2pa_signer(signer_info)?;

        // TO DISCUSS: What if get_value returns an Err(...)?
        if let Ok(Some(cawg_x509_settings)) =
            Settings::get_thread_local_value::<Option<SignerSettings>>("cawg_x509_signer")
        {
            cawg_x509_settings.cawg_signer(c2pa_signer)
        } else {
            Ok(c2pa_signer)
        }
    }

    /// Returns a c2pa signer using the provided signer settings.
    pub fn c2pa_signer(self) -> Result<BoxedSigner> {
        match self {
            SignerSettings::Local {
                alg,
                sign_cert,
                private_key,
                tsa_url,
                referenced_assertions: _,
                roles: _,
            } => {
                create_signer::from_keys(sign_cert.as_bytes(), private_key.as_bytes(), alg, tsa_url)
            }
            SignerSettings::Remote {
                url,
                alg,
                sign_cert,
                tsa_url,
                referenced_assertions: _,
                roles: _,
            } => {
                let certs = cert_chain_pem_to_der(sign_cert.as_bytes())?;
                let reserve_size = 10000 + certs.iter().map(|c| c.len()).sum::<usize>();
                Ok(Box::new(RemoteSigner {
                    url,
                    alg,
                    reserve_size,
                    certs,
                    tsa_url,
                }))
            }
        }
    }

    /// Returns a CAWG X.509 identity signer that wraps the provided c2pa signer.
    pub fn cawg_signer(self, c2pa_signer: BoxedSigner) -> Result<BoxedSigner> {
        match self {
            SignerSettings::Local {
                alg: cawg_alg,
                sign_cert: cawg_sign_cert,
                private_key: cawg_private_key,
                tsa_url: cawg_tsa_url,
                referenced_assertions: cawg_referenced_assertions,
                roles: cawg_roles,
            } => {
                let signer = CawgX509IdentitySigner::from_settings(
                    c2pa_signer,
                    cawg_alg,
                    cawg_sign_cert.as_bytes(),
                    cawg_private_key.as_bytes(),
                    cawg_tsa_url,
                    cawg_referenced_assertions.unwrap_or_default(),
                    cawg_roles.unwrap_or_default(),
                )?;
                Ok(Box::new(signer))
            }

            SignerSettings::Remote {
                url,
                alg: cawg_alg,
                sign_cert: cawg_sign_cert,
                tsa_url: cawg_tsa_url,
                referenced_assertions: cawg_referenced_assertions,
                roles: cawg_roles,
            } => {
                // The identity (CAWG) signature is not RFC 3161 time stamped, so
                // the TSA URL is intentionally unused here (matches the Local case).
                let _ = cawg_tsa_url;

                let signer = CawgX509IdentitySigner::from_remote_settings(
                    c2pa_signer,
                    cawg_alg,
                    url,
                    cawg_sign_cert.as_bytes(),
                    cawg_referenced_assertions.unwrap_or_default(),
                    cawg_roles.unwrap_or_default(),
                )?;
                Ok(Box::new(signer))
            }
        }
    }
}

impl SettingsValidate for SignerSettings {
    fn validate(&self) -> Result<()> {
        Ok(())
    }
}

/// Wraps an `Arc<dyn RawSigner>` so it can be passed as an owned `Box<dyn RawSigner>`.
struct ArcRawSigner(Arc<dyn RawSigner + Send + Sync>);

impl RawSigner for ArcRawSigner {
    fn sign(&self, data: &[u8]) -> std::result::Result<Vec<u8>, RawSignerError> {
        self.0.sign(data)
    }

    fn alg(&self) -> SigningAlg {
        self.0.alg()
    }

    fn max_signature_size(&self) -> usize {
        self.0.max_signature_size()
    }
}

pub(crate) struct CawgX509IdentitySigner {
    c2pa_signer: BoxedSigner,
    identity_signer: Arc<dyn RawSigner + Send + Sync>,
    identity_cert_chain: Vec<Vec<u8>>,
    referenced_assertions: Vec<String>,
    roles: Vec<String>,
}

impl CawgX509IdentitySigner {
    /// Creates a combined signer from cert/key bytes for the identity signer.
    pub(crate) fn from_settings(
        c2pa_signer: BoxedSigner,
        alg: SigningAlg,
        sign_cert: &[u8],
        private_key: &[u8],
        tsa_url: Option<String>,
        referenced_assertions: Vec<String>,
        roles: Vec<String>,
    ) -> Result<Self> {
        // The identity (CAWG) signature is not RFC 3161 time stamped, so the TSA
        // URL is intentionally unused here.
        let _ = tsa_url;
        let raw_signer = signer_from_private_key(private_key, alg)?;
        Ok(Self {
            c2pa_signer,
            identity_signer: Arc::from(raw_signer),
            identity_cert_chain: cert_chain_pem_to_der(sign_cert)?,
            referenced_assertions,
            roles,
        })
    }

    /// Creates a combined signer that delegates identity signing to a remote
    /// HTTP endpoint.
    pub(crate) fn from_remote_settings(
        c2pa_signer: BoxedSigner,
        alg: SigningAlg,
        url: String,
        sign_cert: &[u8],
        referenced_assertions: Vec<String>,
        roles: Vec<String>,
    ) -> Result<Self> {
        let identity_cert_chain = cert_chain_pem_to_der(sign_cert)?;

        // `max_signature_size` must describe only the raw signature: the cert chain
        // is already accounted for separately by `X509CredentialHolder::reserve_size()`
        // (via `cose_reserve_size`). 10_000 bytes is a generous fixed upper bound since
        // the remote endpoint's exact signature size isn't known locally.
        let max_signature_size = 10_000;

        Ok(Self {
            c2pa_signer,
            identity_signer: Arc::new(RemoteRawSigner {
                url,
                alg,
                max_signature_size,
            }),
            identity_cert_chain,
            referenced_assertions,
            roles,
        })
    }

    /// Creates a combined signer from an already-constructed identity [`Signer`].
    pub(crate) fn from_signer(
        c2pa_signer: BoxedSigner,
        identity_signer: BoxedSigner,
        referenced_assertions: &[&str],
        roles: &[&str],
    ) -> Self {
        let identity_cert_chain = identity_signer.certs().unwrap_or_default();
        Self {
            c2pa_signer,
            identity_signer: Arc::new(OwnedSignerWrapper(identity_signer)),
            identity_cert_chain,
            referenced_assertions: referenced_assertions
                .iter()
                .map(|s| s.to_string())
                .collect(),
            roles: roles.iter().map(|s| s.to_string()).collect(),
        }
    }
}

impl Signer for CawgX509IdentitySigner {
    fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
        Signer::sign(&self.c2pa_signer, data)
    }

    fn alg(&self) -> SigningAlg {
        Signer::alg(&self.c2pa_signer)
    }

    fn certs(&self) -> Result<Vec<Vec<u8>>> {
        self.c2pa_signer.certs()
    }

    fn reserve_size(&self) -> usize {
        Signer::reserve_size(&self.c2pa_signer)
    }

    fn time_authority_url(&self) -> Option<String> {
        self.c2pa_signer.time_authority_url()
    }

    fn timestamp_request_headers(&self) -> Option<Vec<(String, String)>> {
        self.c2pa_signer.timestamp_request_headers()
    }

    fn timestamp_request_body(&self, message: &[u8]) -> Result<Vec<u8>> {
        self.c2pa_signer.timestamp_request_body(message)
    }

    fn send_timestamp_request(&self, message: &[u8]) -> Option<Result<Vec<u8>>> {
        self.c2pa_signer.send_timestamp_request(message)
    }

    fn ocsp_val(&self) -> Option<Vec<u8>> {
        self.c2pa_signer.ocsp_val()
    }

    fn direct_cose_handling(&self) -> bool {
        self.c2pa_signer.direct_cose_handling()
    }

    fn dynamic_assertions(&self) -> Vec<Box<dyn DynamicAssertion>> {
        let identity_signer: Box<dyn RawSigner + Sync + Send + 'static> =
            Box::new(ArcRawSigner(Arc::clone(&self.identity_signer)));
        let x509_credential_holder = X509CredentialHolder::from_raw_signer(
            identity_signer,
            self.identity_cert_chain.clone(),
        );

        let mut iab = IdentityAssertionBuilder::for_credential_holder(x509_credential_holder);

        if !self.referenced_assertions.is_empty() {
            let refs: Vec<&str> = self
                .referenced_assertions
                .iter()
                .map(|s| s.as_str())
                .collect();
            iab.add_referenced_assertions(&refs);
        }

        if !self.roles.is_empty() {
            let roles: Vec<&str> = self.roles.iter().map(|s| s.as_str()).collect();
            iab.add_roles(&roles);
        }

        vec![Box::new(iab)]
    }
}

/// Shares one [`CredentialHolder`] between the identity assertion builders
/// handed out on every [`Signer::dynamic_assertions`] call.
struct ArcCredentialHolder(Arc<dyn CredentialHolder + Send + Sync>);

impl CredentialHolder for ArcCredentialHolder {
    fn sig_type(&self) -> &'static str {
        self.0.sig_type()
    }

    fn reserve_size(&self) -> usize {
        self.0.reserve_size()
    }

    fn sign(
        &self,
        signer_payload: &SignerPayload,
    ) -> std::result::Result<Vec<u8>, IdentityBuilderError> {
        self.0.sign(signer_payload)
    }
}

/// A [`Signer`] that signs the C2PA claim with an inner signer and adds one
/// CAWG identity assertion produced by an arbitrary [`CredentialHolder`]
/// (for example an identity claims aggregation credential fetched from an
/// issuer at signing time).
///
/// Unlike [`CawgX509IdentitySigner`], this wrapper keeps whatever dynamic
/// assertions the inner signer already contributes, so wrapping an X.509
/// identity signer yields a manifest with both identity assertions.
pub(crate) struct CawgIdentitySigner {
    c2pa_signer: BoxedSigner,
    credential_holder: Arc<dyn CredentialHolder + Send + Sync>,
    referenced_assertions: Vec<String>,
    roles: Vec<String>,
}

impl CawgIdentitySigner {
    pub(crate) fn new(
        c2pa_signer: BoxedSigner,
        credential_holder: Box<dyn CredentialHolder + Send + Sync>,
        referenced_assertions: &[&str],
        roles: &[&str],
    ) -> Self {
        Self {
            c2pa_signer,
            credential_holder: Arc::from(credential_holder),
            referenced_assertions: referenced_assertions
                .iter()
                .map(|s| s.to_string())
                .collect(),
            roles: roles.iter().map(|s| s.to_string()).collect(),
        }
    }
}

impl Signer for CawgIdentitySigner {
    fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
        Signer::sign(&self.c2pa_signer, data)
    }

    fn alg(&self) -> SigningAlg {
        Signer::alg(&self.c2pa_signer)
    }

    fn certs(&self) -> Result<Vec<Vec<u8>>> {
        self.c2pa_signer.certs()
    }

    fn reserve_size(&self) -> usize {
        Signer::reserve_size(&self.c2pa_signer)
    }

    fn time_authority_url(&self) -> Option<String> {
        self.c2pa_signer.time_authority_url()
    }

    fn timestamp_request_headers(&self) -> Option<Vec<(String, String)>> {
        self.c2pa_signer.timestamp_request_headers()
    }

    fn timestamp_request_body(&self, message: &[u8]) -> Result<Vec<u8>> {
        self.c2pa_signer.timestamp_request_body(message)
    }

    fn send_timestamp_request(&self, message: &[u8]) -> Option<Result<Vec<u8>>> {
        self.c2pa_signer.send_timestamp_request(message)
    }

    fn ocsp_val(&self) -> Option<Vec<u8>> {
        self.c2pa_signer.ocsp_val()
    }

    fn direct_cose_handling(&self) -> bool {
        self.c2pa_signer.direct_cose_handling()
    }

    fn dynamic_assertions(&self) -> Vec<Box<dyn DynamicAssertion>> {
        let mut assertions = self.c2pa_signer.dynamic_assertions();

        let mut iab = IdentityAssertionBuilder::for_credential_holder(ArcCredentialHolder(
            Arc::clone(&self.credential_holder),
        ));

        if !self.referenced_assertions.is_empty() {
            let refs: Vec<&str> = self
                .referenced_assertions
                .iter()
                .map(|s| s.as_str())
                .collect();
            iab.add_referenced_assertions(&refs);
        }

        if !self.roles.is_empty() {
            let roles: Vec<&str> = self.roles.iter().map(|s| s.as_str()).collect();
            iab.add_roles(&roles);
        }

        assertions.push(Box::new(iab));
        assertions
    }
}

#[derive(Debug)]
pub(crate) struct RemoteSigner {
    url: String,
    alg: SigningAlg,
    certs: Vec<Vec<u8>>,
    reserve_size: usize,
    tsa_url: Option<String>,
}

impl Signer for RemoteSigner {
    fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
        use std::io::Read;

        let request = Request::post(&self.url).body(data.to_vec())?;
        let response = SyncGenericResolver::with_redirects()
            .unwrap_or_default()
            .http_resolve(request)
            .map_err(|_| Error::FailedToRemoteSign)?;
        let mut bytes: Vec<u8> = Vec::with_capacity(self.reserve_size);
        response
            .into_body()
            .take(self.reserve_size as u64)
            .read_to_end(&mut bytes)?;
        Ok(bytes)
    }

    fn alg(&self) -> SigningAlg {
        self.alg
    }

    fn certs(&self) -> Result<Vec<Vec<u8>>> {
        Ok(self.certs.clone())
    }

    fn reserve_size(&self) -> usize {
        self.reserve_size
    }

    fn time_authority_url(&self) -> Option<String> {
        self.tsa_url.clone()
    }
}

/// A [`RawSigner`] that delegates identity signing to a remote HTTP endpoint.
///
/// A POST request with the raw bytes-to-be-signed as the body is sent to
/// `url`; the response body (up to `max_signature_size` bytes) is used as
/// the raw signature. This mirrors [`RemoteSigner`], but implements the
/// lower-level [`RawSigner`] trait so it can back a [`CawgX509IdentitySigner`]
/// (whose certificate chain and reserve-size accounting are handled by the
/// SDK, not the raw signer).
#[derive(Debug)]
struct RemoteRawSigner {
    url: String,
    alg: SigningAlg,
    max_signature_size: usize,
}

impl RawSigner for RemoteRawSigner {
    fn sign(&self, data: &[u8]) -> std::result::Result<Vec<u8>, RawSignerError> {
        use std::io::Read;

        let request = Request::post(&self.url)
            .body(data.to_vec())
            .map_err(|e| RawSignerError::InternalError(e.to_string()))?;
        let response = SyncGenericResolver::with_redirects()
            .unwrap_or_default()
            .http_resolve(request)
            .map_err(|e| RawSignerError::InternalError(e.to_string()))?;

        let mut bytes: Vec<u8> = Vec::with_capacity(self.max_signature_size);
        response
            .into_body()
            .take(self.max_signature_size as u64)
            .read_to_end(&mut bytes)
            .map_err(|e| RawSignerError::InternalError(e.to_string()))?;
        Ok(bytes)
    }

    fn alg(&self) -> SigningAlg {
        self.alg
    }

    fn max_signature_size(&self) -> usize {
        self.max_signature_size
    }
}

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

    #[cfg(not(target_arch = "wasm32"))]
    use crate::BoxedSigner;
    use crate::{settings::Settings, utils::test_signer, Signer, SigningAlg};

    #[cfg(not(target_arch = "wasm32"))]
    fn remote_signer_mock_server<'a>(
        server: &'a httpmock::MockServer,
        signed_bytes: &[u8],
    ) -> httpmock::Mock<'a> {
        server.mock(|when, then| {
            when.method(httpmock::Method::POST);
            then.status(200).body(signed_bytes);
        })
    }

    /// Mocks a remote signing endpoint that signs whatever bytes it receives
    /// using a local reference `signer`, simulating a real remote signing
    /// service backed by a private key it never exposes.
    #[cfg(not(target_arch = "wasm32"))]
    fn remote_signer_respond_with_signature(
        server: &httpmock::MockServer,
        signer: BoxedSigner,
    ) -> httpmock::Mock<'_> {
        server.mock(|when, then| {
            when.method(httpmock::Method::POST);
            then.respond_with(move |req: &httpmock::HttpMockRequest| {
                let signed = signer.sign(req.body_ref()).unwrap_or_default();
                http::Response::builder()
                    .status(200)
                    .body(signed)
                    .unwrap()
                    .into()
            });
        })
    }

    /// Legacy test verifying the deprecated thread-local signer API still works.
    #[test]
    #[allow(deprecated)]
    fn test_thread_local_signer() {
        assert!(Settings::signer().is_ok());
    }

    #[test]
    fn test_make_local_signer() {
        let alg = SigningAlg::Ps384;
        let (sign_cert, private_key) = test_signer::cert_chain_and_private_key_for_alg(alg);

        let settings = Settings::new()
            .with_toml(
                &toml::toml! {
                    [signer.local]
                    alg = (alg.to_string())
                    sign_cert = (String::from_utf8(sign_cert.to_vec()).unwrap())
                    private_key = (String::from_utf8(private_key.to_vec()).unwrap())
                }
                .to_string(),
            )
            .unwrap();

        // Test the settings signer path directly (context.signer() uses a custom test
        // signer in test mode, so we test SignerSettings::c2pa_signer() directly here)
        let signer_settings = settings.signer.expect("signer settings should be present");
        let signer = signer_settings.c2pa_signer().unwrap();
        assert_eq!(signer.alg(), alg);
        assert_eq!(signer.time_authority_url(), None);
        assert!(signer.sign(&[1, 2, 3]).is_ok());
    }

    #[test]
    fn test_make_cawg_local_signer_from_settings() {
        let alg = SigningAlg::Ed25519;
        let (sign_cert, private_key) = test_signer::cert_chain_and_private_key_for_alg(alg);

        let settings = Settings::new()
            .with_toml(
                &toml::toml! {
                    [signer.local]
                    alg = (alg.to_string())
                    sign_cert = (String::from_utf8(sign_cert.to_vec()).unwrap())
                    private_key = (String::from_utf8(private_key.to_vec()).unwrap())

                    [cawg_x509_signer.local]
                    alg = (alg.to_string())
                    sign_cert = (String::from_utf8(sign_cert.to_vec()).unwrap())
                    private_key = (String::from_utf8(private_key.to_vec()).unwrap())
                    referenced_assertions = ["c2pa.actions"]
                    roles = ["creator"]
                }
                .to_string(),
            )
            .unwrap();

        let c2pa_settings = settings.signer.expect("signer settings should be present");
        let c2pa_signer = c2pa_settings.c2pa_signer().unwrap();

        let cawg_settings = settings
            .cawg_x509_signer
            .expect("cawg signer settings should be present");
        let combined = cawg_settings.cawg_signer(c2pa_signer).unwrap();

        // Verify the combined signer delegates alg/certs to the underlying c2pa signer.
        assert_eq!(combined.alg(), alg);
        assert!(!combined.certs().unwrap().is_empty());
        // The combined signer produces dynamic assertions (the identity assertion builder).
        assert_eq!(combined.dynamic_assertions().len(), 1);
    }

    #[test]
    fn test_cawg_identity_signer_from_signer_path() {
        use crate::{create_signer, settings::signer::CawgX509IdentitySigner, Signer};

        let alg = SigningAlg::Ps256;
        let (sign_cert, private_key) = test_signer::cert_chain_and_private_key_for_alg(alg);

        let c2pa_signer = create_signer::from_keys(sign_cert, private_key, alg, None).unwrap();
        let identity_signer = create_signer::from_keys(sign_cert, private_key, alg, None).unwrap();

        let combined = CawgX509IdentitySigner::from_signer(
            c2pa_signer,
            identity_signer,
            &["c2pa.actions"],
            &["creator"],
        );

        assert_eq!(combined.alg(), alg);
        assert!(!combined.certs().unwrap().is_empty());
        assert_eq!(combined.dynamic_assertions().len(), 1);
        // Sign delegates to c2pa_signer, so it should succeed with valid data.
        assert!(combined.sign(b"test data").is_ok());
    }

    #[test]
    fn test_cawg_signer_no_referenced_assertions_or_roles() {
        use crate::{create_signer, settings::signer::CawgX509IdentitySigner};

        let alg = SigningAlg::Ps256;
        let (sign_cert, private_key) = test_signer::cert_chain_and_private_key_for_alg(alg);

        let c2pa_signer = create_signer::from_keys(sign_cert, private_key, alg, None).unwrap();
        let identity_signer = create_signer::from_keys(sign_cert, private_key, alg, None).unwrap();

        let combined = CawgX509IdentitySigner::from_signer(c2pa_signer, identity_signer, &[], &[]);

        // dynamic_assertions still returns one builder even with empty refs/roles.
        assert_eq!(combined.dynamic_assertions().len(), 1);
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_make_remote_signer() {
        use httpmock::MockServer;

        use crate::create_signer;

        let alg = SigningAlg::Ps384;
        let (sign_cert, private_key) = test_signer::cert_chain_and_private_key_for_alg(alg);

        let signer = create_signer::from_keys(sign_cert, private_key, alg, None).unwrap();
        let signed_bytes = signer.sign(&[1, 2, 3]).unwrap();

        let server = MockServer::start();
        let mock = remote_signer_mock_server(&server, &signed_bytes);

        let settings = Settings::new()
            .with_toml(
                &toml::toml! {
                    [signer.remote]
                    url = (server.base_url())
                    alg = (alg.to_string())
                    sign_cert = (String::from_utf8(sign_cert.to_vec()).unwrap())
                }
                .to_string(),
            )
            .unwrap();

        // Test the settings signer path directly (context.signer() uses a custom test
        // signer in test mode, so we test SignerSettings::c2pa_signer() directly here)
        let signer_settings = settings.signer.expect("signer settings should be present");
        let signer = signer_settings.c2pa_signer().unwrap();
        assert_eq!(signer.alg(), alg);
        assert_eq!(signer.time_authority_url(), None);
        assert_eq!(signer.sign(&[1, 2, 3]).unwrap(), signed_bytes);

        mock.assert();

        // certs() must return DER-encoded certs (not raw PEM text), matching the
        // Local variant's behavior via create_signer::from_keys.
        let der_certs = signer.certs().unwrap();
        assert!(!der_certs.is_empty());
        let pem_text = String::from_utf8(sign_cert.to_vec()).unwrap();
        let expected_der = crate::crypto::cert_chain_pem_to_der(pem_text.as_bytes()).unwrap();
        assert_eq!(der_certs, expected_der);
        for der in &der_certs {
            assert_ne!(der.as_slice(), pem_text.as_bytes());
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_make_remote_signer_json_escaped_pem() {
        use httpmock::MockServer;

        use crate::create_signer;

        let alg = SigningAlg::Ps384;
        let (sign_cert, private_key) = test_signer::cert_chain_and_private_key_for_alg(alg);

        let signer = create_signer::from_keys(sign_cert, private_key, alg, None).unwrap();
        let signed_bytes = signer.sign(&[1, 2, 3]).unwrap();

        let server = MockServer::start();
        let mock = remote_signer_mock_server(&server, &signed_bytes);

        // Simulate a cert chain delivered with literal "\n" escapes, as happens
        // when a PEM cert is embedded in a JSON config value.
        let pem_text = String::from_utf8(sign_cert.to_vec()).unwrap();
        let escaped_pem = pem_text.replace('\n', "\\n");

        let settings = Settings::new()
            .with_toml(
                &toml::toml! {
                    [signer.remote]
                    url = (server.base_url())
                    alg = (alg.to_string())
                    sign_cert = (escaped_pem)
                }
                .to_string(),
            )
            .unwrap();

        let signer_settings = settings.signer.expect("signer settings should be present");
        let signer = signer_settings.c2pa_signer().unwrap();
        assert_eq!(signer.alg(), alg);
        assert_eq!(signer.sign(&[1, 2, 3]).unwrap(), signed_bytes);

        let der_certs = signer.certs().unwrap();
        assert!(!der_certs.is_empty());
        let expected_der = crate::crypto::cert_chain_pem_to_der(pem_text.as_bytes()).unwrap();
        assert_eq!(der_certs, expected_der);

        mock.assert();
    }

    #[test]
    fn test_make_remote_signer_malformed_pem_errors() {
        let alg = SigningAlg::Ps384;

        // Has BEGIN/END markers (so the parser attempts to decode a block) but
        // the body is not valid base64, so decoding must fail with an error
        // rather than silently producing an empty cert list.
        let malformed_pem =
            "-----BEGIN CERTIFICATE-----\nnot-valid-base64!!!\n-----END CERTIFICATE-----\n";

        let settings = Settings::new()
            .with_toml(
                &toml::toml! {
                    [signer.remote]
                    url = "https://example.com/sign"
                    alg = (alg.to_string())
                    sign_cert = (malformed_pem)
                }
                .to_string(),
            )
            .unwrap();

        let signer_settings = settings.signer.expect("signer settings should be present");
        assert!(signer_settings.c2pa_signer().is_err());
    }

    #[test]
    fn test_make_remote_signer_no_pem_blocks_yields_empty_certs() {
        // No BEGIN/END markers at all: the underlying parser treats this as
        // "no blocks found" and returns an empty cert list rather than an
        // error. This documents that behavior so a future change can't
        // silently alter it without a failing test.
        let alg = SigningAlg::Ps384;

        let settings = Settings::new()
            .with_toml(
                &toml::toml! {
                    [signer.remote]
                    url = "https://example.com/sign"
                    alg = (alg.to_string())
                    sign_cert = "not a pem cert chain at all"
                }
                .to_string(),
            )
            .unwrap();

        let signer_settings = settings.signer.expect("signer settings should be present");
        let signer = signer_settings.c2pa_signer().unwrap();
        assert_eq!(signer.certs().unwrap(), Vec::<Vec<u8>>::new());
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_make_cawg_remote_signer_from_settings() {
        use httpmock::MockServer;

        use crate::create_signer;

        let c2pa_alg = SigningAlg::Ps384;
        let (c2pa_sign_cert, c2pa_private_key) =
            test_signer::cert_chain_and_private_key_for_alg(c2pa_alg);
        let c2pa_signer =
            create_signer::from_keys(c2pa_sign_cert, c2pa_private_key, c2pa_alg, None).unwrap();

        let cawg_alg = SigningAlg::Ed25519;
        let (cawg_sign_cert, cawg_private_key) =
            test_signer::cert_chain_and_private_key_for_alg(cawg_alg);
        let reference_signer =
            create_signer::from_keys(cawg_sign_cert, cawg_private_key, cawg_alg, None).unwrap();
        let signed_bytes = reference_signer.sign(&[1, 2, 3]).unwrap();

        let server = MockServer::start();
        let mock = remote_signer_mock_server(&server, &signed_bytes);

        let settings = Settings::new()
            .with_toml(
                &toml::toml! {
                    [cawg_x509_signer.remote]
                    url = (server.base_url())
                    alg = (cawg_alg.to_string())
                    sign_cert = (String::from_utf8(cawg_sign_cert.to_vec()).unwrap())
                    referenced_assertions = ["c2pa.actions"]
                    roles = ["creator"]
                }
                .to_string(),
            )
            .unwrap();

        let cawg_settings = settings
            .cawg_x509_signer
            .expect("cawg signer settings should be present");
        let combined = cawg_settings.cawg_signer(c2pa_signer).unwrap();

        // The combined signer still delegates alg/certs/sign to the underlying
        // c2pa signer; the remote identity signer only backs dynamic_assertions().
        assert_eq!(combined.alg(), c2pa_alg);
        assert!(!combined.certs().unwrap().is_empty());
        assert_eq!(combined.dynamic_assertions().len(), 1);

        // dynamic_assertions() only builds the assertion; it doesn't invoke the
        // remote identity signer yet, so the mock is intentionally not asserted
        // here (see test_cawg_remote_signer_round_trip for the full path).
        let _ = mock;
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[c2pa_macros::c2pa_test_async]
    async fn test_cawg_remote_signer_round_trip() {
        use std::io::{Cursor, Seek};

        use httpmock::MockServer;

        use crate::{
            create_signer,
            crypto::cose::Verifier,
            identity::{
                tests::fixtures::{manifest_json, parent_json},
                x509::X509SignatureVerifier,
                IdentityAssertion,
            },
            status_tracker::StatusTracker,
            Builder, Reader,
        };

        const TEST_IMAGE: &[u8] = include_bytes!("../../tests/fixtures/CA.jpg");
        const TEST_THUMBNAIL: &[u8] = include_bytes!("../../tests/fixtures/thumbnail.jpg");

        let format = "image/jpeg";
        let mut source = Cursor::new(TEST_IMAGE);
        let mut dest = Cursor::new(Vec::new());

        let c2pa_alg = SigningAlg::Ps256;
        let (c2pa_sign_cert, c2pa_private_key) =
            test_signer::cert_chain_and_private_key_for_alg(c2pa_alg);
        let c2pa_signer =
            create_signer::from_keys(c2pa_sign_cert, c2pa_private_key, c2pa_alg, None).unwrap();

        let cawg_alg = SigningAlg::Ed25519;
        let (cawg_sign_cert, cawg_private_key) =
            test_signer::cert_chain_and_private_key_for_alg(cawg_alg);
        // The "remote" endpoint is backed by a local signer holding the same
        // private key, simulating a real remote signing service.
        let reference_identity_signer =
            create_signer::from_keys(cawg_sign_cert, cawg_private_key, cawg_alg, None).unwrap();

        let server = MockServer::start();
        let mock = remote_signer_respond_with_signature(&server, reference_identity_signer);

        // decode_identity_assertions is disabled so IdentityAssertion::from_manifest
        // below can parse the raw assertion content itself (matches the pattern used
        // by other CAWG X.509 round-trip tests in sdk/src/identity/x509).
        let settings = Settings::new()
            .with_toml(
                &toml::toml! {
                    [cawg_x509_signer.remote]
                    url = (server.base_url())
                    alg = (cawg_alg.to_string())
                    sign_cert = (String::from_utf8(cawg_sign_cert.to_vec()).unwrap())
                    referenced_assertions = ["c2pa.actions"]
                    roles = ["creator"]
                }
                .to_string(),
            )
            .unwrap()
            .with_value("core.decode_identity_assertions", false)
            .unwrap();

        let cawg_settings = settings
            .cawg_x509_signer
            .clone()
            .expect("cawg signer settings should be present");
        let combined_signer = cawg_settings.cawg_signer(c2pa_signer).unwrap();

        let context = crate::Context::new()
            .with_settings(settings)
            .unwrap()
            .into_shared();

        let mut builder = Builder::from_shared_context(&context)
            .with_definition(manifest_json())
            .unwrap();
        builder
            .add_ingredient_from_stream(parent_json(), format, &mut source)
            .unwrap();
        builder
            .add_resource("thumbnail.jpg", Cursor::new(TEST_THUMBNAIL))
            .unwrap();

        builder
            .sign(&combined_signer, format, &mut source, &mut dest)
            .unwrap();

        mock.assert();

        dest.rewind().unwrap();
        let manifest_store = Reader::from_shared_context(&context)
            .with_stream(format, &mut dest)
            .unwrap();
        assert_eq!(manifest_store.validation_status(), None);

        let manifest = manifest_store.active_manifest().unwrap();
        let mut st = StatusTracker::default();
        let mut ia_iter = IdentityAssertion::from_manifest(manifest, &mut st);

        let ia = ia_iter.next().unwrap().unwrap();
        assert!(ia_iter.next().is_none());
        drop(ia_iter);

        let x509_verifier = X509SignatureVerifier {
            cose_verifier: Verifier::IgnoreProfileAndTrustPolicy,
        };
        let sig_info = ia
            .validate(manifest, &mut st, &x509_verifier)
            .await
            .unwrap();

        assert_eq!(sig_info.cert_info.alg.unwrap(), cawg_alg);
    }
}