encypher-c2pa 1.1.0

Offline, verification-only C2PA SDK
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
// Copyright 2026 Encypher Corporation
// SPDX-License-Identifier: Apache-2.0

//! SVG: JUMBF base64-encoded in a `<c2pa:manifest>` metadata element.
//!
//! SVG has no binary container, so the manifest store is base64-encoded inside
//! a metadata element under the C2PA namespace:
//!
//! ```text
//! <metadata><c2pa:manifest xmlns:c2pa="http://c2pa.org/manifest">BASE64</c2pa:manifest></metadata>
//! ```
//!
//! The element is inserted as the first child of the root `<svg>` element. For
//! robustness when reading third-party SVGs, extraction also falls back to the
//! older `<?c2pa-manifest BASE64?>` processing-instruction convention.

use crate::c2pa_formats::util::base64_decode;
#[cfg(test)]
use crate::c2pa_formats::util::base64_encode;
use crate::c2pa_formats::{AssetFormat, DataHashExclusion, FormatError};

const FMT: AssetFormat = AssetFormat::Svg;
const ELEM_OPEN_TAG: &str = "<c2pa:manifest";
const ELEM_CLOSE: &str = "</c2pa:manifest>";
const PI_OPEN: &str = "<?c2pa-manifest ";
const PI_CLOSE: &str = "?>";
/// The wrapper element `embed` writes around `<c2pa:manifest>`.
const META_OPEN: &str = "<metadata>";
const META_CLOSE: &str = "</metadata>";

fn as_str(data: &[u8]) -> Result<&str, FormatError> {
    std::str::from_utf8(data).map_err(|_| FormatError::InvalidStructure {
        format: FMT,
        detail: "SVG is not valid UTF-8",
    })
}

/// Extract the manifest store from the `<c2pa:manifest>` element, falling back
/// to the `<?c2pa-manifest ?>` processing instruction.
pub(crate) fn extract(data: &[u8]) -> Result<Option<Vec<u8>>, FormatError> {
    let text = as_str(data)?;

    // Primary: <c2pa:manifest ...>BASE64</c2pa:manifest>
    if let Some(open) = text.find(ELEM_OPEN_TAG) {
        // Skip to the end of the open tag ('>').
        let after_open = &text[open + ELEM_OPEN_TAG.len()..];
        if let Some(gt) = after_open.find('>') {
            let body = &after_open[gt + 1..];
            if let Some(close) = body.find(ELEM_CLOSE) {
                let b64 = body[..close].trim();
                let bytes = base64_decode(b64).ok_or(FormatError::InvalidStructure {
                    format: FMT,
                    detail: "invalid base64 in c2pa:manifest element",
                })?;
                return Ok(Some(bytes));
            }
        }
    }

    // Fallback: <?c2pa-manifest BASE64?>
    if let Some(open) = text.find(PI_OPEN) {
        let rest = &text[open + PI_OPEN.len()..];
        let close = rest.find(PI_CLOSE).ok_or(FormatError::InvalidStructure {
            format: FMT,
            detail: "unterminated c2pa PI",
        })?;
        let b64 = rest[..close].trim();
        let bytes = base64_decode(b64).ok_or(FormatError::InvalidStructure {
            format: FMT,
            detail: "invalid base64 in c2pa PI",
        })?;
        return Ok(Some(bytes));
    }

    Ok(None)
}

fn xml_tag_end(text: &str, start: usize) -> Option<usize> {
    let mut quote = None;
    for (offset, character) in text[start..].char_indices() {
        match (quote, character) {
            (Some(expected), actual) if actual == expected => quote = None,
            (None, '"' | '\'') => quote = Some(character),
            (None, '>') => return Some(start + offset + 1),
            _ => {}
        }
    }
    None
}

