c2pa 0.91.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
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
// Copyright 2026 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.

//! Structured-text asset handler (C2PA spec A.9): embeds a Manifest Store in a
//! host-format comment line (`-----BEGIN/END C2PA MANIFEST-----`) as a URL
//! reference or `data:` URI. Hashed over raw bytes (no NFC).

use crate::{
    asset_handlers::text_common::{
        self, encode_data_uri, parse_manifest_reference, ManifestReference, BEGIN_DELIMITER,
        END_DELIMITER,
    },
    asset_io::{AssetIO, C2paReader, C2paWriter, ObjectLocations, ReadSeek, ReadWriteSeek},
    error::{Error, Result},
};

#[derive(Clone, Copy)]
enum CommentStyle {
    Line(&'static str),
    Block(&'static str, &'static str),
}

/// A.9.2 excludes `text/html` and `image/svg+xml`, which have their own embedding sections.
static SUPPORTED_TYPES: [&str; 28] = [
    "atom",
    "application/atom+xml",
    "css",
    "text/css",
    "ini",
    "js",
    "mjs",
    "text/javascript",
    "application/javascript",
    "md",
    "markdown",
    "text/markdown",
    "py",
    "text/x-python",
    "rss",
    "application/rss+xml",
    "sql",
    "application/sql",
    "tex",
    "application/x-tex",
    "toml",
    "application/toml",
    "vtt",
    "text/vtt",
    "yaml",
    "yml",
    "application/yaml",
    "text/yaml",
];

const PLACEHOLDER_STORE: &[u8] = b"placeholder manifest";

fn comment_style(asset_type: &str) -> Option<CommentStyle> {
    Some(match asset_type.to_lowercase().as_str() {
        "md"
        | "markdown"
        | "text/markdown"
        | "rss"
        | "application/rss+xml"
        | "atom"
        | "application/atom+xml" => CommentStyle::Block("<!--", "-->"),
        "yaml" | "yml" | "application/yaml" | "text/yaml" | "toml" | "application/toml" | "py"
        | "text/x-python" => CommentStyle::Line("#"),
        "ini" => CommentStyle::Line(";"),
        "js" | "mjs" | "text/javascript" | "application/javascript" => CommentStyle::Line("//"),
        "css" | "text/css" => CommentStyle::Block("/*", "*/"),
        "sql" | "application/sql" => CommentStyle::Line("--"),
        "tex" | "application/x-tex" => CommentStyle::Line("%"),
        "vtt" | "text/vtt" => CommentStyle::Line("NOTE"),
        _ => return None,
    })
}

pub struct StructuredTextIO {
    asset_type: String,
}

/// `[start, end)` is the block's line span (with terminator); `reference` is the
/// text between the delimiters.
struct BlockInfo {
    start: usize,
    end: usize,
    reference: String,
    /// A.9.3.2 multi-line form (delimiters on separate lines), as used in front matter.
    multiline: bool,
}

/// Every manifest block in `text`, in order. A `BEGIN`/`END` pair only counts when the
/// text between the delimiters is a manifest reference (A.9.3): an unterminated `BEGIN`,
/// or a pair wrapping ordinary prose, is content and is skipped rather than treated as a
/// block to read, replace, or strip.
fn find_blocks(text: &str) -> Vec<BlockInfo> {
    let mut blocks = Vec::new();
    let mut search = 0;

    while let Some(rel) = text[search..].find(BEGIN_DELIMITER) {
        let begin = search + rel;
        let after_begin = begin + BEGIN_DELIMITER.len();
        let Some(end_rel) = text[after_begin..].find(END_DELIMITER) else {
            break;
        };
        let end_delim_start = after_begin + end_rel;
        let past_end = end_delim_start + END_DELIMITER.len();
        let reference = text[after_begin..end_delim_start].trim();

        if text_common::is_manifest_reference(reference) {
            let line_start = text[..begin].rfind('\n').map(|i| i + 1).unwrap_or(0);
            let line_end = text[past_end..]
                .find('\n')
                .map(|i| past_end + i + 1)
                .unwrap_or(text.len());
            blocks.push(BlockInfo {
                start: line_start,
                end: line_end,
                reference: reference.to_string(),
                multiline: text[after_begin..end_delim_start].contains('\n'),
            });
        }

        search = past_end;
    }

    blocks
}

fn count_blocks(text: &str) -> usize {
    find_blocks(text).len()
}

fn locate_block(text: &str) -> Option<BlockInfo> {
    find_blocks(text).into_iter().next()
}

fn strip_blocks(text: &str) -> String {
    let blocks = find_blocks(text);
    if blocks.is_empty() {
        return text.to_string();
    }
    let mut out = String::with_capacity(text.len());
    let mut cursor = 0;
    for b in &blocks {
        out.push_str(&text[cursor..b.start]);
        cursor = b.end;
    }
    out.push_str(&text[cursor..]);
    out
}

/// The A.9 exclusion span; an end-of-file block also excludes the preceding newline.
fn exclusion_span(text: &str, block: &BlockInfo) -> (usize, usize) {
    let mut start = block.start;
    if block.end == text.len() && start > 0 {
        let bytes = text.as_bytes();
        if bytes[start - 1] == b'\n' {
            start -= 1;
            if start > 0 && bytes[start - 1] == b'\r' {
                start -= 1;
            }
        }
    }
    (start, block.end - start)
}

fn build_block_line(style: CommentStyle, reference: &str) -> String {
    match style {
        CommentStyle::Line(prefix) => {
            format!("{prefix} {BEGIN_DELIMITER} {reference} {END_DELIMITER}")
        }
        CommentStyle::Block(prefix, suffix) => {
            format!("{prefix} {BEGIN_DELIMITER} {reference} {END_DELIMITER} {suffix}")
        }
    }
}

/// The A.9.3.2 multi-line form used inside front matter: delimiters on their own lines,
/// with no comment prefix, and the reference between them.
fn build_multiline_block(reference: &str, le: &str) -> String {
    format!("{BEGIN_DELIMITER}{le}{reference}{le}{END_DELIMITER}")
}

/// Markdown is the format here with a front matter convention. A leading `---` in YAML or
/// TOML is document syntax rather than front matter, so those keep the comment form.
fn supports_front_matter(lower_asset_type: &str) -> bool {
    matches!(lower_asset_type, "md" | "markdown" | "text/markdown")
}

/// Byte offset just past the opening fence line of a leading front matter section, if the
/// file opens with one and a matching closing fence follows.
fn front_matter_insert_point(text: &str) -> Option<usize> {
    let fence = ["---", "+++"].into_iter().find(|f| text.starts_with(f))?;
    let first_nl = text.find('\n')?;
    if text[..first_nl].trim_end() != fence {
        return None;
    }
    let after_open = first_nl + 1;
    text[after_open..]
        .split_inclusive('\n')
        .any(|line| line.trim_end() == fence)
        .then_some(after_open)
}

/// Inserts the block at the A.9 position: inside leading front matter (A.9.3), else file
/// start, end if the first line is reserved (shebang / XML decl), or after the `WEBVTT`
/// header.
fn insert_block(cleaned: &str, reference: &str, style: CommentStyle, asset_type: &str) -> String {
    let le = if cleaned.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    };
    let lower = asset_type.to_lowercase();

