c2pa 0.80.1

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
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
// 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.

//! The Reader provides a way to read a manifest store from an asset.
//! It also performs validation on the manifest store.

#[cfg(feature = "file_io")]
use std::fs::{read, File};
use std::{
    collections::{HashMap, HashSet},
    io::{Read, Seek, Write},
    sync::Arc,
};

use async_generic::async_generic;
use async_trait::async_trait;
#[cfg(feature = "json_schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;

#[cfg(feature = "file_io")]
use crate::utils::io_utils::uri_to_path;
use crate::{
    assertion::AssertionBase,
    assertions::Metadata,
    claim::Claim,
    context::{Context, ProgressPhase},
    dynamic_assertion::PartialClaim,
    error::{Error, Result},
    jumbf::labels::{manifest_label_from_uri, to_absolute_uri, to_relative_uri},
    jumbf_io, log_item,
    manifest::StoreOptions,
    manifest_store_report::ManifestStoreReport,
    status_tracker::StatusTracker,
    store::Store,
    utils::hash_utils::hash_to_b64,
    validation_results::{ValidationResults, ValidationState},
    validation_status::{ValidationStatus, ASSERTION_MISSING, ASSERTION_NOT_REDACTED},
    Ingredient, Manifest, ManifestAssertion,
};

/// MaybeSend allows for no Send bound on wasm32 targets
/// todo: move this to a common module
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSend: Send {}
#[cfg(target_arch = "wasm32")]
pub trait MaybeSend {}

#[cfg(not(target_arch = "wasm32"))]
impl<T: Send> MaybeSend for T {}
#[cfg(target_arch = "wasm32")]
impl<T> MaybeSend for T {}

/// A trait for post-validation of manifest assertions.
pub trait PostValidator {
    fn validate(
        &self,
        label: &str,
        assertion: &ManifestAssertion,
        uri: &str,
        preliminary_claim: &PartialClaim,
        tracker: &mut StatusTracker,
    ) -> Result<Option<Value>>;
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait AsyncPostValidator {
    async fn validate(
        &self,
        label: &str,
        assertion: &ManifestAssertion,
        uri: &str,
        preliminary_claim: &PartialClaim,
        tracker: &mut StatusTracker,
    ) -> Result<Option<Value>>;
}

/// Use a Reader to read and validate a manifest store.
#[skip_serializing_none]
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "json_schema", derive(JsonSchema), schemars(default))]
#[derive(Default)]
pub struct Reader {
    /// A label for the active (most recent) manifest in the store
    active_manifest: Option<String>,

    /// A HashMap of Manifests
    manifests: HashMap<String, Manifest>,

    /// ValidationStatus generated when loading the ManifestStore from an asset
    validation_status: Option<Vec<ValidationStatus>>,

    /// ValidationStatus generated when loading the ManifestStore from an asset
    validation_results: Option<ValidationResults>,

    /// The validation state of the manifest store
    validation_state: Option<ValidationState>,

    #[serde(skip)]
    /// We keep this around so we can generate a detailed report if needed
    pub(crate) store: Store,

    #[serde(skip)]
    /// Map to hold post-validation assertion values for reports
    /// the key is an assertion uri and the value is the assertion value
    assertion_values: HashMap<String, Value>,

    #[serde(skip)]
    context: Arc<Context>,
}