pub(crate) fn placement_error(data: &[u8]) -> Result<Option<&'static str>, FormatError> {
    let text = as_str(data)?;
    let mut stack: Vec<&str> = Vec::new();
    let mut cursor = 0usize;
    let mut saw_manifest_element = false;
    while let Some(relative) = text[cursor..].find('<') {
        let start = cursor + relative;
        if text[start..].starts_with("<!--") {
            let end = text[start + 4..]
                .find("-->")
                .map(|offset| start + 4 + offset + 3)
                .ok_or(FormatError::InvalidStructure {
                    format: FMT,
                    detail: "unterminated SVG comment",
                })?;
            cursor = end;
            continue;
        }
        if text[start..].starts_with("<?") {
            let end = text[start + 2..]
                .find("?>")
                .map(|offset| start + 2 + offset + 2)
                .ok_or(FormatError::InvalidStructure {
                    format: FMT,
                    detail: "unterminated SVG processing instruction",
                })?;
            cursor = end;
            continue;
        }
        if text[start..].starts_with("<!") {
            cursor = xml_tag_end(text, start + 2).ok_or(FormatError::InvalidStructure {
                format: FMT,
                detail: "unterminated SVG declaration",
            })?;
            continue;
        }

        let closing = text.as_bytes().get(start + 1) == Some(&b'/');
        let name_start = start + if closing { 2 } else { 1 };
        let name_end = text[name_start..]
            .char_indices()
            .find(|(_, character)| {
                !character.is_ascii_alphanumeric() && !matches!(character, ':' | '_' | '-' | '.')
            })
            .map(|(offset, _)| name_start + offset)
            .unwrap_or(text.len());
        if name_end == name_start {
            return Err(FormatError::InvalidStructure {
                format: FMT,
                detail: "SVG contains an empty element name",
            });
        }
        let name = &text[name_start..name_end];
        let end = xml_tag_end(text, name_end).ok_or(FormatError::InvalidStructure {
            format: FMT,
            detail: "unterminated SVG element",
        })?;
        if closing {
            if stack.pop() != Some(name) {
                return Err(FormatError::InvalidStructure {
                    format: FMT,
                    detail: "SVG element nesting is malformed",
                });
            }
        } else {
            if stack.is_empty() && name != "svg" {
                return Err(FormatError::InvalidStructure {
                    format: FMT,
                    detail: "SVG root element is not svg",
                });
            }
            if name == "c2pa:manifest" {
                saw_manifest_element = true;
                if text.find(ELEM_OPEN_TAG) != Some(start) {
                    return Ok(Some(
                        "SVG extractor-selected manifest carrier is not an XML element",
                    ));
                }
                if stack.as_slice() != ["svg", "metadata"] {
                    return Ok(Some("SVG c2pa:manifest is not in root svg metadata"));
                }
            }
            if !text[start..end - 1].trim_end().ends_with('/') {
                stack.push(name);
            }
        }
        cursor = end;
    }
    if !saw_manifest_element && (text.contains(ELEM_OPEN_TAG) || text.contains(PI_OPEN)) {
        return Ok(Some(
            "SVG manifest carrier is not a c2pa:manifest element in root metadata",
        ));
    }
    Ok(None)
}

/// Remove the existing manifest element (or `<?c2pa-manifest ?>` PI
/// fallback), reusing the same span [`exclusions`] computes. A no-op when
/// the asset has no manifest.
#[cfg(test)]
pub(crate) fn strip(asset: &[u8]) -> Result<Vec<u8>, FormatError> {
    let ex = exclusions(asset)?;
    let Some(span) = ex.first() else {
        return Ok(asset.to_vec());
    };
    let mut out = Vec::with_capacity(asset.len());
    out.extend_from_slice(&asset[..span.start]);
    out.extend_from_slice(&asset[span.start + span.length..]);
    Ok(out)
}

