encypher-c2pa 1.10.0

Verification-only C2PA 2.4 and CAWG SDK, offline by default
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
// Copyright 2026 Encypher Corporation
// SPDX-License-Identifier: Apache-2.0

//! `redacted_assertions` resolution and enforcement (C2PA 2.4 Validation,
//! "Preparing the list of redacted assertions", Assertion Validation, and
//! Validate the Ingredients; Architecture, "Redaction of Assertions").
//!
//! Redaction is a claim stating that an assertion in an INGREDIENT's manifest
//! was removed from the store. The redacting claim carries the JUMBF URI; the
//! target manifest's assertion store either no longer carries the box or
//! carries an emptied one, while that manifest's own claim still references it.
//!
//! That is a powerful primitive, so the declaration itself is validated:
//!
//! - A claim may not redact its own assertions ("A claim's
//!   `redacted_assertions` field shall never include a JUMBF URI to any of its
//!   own assertions"; "if the URI points into the claim's own manifest, the
//!   claim shall be rejected with a failure code of `assertion.selfRedacted`").
//! - "Claim generators shall not redact assertions with a label of
//!   `c2pa.actions` or `c2pa.actions.v2` as this assertion type represents
//!   essential information in understanding the history of an asset"
//!   (`assertion.action.redacted`).
//! - A hard binding is what ties a manifest to its bytes, and the claim
//!   generator "shall not redact the hard binding to content assertion"
//!   (`assertion.hardBinding.redacted`, which supersedes the deprecated
//!   `assertion.dataHash.redacted`).
//! - "if the referenced assertion is present and any JUMBF Content box or
//!   padding box within it contains anything other than zero or more `0x00`
//!   bytes, the claim shall be rejected with a failure code of
//!   `assertion.notRedacted`".
//!
//! The lineage index selects the claim-signature method independently of the
//! ingredient manifest hash. Declaration legality and signature validation
//! remain separate checks; neither filters the index.
//!
//! A target manifest that is absent from the store is not a defect. When the
//! last reference to an ingredient manifest is redacted, Architecture requires
//! that manifest to be removed from the store, so the dangling URI is the
//! expected outcome rather than something to report.

use super::{
    ValidationResults, ASSERTION_ACTION_REDACTED, ASSERTION_HARD_BINDING_REDACTED,
    ASSERTION_NOT_REDACTED, ASSERTION_SELF_REDACTED, CLAIM_MALFORMED,
};
use crate::c2pa_cbor::Value;
use crate::c2pa_core::jumbf::ParsedManifest;

/// One lineage-wide list, shared by every validation phase. Each target keeps
/// its declarants so an action cannot borrow another claim's declaration.
#[derive(Default)]
pub(super) struct Index {
    targets: std::collections::HashMap<
        String,
        std::collections::BTreeMap<String, std::collections::HashSet<String>>,
    >,
    nonzero: std::collections::HashMap<String, std::collections::HashSet<String>>,
}

impl Index {
    pub(super) fn add_claim(
        &mut self,
        label: &str,
        claim: &Value,
        manifests: &[ParsedManifest<'_>],
    ) {
        let Some(Value::Array(entries)) = claim.get("redacted_assertions") else {
            return;
        };
        for target in entries
            .iter()
            .take(MAX_REDACTED_ASSERTIONS)
            .filter_map(entry_url)
            .filter_map(|url| match read_entry(url, label) {
                Entry::Absolute(target) => Some(target),
                _ => None,
            })
        {
            self.targets
                .entry(target.manifest.to_string())
                .or_default()
                .entry(target.assertion.to_string())
                .or_default()
                .insert(label.to_string());
            if manifests
                .iter()
                .find(|manifest| manifest.label == target.manifest)
                .and_then(|manifest| manifest.assertion_content_is_zeroed(target.assertion))
                == Some(false)
            {
                self.nonzero
                    .entry(target.manifest.to_string())
                    .or_default()
                    .insert(target.assertion.to_string());
            }
        }
    }

    pub(super) fn is_empty(&self) -> bool {
        self.targets.is_empty()
    }

    pub(super) fn names_manifest(&self, manifest: &str) -> bool {
        self.targets.contains_key(manifest)
    }

    pub(super) fn contains(&self, manifest: &str, assertion: &str) -> bool {
        self.targets
            .get(manifest)
            .is_some_and(|targets| targets.contains_key(assertion))
    }

    pub(super) fn declared_by(&self, declarant: &str, url: &str) -> bool {
        let Entry::Absolute(target) = read_entry(url, declarant) else {
            return false;
        };
        self.targets
            .get(target.manifest)
            .and_then(|targets| targets.get(target.assertion))
            .is_some_and(|declarants| declarants.contains(declarant))
    }

    pub(super) fn verify_target(
        &self,
        manifest: &str,
        assertion: &str,
        url: &str,
        results: &mut ValidationResults,
    ) {
        if let Some(code) = non_redactable(assertion) {
            results.push_failure(
                code,
                url.to_string(),
                format!("assertion '{assertion}' may not be redacted"),
            );
        }
        if self
            .nonzero
            .get(manifest)
            .is_some_and(|targets| targets.contains(assertion))
        {
            results.push_failure(
                ASSERTION_NOT_REDACTED,
                url.to_string(),
                "assertion declared redacted still contains non-zero content".into(),
            );
        }
    }

    pub(super) fn verify_manifest(&self, manifest: &str, results: &mut ValidationResults) {
        if let Some(targets) = self.targets.get(manifest) {
            for assertion in targets.keys() {
                let url = format!("self#jumbf=/c2pa/{manifest}/c2pa.assertions/{assertion}");
                self.verify_target(manifest, assertion, &url, results);
            }
        }
    }
}
/// Ceiling on `redacted_assertions` entries examined for one claim. A claim may
/// not declare more assertions than [`super::MAX_CLAIM_ASSERTION_REFERENCES`],
/// and it cannot lawfully redact more assertions than a store can hold.
pub(super) const MAX_REDACTED_ASSERTIONS: usize = 4_096;

/// A parsed `redacted_assertions` entry.
struct Target<'a> {
    manifest: &'a str,
    assertion: &'a str,
}

