c2pa 0.82.0

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

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

use std::{borrow::Cow, fmt::Debug};

use crate::status_tracker::StatusTracker;

/// Creates a [`LogItem`] struct that is annotated with the source file and line
/// number where the log condition was discovered.
///
/// Takes three parameters, each of which may be a `&'static str` or `String`:
///
/// * `label`: name of object this LogItem references (typically a JUMBF path
///   reference)
/// * `description`: human-readable reason for this `LogItem` to have been
///   generated
/// * `function`: name of the function generating this `LogItem`
///
/// ## Example
///
/// ```
/// # use std::borrow::Cow;
/// # use c2pa::{log_item, status_tracker::{LogKind, LogItem}};
/// let log = log_item!("test1", "test item 1", "test func");
///
/// assert_eq!(
///     log,
///     LogItem {
///         kind: LogKind::Informational,
///         label: Cow::Borrowed("test1"),
///         crate_name: Cow::Borrowed(env!("CARGO_PKG_NAME")),
///         crate_version: Cow::Borrowed(env!("CARGO_PKG_VERSION")),
///         description: Cow::Borrowed("test item 1"),
///         file: Cow::Borrowed(file!()),
///         function: Cow::Borrowed("test func"),
///         line: log.line,
///         ..Default::default()
///     }
/// );
/// #
/// # assert!(log.line > 2);
/// ```
#[macro_export]
#[doc(hidden)]
macro_rules! log_item {
    ($label:expr, $description:expr, $function:expr) => {{
        $crate::status_tracker::LogItem {
            kind: $crate::status_tracker::LogKind::Informational,
            label: $label.into(),
            crate_name: env!("CARGO_PKG_NAME").into(),
            crate_version: env!("CARGO_PKG_VERSION").into(),
            file: file!().into(),
            function: $function.into(),
            line: line!(),
            description: $description.into(),
            ..Default::default()
        }
    }};
}

/// Creates a [`LogItem`] struct that is annotated with the source file and line
/// number where the log condition was discovered.
///
/// Takes two parameters, each of which may be a `&'static str` or `String`:
///
/// * `description`: human-readable reason for this `LogItem` to have been
///   generated
/// * `function`: name of the function generating this `LogItem`
///
/// ## Example
///
/// ```
/// # use c2pa::{log_current_item, status_tracker::{LogKind, LogItem}};
/// let log = log_current_item!("test item 1", "test func");
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! log_current_item {
    ($description:expr, $function:expr) => {{
        $crate::status_tracker::LogItem {
            kind: $crate::status_tracker::LogKind::Informational,
            label: "".to_owned().into(), // will be set to the current status tracker uri
            crate_name: env!("CARGO_PKG_NAME").into(),
            crate_version: env!("CARGO_PKG_VERSION").into(),
            file: file!().into(),
            function: $function.into(),
            line: line!(),
            description: $description.into(),
            ..Default::default()
        }
    }};
}

/// Detailed information about an error or other noteworthy condition.
///
/// Use the [`log_item`](crate::log_item) macro to create a `LogItem`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LogItem {
    /// Kind of log item.
    pub kind: LogKind,

    /// JUBMF label of the item (if available), or other descriptive label
    pub label: Cow<'static, str>,

    /// Description of the error
    pub description: Cow<'static, str>,

    /// Crate where error was detected
    pub crate_name: Cow<'static, str>,

    /// Version of the crate
    pub crate_version: Cow<'static, str>,

    /// Source file where error was detected
    pub file: Cow<'static, str>,

    /// Function where error was detected
    pub function: Cow<'static, str>,

    /// Source line number where error was detected
    pub line: u32,

    /// Error code as string
    pub err_val: Option<Cow<'static, str>>,

    /// C2PA validation status code
    pub validation_status: Option<Cow<'static, str>>,

    /// Ingredient URI (for ingredient-related logs)
    pub ingredient_uri: Option<Cow<'static, str>>,
}

impl Default for LogItem {
    fn default() -> Self {
        LogItem {
            kind: LogKind::Success,
            label: Cow::Borrowed(""),
            description: Cow::Borrowed(""),
            crate_name: env!("CARGO_PKG_NAME").into(),
            crate_version: env!("CARGO_PKG_VERSION").into(),
            file: Cow::Borrowed(""),
            function: Cow::Borrowed(""),
            line: 0,
            err_val: None,
            validation_status: None,
            ingredient_uri: None,
        }
    }
}