impl Reader {
    /// Create a new Reader with the given [`Context`].
    ///
    /// This method takes ownership of the [`Context`] and wraps it in an [`Arc`] internally.
    /// Use this for single-use contexts where you don't need to share the context.
    ///
    /// Use [`Reader::default()`] when no special configuration is needed.
    /// Use [`Reader::from_shared_context`] to share a context across multiple readers.
    ///
    /// # Arguments
    /// * `context` - The [`Context`] to use for the Reader
    ///
    /// # Returns
    /// A new Reader
    ///
    /// # Examples
    ///
    /// ```
    /// # use c2pa::{Context, Reader, Result};
    /// # fn main() -> Result<()> {
    /// // With default settings (no explicit context needed):
    /// let reader = Reader::default();
    ///
    /// // With custom settings:
    /// let context = Context::new().with_settings(r#"{"verify": {"verify_after_sign": true}}"#)?;
    /// let reader = Reader::from_context(context);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_context(context: Context) -> Self {
        Self {
            context: Arc::new(context),
            store: Store::new(),
            assertion_values: HashMap::new(),
            ..Default::default()
        }
    }

    /// Create a new Reader with a shared [`Context`].
    ///
    /// This method allows sharing a single [`Context`] across multiple builders or readers,
    /// even across threads. The [`Arc`] is cloned internally, so you pass a reference.
    ///
    /// # Arguments
    /// * `context` - A reference to an [`Arc<Context>`] to share.
    ///
    /// # Returns
    /// A new [`Reader`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use c2pa::{Context, Reader, Result, Settings};
    /// # use std::sync::Arc;
    /// # fn main() -> Result<()> {
    /// // Create a shared Context once
    /// let ctx = Context::new().with_settings(Settings::new())?.into_shared();
    ///
    /// // Share it across multiple Readers (even across threads!)
    /// let reader1 = Reader::from_shared_context(&ctx);
    /// let reader2 = Reader::from_shared_context(&ctx);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_shared_context(context: &Arc<Context>) -> Self {
        Self {
            context: Arc::clone(context),
            store: Store::new(),
            assertion_values: HashMap::new(),
            ..Default::default()
        }
    }

    /// Add manifest store from a stream to the [`Reader`].
    /// # Arguments
    /// * `format` - The format of the stream.  MIME type or extension that maps to a MIME type.
    /// * `stream` - The stream to read from.  Must implement the Read and Seek traits.
    /// # Returns
    /// The updated [`Reader`] with the added manifest store.
    #[async_generic]
    pub fn with_stream(
        mut self,
        format: &str,
        mut stream: impl Read + Seek + MaybeSend,
    ) -> Result<Self> {
        let mut validation_log = StatusTracker::default();
        stream.rewind()?; // Ensure stream is at the start

        self.context.check_progress(ProgressPhase::Reading, 1, 1)?;

        let store = if _sync {
            Store::from_stream(format, stream, &mut validation_log, &self.context)
        } else {
            Store::from_stream_async(format, stream, &mut validation_log, &self.context).await
        }?;

        if _sync {
            self.with_store(store, &mut validation_log)
        } else {
            self.with_store_async(store, &mut validation_log).await
        }?;
        Ok(self)
    }

    /// Create a manifest store [`Reader`] from a stream.  A Reader is used to validate C2PA data from an asset.
    ///
    /// # Arguments
    /// * `format` - The format of the stream.  MIME type or extension that maps to a MIME type.
    /// * `stream` - The stream to read from.  Must implement the Read and Seek traits.
    ///   Send trait is required for sync operations and Sync trait is required for async operations.
    /// # Returns
    /// A [`Reader`] for the manifest store.
    /// # Note
    /// [CAWG identity assertions](https://cawg.io/identity/) require async calls for validation.
    #[deprecated(
        note = "Use `Reader::from_context(context).with_stream(format, stream)` instead, passing a `Context` explicitly rather than relying on thread-local settings."
    )]
    #[async_generic]
    pub fn from_stream(format: &str, stream: impl Read + Seek + MaybeSend) -> Result<Reader> {
        // Legacy behavior: explicitly get global settings for backward compatibility
        let settings = crate::settings::get_thread_local_settings();
        let context = Context::new().with_settings(settings)?;

        if _sync {
            Reader::from_context(context).with_stream(format, stream)
        } else {
            Reader::from_context(context)
                .with_stream_async(format, stream)
                .await
        }
    }

    #[cfg(feature = "file_io")]
    /// Add manifest store from a file to the [`Reader`].
    /// If the `fetch_remote_manifests` feature is enabled, and the asset refers to a remote manifest, the function fetches a remote manifest.
    ///
    /// NOTE: If the file does not have a manifest store, the function will check for a sidecar manifest with the same base file name and a .c2pa extension.
    ///
    /// # Arguments
    /// * `path` - The path to the file.
    ///
    /// # Returns
    /// The updated [`Reader`] with the added manifest store.
    ///
    /// # Errors
    /// Returns an [`Error`] when the manifest data cannot be read from the specified file.  If there's no error upon reading, you must still check validation status to ensure that the manifest data is validated.  That is, even if there are no errors, the data still might not be valid.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use c2pa::{Context, Reader};
    /// # fn main() -> c2pa::Result<()> {
    /// let reader = Reader::default().with_file("path/to/file.jpg")?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Note
    /// [CAWG identity assertions](https://cawg.io/identity/) require async calls for validation.
    #[async_generic]
    pub fn with_file<P: AsRef<std::path::Path>>(mut self, path: P) -> Result<Self> {
        let path = path.as_ref();
        let format = crate::format_from_path(path).ok_or(crate::Error::UnsupportedType)?;
        let mut file = File::open(path)?;

        // Try loading from stream first
        let mut validation_log = StatusTracker::default();
        let store = if _sync {
            Store::from_stream(&format, &mut file, &mut validation_log, &self.context)
        } else {
            Store::from_stream_async(&format, &mut file, &mut validation_log, &self.context).await
        };

        match store {
            Err(Error::JumbfNotFound) => {
                // if not embedded or cloud, check for sidecar first and load if it exists
                let potential_sidecar_path = path.with_extension("c2pa");
                if potential_sidecar_path.exists() {
                    let manifest_data = read(potential_sidecar_path)?;
                    validation_log = StatusTracker::default();
                    let store = if _sync {
                        Store::from_manifest_data_and_stream(
                            &manifest_data,
                            &format,
                            &mut file,
                            &mut validation_log,
                            &self.context,
                        )
                    } else {
                        Store::from_manifest_data_and_stream_async(
                            &manifest_data,
                            &format,
                            &mut file,
                            &mut validation_log,
                            &self.context,
                        )
                        .await
                    }?;
                    if _sync {
                        self.with_store(store, &mut validation_log)
                    } else {
                        self.with_store_async(store, &mut validation_log).await
                    }?;
                    Ok(self)
                } else {
                    Err(Error::JumbfNotFound)
                }
            }
            Ok(store) => {
                if _sync {
                    self.with_store(store, &mut validation_log)
                } else {
                    self.with_store_async(store, &mut validation_log).await
                }?;
                Ok(self)
            }
            Err(e) => Err(e),
        }
    }

    /// Create a manifest store [`Reader`] from a file.
    /// If the `fetch_remote_manifests` feature is enabled, and the asset refers to a remote manifest, the function fetches a remote manifest.
    ///
    /// NOTE: If the file does not have a manifest store, the function will check for a sidecar manifest with the same base file name and a .c2pa extension.
    ///
    /// # Arguments
    /// * `path` - The path to the file.
    ///
    /// # Returns
    /// A [`Reader`] for the manifest store.
    ///
    /// # Errors
    /// Returns an [`Error`] when the manifest data cannot be read from the specified file.  If there's no error upon reading, you must still check validation status to ensure that the manifest data is validated.  That is, even if there are no errors, the data still might not be valid.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use c2pa::Reader;
    /// let reader = Reader::from_file("path/to/file.jpg").unwrap();
    /// ```
    ///
    /// # Note
    /// [CAWG identity assertions](https://cawg.io/identity/) require async calls for validation.
    #[cfg(feature = "file_io")]
    #[deprecated(
        note = "Use `Reader::from_context(context).with_file(path)` instead, passing a `Context` explicitly rather than relying on thread-local settings."
    )]
    #[async_generic]
    pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Reader> {
        // Legacy behavior: explicitly get thread-local settings for backward compatibility
        let settings = crate::settings::get_thread_local_settings();
        let context = Context::new().with_settings(settings)?;

        if _sync {
            Reader::from_context(context).with_file(path)
        } else {
            Reader::from_context(context).with_file_async(path).await
        }
    }

    /// Create a manifest store [`Reader`] from a JSON string.
    /// # Arguments
    /// * `json` - A JSON string containing a manifest store definition.
    /// # Returns
    /// A [`Reader`] for the manifest store.
    /// # WARNING
    /// This function is intended for use in testing. Don't use it in an implementation.
    pub fn from_json(json: &str) -> Result<Reader> {
        serde_json::from_str(json).map_err(crate::Error::JsonError)
    }

    /// Add manifest store from existing `c2pa_data` and a stream to the [`Reader`].
    /// Use this to validate a remote manifest or a sidecar manifest.
    /// # Arguments
    /// * `c2pa_data` - A C2PA manifest store in JUMBF format.
    /// * `format` - The format of the stream.
    /// * `stream` - The stream to verify the store against.
    /// # Returns
    /// The updated [`Reader`] with the added manifest store.
    /// # Errors
    /// This function returns an [`Error`] if the c2pa_data is not valid, or severe errors occur in validation.
    /// You must check validation status for non-severe errors.
    #[async_generic]
    pub fn with_manifest_data_and_stream(
        mut self,
        c2pa_data: &[u8],
        format: &str,
        stream: impl Read + Seek + MaybeSend,
    ) -> Result<Self> {
        let mut validation_log = StatusTracker::default();

        let store = if _sync {
            Store::from_manifest_data_and_stream(
                c2pa_data,
                format,
                stream,
                &mut validation_log,
                &self.context,
            )
        } else {
            Store::from_manifest_data_and_stream_async(
                c2pa_data,
                format,
                stream,
                &mut validation_log,
                &self.context,
            )
            .await
        }?;
        if _sync {
            self.with_store(store, &mut validation_log)
        } else {
            self.with_store_async(store, &mut validation_log).await
        }?;
        Ok(self)
    }

    /// Create a manifest store [`Reader`] from existing `c2pa_data` and a stream.
    /// Use this to validate a remote manifest or a sidecar manifest.
    /// # Arguments
    /// * `c2pa_data` - A C2PA manifest store in JUMBF format.
    /// * `format` - The format of the stream.
    /// * `stream` - The stream to verify the store against.
    /// # Returns
    /// A [`Reader`] for the manifest store.
    /// # Errors
    /// This function returns an [`Error`] ef the c2pa_data is not valid, or severe errors occur in validation.
    /// You must check validation status for non-severe errors.
    #[deprecated(
        note = "Use `Reader::from_context(context).with_manifest_data_and_stream(c2pa_data, format, stream)` instead, passing a `Context` explicitly rather than relying on thread-local settings."
    )]
    #[async_generic]
    pub fn from_manifest_data_and_stream(
        c2pa_data: &[u8],
        format: &str,
        stream: impl Read + Seek + MaybeSend,
    ) -> Result<Reader> {
        // Get thread-local settings (if any) for backward compatibility
        let settings = crate::settings::get_thread_local_settings();
        let context = Context::new().with_settings(settings).unwrap_or_default();
        if _sync {
            Reader::from_context(context).with_manifest_data_and_stream(c2pa_data, format, stream)
        } else {
            Reader::from_context(context)
                .with_manifest_data_and_stream_async(c2pa_data, format, stream)
                .await
        }
    }

    /// Add manifest store from an initial segment and a fragment stream to the [`Reader`].
    /// This would be used to load and validate fragmented MP4 files that span multiple separate asset files.
    /// # Arguments
    /// * `format` - The format of the stream.
    /// * `stream` - The initial segment stream.
    /// * `fragment` - The fragment stream.
    /// # Returns
    /// The updated [`Reader`] with the added manifest store.
    /// # Errors
    /// This function returns an [`Error`] if the streams are not valid, or severe errors occur in validation.
    /// You must check validation status for non-severe errors.
    #[async_generic]
    pub fn with_fragment(
        mut self,
        format: &str,
        mut stream: impl Read + Seek + MaybeSend,
        mut fragment: impl Read + Seek + MaybeSend,
    ) -> Result<Self> {
        let mut validation_log = StatusTracker::default();

        let store = if _sync {
            Store::load_fragment_from_stream(
                format,
                &mut stream,
                &mut fragment,
                &mut validation_log,
                &self.context,
            )
        } else {
            Store::load_fragment_from_stream_async(
                format,
                &mut stream,
                &mut fragment,
                &mut validation_log,
                &self.context,
            )
            .await
        }?;

        if _sync {
            self.with_store(store, &mut validation_log)
        } else {
            self.with_store_async(store, &mut validation_log).await
        }?;
        Ok(self)
    }

    /// Create a [`Reader`] from an initial segment and a fragment stream.
    /// This would be used to load and validate fragmented MP4 files that span multiple separate asset files.
    /// # Arguments
    /// * `format` - The format of the stream.
    /// * `stream` - The initial segment stream.
    /// * `fragment` - The fragment stream.
    /// # Returns
    /// A [`Reader`] for the manifest store.
    /// # Errors
    /// This function returns an [`Error`] if the streams are not valid, or severe errors occur in validation.
    /// You must check validation status for non-severe errors.
    #[async_generic]
    pub fn from_fragment(
        format: &str,
        stream: impl Read + Seek + MaybeSend,
        fragment: impl Read + Seek + MaybeSend,
    ) -> Result<Self> {
        if _sync {
            Reader::default().with_fragment(format, stream, fragment)
        } else {
            Reader::default()
                .with_fragment_async(format, stream, fragment)
                .await
        }
    }

    /// Add manifest store from an initial segment and fragments to the [`Reader`].
    /// This would be used to load and validate fragmented MP4 files that span
    /// multiple separate asset files.
    /// # Arguments
    /// * `path` - The path to the initial segment file.
    /// * `fragments` - A vector of paths to fragment files.
    /// # Returns
    /// The updated [`Reader`] with the added manifest store.
    /// # Errors
    /// Returns an [`Error`] when the manifest data cannot be read from the specified files.
    #[cfg(feature = "file_io")]
    pub fn with_fragmented_files<P: AsRef<std::path::Path>>(
        mut self,
        path: P,
        fragments: &Vec<std::path::PathBuf>,
    ) -> Result<Self> {
        let mut validation_log = StatusTracker::default();

        let asset_type = jumbf_io::get_supported_file_extension(path.as_ref())
            .ok_or(crate::Error::UnsupportedType)?;

        let mut init_segment = std::fs::File::open(path.as_ref())?;

        match Store::load_from_file_and_fragments(
            &asset_type,
            &mut init_segment,
            fragments,
            &mut validation_log,
            &self.context,
        ) {
            Ok(store) => {
                self.with_store(store, &mut validation_log)?;
                Ok(self)
            }
            Err(e) => Err(e),
        }
    }

    /// Loads a [`Reader`]` from an initial segment and fragments.  This
    /// would be used to load and validate fragmented MP4 files that span
    /// multiple separate asset files.
    #[cfg(feature = "file_io")]
    #[deprecated(
        note = "Use `Reader::from_context(context).with_fragmented_files(path, fragments)` instead, passing a `Context` explicitly rather than relying on thread-local settings."
    )]
    pub fn from_fragmented_files<P: AsRef<std::path::Path>>(
        path: P,
        fragments: &Vec<std::path::PathBuf>,
    ) -> Result<Reader> {
        let settings = crate::settings::get_thread_local_settings();
        let context = Context::new().with_settings(settings)?;
        Reader::from_context(context).with_fragmented_files(path, fragments)
    }

    /// Returns a [Vec] of mime types that [c2pa-rs] is able to read.
    pub fn supported_mime_types() -> Vec<String> {
        jumbf_io::supported_reader_mime_types()
    }

    /// replace assertion values in the reader json with the values from the assertion_values map
    /// # Arguments
    /// * `reader_json` - The reader json to update
    /// # Returns
    /// The updated reader json
    fn to_json_formatted(&self) -> Result<Value> {
        let mut json = serde_json::to_value(self).map_err(Error::JsonError)?;

        // If we ran post-validation, we need to update the assertion values in the report
        if !self.assertion_values.is_empty() {
            if let Some(manifests) = json.get_mut("manifests").and_then(|m| m.as_object_mut()) {
                for (manifest_label, manifest) in manifests.iter_mut() {
                    // Get assertions array once instead of multiple lookups
                    if let Some(assertions) = manifest
                        .get_mut("assertions")
                        .and_then(|a| a.as_array_mut())
                    {
                        for assertion in assertions.iter_mut() {
                            // Get label once and reuse
                            if let Some(label) = assertion.get("label").and_then(|l| l.as_str()) {
                                let uri =
                                    crate::jumbf::labels::to_assertion_uri(manifest_label, label);
                                if let Some(value) = self.assertion_values.get(&uri) {
                                    // Only create new string if we need to insert
                                    if let Some(assertion_mut) = assertion.as_object_mut() {
                                        assertion_mut.insert("data".to_string(), value.clone());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // Convert hash values to base64 strings
        Ok(hash_to_b64(json))
    }

    /// Convert the reader to a JSON value with detailed formatting.
    /// This view more closely resembles the original JUMBF manifest store.
    fn to_json_detailed_formatted(&self) -> Result<Value> {
        let report = match self.validation_results() {
            Some(results) => ManifestStoreReport::from_store_with_results(&self.store, results),
            None => ManifestStoreReport::from_store(&self.store),
        }?;

        let mut json = serde_json::to_value(report).map_err(Error::JsonError)?;

        // If we ran post-validation, we need to update the assertion values in the report
        if !self.assertion_values.is_empty() {
            if let Some(manifests) = json.get_mut("manifests").and_then(|m| m.as_object_mut()) {
                for (manifest_label, manifest) in manifests.iter_mut() {
                    if let Some(assertions) = manifest
                        .get_mut("assertion_store")
                        .and_then(|a| a.as_object_mut())
                    {
                        for (label, assertion) in assertions.iter_mut() {
                            let uri = crate::jumbf::labels::to_assertion_uri(manifest_label, label);
                            if let Some(value) = self.assertion_values.get(&uri) {
                                *assertion = value.clone();
                            }
                        }
                    }
                }
            }
        }
        // Convert hash values to base64 strings
        json = hash_to_b64(json);
        Ok(json)
    }

    /// Get the Reader as a JSON string
    /// This just calls to_json_formatted
    pub fn json(&self) -> String {
        self.json_checked().unwrap_or_else(|_| "{}".to_string())
    }

    /// Get the manifest store as a crJSON [`Value`](serde_json::Value).
    ///
    /// crJSON is a standardized JSON format for C2PA manifest data.
    /// Returns an error if conversion fails.
    pub fn to_crjson_value(&self) -> Result<Value> {
        crate::crjson::from_reader(self)
    }

    /// Get the manifest store as a pretty-printed crJSON string.
    ///
    /// crJSON is a standardized JSON format for C2PA manifest data.
    /// Returns `"{}"` if conversion or formatting fails.
    pub fn crjson(&self) -> String {
        self.crjson_checked().unwrap_or_else(|_| "{}".to_string())
    }

    /// Get the manifest store as a pretty-printed crJSON string, returning an error if it fails.
    ///
    /// crJSON is a standardized JSON format for C2PA manifest data.
    pub fn crjson_checked(&self) -> Result<String> {
        self.to_crjson_value()
            .and_then(|v| serde_json::to_string_pretty(&v).map_err(Error::JsonError))
    }

    /// Get the Reader as a JSON string, returning an error if formatting fails
    ///
    /// This is useful when you need to handle errors from deeply nested or malformed structures.
    /// For a version that never fails, use [`Self::json()`].
    pub fn json_checked(&self) -> Result<String> {
        let value = self.to_json_formatted()?;
        serde_json::to_string_pretty(&value).map_err(Error::JsonError)
    }

    /// Get the Reader as a detailed JSON string
    /// This just calls to_json_detailed_formatted
    pub fn detailed_json(&self) -> String {
        self.detailed_json_checked()
            .unwrap_or_else(|_| "{}".to_string())
    }

    /// Get the Reader as a detailed JSON string, returning an error if formatting fails
    ///
    /// This is useful when you need to handle errors from deeply nested or malformed structures.
    /// For a version that never fails, use [`Self::detailed_json()`].
    pub fn detailed_json_checked(&self) -> Result<String> {
        let value = self.to_json_detailed_formatted()?;
        serde_json::to_string_pretty(&value).map_err(Error::JsonError)
    }

    /// Returns the remote url of the manifest if this [`Reader`] obtained the manifest remotely.
    pub fn remote_url(&self) -> Option<&str> {
        self.store.remote_url()
    }

    /// Returns if the [`Reader`] was created from an embedded manifest.
    pub fn is_embedded(&self) -> bool {
        self.store.is_embedded()
    }

    /// Get the [`ValidationStatus`] array of the manifest store if it exists.
    /// Call this method to check for validation errors.
    ///
    /// This validation report only includes error statuses applied to the active manifest
    /// and error statuses for ingredients that are not already reported by the ingredient status.
    /// Use the [`ValidationStatus`] `url` method to identify the associated manifest; this can be useful when a validation error does not refer to the active manifest.
    /// # Example
    /// ```no_run
    /// use c2pa::Reader;
    /// let stream = std::io::Cursor::new(include_bytes!("../tests/fixtures/CA.jpg"));
    /// let reader = Reader::from_stream("image/jpeg", stream).unwrap();
    /// let status = reader.validation_status();
    /// ```
    pub fn validation_status(&self) -> Option<&[ValidationStatus]> {
        self.validation_status.as_deref()
    }

    /// Get the [`ValidationResults`] map of an asset if it exists.
    ///
    /// Call this method to check for detailed validation results.
    /// The validation_state method should be used to determine the overall validation state.
    ///
    /// The results are divided between the active manifest and ingredient deltas.
    /// The deltas will only exist if there are validation errors not already reported in ingredients
    /// It is normal for there to be many success and information statuses.
    /// Any errors will be reported in the failure array.
    ///
    /// # Example
    /// ```no_run
    /// use c2pa::Reader;
    /// let stream = std::io::Cursor::new(include_bytes!("../tests/fixtures/CA.jpg"));
    /// let reader = Reader::from_stream("image/jpeg", stream).unwrap();
    /// let status = reader.validation_results();
    /// ```
    pub fn validation_results(&self) -> Option<&ValidationResults> {
        self.validation_results.as_ref()
    }

    /// Get the [`ValidationState`] of the manifest store.
    pub fn validation_state(&self) -> ValidationState {
        if let Some(validation_results) = self.validation_results() {
            return validation_results.validation_state();
        }

        let verify_trust = self.context.settings().verify.verify_trust;
        match self.validation_status() {
            Some(status) => {
                // if there are any errors, the state is invalid unless the only error is an untrusted credential
                let errs = status
                    .iter()
                    .any(|s| s.code() != crate::validation_status::SIGNING_CREDENTIAL_UNTRUSTED);
                if errs {
                    ValidationState::Invalid
                } else if verify_trust {
                    // If we verified trust and didn't get an error, we can assume it is trusted
                    ValidationState::Trusted
                } else {
                    ValidationState::Valid
                }
            }
            None => {
                if verify_trust {
                    // if we are verifying trust, and there is no validation status, we can assume it is trusted
                    ValidationState::Trusted
                } else {
                    ValidationState::Valid
                }
            }
        }
    }

    /// Return the active [`Manifest`], or `None` if there's no active manifest.
    pub fn active_manifest(&self) -> Option<&Manifest> {
        if let Some(label) = self.active_manifest.as_ref() {
            self.manifests.get(label)
        } else {
            None
        }
    }

    /// Return the active [`Manifest`], or `None` if there's no active manifest.
    pub fn active_label(&self) -> Option<&str> {
        self.active_manifest.as_deref()
    }

    /// Returns an iterator over a collection of [`Manifest`] structs.
    pub fn iter_manifests(&self) -> impl Iterator<Item = &Manifest> + '_ {
        self.manifests.values()
    }

    /// Returns a reference to the [`Manifest`] collection.
    pub fn manifests(&self) -> &HashMap<String, Manifest> {
        &self.manifests
    }

    /// Given a label, return the associated [`Manifest`], if it exists.
    /// # Arguments
    /// * `label` - The label of the requested [`Manifest`].
    pub fn get_manifest(&self, label: &str) -> Option<&Manifest> {
        self.manifests.get(label)
    }

    /// Write a resource identified by URI to the given stream.
    /// Use this function, for example, to get a thumbnail or icon image and write it to a stream.
    /// # Arguments
    /// * `uri` - The URI of the resource to write (from an identifier field).
    /// * `stream` - The stream to write to.
    /// # Returns
    /// The number of bytes written.
    /// # Errors
    /// Returns [`Error`] if the resource does not exist.
    /// # Example
    /// ```no_run
    /// use std::io::Cursor;
    ///
    /// use c2pa::{Context, Reader};
    /// // Create a Reader from an in-memory stream (placeholder bytes shown here).
    /// let input = Cursor::new(Vec::new());
    /// let reader = Reader::default().with_stream("image/jpeg", input).unwrap();
    ///
    /// // Get a resource identifier from the active manifest (e.g., a thumbnail).
    /// let manifest = reader.active_manifest().unwrap();
    /// let uri = &manifest.thumbnail_ref().unwrap().identifier;
    ///
    /// // Write that resource to an output stream.
    /// let out = Cursor::new(Vec::new());
    /// let bytes_written = reader.resource_to_stream(uri, out).unwrap();
    /// ```
    pub fn resource_to_stream(
        &self,
        uri: &str,
        stream: impl Write + Read + Seek + MaybeSend,
    ) -> Result<usize> {
        // get the manifest referenced by the uri, or the active one if None
        // add logic to search for local or absolute uri identifiers
        let (manifest, label) = match manifest_label_from_uri(uri) {
            Some(label) => (self.manifests.get(&label), label),
            None => (
                self.active_manifest(),
                self.active_label().unwrap_or_default().to_string(),
            ),
        };
        let relative_uri = to_relative_uri(uri);
        let absolute_uri = to_absolute_uri(&label, uri);

        if let Some(manifest) = manifest {
            let find_resource = |uri: &str| -> Result<&crate::ResourceStore> {
                let mut resources = manifest.resources();
                if !resources.exists(uri) {
                    // also search ingredients resources to support Reader model
                    for ingredient in manifest.ingredients() {
                        if ingredient.resources().exists(uri) {
                            resources = ingredient.resources();
                            return Ok(resources);
                        }
                    }
                } else {
                    return Ok(resources);
                }
                Err(Error::ResourceNotFound(uri.to_owned()))
            };
            let result = find_resource(&relative_uri);
            match result {
                Ok(resource) => resource.write_stream(&relative_uri, stream),
                Err(_) => match find_resource(&absolute_uri) {
                    Ok(resource) => resource.write_stream(&absolute_uri, stream),
                    Err(e) => Err(e),
                },
            }
        } else {
            Err(Error::ResourceNotFound(uri.to_owned()))
        }
        .map(|size| size as usize)
    }

    /// Write all resources to a folder.
    ///
    ///
    /// This function writes all resources to a folder.
    /// Resources are stored in sub-folders corresponding to manifest label.
    /// Conversions ensure the file paths are valid.
    ///
    /// # Arguments
    /// * `path` - The path to the folder to write to.
    /// # Errors
    /// Returns an [`Error`] if the resources cannot be written to the folder.
    /// # Example
    /// ```no_run
    /// use c2pa::Reader;
    /// let reader = Reader::from_file("path/to/file.jpg").unwrap();
    /// reader.to_folder("path/to/folder").unwrap();
    /// ```
    #[cfg(feature = "file_io")]
    pub fn to_folder<P: AsRef<std::path::Path>>(&self, path: P) -> Result<()> {
        std::fs::create_dir_all(&path)?;
        std::fs::write(path.as_ref().join("manifest_store.json"), self.json())?;
        let c2pa_data = self.store.to_jumbf_internal(0)?;
        std::fs::write(path.as_ref().join("manifest_data.c2pa"), c2pa_data)?;
        for manifest in self.manifests.values() {
            let resources = manifest.resources();
            for (uri, data) in resources.resources() {
                let id_path = uri_to_path(uri, manifest.label());
                let path = path.as_ref().join(id_path);
                if let Some(parent) = path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                let mut file = std::fs::File::create(&path)?;
                file.write_all(data)?;
            }
        }
        Ok(())
    }

    #[async_generic()]
    pub(crate) fn with_store(
        &mut self,
        store: Store,
        validation_log: &mut StatusTracker,
    ) -> Result<&Self> {
        let active_manifest = store.provenance_label();
        let mut manifests = HashMap::new();
        let mut options = StoreOptions::default();

        for claim in store.claims() {
            let manifest_label = claim.label();
            let result = if _sync {
                Manifest::from_store(
                    &store,
                    manifest_label,
                    &mut options,
                    validation_log,
                    self.context.settings(),
                )
            } else {
                Manifest::from_store_async(
                    &store,
                    manifest_label,
                    &mut options,
                    validation_log,
                    self.context.settings(),
                )
                .await
            };

            match result {
                Ok(mut manifest) => {
                    // Populate manifest_data for ingredients using efficient flat store builder
                    for ingredient in manifest.ingredients_mut() {
                        if let Some(active_label) = ingredient.active_manifest() {
                            if let Some(claim) = store.get_claim(active_label) {
                                let ingredient_store = Self::build_ingredient_store(&store, claim)?;
                                let jumbf = ingredient_store.to_jumbf_internal(0)?;
                                ingredient.set_manifest_data(jumbf)?;
                            }
                        }
                    }
                    manifests.insert(manifest_label.to_owned(), manifest);
                }
                Err(e) => {
                    let uri = crate::jumbf::labels::to_manifest_uri(manifest_label);
                    let code = ValidationStatus::code_from_error(&e);
                    log_item!(uri.clone(), "Failed to load manifest", "Reader::from_store")
                        .validation_status(code)
                        .failure(validation_log, Error::C2PAValidation(e.to_string()))?;
                }
            };
        }

        let validation_results = ValidationResults::from_store(&store, validation_log);

        // resolve redactions
        // Even though we validate
        // compare options.redacted_assertions and options.missing_assertions
        // remove all overlapping values from both arrays
        // any remaining redacted assertions are not actually redacted
        // any remaining missing assertions are not actually missing

        let mut redacted = options.redacted_assertions.clone();
        let mut missing = options.missing_assertions.clone();
        redacted.retain(|item| !missing.contains(item));
        missing.retain(|item| !options.redacted_assertions.contains(item));

        // Add any remaining redacted assertions to the validation results
        for uri in &redacted {
            log_item!(uri.clone(), "assertion not redacted", "Reader::from_store")
                .validation_status(ASSERTION_NOT_REDACTED)
                .informational(validation_log);
        }

        for uri in &missing {
            log_item!(uri.clone(), "assertion missing", "Reader::from_store")
                .validation_status(ASSERTION_MISSING)
                .informational(validation_log);
        }

        let validation_state = validation_results.validation_state();

        self.active_manifest = active_manifest;
        self.manifests = manifests;
        self.validation_status = validation_results.validation_errors();
        self.validation_results = Some(validation_results);
        self.validation_state = Some(validation_state);
        self.store = store;
        Ok(self)
    }

    /// Post-validate the reader. This function is called after the reader is created.
    #[async_generic(async_signature(
        &mut self,
        validator: &impl AsyncPostValidator
    ))]
    pub fn post_validate(&mut self, validator: &impl PostValidator) -> Result<()> {
        let mut validation_log = StatusTracker::default();
        let mut validation_results = self.validation_results.take().unwrap_or_default();
        let mut assertion_values = HashMap::new();
        if let Some(active_label) = self.active_label() {
            let values = if _sync {
                self.walk_manifest(active_label, validator, &mut validation_log)
            } else {
                self.walk_manifest_async(active_label, validator, &mut validation_log)
                    .await
            }?;
            assertion_values.extend(values);
            for log in validation_log.logged_items() {
                if let Some(status) = ValidationStatus::from_log_item(log) {
                    validation_results.add_status(status);
                } else {
                    eprintln!("Failed to create status from log item: {log:?}");
                }
            }
        }
        self.validation_results = Some(validation_results);
        self.assertion_values.extend(assertion_values);
        Ok(())
    }

    #[async_generic(async_signature(
        &self,
        manifest_label: &str,
        validator: &impl AsyncPostValidator,
        validation_log: &mut StatusTracker
    ))]
    fn walk_manifest(
        &self,
        manifest_label: &str,
        validator: &impl PostValidator,
        validation_log: &mut StatusTracker,
    ) -> Result<HashMap<String, Value>> {
        let mut assertion_values = HashMap::new();
        let mut stack: Vec<(String, Option<String>)> = vec![(manifest_label.to_string(), None)];
        let mut seen = HashSet::new();

        while let Some((current_label, parent_uri)) = stack.pop() {
            seen.insert(current_label.clone());

            // If we're processing an ingredient, push its URI to the validation log
            if let Some(uri) = &parent_uri {
                validation_log.push_ingredient_uri(uri.clone());
            }

            let manifest = match self.get_manifest(&current_label) {
                Some(m) => m,
                None => {
                    // skip this manifest if not found
                    continue;
                }
            };

            let mut partial_claim = crate::dynamic_assertion::PartialClaim::default();
            {
                if let Some(claim) = self.store.get_claim(&current_label) {
                    for assertion in claim.assertions() {
                        partial_claim.add_assertion(assertion);
                    }
                }
            }

            // Process assertions for current manifest
            for assertion in manifest.assertions().iter() {
                let assertion_uri =
                    crate::jumbf::labels::to_assertion_uri(&current_label, assertion.label());
                let result = if _sync {
                    validator.validate(
                        assertion.label(),
                        assertion,
                        &assertion_uri,
                        &partial_claim,
                        validation_log,
                    )
                } else {
                    validator
                        .validate(
                            assertion.label(),
                            assertion,
                            &assertion_uri,
                            &partial_claim,
                            validation_log,
                        )
                        .await
                }?;
                if let Some(value) = result {
                    assertion_values.insert(assertion_uri, value);
                }
            }

            // Add ingredients to stack for processing
            for ingredient in manifest.ingredients().iter() {
                if let Some(label) = ingredient.active_manifest() {
                    if !seen.contains(label) {
                        let ingredient_uri = crate::jumbf::labels::to_assertion_uri(
                            &current_label,
                            ingredient.label().unwrap_or("unknown"),
                        );
                        stack.push((label.to_string(), Some(ingredient_uri)));
                    }
                }
            }

            // If we're processing an ingredient, pop its URI from the validation log
            if parent_uri.is_some() {
                validation_log.pop_ingredient_uri();
            }
        }

        Ok(assertion_values)
    }

    /// Build a flat ingredient store for a claim by walking ingredient assertions.
    fn build_ingredient_store(store: &Store, claim: &Claim) -> Result<Store> {
        let mut ingredient_store = Store::new();
        let mut visited = HashSet::new();
        let mut path = Vec::new();

        fn collect_flat(
            store: &Store,
            claim: &Claim,
            ingredient_store: &mut Store,
            visited: &mut HashSet<String>,
            path: &mut Vec<String>,
        ) -> Result<()> {
            use crate::assertions::Ingredient as IngredientAssertion;

            let claim_label = claim.label().to_string();

            if visited.contains(&claim_label) {
                return Ok(());
            }

            // Cycle detection
            if path.iter().any(|p| p == &claim_label) {
                return Ok(());
            }

            path.push(claim_label.clone());

            for ing_assertion in claim.ingredient_assertions() {
                let ingredient = IngredientAssertion::from_assertion(ing_assertion.assertion())?;
                let manifest_uri = ingredient
                    .active_manifest
                    .as_ref()
                    .or(ingredient.c2pa_manifest.as_ref());
                if let Some(manifest_uri) = manifest_uri {
                    let ingredient_label = Store::manifest_label_from_path(&manifest_uri.url());
                    if let Some(ingredient_claim) = store.get_claim(&ingredient_label) {
                        collect_flat(store, ingredient_claim, ingredient_store, visited, path)?;
                    }
                }
            }

            // Post-order: add after all children
            ingredient_store.insert_restored_claim(claim_label.clone(), claim.clone());
            visited.insert(claim_label);
            path.pop();

            Ok(())
        }

        collect_flat(store, claim, &mut ingredient_store, &mut visited, &mut path)?;

        Ok(ingredient_store)
    }

    /// Convert the Reader back into a Builder.
    /// This can be used to modify an existing manifest store.
    /// # Errors
    /// Returns an [`Error`] if there is no active manifest.
    pub fn into_builder(mut self) -> Result<crate::Builder> {
        // Preserve the Reader's context in the new Builder
        let context = self.context;
        let mut builder = crate::Builder::from_shared_context(&context);
        if let Some(label) = &self.active_manifest {
            if let Some(parts) = crate::jumbf::labels::manifest_label_to_parts(label) {
                builder.definition.vendor = parts.cgi.clone();
                if parts.is_v1 {
                    builder.definition.claim_version = Some(1);
                }
            }
            builder.definition.label = Some(label.to_string());
            if let Some(mut manifest) = self.manifests.remove(label) {
                builder.definition.claim_generator_info =
                    manifest.claim_generator_info.take().unwrap_or_default();
                builder.definition.format = manifest.format().unwrap_or_default().to_string();
                builder.definition.title = manifest.title().map(|s| s.to_owned());
                builder.definition.instance_id = manifest.instance_id().to_owned();
                builder.definition.thumbnail = manifest.thumbnail_ref().cloned();
                builder.definition.redactions = manifest.redactions.take();
                let ingredients = std::mem::take(&mut manifest.ingredients);
                for mut ingredient in ingredients {
                    if let Some(active_manifest) = ingredient.active_manifest() {
                        if ingredient.manifest_data_ref().is_none() {
                            if let Some(claim) = self.store.get_claim(active_manifest) {
                                let ingredient_store =
                                    Self::build_ingredient_store(&self.store, claim)?;
                                let jumbf = ingredient_store.to_jumbf_internal(0)?;
                                ingredient.set_manifest_data(jumbf)?;
                            }
                        }
                    }
                    builder.add_ingredient(ingredient);
                }
                for assertion in manifest.assertions.iter() {
                    builder.add_assertion(assertion.label(), assertion.value()?)?;
                }
                for (uri, data) in manifest.resources().resources() {
                    builder.add_resource(uri, std::io::Cursor::new(data))?;
                }
            }
        }
        Ok(builder)
    }

    /// Returns the [`ArchiveType`] from the active manifest's `org.contentauth.archive.metadata` assertion, if present.
    pub(crate) fn active_archive_type(&self) -> Option<crate::assertions::labels::ArchiveType> {
        let manifest = self.active_manifest()?;
        let metadata: Metadata = manifest
            .find_assertion(crate::assertions::labels::ARCHIVE_METADATA)
            .ok()?;
        metadata
            .value
            .get("archive:type")
            .and_then(|v: &Value| v.as_str())
            .map(crate::assertions::labels::ArchiveType::from_str)
    }

    /// Convert a Reader into an [`Ingredient`] using the parent ingredient from the active manifest.
    /// # Errors
    /// Returns an [`Error`] if there is no parent ingredient.
    pub(crate) fn to_ingredient(&self) -> Result<Ingredient> {
        let mut ingredient = self
            .active_manifest()
            .and_then(|m| m.ingredients().first())
            .ok_or_else(|| Error::IngredientNotFound)?
            .to_owned();

        // populate manifest_data on demand for ingredients with an active manifest
        if let Some(active_manifest) = ingredient.active_manifest() {
            if ingredient.manifest_data_ref().is_none() {
                if let Some(claim) = self.store.get_claim(active_manifest) {
                    let ingredient_store = Self::build_ingredient_store(&self.store, claim)?;
                    let jumbf = ingredient_store.to_jumbf_internal(0)?;
                    ingredient.set_manifest_data(jumbf)?;
                }
            }
        }

        Ok(ingredient)
    }
}

