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

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

#[cfg(feature = "file_io")]
use std::path::Path;
use std::{
    collections::HashMap,
    io::{Read, Seek, Write},
};

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

use crate::{
    claim::ClaimAssetData,
    jumbf::labels::manifest_label_from_uri,
    status_tracker::{DetailedStatusTracker, StatusTracker},
    store::Store,
    utils::base64,
    validation_status::{status_for_store, ValidationStatus},
    Error, Manifest, Result,
};

#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "json_schema", derive(JsonSchema))]
/// A Container for a set of Manifests and a ValidationStatus list
pub struct ManifestStore {
    #[serde(skip_serializing_if = "Option::is_none")]
    /// A label for the active (most recent) manifest in the store
    active_manifest: Option<String>,
    /// A HashMap of Manifests
    manifests: HashMap<String, Manifest>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// ValidationStatus generated when loading the ManifestStore from an asset
    validation_status: Option<Vec<ValidationStatus>>,
    #[serde(skip)]
    /// The internal store representing the manifest store
    store: Store,
}

impl ManifestStore {
    /// allocates a new empty ManifestStore
    pub fn new() -> Self {
        ManifestStore {
            active_manifest: None,
            manifests: HashMap::<String, Manifest>::new(),
            validation_status: None,
            store: Store::new(),
        }
    }

    /// Returns a reference to the active manifest label or None
    pub fn active_label(&self) -> Option<&str> {
        self.active_manifest.as_deref()
    }

    /// Returns a reference to the active manifest or None
    pub fn get_active(&self) -> Option<&Manifest> {
        if let Some(label) = self.active_manifest.as_ref() {
            self.get(label)
        } else {
            None
        }
    }

    /// Returns a reference to manifest HashMap
    #[cfg(feature = "v1_api")]
    pub fn manifests(&self) -> &HashMap<String, Manifest> {
        &self.manifests
    }

    /// Returns a reference to the requested manifest or None
    pub fn get(&self, label: &str) -> Option<&Manifest> {
        self.manifests.get(label)
    }

    // writes a resource identified uri to the given stream
    pub fn get_resource(&self, uri: &str, stream: impl Write + Read + Seek + Send) -> Result<u64> {
        // get the manifest referenced by the uri, or the active one if None
        let manifest = match manifest_label_from_uri(uri) {
            Some(label) => self.get(&label),
            None => self.get_active(),
        };
        if let Some(manifest) = manifest {
            let mut resources = manifest.resources();
            if !resources.exists(uri) {
                // also search ingredients to support Reader model
                for ingredient in manifest.ingredients() {
                    if ingredient.resources().exists(uri) {
                        resources = ingredient.resources();
                        break;
                    }
                }
            }
            resources.write_stream(uri, stream)
        } else {
            Err(Error::ResourceNotFound(uri.to_owned()))
        }
    }

    /// Returns a reference the [ValidationStatus] Vec or None
    pub fn validation_status(&self) -> Option<&[ValidationStatus]> {
        self.validation_status.as_deref()
    }

    /// creates a ManifestStore from a Store with validation
    pub(crate) fn from_store(store: Store, validation_log: &impl StatusTracker) -> ManifestStore {
        Self::from_store_impl(
            store,
            validation_log,
            #[cfg(feature = "file_io")]
            None,
        )
    }

    /// creates a ManifestStore from a Store writing resources to resource_path
    #[cfg(feature = "file_io")]
    pub(crate) fn from_store_with_resources(
        store: Store,
        validation_log: &impl StatusTracker,
        resource_path: &Path,
    ) -> ManifestStore {
        Self::from_store_impl(store, validation_log, Some(resource_path))
    }