    if supports_front_matter(&lower) {
        if let Some(at) = front_matter_insert_point(cleaned) {
            let block = build_multiline_block(reference, le);
            return format!("{}{block}{le}{}", &cleaned[..at], &cleaned[at..]);
        }
    }

    let block_line = build_block_line(style, reference);

    if lower == "vtt" || lower == "text/vtt" || cleaned.starts_with("WEBVTT") {
        if let Some(nl) = cleaned.find('\n') {
            let (head, rest) = cleaned.split_at(nl + 1);
            let rest = rest.trim_start_matches(['\r', '\n']);
            return format!("{head}{le}{block_line}{le}{le}{rest}");
        }
    }

    let trimmed = cleaned.trim_start();
    if trimmed.starts_with("#!") || trimmed.starts_with("<?xml") {
        let base = cleaned.trim_end_matches(['\r', '\n']);
        return format!("{base}{le}{block_line}");
    }

    format!("{block_line}{le}{cleaned}")
}

impl C2paReader for StructuredTextIO {
    fn read_c2pa(&self, reader: &mut dyn ReadSeek) -> Result<Vec<u8>> {
        let text = text_common::read_text_stream(reader)?;

        // More than one block ⇒ treat as no manifest (A.9).
        if count_blocks(&text) != 1 {
            return Err(Error::JumbfNotFound);
        }

        let block = locate_block(&text).ok_or(Error::JumbfNotFound)?;
        match parse_manifest_reference(&block.reference)? {
            ManifestReference::External => Err(Error::JumbfNotFound),
            ManifestReference::Embedded(bytes) if !bytes.is_empty() => Ok(bytes),
            ManifestReference::Embedded(_) => Err(Error::JumbfNotFound),
        }
    }