/// Convert the Reader to a JSON value.
impl TryFrom<Reader> for serde_json::Value {
    type Error = Error;

    fn try_from(reader: Reader) -> Result<Self> {
        reader.to_json_formatted()
    }
}
impl TryFrom<&Reader> for serde_json::Value {
    type Error = Error;

    fn try_from(reader: &Reader) -> Result<Self> {
        reader.to_json_formatted()
    }
}

/// Prints the JSON of the manifest data.
impl std::fmt::Display for Reader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let json = self.json_checked().map_err(|_| std::fmt::Error)?;
        f.write_str(&json)
    }
}

/// Prints the full debug details of the manifest data.
impl std::fmt::Debug for Reader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let json = self.detailed_json_checked().map_err(|_| std::fmt::Error)?;
        f.write_str(&json)
    }
}

impl TryInto<crate::Builder> for Reader {
    type Error = Error;

    fn try_into(self) -> Result<crate::Builder> {
        self.into_builder()
    }
}

#[cfg(test)]
pub mod tests {
    #![allow(clippy::expect_used)]
    #![allow(clippy::panic)]
    #![allow(clippy::unwrap_used)]
    use std::io::Cursor;

    use super::*;
    use crate::utils::test::test_context;

    const IMAGE_COMPLEX_MANIFEST: &[u8] = include_bytes!("../tests/fixtures/CACAE-uri-CA.jpg");
    const IMAGE_WITH_MANIFEST: &[u8] = include_bytes!("../tests/fixtures/CA.jpg");
    #[cfg(feature = "fetch_remote_manifests")]
    const IMAGE_WITH_REMOTE_MANIFEST: &[u8] = include_bytes!("../tests/fixtures/cloud.jpg");
    const IMAGE_WITH_INGREDIENT_MANIFEST: &[u8] = include_bytes!("../tests/fixtures/CACA.jpg");
    const SAMPLE1_HEIC: &[u8] = include_bytes!("../tests/fixtures/sample1.heic");