impl LogItem {
    /// Add a C2PA validation status code.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::borrow::Cow;
    /// # use c2pa::{log_item, status_tracker::{LogKind, LogItem}};
    /// let log = log_item!("test1", "test item 1", "test func").validation_status("claim.missing");
    ///
    /// assert_eq!(
    ///     log,
    ///     LogItem {
    ///         kind: LogKind::Informational,
    ///         label: Cow::Borrowed("test1"),
    ///         description: Cow::Borrowed("test item 1"),
    ///         crate_name: Cow::Borrowed(env!("CARGO_PKG_NAME")),
    ///         crate_version: Cow::Borrowed(env!("CARGO_PKG_VERSION")),
    ///         file: Cow::Borrowed(file!()),
    ///         function: Cow::Borrowed("test func"),
    ///         line: 7,
    ///         validation_status: Some(Cow::Borrowed("claim.missing")),
    ///         ..Default::default()
    ///     }
    /// );
    /// ```
    #[must_use]
    pub fn validation_status(self, status: &'static str) -> Self {
        LogItem {
            validation_status: Some(status.into()),
            ..self
        }
    }

    /// Add an ingredient URI.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::borrow::Cow;
    /// # use c2pa::{log_item, status_tracker::{LogKind, LogItem}};
    /// let log = log_item!("test1", "test item 1", "test func")
    ///     .set_ingredient_uri("self#jumbf=/c2pa/contentauth:urn:uuid:bef41f24-13aa-4040-8efa-08e5e85c4a00/c2pa.assertions/c2pa.ingredient__1");
    /// ```
    pub fn set_ingredient_uri<S: Into<String>>(self, uri: S) -> Self {
        LogItem {
            ingredient_uri: Some(uri.into().into()),
            ..self
        }
    }

    /// Set the log item kind to [`LogKind::Success`] and add it to the
    /// [`StatusTracker`].
    pub fn success(mut self, tracker: &mut StatusTracker) {
        self.kind = LogKind::Success;
        tracker.add_non_error(self);
    }

    /// Set the log item kind to [`LogKind::Informational`] and add it to the
    /// [`StatusTracker`].
    pub fn informational(mut self, tracker: &mut StatusTracker) {
        self.kind = LogKind::Informational;
        tracker.add_non_error(self);
    }

    /// Set the log item kind to [`LogKind::Failure`] and add it to the
    /// [`StatusTracker`].
    ///
    /// Some implementations are configured to stop immediately on errors. If
    /// so, this function will return `Err(err)`.
    ///
    /// If the implementation is configured to aggregate all log messages, this
    /// function will return `Ok(E)`.  The error value
    /// is available regardless of ErrorBehavior.
    pub fn failure<E: Debug>(mut self, tracker: &mut StatusTracker, err: E) -> Result<E, E> {
        self.kind = LogKind::Failure;
        self.err_val = Some(format!("{err:?}").into());
        tracker.add_error(self, err)
    }

    /// Set the log item kind to [`LogKind::Failure`] and add it to the
    /// [`StatusTracker`].
    ///
    /// Does not return a [`Result`] and thus ignores the [`StatusTracker`]
    /// error-handling configuration.
    pub fn failure_no_throw<E: Debug>(mut self, tracker: &mut StatusTracker, err: E) {
        self.kind = LogKind::Failure;
        self.err_val = Some(format!("{err:?}").into());

        tracker.add_non_error(self);
    }

    /// Set the log item kind to [`LogKind::Failure`] and add it to the
    /// [`StatusTracker`].
    ///
    /// Always return the passed error value.  This allows the error status to
    /// propagate correctly from closures.
    pub fn failure_as_err<E: Debug>(mut self, tracker: &mut StatusTracker, err: E) -> E {
        self.kind = LogKind::Failure;
        self.err_val = Some(format!("{err:?}").into());
        match tracker.add_error(self, err) {
            Ok(e) => e,
            Err(e) => e,
        }
    }
}