/// Insert a `<metadata><c2pa:manifest>` element as the first child of `<svg>`.
///
/// Any existing manifest element is stripped first: prior insertion always
/// landed the new element first in document order, so a first-match reader
/// happened to pick up the fresh manifest, but the stale element was never
/// actually removed (permanent orphan markup, and one insertion-point change
/// away from silently flipping to a stale-wins bug).
#[cfg(test)]
pub(crate) fn embed(asset: &[u8], manifest_store: &[u8]) -> Result<Vec<u8>, FormatError> {
    let clean = strip(asset)?;
    let text = as_str(&clean)?;
    // Find the end of the opening <svg ...> tag.
    let svg_open = text.find("<svg").ok_or(FormatError::InvalidStructure {
        format: FMT,
        detail: "no <svg> root element",
    })?;
    let after_svg = &text[svg_open..];
    let gt = after_svg.find('>').ok_or(FormatError::InvalidStructure {
        format: FMT,
        detail: "unterminated <svg> tag",
    })?;
    let insert_at = svg_open + gt + 1;

    let elem = format!(
        "<metadata><c2pa:manifest xmlns:c2pa=\"http://c2pa.org/manifest\">{}</c2pa:manifest></metadata>",
        base64_encode(manifest_store)
    );
    let mut out = Vec::with_capacity(clean.len() + elem.len());
    out.extend_from_slice(&clean[..insert_at]);
    out.extend_from_slice(elem.as_bytes());
    out.extend_from_slice(&clean[insert_at..]);
    Ok(out)
}