    #[test]
    // Verify that we can convert a Reader back into a Builder re-sign and the read it back again
    fn test_into_builder() -> Result<()> {
        let context = test_context().into_shared();
        let mut source = Cursor::new(IMAGE_WITH_INGREDIENT_MANIFEST);
        let format = "image/jpeg";
        let reader = Reader::from_shared_context(&context).with_stream(format, &mut source)?;
        println!("{reader}");

        assert_eq!(reader.validation_state(), ValidationState::Trusted);
        let mut builder: crate::Builder = reader.try_into()?;
        println!("{builder}");

        source.set_position(0);
        let mut dest = Cursor::new(Vec::new());
        builder.save_to_stream(format, &mut source, &mut dest)?;

        dest.set_position(0);
        let reader2 = Reader::from_shared_context(&context).with_stream(format, &mut dest)?;
        println!("{reader2}");

        assert_eq!(reader2.validation_state(), ValidationState::Trusted);
        //std::fs::write("../target/CA-rebuilt.jpg", dest.get_ref())?;
        Ok(())
    }

    #[test]
    fn test_reader_embedded() -> Result<()> {
        let reader =
            Reader::default().with_stream("image/jpeg", Cursor::new(IMAGE_WITH_MANIFEST))?;
        assert_eq!(reader.remote_url(), None);
        assert!(reader.is_embedded());

        Ok(())
    }