/// How a `redacted_assertions` entry reads.
enum Entry<'a> {
    /// An absolute URI naming an assertion box in another manifest.
    Absolute(Target<'a>),
    /// A URI that can only mean the declaring manifest's own assertion store.
    SelfScoped,
    /// Not a JUMBF assertion URI at all.
    Malformed,
}

/// Read one `redacted_assertions` entry.
///
/// The lawful form is the ABSOLUTE assertion URI: a redaction names a box in
/// another manifest. A relative `self#jumbf=c2pa.assertions/...` URI can only
/// mean the declaring manifest's own store, which is the self-redaction the
/// spec prohibits rather than something to reinterpret.
fn read_entry<'a>(url: &'a str, declaring_label: &str) -> Entry<'a> {
    let Some(rest) = url.strip_prefix("self#jumbf=") else {
        return Entry::Malformed;
    };
    let Some(absolute) = rest.strip_prefix("/c2pa/") else {
        return match rest.strip_prefix("c2pa.assertions/") {
            Some(assertion) if !assertion.is_empty() && !assertion.contains('/') => {
                Entry::SelfScoped
            }
            _ => Entry::Malformed,
        };
    };
    let Some((manifest, assertion)) = absolute.split_once("/c2pa.assertions/") else {
        return Entry::Malformed;
    };
    if manifest.is_empty() || assertion.is_empty() || assertion.contains('/') {
        return Entry::Malformed;
    }
    if manifest == declaring_label {
        return Entry::SelfScoped;
    }
    Entry::Absolute(Target {
        manifest,
        assertion,
    })
}

/// The failure code for an assertion type that may never be redacted, if any.
fn non_redactable(alabel: &str) -> Option<&'static str> {
    let base = super::refs::base_label(alabel);
    if base == "c2pa.actions" || base == "c2pa.actions.v2" {
        return Some(ASSERTION_ACTION_REDACTED);
    }
    if base.starts_with("c2pa.hash.") {
        return Some(ASSERTION_HARD_BINDING_REDACTED);
    }
    None
}

/// The textual JUMBF URI of a `redacted_assertions` entry.
///
/// A bare text URI is the schema form. A hashed-URI map in the position is
/// tolerated for its `url`, because the entry still identifies exactly one
/// assertion box and refusing to read it would silently drop the redaction.
fn entry_url(entry: &Value) -> Option<&str> {
    entry
        .as_text()
        .or_else(|| entry.get("url").and_then(Value::as_text))
}