    // internal implementation of from_store
    fn from_store_impl(
        store: Store,
        validation_log: &impl StatusTracker,
        #[cfg(feature = "file_io")] resource_path: Option<&Path>,
    ) -> ManifestStore {
        let mut statuses = status_for_store(&store, validation_log);

        let mut manifest_store = ManifestStore::new();
        manifest_store.active_manifest = store.provenance_label();
        manifest_store.store = store;

        let store = &manifest_store.store;
        for claim in store.claims() {
            let manifest_label = claim.label();
            #[cfg(feature = "file_io")]
            let result = Manifest::from_store(store, manifest_label, resource_path);
            #[cfg(not(feature = "file_io"))]
            let result = Manifest::from_store(store, manifest_label);
            match result {
                Ok(manifest) => {
                    manifest_store
                        .manifests
                        .insert(manifest_label.to_owned(), manifest);
                }
                Err(e) => {
                    statuses.push(ValidationStatus::from_error(&e));
                }
            };
        }

        if !statuses.is_empty() {
            manifest_store.validation_status = Some(statuses);
        }

        manifest_store
    }

    pub(crate) fn store(&self) -> &Store {
        &self.store
    }

    /// Creates a new Manifest Store from a Manifest
    #[allow(dead_code)]
    pub fn from_manifest(manifest: &Manifest) -> Result<Self> {
        use crate::status_tracker::OneShotStatusTracker;
        let store = manifest.to_store()?;
        Ok(Self::from_store_impl(
            store,
            &OneShotStatusTracker::new(),
            #[cfg(feature = "file_io")]
            manifest.resources().base_path(),
        ))
    }

    /// Generate a Store from a format string and bytes.
    #[cfg(feature = "v1_api")]
    pub fn from_bytes(format: &str, image_bytes: &[u8], verify: bool) -> Result<ManifestStore> {
        let mut validation_log = DetailedStatusTracker::new();

        Store::load_from_memory(format, image_bytes, verify, &mut validation_log)
            .map(|store| Self::from_store(store, &validation_log))
    }