    #[test]
    fn test_reader_new_with_stream() -> Result<()> {
        let context = test_context();

        let mut source = Cursor::new(IMAGE_WITH_MANIFEST);

        let reader = Reader::from_context(context).with_stream("image/jpeg", &mut source)?;

        assert_eq!(reader.remote_url(), None);
        assert!(reader.is_embedded());
        assert_eq!(reader.validation_state(), ValidationState::Trusted);
        assert!(reader.active_manifest().is_some());

        Ok(())
    }

    #[test]
    #[cfg(feature = "fetch_remote_manifests")]
    fn test_reader_remote_url() -> Result<()> {
        let reader =
            Reader::default().with_stream("image/jpeg", Cursor::new(IMAGE_WITH_REMOTE_MANIFEST))?;
        let remote_url = reader.remote_url();
        assert_eq!(remote_url, Some("https://cai-manifests.adobe.com/manifests/adobe-urn-uuid-5f37e182-3687-462e-a7fb-573462780391"));
        assert!(!reader.is_embedded());

        Ok(())
    }

    #[test]
    #[cfg(feature = "file_io")]
    fn test_reader_from_file_no_manifest() -> Result<()> {
        let result = Reader::default().with_file("tests/fixtures/IMG_0003.jpg");
        assert!(matches!(result, Err(Error::JumbfNotFound)));
        Ok(())
    }