/// Descriptive nature of this [`LogItem`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LogKind {
    /// This [`LogItem`] describes a success condition.
    Success,

    /// This [`LogItem`] describes an informational condition.
    Informational,

    /// This [`LogItem`] describes a failure or error condition.
    Failure,
}

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

    use std::borrow::Cow;

    use crate::status_tracker::{LogItem, LogKind, StatusTracker};

    #[test]
    fn r#macro() {
        let log = log_item!("test1", "test item 1", "test func");

        assert_eq!(
            log,
            LogItem {
                kind: LogKind::Informational,
                label: Cow::Borrowed("test1"),
                description: Cow::Borrowed("test item 1"),
                crate_name: env!("CARGO_PKG_NAME").into(),
                crate_version: env!("CARGO_PKG_VERSION").into(),
                file: Cow::Borrowed(file!()),
                function: Cow::Borrowed("test func"),
                line: log.line,
                err_val: None,
                validation_status: None,
                ..Default::default()
            }
        );

        assert!(log.line > 2);
    }

    #[test]
    fn macro_from_string() {
        let desc = "test item 1".to_string();
        let log = log_item!("test1", desc, "test func");

        assert_eq!(
            log,
            LogItem {
                kind: crate::status_tracker::LogKind::Informational,
                label: Cow::Borrowed("test1"),
                description: Cow::Owned("test item 1".to_string()),
                crate_name: env!("CARGO_PKG_NAME").into(),
                crate_version: env!("CARGO_PKG_VERSION").into(),
                file: Cow::Borrowed(file!()),
                function: Cow::Borrowed("test func"),
                line: log.line,
                err_val: None,
                validation_status: None,
                ..Default::default()
            }
        );

        assert!(log.line > 2);
    }

    #[test]
    fn success() {
        let mut tracker = StatusTracker::default();
        log_item!("test1", "test item 1", "test func").success(&mut tracker);

        let log_item = tracker.logged_items().first().unwrap();

        assert_eq!(
            log_item,
            &LogItem {
                kind: LogKind::Success,
                label: Cow::Borrowed("test1"),
                description: Cow::Borrowed("test item 1"),
                crate_name: env!("CARGO_PKG_NAME").into(),
                crate_version: env!("CARGO_PKG_VERSION").into(),
                file: Cow::Borrowed(file!()),
                function: Cow::Borrowed("test func"),
                line: log_item.line,
                err_val: None,
                validation_status: None,
                ingredient_uri: None,
            }
        );
    }

    #[test]
    fn informational() {
        let mut tracker = StatusTracker::default();
        log_item!("test1", "test item 1", "test func").informational(&mut tracker);

        let log_item = tracker.logged_items().first().unwrap();

        assert_eq!(
            log_item,
            &LogItem {
                kind: LogKind::Informational,
                label: Cow::Borrowed("test1"),
                description: Cow::Borrowed("test item 1"),
                crate_name: env!("CARGO_PKG_NAME").into(),
                crate_version: env!("CARGO_PKG_VERSION").into(),
                file: Cow::Borrowed(file!()),
                function: Cow::Borrowed("test func"),
                line: log_item.line,
                err_val: None,
                validation_status: None,
                ..Default::default()
            }
        );
    }

    #[test]
    fn failure() {
        let mut tracker = StatusTracker::default();
        log_item!("test1", "test item 1", "test func")
            .failure(&mut tracker, "sample error message")
            .unwrap();

        let log_item = tracker.logged_items().first().unwrap();

        assert_eq!(
            log_item,
            &LogItem {
                kind: LogKind::Failure,
                label: Cow::Borrowed("test1"),
                description: Cow::Borrowed("test item 1"),
                crate_name: env!("CARGO_PKG_NAME").into(),
                crate_version: env!("CARGO_PKG_VERSION").into(),
                file: Cow::Borrowed(file!()),
                function: Cow::Borrowed("test func"),
                line: log_item.line,
                err_val: Some(Cow::Borrowed("\"sample error message\"")),
                validation_status: None,
                ..Default::default()
            }
        );
    }

    #[test]
    fn failure_no_throw() {
        let mut tracker = StatusTracker::default();
        log_item!("test1", "test item 1", "test func")
            .failure_no_throw(&mut tracker, "sample error message");

        let log_item = tracker.logged_items().first().unwrap();

        assert_eq!(
            log_item,
            &LogItem {
                kind: LogKind::Failure,
                label: Cow::Borrowed("test1"),
                description: Cow::Borrowed("test item 1"),
                crate_name: env!("CARGO_PKG_NAME").into(),
                crate_version: env!("CARGO_PKG_VERSION").into(),
                file: Cow::Borrowed(file!()),
                function: Cow::Borrowed("test func"),
                line: log_item.line,
                err_val: Some(Cow::Borrowed("\"sample error message\"")),
                ..Default::default()
            }
        );
    }

    #[test]
    fn validation_status() {
        let log_item =
            log_item!("test1", "test item 1", "test func").validation_status("claim.missing");

        assert_eq!(
            log_item,
            LogItem {
                kind: LogKind::Informational,
                label: Cow::Borrowed("test1"),
                description: Cow::Borrowed("test item 1"),
                crate_name: env!("CARGO_PKG_NAME").into(),
                crate_version: env!("CARGO_PKG_VERSION").into(),
                file: Cow::Borrowed(file!()),
                function: Cow::Borrowed("test func"),
                line: log_item.line,
                err_val: None,
                validation_status: Some(Cow::Borrowed("claim.missing")),
                ..Default::default()
            }
        );
    }

    #[test]
    fn impl_clone() {
        // Generate coverage for the #[derive(...)] line.
        let li1 = log_item!("test1", "test item 1", "test func");
        let li2 = li1.clone();

        assert_eq!(li1, li2);
    }
}