    /// Generate a Store from a format string and stream.
    #[async_generic(async_signature(
        format: &str,
        mut stream: impl Read + Seek + Send,
        verify: bool,
    ))]
    pub fn from_stream(
        format: &str,
        mut stream: impl Read + Seek + Send,
        verify: bool,
    ) -> Result<ManifestStore> {
        let mut validation_log = DetailedStatusTracker::new();

        let manifest_bytes = Store::load_jumbf_from_stream(format, &mut stream)?;
        let store = Store::from_jumbf(&manifest_bytes, &mut validation_log)?;
        if verify {
            // verify store and claims
            if _sync {
                Store::verify_store(
                    &store,
                    &mut ClaimAssetData::Stream(&mut stream, format),
                    &mut validation_log,
                )?;
            } else {
                Store::verify_store_async(
                    &store,
                    &mut ClaimAssetData::Stream(&mut stream, format),
                    &mut validation_log,
                )
                .await?;
            }
        }
        Ok(Self::from_store(store, &validation_log))
    }

    #[cfg(feature = "file_io")]
    /// Loads a ManifestStore from a file
    /// Example:
    ///
    /// ```
    /// # use c2pa::Result;
    /// use c2pa::ManifestStore;
    /// # fn main() -> Result<()> {
    /// let manifest_store = ManifestStore::from_file("tests/fixtures/C.jpg")?;
    /// println!("{}", manifest_store);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "v1_api")]
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<ManifestStore> {
        let mut validation_log = DetailedStatusTracker::new();

        let store = Store::load_from_asset(path.as_ref(), true, &mut validation_log)?;
        Ok(Self::from_store(store, &validation_log))
    }

    #[cfg(feature = "file_io")]
    /// Loads a ManifestStore from a file adding resources to a folder
    /// Example:
    ///
    /// ```
    /// # use c2pa::Result;
    /// use c2pa::ManifestStore;
    /// # fn main() -> Result<()> {
    /// let manifest_store = ManifestStore::from_file_with_resources(
    ///     "tests/fixtures/C.jpg",
    ///     "../target/tmp/manifest_store",
    /// )?;
    /// println!("{}", manifest_store);
    /// # Ok(())
    /// # }
    /// ```
    #[allow(dead_code)]
    pub fn from_file_with_resources<P: AsRef<Path>>(
        path: P,
        resource_path: P,
    ) -> Result<ManifestStore> {
        let mut validation_log = DetailedStatusTracker::new();

        let store = Store::load_from_asset(path.as_ref(), true, &mut validation_log)?;
        Ok(Self::from_store_with_resources(
            store,
            &validation_log,
            resource_path.as_ref(),
        ))
    }

    /// Loads a ManifestStore from a file
    #[allow(dead_code)]
    pub async fn from_bytes_async(
        format: &str,
        image_bytes: &[u8],
        verify: bool,
    ) -> Result<ManifestStore> {
        let mut validation_log = DetailedStatusTracker::new();

        Store::load_from_memory_async(format, image_bytes, verify, &mut validation_log)
            .await
            .map(|store| Self::from_store(store, &validation_log))
    }

    /// Loads a ManifestStore from an init segment and fragment.  This
    /// would be used to load and validate fragmented MP4 files that span
    /// multiple separate assets.
    pub async fn from_fragment_bytes_async(
        format: &str,
        init_bytes: &[u8],
        fragment_bytes: &[u8],
        verify: bool,
    ) -> Result<ManifestStore> {
        let mut validation_log = DetailedStatusTracker::new();

        Store::load_fragment_from_memory_async(
            format,
            init_bytes,
            fragment_bytes,
            verify,
            &mut validation_log,
        )
        .await
        .map(|store| Self::from_store(store, &validation_log))
    }

    /// Asynchronously loads a manifest from a buffer holding a binary manifest (.c2pa) and validates against an asset buffer
    ///
    /// # Example: Creating a manifest store from a .c2pa manifest and validating it against an asset
    /// ```
    /// use c2pa::{Result, ManifestStore};
    ///
    /// # fn main() -> Result<()> {
    /// #    async {
    ///         let asset_bytes = include_bytes!("../tests/fixtures/cloud.jpg");
    ///         let manifest_bytes = include_bytes!("../tests/fixtures/cloud_manifest.c2pa");
    ///
    ///         let manifest_store = ManifestStore::from_manifest_and_asset_bytes_async(manifest_bytes, "image/jpg", asset_bytes)
    ///             .await
    ///             .unwrap();
    ///
    ///         println!("{}", manifest_store);
    /// #    };
    /// #
    /// #    Ok(())
    /// }
    /// ```
    pub async fn from_manifest_and_asset_bytes_async(
        manifest_bytes: &[u8],
        format: &str,
        asset_bytes: &[u8],
    ) -> Result<ManifestStore> {
        let mut validation_log = DetailedStatusTracker::new();
        let store = Store::from_jumbf(manifest_bytes, &mut validation_log)?;

        Store::verify_store_async(
            &store,
            &mut ClaimAssetData::Bytes(asset_bytes, format),
            &mut validation_log,
        )
        .await?;

        Ok(Self::from_store(store, &validation_log))
    }

    /// Synchronously loads a manifest from a buffer holding a binary manifest (.c2pa) and validates against an asset buffer
    ///
    /// # Example: Creating a manifest store from a .c2pa manifest and validating it against an asset
    /// ```
    /// use c2pa::{Result, ManifestStore};
    ///
    /// # fn main() -> Result<()> {
    /// #    async {
    ///         let asset_bytes = include_bytes!("../tests/fixtures/cloud.jpg");
    ///         let manifest_bytes = include_bytes!("../tests/fixtures/cloud_manifest.c2pa");
    ///
    ///         let manifest_store = ManifestStore::from_manifest_and_asset_bytes(manifest_bytes, "image/jpg", asset_bytes)
    ///             .unwrap();
    ///
    ///         println!("{}", manifest_store);
    /// #    };
    /// #
    /// #    Ok(())
    /// }
    pub fn from_manifest_and_asset_bytes(
        manifest_bytes: &[u8],
        format: &str,
        asset_bytes: &[u8],
    ) -> Result<ManifestStore> {
        let mut validation_log = DetailedStatusTracker::new();
        let store = Store::from_jumbf(manifest_bytes, &mut validation_log)?;

        Store::verify_store(
            &store,
            &mut ClaimAssetData::Bytes(asset_bytes, format),
            &mut validation_log,
        )?;

        Ok(Self::from_store(store, &validation_log))
    }
}