    #[test]
    #[cfg(feature = "file_io")]
    fn test_reader_from_file_validation_err() -> Result<()> {
        let reader = Reader::default().with_file("tests/fixtures/XCA.jpg")?;
        assert!(reader.validation_status().is_some());
        assert_eq!(
            reader.validation_status().unwrap()[0].code(),
            crate::validation_status::ASSERTION_DATAHASH_MISMATCH
        );
        assert_eq!(reader.validation_state(), ValidationState::Invalid);
        Ok(())
    }

    /// BMFF hash verification now fires at least one `VerifyingAssetHash` progress event per
    /// hash pass (file-level or per-chunk/track), matching the granularity of the data-hash path.
    ///
    /// Uses in-memory streams and an embedded fixture so this runs on targets without a usable
    /// host filesystem (e.g. WASI without preopened paths).
    #[test]
    fn test_bmff_read_reports_verifying_asset_hash_progress() -> Result<()> {
        use std::sync::Mutex;

        use crate::Builder;

        let received = Arc::new(Mutex::new(Vec::<(ProgressPhase, u32, u32)>::new()));
        let received_cb = Arc::clone(&received);
        let ctx = test_context()
            .with_progress_callback(move |phase, step, total| {
                received_cb.lock().unwrap().push((phase, step, total));
                true
            })
            .into_shared();

        let mut builder = Builder::from_shared_context(&ctx);
        let ctx_for_signer = builder.context().clone();
        let signer = ctx_for_signer.signer()?;
        let mut source = Cursor::new(SAMPLE1_HEIC);
        let mut dest = Cursor::new(Vec::new());
        builder.sign(signer, "heic", &mut source, &mut dest)?;

        received.lock().unwrap().clear();

        dest.set_position(0);
        let _reader = Reader::from_shared_context(&ctx).with_stream("image/heic", &mut dest)?;

        let asset_hash_events: Vec<_> = received
            .lock()
            .unwrap()
            .iter()
            .filter(|(p, _, _)| *p == ProgressPhase::VerifyingAssetHash)
            .cloned()
            .collect();

        assert!(
            !asset_hash_events.is_empty(),
            "expected at least one VerifyingAssetHash event; got none"
        );
        // Steps should be monotonically increasing, starting from 1.
        for (i, (_, step, _)) in asset_hash_events.iter().enumerate() {
            assert_eq!(
                *step,
                (i + 1) as u32,
                "expected step {} but got {step} at index {i}",
                i + 1
            );
        }

        Ok(())
    }