    fn read_xmp(&self, _asset_reader: &mut dyn ReadSeek) -> Option<String> {
        None
    }
}

impl C2paWriter for StructuredTextIO {
    fn write_c2pa(
        &self,
        input_stream: &mut dyn ReadSeek,
        output_stream: &mut dyn ReadWriteSeek,
        store_bytes: &[u8],
    ) -> Result<()> {
        let style = comment_style(&self.asset_type).ok_or(Error::UnsupportedType)?;

        let text = text_common::read_text_stream(input_stream)?;
        let reference = encode_data_uri(store_bytes);

        // Replace an existing block in place (preserves offset for update
        // manifests); otherwise insert at the A.9 position.
        let result = if count_blocks(&text) == 1 {
            let b = locate_block(&text).ok_or(Error::EmbeddingError)?;
            let bytes = text.as_bytes();
            let terminator = if b.end >= 2 && &bytes[b.end - 2..b.end] == b"\r\n" {
                "\r\n"
            } else if b.end >= 1 && bytes[b.end - 1] == b'\n' {
                "\n"
            } else {
                ""
            };
            // Keep the form the file already uses, so a front matter block stays multi-line.
            let replacement = if b.multiline {
                let le = if terminator.is_empty() {
                    "\n"
                } else {
                    terminator
                };
                build_multiline_block(&reference, le)
            } else {
                build_block_line(style, &reference)
            };
            let mut out = String::with_capacity(text.len() + replacement.len());
            out.push_str(&text[..b.start]);
            out.push_str(&replacement);
            out.push_str(terminator);
            out.push_str(&text[b.end..]);
            out
        } else {
            insert_block(&strip_blocks(&text), &reference, style, &self.asset_type)
        };

        output_stream.rewind()?;
        output_stream.write_all(result.as_bytes())?;
        Ok(())
    }

    fn get_object_locations(
        &self,
        input_stream: &mut dyn ReadSeek,
    ) -> Result<Vec<ObjectLocations>> {
        let text = text_common::read_text_stream(input_stream)?;

        let (full_len, block_start, block_len) = match locate_block(&text) {
            Some(b) => {
                let (start, len) = exclusion_span(&text, &b);
                (text.len(), start, len)
            }
            None => {
                // No manifest yet: use a placeholder block for the exclusion.
                let style = comment_style(&self.asset_type).ok_or(Error::UnsupportedType)?;
                let reference = encode_data_uri(PLACEHOLDER_STORE);
                let with_block = insert_block(&text, &reference, style, &self.asset_type);
                let b = locate_block(&with_block).ok_or(Error::EmbeddingError)?;
                let (start, len) = exclusion_span(&with_block, &b);
                (with_block.len(), start, len)
            }
        };

        Ok(text_common::hash_positions(
            full_len,
            block_start,
            block_len,
        ))
    }

