c2pa 0.79.5

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

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

use std::{
    borrow::Cow,
    collections::HashMap,
    io::{Read, Seek, Write},
};

#[cfg(feature = "json_schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[cfg(feature = "file_io")]
use {
    crate::utils::io_utils::uri_to_path,
    std::{
        fs::{create_dir_all, read, write},
        path::{Path, PathBuf},
    },
};

use crate::{
    assertions::{labels, AssetType, EmbeddedData},
    asset_io::CAIRead,
    claim::Claim,
    error::Error,
    hashed_uri::HashedUri,
    jumbf::labels::{assertion_label_from_uri, to_absolute_uri, DATABOXES},
    maybe_send_sync::MaybeSend,
    utils::mime::format_to_mime,
    Result,
};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "json_schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum UriOrResource {
    ResourceRef(ResourceRef),
    HashedUri(HashedUri),
}
impl UriOrResource {
    pub fn to_hashed_uri(
        &self,
        resources: &ResourceStore,
        claim: &mut Claim,
    ) -> Result<UriOrResource> {
        match self {
            UriOrResource::ResourceRef(r) => {
                let data = resources.get(&r.identifier)?;
                let hash_uri = match claim.version() {
                    1 => claim.add_databox(&r.format, data.to_vec(), None)?,
                    _ => {
                        let icon_assertion = EmbeddedData::new(
                            labels::ICON,
                            format_to_mime(&r.format),
                            data.to_vec(),
                        );
                        claim.add_assertion(&icon_assertion)?
                    }
                };
                Ok(UriOrResource::HashedUri(hash_uri))
            }
            UriOrResource::HashedUri(h) => Ok(UriOrResource::HashedUri(h.clone())),
        }
    }

    pub fn to_resource_ref(
        &self,
        resources: &mut ResourceStore,
        claim: &Claim,
    ) -> Result<UriOrResource> {
        match self {
            UriOrResource::ResourceRef(r) => Ok(UriOrResource::ResourceRef(r.clone())),
            UriOrResource::HashedUri(h) => {
                let (format, data) = if h.url().contains(DATABOXES) {
                    let data_box = claim.get_databox(h).ok_or(Error::MissingDataBox)?;
                    (data_box.format.to_owned(), data_box.data.clone())
                } else {
                    let (label, instance) = Claim::assertion_label_from_link(&h.url());
                    let assertion =
                        claim
                            .get_assertion(&label, instance)
                            .ok_or(Error::AssertionMissing {
                                url: h.url().to_string(),
                            })?;
                    (
                        assertion.content_type().to_string(),
                        assertion.data().to_vec(),
                    )
                };
                let url = to_absolute_uri(claim.label(), &h.url());
                let resource_ref = resources.add_with(&url, &format, data)?;
                Ok(UriOrResource::ResourceRef(resource_ref))
            }
        }
    }
}

impl From<ResourceRef> for UriOrResource {
    fn from(r: ResourceRef) -> Self {
        Self::ResourceRef(r)
    }
}

impl From<HashedUri> for UriOrResource {
    fn from(h: HashedUri) -> Self {
        Self::HashedUri(h)
    }
}

#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[cfg_attr(feature = "json_schema", derive(JsonSchema))]
/// A reference to a resource to be used in JSON serialization.
///
/// The underlying data can be read as a stream via [`Reader::resource_to_stream`][crate::Reader::resource_to_stream].
pub struct ResourceRef {
    /// The mime type of the referenced resource.
    pub format: String,

    /// A URI that identifies the resource as referenced from the manifest.
    ///
    /// This may be a JUMBF URI, a file path, a URL or any other string.
    /// Relative JUMBF URIs will be resolved with the manifest label.
    /// Relative file paths will be resolved with the base path if provided.
    pub identifier: String,

    /// More detailed data types as defined in the C2PA spec.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_types: Option<Vec<AssetType>>,

    /// The algorithm used to hash the resource (if applicable).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alg: Option<String>,

    /// The hash of the resource (if applicable).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
}

impl ResourceRef {
    pub fn new<S: Into<String>, I: Into<String>>(format: S, identifier: I) -> Self {
        Self {
            format: format.into(),
            identifier: identifier.into(),
            data_types: None,
            alg: None,
            hash: None,
        }
    }
}

/// Resource store to contain binary objects referenced from JSON serializable structures
#[derive(Clone, Debug, Serialize)]
#[cfg_attr(feature = "json_schema", derive(JsonSchema))]
#[doc(hidden)]
pub struct ResourceStore {
    resources: HashMap<String, Vec<u8>>,
    #[cfg(feature = "file_io")]
    #[serde(skip_serializing_if = "Option::is_none")]
    base_path: Option<PathBuf>,
    #[serde(skip_serializing_if = "Option::is_none")]
    label: Option<String>,
}

impl ResourceStore {
    /// Create a new resource reference.
    pub fn new() -> Self {
        ResourceStore {
            resources: HashMap::new(),
            #[cfg(feature = "file_io")]
            base_path: None,
            label: None,
        }
    }