    #[test]
    fn test_reader_trusted() -> Result<()> {
        let context = Context::new();
        let reader = Reader::from_context(context)
            .with_stream("image/jpeg", std::io::Cursor::new(IMAGE_COMPLEX_MANIFEST))?;
        assert_eq!(reader.validation_state(), ValidationState::Trusted);
        Ok(())
    }

    #[test]
    /// Test that the reader can validate a file with nested assertion errors
    fn test_reader_from_file_nested_errors() -> Result<()> {
        // disable trust check so that the status is Valid vs Trusted
        let settings = crate::Settings::default()
            .with_value("verify.verify_trust", false)
            .unwrap();
        let context = Context::new().with_settings(settings).unwrap();
        let reader = Reader::from_context(context)
            .with_stream("image/jpeg", std::io::Cursor::new(IMAGE_COMPLEX_MANIFEST))?;
        println!("{reader}");
        assert_eq!(reader.validation_status(), None);
        assert_eq!(reader.validation_state(), ValidationState::Valid);
        assert_eq!(reader.manifests.len(), 3);
        Ok(())
    }

    #[test]
    /// Test that the reader can validate a file with nested assertion errors
    fn test_reader_nested_resource() -> Result<()> {
        let reader = Reader::default()
            .with_stream("image/jpeg", std::io::Cursor::new(IMAGE_COMPLEX_MANIFEST))?;
        assert_eq!(reader.validation_status(), None);
        assert_eq!(reader.manifests.len(), 3);
        let manifest = reader.active_manifest().unwrap();
        let ingredient = manifest.ingredients().iter().next().unwrap();
        let uri = ingredient.thumbnail_ref().unwrap().identifier.clone();
        let stream = std::io::Cursor::new(Vec::new());
        let bytes_written = reader.resource_to_stream(&uri, stream)?;
        assert_eq!(bytes_written, 41810);
        Ok(())
    }