impl Default for ManifestStore {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for ManifestStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut json = serde_json::to_string_pretty(self).unwrap_or_default();

        fn omit_tag(mut json: String, tag: &str) -> String {
            while let Some(index) = json.find(&format!("\"{tag}\": [")) {
                if let Some(idx2) = json[index..].find(']') {
                    json = format!(
                        "{}\"{}\": \"<omitted>\"{}",
                        &json[..index],
                        tag,
                        &json[index + idx2 + 1..]
                    );
                }
            }
            json
        }

        // Make a base64 hash from Vec<u8> values.
        fn b64_tag(mut json: String, tag: &str) -> String {
            while let Some(index) = json.find(&format!("\"{tag}\": [")) {
                if let Some(idx2) = json[index..].find(']') {
                    let idx3 = json[index..].find('[').unwrap_or_default();

                    let bytes: Vec<u8> =
                        serde_json::from_slice(json[index + idx3..index + idx2 + 1].as_bytes())
                            .unwrap_or_default();

                    json = format!(
                        "{}\"{}\": \"{}\"{}",
                        &json[..index],
                        tag,
                        base64::encode(&bytes),
                        &json[index + idx2 + 1..]
                    );
                }
            }

            json
        }

        json = b64_tag(json, "hash");
        json = omit_tag(json, "pad");