    /// Set a manifest label for this store used to resolve relative JUMBF URIs.
    pub fn set_label<S: Into<String>>(&mut self, label: S) -> &Self {
        self.label = Some(label.into());
        self
    }

    #[cfg(feature = "file_io")]
    // Returns the base path for relative file paths if it is set.
    pub fn base_path(&self) -> Option<&Path> {
        self.base_path.as_deref()
    }

    #[cfg(feature = "file_io")]
    /// Sets a base path for relative file paths.
    ///
    /// Identifiers will be interpreted as file paths and resources will be written to files if this is set.
    pub fn set_base_path<P: Into<PathBuf>>(&mut self, base_path: P) {
        self.base_path = Some(base_path.into());
    }

    #[cfg(feature = "file_io")]
    /// Returns and removes the base path.
    pub fn take_base_path(&mut self) -> Option<PathBuf> {
        self.base_path.take()
    }

    /// Generates a unique ID for a given content type (adds a file extension).
    pub fn id_from(&self, key: &str, format: &str) -> String {
        let ext = match format {
            "jpg" | "jpeg" | "image/jpeg" => ".jpg",
            "png" | "image/png" => ".png",
            //make "svg" | "image/svg+xml" => ".svg",
            "c2pa" | "application/x-c2pa-manifest-store" | "application/c2pa" => ".c2pa",
            "ocsp" => ".ocsp",
            _ => "",
        };
        // clean string for possible filesystem use
        let id_base = key.replace(['/', ':'], "-");

        // ensure it is unique in this store
        let mut count = 1;
        let mut id = format!("{id_base}{ext}");
        while self.exists(&id) {
            id = format!("{id_base}-{count}{ext}");
            count += 1;
        }
        id
    }

    /// Adds a resource, generating a [`ResourceRef`] from a key and format.
    ///
    /// The generated identifier may be different from the key.
    pub fn add_with<R>(&mut self, key: &str, format: &str, value: R) -> crate::Result<ResourceRef>
    where
        R: Into<Vec<u8>>,
    {
        let id = self.id_from(key, format);
        self.add(&id, value)?;
        Ok(ResourceRef::new(format, id))
    }

    /// Adds a resource from a URI, generating a [`ResourceRef`].
    ///
    /// The generated identifier may be different from the key.
    pub(crate) fn add_uri<R>(
        &mut self,
        uri: &str,
        format: &str,
        value: R,
    ) -> crate::Result<ResourceRef>
    where
        R: Into<Vec<u8>>,
    {
        #[cfg(feature = "file_io")]
        let mut id = uri.to_string();
        #[cfg(not(feature = "file_io"))]
        let id = uri.to_string();

        // if it isn't jumbf, assume it's an external uri and use it as is
        if id.starts_with("self#jumbf=") {
            #[cfg(feature = "file_io")]
            if self.base_path.is_some() {
                let mut path = uri_to_path(&id, self.label.as_deref());
                // add a file extension if it doesn't have one
                if !(id.ends_with(".jpeg") || id.ends_with(".png")) {
                    if let Some(ext) = crate::utils::mime::format_to_extension(format) {
                        path.set_extension(ext);
                    }
                }
                id = path.display().to_string()
            }
            if !self.exists(&id) {
                self.add(&id, value)?;
            }
        }
        Ok(ResourceRef::new(format, id))
    }

    /// Adds a resource, using a given id value.
    pub fn add<S, R>(&mut self, id: S, value: R) -> crate::Result<&mut Self>
    where
        S: Into<String>,
        R: Into<Vec<u8>>,
    {
        #[cfg(feature = "file_io")]
        if let Some(base) = self.base_path.as_ref() {
            let path = base.join(id.into());
            create_dir_all(path.parent().unwrap_or(Path::new("")))?;
            write(path, value.into())?;
            return Ok(self);
        }
        self.resources.insert(id.into(), value.into());
        Ok(self)
    }

    /// Returns a [`HashMap`] of internal resources.
    pub fn resources(&self) -> &HashMap<String, Vec<u8>> {
        &self.resources
    }