/// The byte span of the embedded manifest element as a single exclusion.
///
/// Covers the same `<c2pa:manifest>` element [`extract`] locates, extended to
/// include the `<metadata>...</metadata>` wrapper [`embed`] writes around it
/// (when present, immediately adjacent). Falls back to the `<?c2pa-manifest ?>`
/// processing instruction. Empty if no manifest is present.
pub(crate) fn exclusions(data: &[u8]) -> Result<Vec<DataHashExclusion>, FormatError> {
    let text = as_str(data)?;

    // Primary: the <c2pa:manifest> element (plus its <metadata> wrapper).
    if let Some(open) = text.find(ELEM_OPEN_TAG) {
        let after_open = &text[open + ELEM_OPEN_TAG.len()..];
        if let Some(gt) = after_open.find('>') {
            let body_start = open + ELEM_OPEN_TAG.len() + gt + 1;
            if let Some(rel_close) = text[body_start..].find(ELEM_CLOSE) {
                let mut start = open;
                let mut end = body_start + rel_close + ELEM_CLOSE.len();
                // Absorb the wrapper iff it is immediately adjacent (as `embed` writes it).
                if text[..start].ends_with(META_OPEN) {
                    start -= META_OPEN.len();
                }
                if text[end..].starts_with(META_CLOSE) {
                    end += META_CLOSE.len();
                }
                return Ok(vec![DataHashExclusion {
                    start,
                    length: end - start,
                }]);
            }
        }
    }

    // Fallback: the <?c2pa-manifest ?> processing instruction.
    if let Some(open) = text.find(PI_OPEN) {
        let rest = &text[open + PI_OPEN.len()..];
        let close = rest.find(PI_CLOSE).ok_or(FormatError::InvalidStructure {
            format: FMT,
            detail: "unterminated c2pa PI",
        })?;
        let end = open + PI_OPEN.len() + close + PI_CLOSE.len();
        return Ok(vec![DataHashExclusion {
            start: open,
            length: end - open,
        }]);
    }

    Ok(Vec::new())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::c2pa_formats::tests::dummy_manifest_store;

    fn tiny_svg() -> Vec<u8> {
        br#"<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>"#
            .to_vec()
    }

    #[test]
    fn roundtrip() {
        let store = dummy_manifest_store();
        let embedded = embed(&tiny_svg(), &store).unwrap();
        assert_eq!(
            extract(&embedded).unwrap().as_deref(),
            Some(store.as_slice())
        );
    }

    #[test]
    fn re_embed_replaces_manifest() {
        let first_store = dummy_manifest_store();
        let second_assertion =
            crate::c2pa_core::jumbf::assertion_box("c2pa.actions.v2", &[0xa0], None);
        let second_manifest = crate::c2pa_core::jumbf::build_manifest(
            "urn:c2pa:test:0002",
            &[second_assertion],
            &[0xa0],
            &[0xd2, 0x84],
        );
        let second_store = crate::c2pa_core::jumbf::build_manifest_store(&[second_manifest]);
        assert_ne!(first_store, second_store, "fixture stores must differ");

        let first = embed(&tiny_svg(), &first_store).unwrap();
        let second = embed(&first, &second_store).unwrap();
        assert_eq!(
            extract(&second).unwrap().as_deref(),
            Some(second_store.as_slice())
        );
        let text = std::str::from_utf8(&second).unwrap();
        let occurrences = text.matches(ELEM_OPEN_TAG).count();
        assert_eq!(
            occurrences, 1,
            "re-embed must leave exactly one c2pa:manifest element"
        );
    }

    #[test]
    fn manifest_element_is_svg_child() {
        let store = dummy_manifest_store();
        let embedded = embed(&tiny_svg(), &store).unwrap();
        let text = std::str::from_utf8(&embedded).unwrap();
        assert!(text.find("<svg").unwrap() < text.find(ELEM_OPEN_TAG).unwrap());
        assert!(text.contains("</c2pa:manifest></metadata>"));
    }

    #[test]
    fn extracts_live_style_element() {
        // Mirrors the live pipeline's exact element shape.
        let store = dummy_manifest_store();
        let b64 = base64_encode(&store);
        let svg = format!(
            "<svg xmlns=\"http://www.w3.org/2000/svg\"><metadata><c2pa:manifest xmlns:c2pa=\"http://c2pa.org/manifest\">{b64}</c2pa:manifest></metadata></svg>"
        );
        assert_eq!(
            extract(svg.as_bytes()).unwrap().as_deref(),
            Some(store.as_slice())
        );
        assert_eq!(placement_error(svg.as_bytes()).unwrap(), None);
    }

    #[test]
    fn roundtrip_no_xml_decl() {
        let store = dummy_manifest_store();
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>".to_vec();
        let embedded = embed(&svg, &store).unwrap();
        assert_eq!(
            extract(&embedded).unwrap().as_deref(),
            Some(store.as_slice())
        );
    }

    #[test]
    fn bare_asset_has_no_manifest() {
        assert_eq!(extract(&tiny_svg()).unwrap(), None);
    }

    #[test]
    fn base64_roundtrips_arbitrary_bytes() {
        for n in 0..32usize {
            let data: Vec<u8> = (0..n).map(|i| (i * 7 + 3) as u8).collect();
            let enc = base64_encode(&data);
            assert_eq!(base64_decode(&enc).unwrap(), data, "len {n}");
        }
    }

    #[test]
    fn exclusions_cover_manifest_element() {
        let store = dummy_manifest_store();
        let asset = tiny_svg();
        let embedded = embed(&asset, &store).unwrap();
        let ex = exclusions(&embedded).unwrap();
        assert_eq!(ex.len(), 1);
        let DataHashExclusion { start, length } = ex[0];
        let span = &embedded[start..start + length];
        // The span is exactly the inserted <metadata>...</metadata> element.
        assert!(span.starts_with(b"<metadata><c2pa:manifest"));
        assert!(span.ends_with(b"</c2pa:manifest></metadata>"));
        // Deleting the span restores the original asset byte-for-byte.
        let mut rebuilt = embedded[..start].to_vec();
        rebuilt.extend_from_slice(&embedded[start + length..]);
        assert_eq!(rebuilt, asset);
    }

    #[test]
    fn exclusions_pi_fallback() {
        let store = dummy_manifest_store();
        let b64 = base64_encode(&store);
        let svg = format!("<svg><?c2pa-manifest {b64}?></svg>");
        let ex = exclusions(svg.as_bytes()).unwrap();
        assert_eq!(ex.len(), 1);
        let DataHashExclusion { start, length } = ex[0];
        let span = &svg.as_bytes()[start..start + length];
        assert!(span.starts_with(b"<?c2pa-manifest "));
        assert!(span.ends_with(b"?>"));
    }

    #[test]
    fn strict_placement_requires_root_metadata_parent() {
        let b64 = base64_encode(&dummy_manifest_store());
        let svg = format!(
            "<svg xmlns=\"http://www.w3.org/2000/svg\"><g><metadata><c2pa:manifest>{b64}</c2pa:manifest></metadata></g></svg>"
        );
        assert!(placement_error(svg.as_bytes()).unwrap().is_some());
    }

    #[test]
    fn exclusions_empty_without_manifest() {
        assert!(exclusions(&tiny_svg()).unwrap().is_empty());
    }
}