/// Validate one claim's `redacted_assertions` field.
///
/// Codes land on the DECLARING manifest's status set: it is that claim which
/// is rejected when a redaction is illegal.
pub(super) fn verify_claim_redactions(
    declaring_label: &str,
    claim: &Value,
    manifests: &[ParsedManifest<'_>],
    results: &mut ValidationResults,
) {
    let Some(Value::Array(entries)) = claim.get("redacted_assertions") else {
        return;
    };
    let claim_url = format!("self#jumbf=/c2pa/{declaring_label}/c2pa.claim.v2");
    if entries.len() > MAX_REDACTED_ASSERTIONS {
        results.push_failure(
            CLAIM_MALFORMED,
            claim_url,
            format!("redacted_assertions count exceeds verifier bound ({MAX_REDACTED_ASSERTIONS})"),
        );
        return;
    }
    for entry in entries {
        let Some(url) = entry_url(entry) else {
            results.push_failure(
                CLAIM_MALFORMED,
                claim_url.clone(),
                "redacted_assertions entry is not a JUMBF URI".into(),
            );
            continue;
        };
        let target = match read_entry(url, declaring_label) {
            Entry::Absolute(target) => target,
            Entry::SelfScoped => {
                results.push_failure(
                    ASSERTION_SELF_REDACTED,
                    claim_url.clone(),
                    format!("claim redacts an assertion of its own manifest: '{url}'"),
                );
                continue;
            }
            Entry::Malformed => {
                results.push_failure(
                    CLAIM_MALFORMED,
                    claim_url.clone(),
                    format!(
                        "redacted_assertions entry '{url}' is not an absolute JUMBF assertion URI"
                    ),
                );
                continue;
            }
        };
        if manifests
            .iter()
            .find(|manifest| manifest.label == target.manifest)
            .and_then(|manifest| manifest.assertion_content_is_zeroed(target.assertion))
            == Some(false)
        {
            results.push_failure(
                ASSERTION_NOT_REDACTED,
                url.to_string(),
                "assertion declared redacted still contains non-zero content".into(),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::c2pa_cbor::{encode, Profile};
    use crate::c2pa_core::jumbf::{assertion_box, redacted_assertion_box, superbox_content};

    const PARENT: &str = "urn:c2pa:parent";
    const CHILD: &str = "urn:c2pa:child";

    fn vmap(fields: Vec<(&str, Value)>) -> Value {
        Value::Map(
            fields
                .into_iter()
                .map(|(key, value)| (Value::Text(key.into()), value))
                .collect(),
        )
    }

    fn claim_redacting(urls: &[String]) -> Value {
        vmap(vec![(
            "redacted_assertions",
            Value::Array(urls.iter().map(|url| Value::Text(url.clone())).collect()),
        )])
    }

    fn uri(manifest: &str, assertion: &str) -> String {
        format!("self#jumbf=/c2pa/{manifest}/c2pa.assertions/{assertion}")
    }

    /// A child manifest whose assertion store carries `boxes`.
    struct Store {
        boxes: Vec<(String, Vec<u8>)>,
    }

    impl Store {
        fn new(entries: Vec<(String, Vec<u8>)>) -> Self {
            Self {
                boxes: entries
                    .into_iter()
                    .map(|(label, raw)| {
                        (
                            label,
                            superbox_content(&raw).expect("superbox content").to_vec(),
                        )
                    })
                    .collect(),
            }
        }

        fn child(&self) -> ParsedManifest<'_> {
            ParsedManifest {
                label: CHILD.into(),
                manifest_jumbf: &[],
                assertions: Vec::new(),
                assertion_jumbf: self
                    .boxes
                    .iter()
                    .map(|(label, bytes)| (label.clone(), bytes.as_slice()))
                    .collect(),
                claim_cbor: None,
                signature_cose: None,
                claim_count: 1,
                claim_box_label: None,
            }
        }
    }

    fn intact(label: &str) -> (String, Vec<u8>) {
        let cbor = encode(
            &vmap(vec![("v", Value::Bytes(vec![1, 2, 3]))]),
            Profile::CanonicalForHashedSubstructures,
        )
        .expect("encode");
        (label.to_string(), assertion_box(label, &cbor, None))
    }

    fn emptied(label: &str) -> (String, Vec<u8>) {
        (label.to_string(), redacted_assertion_box(label, 32))
    }

    fn run(claim: &Value, store: &Store) -> ValidationResults {
        let manifests = [store.child()];
        let mut results = ValidationResults::default();
        verify_claim_redactions(PARENT, claim, &manifests, &mut results);
        let mut index = Index::default();
        index.add_claim(PARENT, claim, &manifests);
        if let Some(targets) = index.targets.get(CHILD) {
            for label in targets.keys() {
                index.verify_target(CHILD, label, &uri(CHILD, label), &mut results);
            }
        }
        results
    }

    /// A claim may not redact an assertion of its own manifest, in either the
    /// absolute or the relative spelling.
    #[test]
    fn self_redaction_is_rejected() {
        let store = Store::new(vec![intact("c2pa.metadata")]);
        for url in [
            uri(PARENT, "c2pa.metadata"),
            "self#jumbf=c2pa.assertions/c2pa.metadata".to_string(),
        ] {
            let results = run(&claim_redacting(&[url.clone()]), &store);
            assert!(
                results.has_failure(ASSERTION_SELF_REDACTED),
                "{url}: {:?}",
                results.failure
            );
        }
    }

    /// An actions assertion and a hard binding may never be redacted; each has
    /// its own registered failure code.
    #[test]
    fn actions_and_hard_bindings_may_not_be_redacted() {
        let store = Store::new(vec![]);
        for (label, code) in [
            ("c2pa.actions", ASSERTION_ACTION_REDACTED),
            ("c2pa.actions.v2__1", ASSERTION_ACTION_REDACTED),
            ("c2pa.hash.data", ASSERTION_HARD_BINDING_REDACTED),
            ("c2pa.hash.bmff.v3", ASSERTION_HARD_BINDING_REDACTED),
        ] {
            let results = run(&claim_redacting(&[uri(CHILD, label)]), &store);
            assert!(results.has_failure(code), "{label}: {:?}", results.failure);
        }
        // An ordinary assertion the store no longer carries is lawful.
        let results = run(&claim_redacting(&[uri(CHILD, "c2pa.metadata")]), &store);
        assert!(results.failure.is_empty(), "{:?}", results.failure);
    }

    /// A declared redaction whose target still carries content is
    /// `assertion.notRedacted`; an emptied-in-place box is lawful.
    #[test]
    fn declared_redaction_must_have_happened() {
        let still_there = Store::new(vec![intact("c2pa.metadata")]);
        let results = run(
            &claim_redacting(&[uri(CHILD, "c2pa.metadata")]),
            &still_there,
        );
        assert!(results.has_failure(ASSERTION_NOT_REDACTED));

        let zeroed = Store::new(vec![emptied("c2pa.metadata")]);
        let results = run(&claim_redacting(&[uri(CHILD, "c2pa.metadata")]), &zeroed);
        assert!(results.failure.is_empty(), "{:?}", results.failure);
    }

    /// An entry that is not a JUMBF assertion URI is a malformed claim.
    #[test]
    fn malformed_entries_are_rejected() {
        let store = Store::new(vec![]);
        for url in [
            "https://example.com/assertion".to_string(),
            format!("self#jumbf=/c2pa/{CHILD}"),
            format!("self#jumbf=/c2pa/{CHILD}/c2pa.assertions/"),
            format!("self#jumbf=/c2pa/{CHILD}/c2pa.signature"),
        ] {
            let results = run(&claim_redacting(&[url.clone()]), &store);
            assert!(
                results.has_failure(CLAIM_MALFORMED),
                "{url}: {:?}",
                results.failure
            );
        }
    }

    /// Method selection uses the lineage list, including prohibited targets.
    #[test]
    fn indexed_redactions_select_the_ingredient_method() {
        for label in ["c2pa.metadata", "c2pa.actions", "c2pa.hash.data"] {
            let mut index = Index::default();
            index.add_claim(PARENT, &claim_redacting(&[uri(CHILD, label)]), &[]);
            assert!(index.names_manifest(CHILD));
            assert!(index.declared_by(PARENT, &uri(CHILD, label)));
        }
        let mut index = Index::default();
        index.add_claim(CHILD, &claim_redacting(&[uri(CHILD, "c2pa.metadata")]), &[]);
        assert!(!index.names_manifest(CHILD));
    }

    /// A self-redaction must reach a consumer's report from the verification
    /// pipeline, in the default (generous) posture.
    #[test]
    fn a_self_redaction_reaches_the_verification_report() {
        use super::super::{
            verify_manifest, CawgTrustInputs, StoreContext, VerifyInput,
            MAX_REPORT_DECODED_VALUE_NODES,
        };
        use crate::c2pa_core::EngineProfile;
        use crate::c2pa_formats::AssetFormat;

        let claim = claim_redacting(&[uri(PARENT, "c2pa.metadata")]);
        let claim_cbor =
            encode(&claim, Profile::CanonicalForHashedSubstructures).expect("encode claim");
        let manifest = ParsedManifest {
            label: PARENT.into(),
            manifest_jumbf: &[],
            assertions: Vec::new(),
            assertion_jumbf: Vec::new(),
            claim_cbor: Some(&claim_cbor),
            signature_cose: None,
            claim_count: 1,
            claim_box_label: Some("c2pa.claim.v2".into()),
        };
        let manifests = [manifest];
        let manifest_hashes = std::collections::HashMap::new();
        let input = VerifyInput {
            data: &[],
            mime: "application/c2pa",
            claim_signer_trust: None,
            tsa_trust: None,
            allowed_certs: None,
            validation_time: None,
            profile: EngineProfile::GENEROUS,
            evidence: Default::default(),
            cawg_strict_encoding: false,
        };
        let mut report_decode_nodes = MAX_REPORT_DECODED_VALUE_NODES;
        let out = verify_manifest(
            &manifests[0],
            StoreContext {
                manifests: &manifests,
                manifest_hashes: &manifest_hashes,
            },
            &input,
            AssetFormat::C2paStore,
            &[],
            None,
            CawgTrustInputs::default(),
            &mut report_decode_nodes,
        );
        assert!(
            out.results.has_failure(ASSERTION_SELF_REDACTED),
            "{:?}",
            out.results.failure
        );
    }
}