    fn remove_c2pa(
        &self,
        input_stream: &mut dyn ReadSeek,
        output_stream: &mut dyn ReadWriteSeek,
    ) -> Result<()> {
        let text = text_common::read_text_stream(input_stream)?;
        let cleaned = strip_blocks(&text);
        output_stream.rewind()?;
        output_stream.write_all(cleaned.as_bytes())?;
        Ok(())
    }
}

impl AssetIO for StructuredTextIO {
    fn new(asset_type: &str) -> Self {
        StructuredTextIO {
            asset_type: asset_type.to_string(),
        }
    }

    fn get_handler(&self, asset_type: &str) -> Box<dyn AssetIO> {
        Box::new(StructuredTextIO::new(asset_type))
    }

    fn get_reader(&self) -> &dyn C2paReader {
        self
    }

    fn get_writer(&self, asset_type: &str) -> Option<Box<dyn C2paWriter>> {
        Some(Box::new(StructuredTextIO::new(asset_type)))
    }

    fn supported_types(&self) -> &[&str] {
        &SUPPORTED_TYPES
    }
}

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

    use std::io::Cursor;

    use super::*;
    use crate::asset_io::ObjectType;

    fn embed(asset_type: &str, source: &str, store: &[u8]) -> String {
        let io = StructuredTextIO::new(asset_type);
        let mut input = Cursor::new(source.as_bytes().to_vec());
        let mut output = Cursor::new(Vec::new());
        io.write_c2pa(&mut input, &mut output, store).unwrap();
        String::from_utf8(output.into_inner()).unwrap()
    }

    fn read_back(asset_type: &str, text: &str) -> Result<Vec<u8>> {
        let io = StructuredTextIO::new(asset_type);
        let mut input = Cursor::new(text.as_bytes().to_vec());
        io.read_c2pa(&mut input)
    }

    #[test]
    fn markdown_uses_html_comment_and_round_trips() {
        let store = b"markdown store bytes";
        let out = embed("md", "# Title\n\nBody text.\n", store);
        assert!(out.contains("<!-- -----BEGIN C2PA MANIFEST-----"));
        assert!(out.contains("-----END C2PA MANIFEST----- -->"));
        assert_eq!(read_back("md", &out).unwrap(), store);
    }

    #[test]
    fn yaml_uses_hash_comment() {
        let out = embed("yaml", "key: value\n", b"yaml store");
        assert!(out.starts_with("# -----BEGIN C2PA MANIFEST-----"));
        assert_eq!(read_back("yaml", &out).unwrap(), b"yaml store");
    }

    #[test]
    fn full_range_covers_more_than_md_yaml_toml() {
        for (t, needle) in [
            ("js", "// -----BEGIN"),
            ("css", "/* -----BEGIN"),
            ("sql", "-- -----BEGIN"),
            ("tex", "% -----BEGIN"),
            ("py", "# -----BEGIN"),
        ] {
            let out = embed(t, "content\n", b"store");
            assert!(out.contains(needle), "{t} should use {needle}");
            assert_eq!(read_back(t, &out).unwrap(), b"store");
        }
    }

    #[test]
    fn shebang_forces_block_to_end_of_file() {
        let out = embed("py", "#!/usr/bin/env python\nprint('hi')\n", b"store");
        assert!(out.starts_with("#!/usr/bin/env python"));
        assert!(out.trim_end().ends_with("-----END C2PA MANIFEST-----"));
        assert_eq!(read_back("py", &out).unwrap(), b"store");
    }

    #[test]
    fn end_placed_block_exclusion_starts_at_preceding_newline() {
        let out = embed("py", "#!/usr/bin/env python\nprint('hi')\n", b"store");
        let io = StructuredTextIO::new("py");
        let mut cursor = Cursor::new(out.clone().into_bytes());
        let locations = io.get_object_locations(&mut cursor).unwrap();
        let cai = locations
            .iter()
            .find(|p| p.htype == ObjectType::C2pa)
            .unwrap();
        let excluded =
            &out.as_bytes()[(cai.offset as usize)..(cai.offset as usize) + (cai.length as usize)];
        assert_eq!(
            excluded[0], b'\n',
            "exclusion must begin at the preceding newline"
        );
        assert_eq!(
            (cai.offset as usize) + (cai.length as usize),
            out.len(),
            "exclusion runs to EOF"
        );
        let excluded = std::str::from_utf8(excluded).unwrap();
        assert!(excluded.contains(BEGIN_DELIMITER) && excluded.contains(END_DELIMITER));
    }

    #[test]
    fn webvtt_block_follows_header() {
        let out = embed(
            "vtt",
            "WEBVTT\n\n00:00:00.000 --> 00:00:05.000\nHello.\n",
            b"vtt store",
        );
        assert!(out.starts_with("WEBVTT"));
        assert!(out.contains("NOTE -----BEGIN C2PA MANIFEST-----"));
        assert_eq!(read_back("vtt", &out).unwrap(), b"vtt store");
    }

    #[test]
    fn external_url_reference_is_not_an_embedded_store() {
        let text = "// -----BEGIN C2PA MANIFEST----- https://example.com/a.c2pa -----END C2PA MANIFEST-----\ncode\n";
        assert!(matches!(read_back("js", text), Err(Error::JumbfNotFound)));
    }

    #[test]
    fn multiple_blocks_treated_as_no_manifest() {
        let mut text = embed("yaml", "a: 1\n", b"first");
        text.push_str("# -----BEGIN C2PA MANIFEST----- data:application/c2pa;base64,AAAA -----END C2PA MANIFEST-----\n");
        assert!(matches!(
            read_back("yaml", &text),
            Err(Error::JumbfNotFound)
        ));
    }

    #[test]
    fn replace_and_remove() {
        let first = embed("toml", "a = 1\n", b"first store");
        // Replace.
        let io = StructuredTextIO::new("toml");
        let mut input = Cursor::new(first.into_bytes());
        let mut output = Cursor::new(Vec::new());
        io.write_c2pa(&mut input, &mut output, b"second").unwrap();
        let replaced = String::from_utf8(output.into_inner()).unwrap();
        assert_eq!(count_blocks(&replaced), 1);
        assert_eq!(read_back("toml", &replaced).unwrap(), b"second");

        // Remove.
        let mut input = Cursor::new(replaced.into_bytes());
        let mut output = Cursor::new(Vec::new());
        io.remove_c2pa(&mut input, &mut output).unwrap();
        let removed = String::from_utf8(output.into_inner()).unwrap();
        assert_eq!(removed, "a = 1\n");
    }

    #[test]
    fn replace_preserves_block_offset() {
        // Shebang forces the block to a non-zero end-of-file offset; a same-size
        // store must leave that offset byte-identical (update manifests).
        let first = embed("py", "#!/usr/bin/env python\nprint('x')\n", b"AAAA");
        let offset_before = first.find(BEGIN_DELIMITER).unwrap();

        let io = StructuredTextIO::new("py");
        let mut input = Cursor::new(first.into_bytes());
        let mut output = Cursor::new(Vec::new());
        io.write_c2pa(&mut input, &mut output, b"BBBB").unwrap();
        let replaced = String::from_utf8(output.into_inner()).unwrap();

        assert_eq!(count_blocks(&replaced), 1);
        assert_eq!(
            replaced.find(BEGIN_DELIMITER).unwrap(),
            offset_before,
            "block offset must be preserved on replace (update manifests)"
        );
        assert_eq!(read_back("py", &replaced).unwrap(), b"BBBB");
    }

    #[test]
    fn object_locations_exclude_exactly_the_block() {
        let out = embed("md", "# Doc\n", b"store bytes");
        let io = StructuredTextIO::new("md");
        let mut cursor = Cursor::new(out.clone().into_bytes());
        let locations = io.get_object_locations(&mut cursor).unwrap();
        let cai = locations
            .iter()
            .find(|p| p.htype == ObjectType::C2pa)
            .unwrap();
        let excluded =
            &out.as_bytes()[(cai.offset as usize)..(cai.offset as usize) + (cai.length as usize)];
        let excluded = std::str::from_utf8(excluded).unwrap();
        assert!(excluded.contains(BEGIN_DELIMITER) && excluded.contains(END_DELIMITER));
    }

    /// An unterminated `BEGIN` is not a block (A.9.5 step 4), so a file whose prose
    /// mentions the delimiter stays signable.
    #[test]
    fn unterminated_begin_is_content_not_a_block() {
        let src = format!("# Doc\n\nSee {BEGIN_DELIMITER} for the format.\n");
        let out = embed("md", &src, b"store");
        assert_eq!(read_back("md", &out).unwrap(), b"store");
        assert!(
            out.contains(&format!("See {BEGIN_DELIMITER} for the format.")),
            "the prose line must survive untouched"
        );
    }

    /// A stray `BEGIN` alongside a real block must not make the manifest unreadable.
    #[test]
    fn stray_begin_does_not_hide_the_manifest() {
        let signed = embed("md", "# Doc\n", b"first");
        let with_stray = format!("{signed}stray {BEGIN_DELIMITER} text\n");
        let out = embed("md", &with_stray, b"second");
        assert_eq!(count_blocks(&out), 1);
        assert_eq!(read_back("md", &out).unwrap(), b"second");
    }

    /// Delimiters wrapping prose are not a manifest reference (A.9.3), so embedding
    /// must not overwrite that line.
    #[test]
    fn prose_between_delimiters_is_preserved() {
        let src = format!("# Doc\n\n{BEGIN_DELIMITER} not a reference {END_DELIMITER}\n\ntail\n");
        let out = embed("md", &src, b"store");
        assert!(out.contains("not a reference"), "prose must be preserved");
        assert!(out.contains("tail"));
        assert_eq!(read_back("md", &out).unwrap(), b"store");
    }

    /// A.9.4 requires LF or CRLF preserved byte-exactly; the block must round-trip in a
    /// CRLF file and the exclusion range must cover it exactly.
    #[test]
    fn crlf_file_round_trips() {
        let out = embed("yaml", "a: 1\r\nb: 2\r\n", b"crlf store");
        assert!(out.contains("\r\n"), "CRLF must be preserved");
        assert_eq!(read_back("yaml", &out).unwrap(), b"crlf store");

        let io = StructuredTextIO::new("yaml");
        let mut cursor = Cursor::new(out.clone().into_bytes());
        let locations = io.get_object_locations(&mut cursor).unwrap();
        let cai = locations
            .iter()
            .find(|p| p.htype == ObjectType::C2pa)
            .unwrap();
        let excluded = &out[(cai.offset as usize)..(cai.offset as usize) + (cai.length as usize)];
        assert!(excluded.contains(BEGIN_DELIMITER) && excluded.contains(END_DELIMITER));
        assert!(
            !out[(cai.offset as usize) + (cai.length as usize)..].contains(BEGIN_DELIMITER),
            "exclusion must cover the whole block"
        );
    }

    /// A.9.3: a Markdown file with front matter carries the block inside it, in the
    /// multi-line form, leaving the fences and existing keys intact.
    #[test]
    fn markdown_front_matter_holds_the_block() {
        let src = "---\ntitle: My Document\n---\n\n# Body\n";
        let out = embed("md", src, b"front matter store");

        assert!(out.starts_with("---\n"), "opening fence must stay first");
        assert!(out.contains("title: My Document"));
        assert!(out.contains("# Body"));
        assert_eq!(read_back("md", &out).unwrap(), b"front matter store");

        // Multi-line form: no comment prefix, delimiters on their own lines.
        assert!(out.contains(&format!("\n{BEGIN_DELIMITER}\n")));
        assert!(out.contains(&format!("\n{END_DELIMITER}\n")));
        assert!(
            !out.contains("<!--"),
            "front matter form takes no comment prefix"
        );

        // The block must sit between the fences, not before the opening one.
        let block_at = out.find(BEGIN_DELIMITER).unwrap();
        let closing_fence = out[4..].find("\n---").unwrap() + 4;
        assert!(block_at > 3 && block_at < closing_fence);
    }

    /// A.9.4 NOTE: the front matter delimiters are not part of the exclusion range —
    /// only the lines from BEGIN through END.
    #[test]
    fn front_matter_exclusion_omits_the_fences() {
        let out = embed("md", "---\ntitle: T\n---\n\nbody\n", b"store");
        let io = StructuredTextIO::new("md");
        let mut cursor = Cursor::new(out.clone().into_bytes());
        let locations = io.get_object_locations(&mut cursor).unwrap();
        let cai = locations
            .iter()
            .find(|p| p.htype == ObjectType::C2pa)
            .unwrap();

        let excluded = &out[(cai.offset as usize)..(cai.offset as usize) + (cai.length as usize)];
        assert!(excluded.starts_with(BEGIN_DELIMITER), "got {excluded:?}");
        assert!(excluded.trim_end().ends_with(END_DELIMITER));
        // The fences and the front matter keys stay outside the excluded range.
        assert!(
            out[..(cai.offset as usize)].starts_with("---\n"),
            "opening fence precedes the exclusion"
        );
        assert!(out[(cai.offset as usize) + (cai.length as usize)..].contains("---"));
        assert!(!excluded.contains("title: T"));
    }

    /// Replacing a front matter block keeps the multi-line form and the fences.
    #[test]
    fn front_matter_replace_keeps_form() {
        let first = embed("md", "---\ntitle: T\n---\n\nbody\n", b"AAAA");
        let io = StructuredTextIO::new("md");
        let mut input = Cursor::new(first.clone().into_bytes());
        let mut output = Cursor::new(Vec::new());
        io.write_c2pa(&mut input, &mut output, b"BBBB").unwrap();
        let replaced = String::from_utf8(output.into_inner()).unwrap();

        assert_eq!(count_blocks(&replaced), 1);
        assert_eq!(read_back("md", &replaced).unwrap(), b"BBBB");
        assert!(replaced.contains(&format!("\n{BEGIN_DELIMITER}\n")));
        assert!(!replaced.contains("<!--"));
        assert!(replaced.contains("title: T"));
        assert_eq!(
            replaced.find(BEGIN_DELIMITER),
            first.find(BEGIN_DELIMITER),
            "offset must be preserved on replace"
        );
    }

    /// Markdown without front matter keeps the comment form, and a YAML file's leading
    /// `---` is document syntax rather than front matter.
    #[test]
    fn leading_dashes_only_count_for_markdown_front_matter() {
        let md = embed("md", "# No front matter\n", b"store");
        assert!(md.starts_with("<!-- "), "got {md:?}");

        let yaml = embed("yaml", "---\nkey: value\n", b"store");
        assert!(
            yaml.starts_with("# "),
            "YAML keeps the comment form, got {yaml:?}"
        );
        assert_eq!(read_back("yaml", &yaml).unwrap(), b"store");
    }

    #[test]
    fn external_url_block_is_still_a_block() {
        let text =
            format!("// {BEGIN_DELIMITER} https://example.com/a.c2pa {END_DELIMITER}\ncode\n");
        assert_eq!(count_blocks(&text), 1);
        // Replacing it must not leave a second block behind.
        let out = embed("js", &text, b"store");
        assert_eq!(count_blocks(&out), 1);
        assert_eq!(read_back("js", &out).unwrap(), b"store");
    }
}