        f.write_str(&json)
    }
}

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

    #[cfg(target_arch = "wasm32")]
    use wasm_bindgen_test::*;

    use super::*;
    use crate::{status_tracker::OneShotStatusTracker, utils::test::create_test_store};

    #[cfg(target_arch = "wasm32")]
    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);

    // #[cfg_attr(not(target_arch = "wasm32"), test)]
    // #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    #[test]
    fn manifest_report() {
        let store = create_test_store().expect("creating test store");

        let manifest_store = ManifestStore::from_store(store, &OneShotStatusTracker::new());
        assert!(manifest_store.active_manifest.is_some());
        assert!(!manifest_store.manifests.is_empty());
        let manifest = manifest_store.get_active().unwrap();
        assert!(!manifest.ingredients().is_empty());
        // make sure we have two different ingredients
        assert_eq!(manifest.ingredients()[0].format(), "image/jpeg");
        assert_eq!(manifest.ingredients()[1].format(), "image/png");

        let full_report = manifest_store.to_string();
        assert!(!full_report.is_empty());
        println!("{full_report}");
    }

    #[test]
    #[cfg(feature = "v1_api")]
    fn manifest_report_image() {
        let image_bytes = include_bytes!("../tests/fixtures/CA.jpg");

        let manifest_store = ManifestStore::from_bytes("image/jpeg", image_bytes, true).unwrap();

        assert!(!manifest_store.manifests.is_empty());
        assert!(manifest_store.active_label().is_some());
        assert!(manifest_store.get_active().is_some());
        assert!(!manifest_store.manifests().is_empty());
        assert!(manifest_store.validation_status().is_none());
        let manifest = manifest_store.get_active().unwrap();
        assert!(!manifest.ingredients().is_empty());
        assert_eq!(manifest.issuer().unwrap(), "C2PA Test Signing Cert");
        assert!(manifest.time().is_some());
    }

    #[cfg_attr(not(target_arch = "wasm32"), actix::test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    #[cfg(feature = "v1_api")]
    async fn manifest_report_image_async() {
        let image_bytes = include_bytes!("../tests/fixtures/CA.jpg");

        let manifest_store = ManifestStore::from_bytes_async("image/jpeg", image_bytes, true)
            .await
            .unwrap();

        assert!(!manifest_store.manifests.is_empty());
        assert!(manifest_store.active_label().is_some());
        assert!(manifest_store.get_active().is_some());
        assert!(!manifest_store.manifests().is_empty());
        assert!(manifest_store.validation_status().is_none());
        let manifest = manifest_store.get_active().unwrap();
        assert!(!manifest.ingredients().is_empty());
        assert_eq!(manifest.issuer().unwrap(), "C2PA Test Signing Cert");
        assert!(manifest.time().is_some());
    }

    #[test]
    #[cfg(feature = "file_io")]
    #[cfg(feature = "v1_api")]
    fn manifest_report_from_file() {
        let manifest_store = ManifestStore::from_file("tests/fixtures/CA.jpg").unwrap();
        println!("{manifest_store}");

        assert!(manifest_store.active_label().is_some());
        assert!(manifest_store.get_active().is_some());
        assert!(!manifest_store.manifests().is_empty());
        assert!(manifest_store.validation_status().is_none());
        let manifest = manifest_store.get_active().unwrap();
        assert!(!manifest.ingredients().is_empty());
        assert_eq!(manifest.issuer().unwrap(), "C2PA Test Signing Cert");
        assert!(manifest.time().is_some());
    }

    #[cfg_attr(not(target_arch = "wasm32"), actix::test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    #[cfg(feature = "v1_api")]
    async fn manifest_report_from_manifest_and_asset_bytes_async() {
        let asset_bytes = include_bytes!("../tests/fixtures/cloud.jpg");
        let manifest_bytes = include_bytes!("../tests/fixtures/cloud_manifest.c2pa");

        let manifest_store = ManifestStore::from_manifest_and_asset_bytes_async(
            manifest_bytes,
            "image/jpg",
            asset_bytes,
        )
        .await
        .unwrap();
        assert!(!manifest_store.manifests().is_empty());
        assert!(manifest_store.validation_status().is_none());
        println!("{manifest_store}");
    }

    #[test]
    #[cfg(feature = "file_io")]
    #[cfg(feature = "v1_api")]
    fn manifest_report_from_file_with_resources() {
        let manifest_store = ManifestStore::from_file_with_resources(
            "tests/fixtures/CIE-sig-CA.jpg",
            "../target/ms",
        )
        .expect("from_store_with_resources");
        println!("{manifest_store}");

        assert!(manifest_store.active_label().is_some());
        assert!(manifest_store.get_active().is_some());
        assert!(!manifest_store.manifests().is_empty());
        assert!(manifest_store.validation_status().is_none());
        let manifest = manifest_store.get_active().unwrap();
        assert!(!manifest.ingredients().is_empty());
        assert_eq!(manifest.issuer().unwrap(), "C2PA Test Signing Cert");
        assert!(manifest.time().is_some());
    }

    #[test]
    #[cfg(feature = "v1_api")]
    fn manifest_report_from_stream() {
        let image_bytes: &[u8] = include_bytes!("../tests/fixtures/CA.jpg");
        let stream = std::io::Cursor::new(image_bytes);
        let manifest_store = ManifestStore::from_stream("image/jpeg", stream, true).unwrap();
        println!("{manifest_store}");

        assert!(manifest_store.active_label().is_some());
        assert!(manifest_store.get_active().is_some());
        assert!(!manifest_store.manifests().is_empty());
        assert!(manifest_store.validation_status().is_none());
        let manifest = manifest_store.get_active().unwrap();
        assert!(!manifest.ingredients().is_empty());
        assert_eq!(manifest.issuer().unwrap(), "C2PA Test Signing Cert");
        assert!(manifest.time().is_some());
    }
}