    /// Returns a copy on write reference to the resource if found.
    ///
    /// Returns [`Error::ResourceNotFound`] if it cannot find a resource matching that ID.
    pub fn get(&self, id: &str) -> Result<Cow<'_, Vec<u8>>> {
        #[cfg(feature = "file_io")]
        if !self.resources.contains_key(id) {
            match self.base_path.as_ref() {
                Some(base) => {
                    // read the file, save in Map and then return a reference
                    let path = base.join(id);
                    let value = read(path).map_err(|_| {
                        let path = base.join(id).to_string_lossy().into_owned();
                        Error::ResourceNotFound(path)
                    })?;
                    return Ok(Cow::Owned(value));
                }
                None => return Err(Error::ResourceNotFound(id.to_string())),
            }
        }
        self.resources.get(id).map_or_else(
            || Err(Error::ResourceNotFound(id.to_string())),
            |v| Ok(Cow::Borrowed(v)),
        )
    }

    pub fn write_stream(
        &self,
        id: &str,
        mut stream: impl Write + Read + Seek + MaybeSend,
    ) -> Result<u64> {
        #[cfg(feature = "file_io")]
        if !self.resources.contains_key(id) {
            match self.base_path.as_ref() {
                Some(base) => {
                    // read from, the file to stream
                    let path = base.join(id);
                    let mut file = std::fs::File::open(path)?;
                    return std::io::copy(&mut file, &mut stream).map_err(Error::IoError);
                }
                None => return Err(Error::ResourceNotFound(id.to_string())),
            }
        }
        match self.resources().get(id) {
            Some(data) => {
                stream.write_all(data).map_err(Error::IoError)?;
                Ok(data.len() as u64)
            }
            None => Err(Error::ResourceNotFound(id.to_string())),
        }
    }

    /// Returns `true` if the resource has been added or exists as file.
    pub fn exists(&self, id: &str) -> bool {
        if self.resources.contains_key(id) {
            return true;
        }

        #[cfg(feature = "file_io")]
        if let Some(base) = self.base_path.as_ref() {
            let path = base.join(id);
            return path.exists();
        }

        false
    }

    #[cfg(feature = "file_io")]
    // Returns the full path for an ID.
    pub fn path_for_id(&self, id: &str) -> Option<PathBuf> {
        self.base_path.as_ref().map(|base| base.join(id))
    }
}

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

pub trait ResourceResolver {
    /// Read the data in a [`ResourceRef`][ResourceRef] via a stream.
    fn open(&self, reference: &ResourceRef) -> Result<Box<dyn CAIRead>>;
}

impl ResourceResolver for ResourceStore {
    fn open(&self, reference: &ResourceRef) -> Result<Box<dyn CAIRead>> {
        let data = self.get(&reference.identifier)?.into_owned();
        let cursor = std::io::Cursor::new(data);
        Ok(Box::new(cursor))
    }
}

pub fn mime_from_uri(uri: &str) -> String {
    if let Some(label) = assertion_label_from_uri(uri) {
        if label.starts_with(labels::THUMBNAIL) {
            // https://spec.c2pa.org/specifications/specifications/1.0/specs/C2PA_Specification.html#_thumbnail
            if let Some(ext) = label.rsplit('.').next() {
                return format!("image/{ext}");
            }
        }
    }

    // Unknown binary data.
    String::from("application/octet-stream")
}

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

    use std::io::Cursor;

    use super::*;
    use crate::{
        crypto::raw_signature::SigningAlg, utils::test_signer::test_signer, Builder, Reader,
    };

    #[test]
    fn resource_store() {
        let mut c = ResourceStore::new();
        let value = b"my value";
        c.add("abc123.jpg", value.to_vec()).expect("add");
        let v = c.get("abc123.jpg").unwrap();
        assert_eq!(v.to_vec(), b"my value");
        c.add("cba321.jpg", value.to_vec()).expect("add");
        assert!(c.exists("cba321.jpg"));
        assert!(!c.exists("foo"));

        let json = r#"{
            "claim_generator": "test",
            "format" : "image/jpeg",
            "instance_id": "12345",
            "thumbnail": {
                "format": "image/jpeg",
                "identifier": "abc123"
            },
            "assertions": [
                {
                    "label": "c2pa.actions",
                    "data": {
                        "actions": [
                            {
                                "action": "c2pa.created",
                                "digitalSourceType": "http://c2pa.org/digitalsourcetype/empty"
                            }
                        ]
                    }
                }
            ],
            "ingredients": [{
                "title": "A.jpg",
                "format": "image/jpeg",
                "document_id": "xmp.did:813ee422-9736-4cdc-9be6-4e35ed8e41cb",
                "instance_id": "xmp.iid:813ee422-9736-4cdc-9be6-4e35ed8e41cb",
                "relationship": "parentOf",
                "thumbnail": {
                    "format": "image/jpeg",
                    "identifier": "cba321"
                }
            }]
        }"#;

        let mut builder = Builder::default().with_definition(json).expect("from json");
        builder
            .add_resource("abc123", Cursor::new(value))
            .expect("add_resource");
        builder
            .add_resource("cba321", Cursor::new(value))
            .expect("add_resource");

        let image = include_bytes!("../tests/fixtures/earth_apollo17.jpg");

        let signer = test_signer(SigningAlg::Ps256);

        // Embed a manifest using the signer.
        let mut output_image = Cursor::new(Vec::new());
        builder
            .sign(
                &*signer,
                "image/jpeg",
                &mut Cursor::new(image),
                &mut output_image,
            )
            .expect("sign");

        output_image.set_position(0);
        let reader = Reader::default()
            .with_stream("jpeg", &mut output_image)
            .expect("from_bytes");
        let _json = reader.json();
        println!("{_json}");
    }
}