    #[test]
    #[cfg(feature = "file_io")]
    /// Tests that the reader can write resources to a folder and that ingredients have manifest_data populated
    fn test_reader_to_folder() -> Result<()> {
        // Skip this test in GitHub workflow when target is WASI
        if std::env::var("GITHUB_ACTIONS").is_ok() && cfg!(target_os = "wasi") {
            eprintln!("Skipping test_reader_to_folder on WASI in GitHub Actions");
            return Ok(());
        }

        use crate::utils::{io_utils::tempdirectory, test::temp_dir_path};
        let reader = Reader::default().with_stream(
            "image/jpeg",
            std::io::Cursor::new(IMAGE_WITH_INGREDIENT_MANIFEST),
        )?;
        assert_eq!(reader.validation_status(), None);

        // Verify that ingredients have manifest_data populated
        if let Some(manifest) = reader.active_manifest() {
            for ingredient in manifest.ingredients() {
                assert!(
                    ingredient.manifest_data().is_some(),
                    "Ingredient should have manifest_data populated"
                );
            }
        }

        let temp_dir = tempdirectory().unwrap();
        reader.to_folder(temp_dir.path())?;
        let path = temp_dir_path(&temp_dir, "manifest_store.json");
        assert!(path.exists());
        let path = temp_dir_path(&temp_dir, "manifest_data.c2pa");
        assert!(path.exists());
        Ok(())
    }

    #[test]
    #[cfg(feature = "file_io")]
    /// Test that the reader can validate a file with nested assertion errors
    fn test_reader_detailed_json() -> Result<()> {
        let reader = Reader::default().with_file("tests/fixtures/CACAE-uri-CA.jpg")?;
        let json = reader.json();
        let detailed_json = reader.detailed_json();
        let parsed_json: Value = serde_json::from_str(json.as_str())?;
        let parsed_detailed_json: Value = serde_json::from_str(detailed_json.as_str())?;

        // Undetailed JSON doesn't include "claim" object as child of active manifest object
        // Detailed JSON does include the "claim" object.
        assert!(
            if let Some(active_manifest) = parsed_json["active_manifest"].as_str() {
                let mut is_valid = parsed_json["manifests"]
                    .get(active_manifest)
                    .and_then(|m| m.get("claim"))
                    .is_none();
                is_valid &= parsed_detailed_json["manifests"]
                    .get(active_manifest)
                    .and_then(|m| m.get("claim"))
                    .is_some();
                is_valid
            } else {
                false
            }
        );
        assert!(json.len() < detailed_json.len()); // Detailed JSON should contain more information
        Ok(())
    }

    #[test]
    fn test_reader_post_validate() -> Result<()> {
        use crate::{log_item, status_tracker::StatusTracker};

        let mut reader = Reader::default()
            .with_stream("image/jpeg", std::io::Cursor::new(IMAGE_WITH_MANIFEST))?;

        struct TestValidator;
        impl PostValidator for TestValidator {
            fn validate(
                &self,
                label: &str,
                assertion: &ManifestAssertion,
                uri: &str,
                _preliminary_claim: &PartialClaim,
                tracker: &mut StatusTracker,
            ) -> Result<Option<Value>> {
                let desc = tracker
                    .ingredient_uri()
                    .unwrap_or("active_manifest")
                    .to_string();
                #[allow(clippy::single_match)]
                match label {
                    "c2pa.actions" => {
                        let actions = assertion.to_assertion::<crate::assertions::Actions>()?;
                        // build a comma separated string list of actions
                        let desc = actions
                            .actions
                            .iter()
                            .map(|action| action.action().to_string())
                            .collect::<Vec<String>>()
                            .join(",");

                        log_item!(uri.to_string(), desc.clone(), "test validator")
                            .validation_status("cai.test.action")
                            .success(tracker);
                        let result = Value::String(desc);
                        return Ok(Some(result));
                    }
                    _ => {}
                }
                log_item!(uri.to_string(), desc, "test validator")
                    .validation_status("cai.test.something")
                    .success(tracker);
                Ok(None)
            }
        }

        reader.post_validate(&TestValidator {})?;

        println!("{reader}");
        //Err(Error::NotImplemented("foo".to_string()))
        Ok(())
    }

    #[test]
    fn test_reader_is_send_sync() {
        // Compile-time assertion that Reader is Send + Sync on non-WASM
        // On WASM, MaybeSend/MaybeSync don't require Send + Sync, so these traits
        // won't be implemented, but that's correct for single-threaded WASM
        #[cfg(not(target_arch = "wasm32"))]
        {
            fn assert_send<T: Send>() {}
            fn assert_sync<T: Sync>() {}

            assert_send::<Reader>();
            assert_sync::<Reader>();
        }
    }
}