c2pa 0.91.3

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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
// 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.

// TODO: Remove this after we finish the PDF write feature.
#![allow(dead_code)]

use std::io::{Read, Write};

use lopdf::{
    dictionary, Document, LoadOptions, Object,
    Object::{Array, Name, Reference},
    ObjectId, Stream,
};
use thiserror::Error;

// Associated File Relationship
static AF_RELATIONSHIP_KEY: &[u8] = b"AFRelationship";
static ANNOTATIONS_KEY: &[u8] = b"Annots";
static ASSOCIATED_FILE_KEY: &[u8] = b"AF";
static C2PA_RELATIONSHIP: &[u8] = b"C2PA_Manifest";
static CONTENT_CREDS: &str = "Content Credentials";
static EMBEDDED_FILES_KEY: &[u8] = b"EmbeddedFiles";
static METADATA_KEY: &[u8] = b"Metadata";
static SUBTYPE_KEY: &[u8] = b"Subtype";
static TYPE_KEY: &[u8] = b"Type";
static NAMES_KEY: &[u8] = b"Names";

const MAX_PDF_DECOMPRESSED_SIZE: usize = 64 * 1024 * 1024;

/// Error representing failure scenarios while interacting with PDFs.
#[derive(Debug, Error)]
pub enum Error {
    /// Error occurred while reading the PDF. Look into the wrapped `lopdf::Error` for more
    /// information on the cause.
    #[error(transparent)]
    UnableToReadPdf(#[from] lopdf::Error),

    /// No Manifest is present in the PDF.
    #[error("No manifest is present in the PDF.")]
    NoManifest,

    /// Error occurred while adding a C2PA manifest as an `Annotation` to the PDF.
    #[error("Unable to add C2PA manifest as an annotation to the PDF.")]
    AddingAnnotation,

    // The PDF has an `AFRelationship` set to C2PA, but we were unable to find
    // the manifest bytes in the PDF's embedded files.
    #[error("Unable to find C2PA manifest in the PDF's embedded files.")]
    UnableToFindEmbeddedFileManifest,

    /// This error occurs when we an error was encountered trying to find the PDF's C2PA embedded
    /// file specification in the array of Associated Files defined in the catalog.
    #[error("Unable to find a C2PA embedded file specification in PDF's associated files array")]
    FindingC2PAFileSpec,

    /// A manifest is present, but its object is recorded via a compressed xref
    /// entry (stored inside an `/ObjStm`), which carries no byte offset in the
    /// outer file — its raw byte range can't be located this way.
    #[error("C2PA manifest object is stored in a compressed xref entry; its byte range can't be determined")]
    ManifestObjectNotByteAddressable,
}

/// MIME subtype for a C2PA Manifest Store's embedded file specification, per
/// C2PA spec §A.4.1: "The embedded file specification dictionary shall have
/// a Subtype key whose value is `application/c2pa`".
const C2PA_MIME_TYPE: &str = "application/c2pa";

#[cfg_attr(test, mockall::automock)]
pub(crate) trait C2paPdf: Sized {
    /// Save the `C2paPdf` implementation to the provided `writer`.
    fn save_to<W: Write + 'static>(&mut self, writer: &mut W) -> Result<(), std::io::Error>;

    /// Returns `true` if the `PDF` is password protected, `false` otherwise.
    fn is_password_protected(&self) -> bool;

    /// Returns `true` if this PDF has C2PA Manifests, `false` otherwise.
    fn has_c2pa_manifest(&self) -> bool;

    /// Writes provided `bytes` as a PDF `Embedded File`
    fn write_manifest_as_embedded_file(&mut self, bytes: Vec<u8>) -> Result<(), Error>;

    /// Writes provided `bytes` as a PDF `Annotation`.
    fn write_manifest_as_annotation(&mut self, vec: Vec<u8>) -> Result<(), Error>;

    /// Returns a reference to the C2PA manifest bytes.
    #[allow(clippy::needless_lifetimes)] // required for automock::mockall
    fn read_manifest_bytes<'a>(&'a self) -> Result<Option<Vec<&'a [u8]>>, Error>;

    fn remove_manifest_bytes(&mut self) -> Result<(), Error>;

    fn read_xmp(&self) -> Option<String>;

    /// Writes `xmp` as the PDF's XML metadata stream (the `/Metadata` entry
    /// on the document's `/Catalog`), creating that entry if none exists, or
    /// replacing an existing one's content otherwise.
    fn write_xmp(&mut self, xmp: String) -> Result<(), Error>;

    /// Returns the byte offset of the `N G obj` declaration for the C2PA
    /// manifest's embedded-file stream, as recorded in this document's xref
    /// table.
    ///
    /// Returns `Ok(None)` if no manifest is present at all. Returns
    /// [`Error::ManifestObjectNotByteAddressable`] if a manifest is present
    /// but its object is recorded via a compressed xref entry (inside an
    /// `/ObjStm`), which has no byte offset in the outer file — callers must
    /// not treat that case as "no manifest".
    ///
    /// Callers must parse the exact same bytes that produced this `C2paPdf`
    /// (e.g. via [`Pdf::from_bytes`]) for the offset to be meaningful.
    fn manifest_object_offset(&self) -> Result<Option<u64>, Error>;
}

pub(crate) struct Pdf {
    document: Document,
}

impl C2paPdf for Pdf {
    /// Saves the in-memory PDF to the provided `writer`.
    fn save_to<W: Write>(&mut self, writer: &mut W) -> Result<(), std::io::Error> {
        self.document.save_to(writer)
    }

    fn is_password_protected(&self) -> bool {
        self.document.is_encrypted()
    }

    /// Determines if this PDF has a C2PA manifest embedded.
    ///
    /// This is done by checking if the Associated File key of the catalog points to a
    /// [Object::Dictionary] with an `AFRelationship` set to `C2PA_Manifest`.
    fn has_c2pa_manifest(&self) -> bool {
        self.c2pa_file_spec_object_id().is_some()
    }

    /// Writes the provided `bytes` to the PDF as an `EmbeddedFile`.
    fn write_manifest_as_embedded_file(&mut self, bytes: Vec<u8>) -> Result<(), Error> {
        // Add `FileStream` and `FileSpec` to the PDF.
        let file_stream_ref = self.add_c2pa_embedded_file_stream(bytes);
        let file_spec_ref = self.add_embedded_file_specification(file_stream_ref);

        self.push_associated_file(file_spec_ref)?;

        let mut manifest_name_file_pair = vec![
            Object::string_literal(CONTENT_CREDS),
            Reference(file_spec_ref),
        ];

        let Ok(catalog_names) = self.document.catalog_mut()?.get_mut(NAMES_KEY) else {
            // No /Names key exists in the Catalog. We can safely add the /Names key and construct
            // the remaining objects.
            // Add /EmbeddedFiles dictionary as indirect object.
            let embedded_files_ref = self.document.add_object(dictionary! {
                NAMES_KEY => manifest_name_file_pair
            });

            // Add /Names dictionary as indirect object
            let names_ref = self.document.add_object(dictionary! {
                EMBEDDED_FILES_KEY => Reference(embedded_files_ref)
            });

            // Set /Names key in `Catalog` to reference above indirect object names dictionary.
            self.document.catalog_mut()?.set(NAMES_KEY, names_ref);
            return Ok(());
        };

        // Follows the Reference to the /EmbeddedFiles Dictionary, if the Object is a Reference.
        let names_dictionary = match catalog_names.as_reference() {
            Ok(object_id) => self.document.get_object_mut(object_id)?.as_dict_mut()?,
            _ => catalog_names.as_dict_mut()?,
        };

        let Ok(embedded_files) = names_dictionary.get_mut(EMBEDDED_FILES_KEY) else {
            // We have a /Names dictionary, but are missing the /EmbeddedFiles dictionary
            // and its /Names array of embedded files.
            names_dictionary.set(
                EMBEDDED_FILES_KEY,
                dictionary! { NAMES_KEY => manifest_name_file_pair },
            );
            return Ok(());
        };

        // Follows the reference to the /EmbeddedFiles Dictionary, if the Object is a Reference.
        let embedded_files_dictionary = match embedded_files.as_reference() {
            Ok(object_id) => self.document.get_object_mut(object_id)?.as_dict_mut()?,
            _ => embedded_files.as_dict_mut()?,
        };

        let Ok(names) = embedded_files_dictionary.get_mut(NAMES_KEY) else {
            // This PDF has the /Names dictionary, and it has the /EmbeddedFiles
            // dictionary, but the /EmbeddedFiles Dictionary is missing the /Names Array.
            embedded_files_dictionary.set(
                NAMES_KEY,
                dictionary! { NAMES_KEY => manifest_name_file_pair },
            );

            return Ok(());
        };

        // Follows the reference to the /Names Array, if the Object is a Reference.
        let names_array = match names.as_reference() {
            Ok(object_id) => self.document.get_object_mut(object_id)?.as_array_mut()?,
            _ => names.as_array_mut()?,
        };

        // The PDF has the /Names dictionary, which contains the /EmbeddedFiles Dictionary, which
        // contains the /Names array. Append the manifest's name (Content Credentials)
        // and its reference.
        names_array.append(&mut manifest_name_file_pair);

        Ok(())
    }

    /// Writes the provided bytes to the PDF as a `FileAttachment` `Annotation`. This `Annotation`
    /// is added to the first page of the `PDF`, to the lower left corner.
    fn write_manifest_as_annotation(&mut self, bytes: Vec<u8>) -> Result<(), Error> {
        let file_stream_reference = self.add_c2pa_embedded_file_stream(bytes);
        let file_spec_reference = self.add_embedded_file_specification(file_stream_reference);

        self.push_associated_file(file_spec_reference)?;
        self.add_file_attachment_annotation(file_spec_reference)?;

        Ok(())
    }

    /// Gets a reference to the `C2PA` manifest bytes of the PDF.
    ///
    /// This method will read the bytes of the manifest, whether the manifest was added to the
    /// PDF via an `Annotation` or an `EmbeddedFile`.
    ///
    /// Returns an `Ok(None)` if no manifest is present. Returns a `Ok(Some(Vec<&[u8]>))` when a manifest
    /// is present.
    ///
    /// ### Note:
    ///
    /// A `Vec<&[u8]>` is returned because it's possible for a PDF's manifests to be stored
    /// separately, due to PDF's "Incremental Update" feature. See the spec for more details:
    /// [embedding_manifests_into_pdfs - C2PA Technical Specification](https://spec.c2pa.org/specifications/specifications/1.3/specs/C2PA_Specification.html#_embedding_manifests_into_pdfs)
    fn read_manifest_bytes(&self) -> Result<Option<Vec<&[u8]>>, Error> {
        let Some(id) = self.c2pa_file_spec_object_id() else {
            return Ok(None);
        };

        let ef = &self
            .document
            .get_object(id)
            .and_then(Object::as_dict)?
            .get_deref(b"EF", &self.document)?
            .as_dict()?; // EF dictionary

        Ok(Some(vec![
            &ef.get_deref(b"F", &self.document)? // F embedded file stream
                .as_stream()?
                .content,
        ]))
    }

    fn remove_manifest_bytes(&mut self) -> Result<(), Error> {
        if !self.has_c2pa_manifest() {
            return Err(Error::NoManifest);
        }

        // Find the File Spec, which contains the reference to the manifest.
        let file_spec_ref = self.c2pa_file_spec_object_id().ok_or(Error::NoManifest)?;

        // Find the manifest's file stream.
        let file_stream_ef_ref = self
            .document
            .get_object(file_spec_ref)?
            .as_dict()?
            .get(b"EF")?;

        let file_stream_ref = file_stream_ef_ref.as_dict()?.get(b"F")?.as_reference()?;

        // Attempt to remove the manifest from the PDF's `Embedded Files`s. If the manifest
        // isn't in the PDF's embedded files, remove the manifest from the PDF's annotations.
        //
        // We do the operation in this order because a PDF's annotations are attached to a page.
        // It's possible we'd have to iterate over every page of the PDF before determining the
        // manifest is referenced from an Embedded File instead.
        self.remove_manifest_from_embedded_files()
            .or_else(|_| self.remove_manifest_from_annotations())?;

        // Remove C2PA associated files from the `AF` key in the catalog.
        self.remove_c2pa_file_spec_reference()?;

        // Delete the manifest and its descriptor from the PDF
        self.document.delete_object(file_stream_ref);
        self.document.delete_object(file_spec_ref);

        Ok(())
    }

    /// Reads the `Metadata` field referenced in the PDF document's `Catalog` entry. Will return
    /// `None` if no Metadata is present.
    fn read_xmp(&self) -> Option<String> {
        self.document
            .catalog()
            .and_then(|catalog| catalog.get_deref(b"Metadata", &self.document))
            .and_then(Object::as_stream)
            .ok()
            .and_then(|stream_dict| {
                let Ok(subtype_bytes) = stream_dict
                    .dict
                    .get_deref(SUBTYPE_KEY, &self.document)
                    .and_then(Object::as_name)
                else {
                    return None;
                };
                let subtype_str = str::from_utf8(subtype_bytes).ok()?;

                if subtype_str.to_lowercase() != "xml" {
                    return None;
                }

                String::from_utf8(stream_dict.content.clone()).ok()
            })
    }

    /// Writes `xmp` as the PDF's XML metadata stream.
    ///
    /// If `/Metadata` on the Catalog is already an indirect reference, replaces
    /// the referenced object in place with a fresh `/Type /Metadata /Subtype
    /// /XML` stream holding `xmp` — any other keys the previous object carried
    /// are discarded, since none are meaningful for a stream this method didn't
    /// itself create. Otherwise (no `/Metadata` entry at all, or one that isn't
    /// a reference — e.g. a malformed direct value) adds a new indirect stream
    /// object and points `/Metadata` at it.
    ///
    /// A stream is never written as a *direct* dictionary value: PDF syntax
    /// only allows `stream`/`endstream` immediately after a top-level `N G
    /// obj` declaration, so overwriting a non-reference `/Metadata` value
    /// in place with a `Stream` object would serialize as invalid PDF.
    fn write_xmp(&mut self, xmp: String) -> Result<(), Error> {
        let stream = Object::Stream(Stream::new(
            dictionary! {
                TYPE_KEY => Name("Metadata".into()),
                SUBTYPE_KEY => Name("XML".into()),
            },
            xmp.into_bytes(),
        ));

        let existing_reference = self
            .document
            .catalog()?
            .get(METADATA_KEY)
            .ok()
            .and_then(|object| object.as_reference().ok());

        match existing_reference {
            Some(object_id) => *self.document.get_object_mut(object_id)? = stream,
            None => {
                let metadata_ref = self.document.add_object(stream);
                self.document
                    .catalog_mut()?
                    .set(METADATA_KEY, Reference(metadata_ref));
            }
        }

        Ok(())
    }

    fn manifest_object_offset(&self) -> Result<Option<u64>, Error> {
        let Some((id, _generation)) = self.c2pa_manifest_stream_object_id() else {
            return Ok(None);
        };

        match self.document.reference_table.get(id) {
            Some(lopdf::xref::XrefEntry::Normal { offset, .. }) => Ok(Some(*offset as u64)),
            Some(lopdf::xref::XrefEntry::Compressed { .. }) => {
                Err(Error::ManifestObjectNotByteAddressable)
            }
            // Free/UnusableFree/missing: the manifest dict traversal found the
            // object, but the xref table disagrees it exists — treat this as
            // unlocatable rather than silently reporting no manifest.
            _ => Err(Error::ManifestObjectNotByteAddressable),
        }
    }
}

impl Pdf {
    #[allow(dead_code)]
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        let document = Document::load_mem_with_options(
            bytes,
            LoadOptions {
                max_decompressed_size: Some(MAX_PDF_DECOMPRESSED_SIZE),
                ..Default::default()
            },
        )?;
        Ok(Self { document })
    }

    pub fn from_reader<R: Read>(source: R) -> Result<Self, Error> {
        let document = Document::load_from_with_options(
            source,
            LoadOptions {
                max_decompressed_size: Some(MAX_PDF_DECOMPRESSED_SIZE),
                ..Default::default()
            },
        )?;
        Ok(Self { document })
    }

    /// Returns a reference to the Associated Files array from the PDF's Catalog.
    fn associated_files(&self) -> Result<&Vec<Object>, Error> {
        Ok(self
            .document
            .catalog()?
            .get_deref(ASSOCIATED_FILE_KEY, &self.document)?
            .as_array()?)
    }

    /// Returns the [ObjectId] of the C2PA manifest's embedded-file stream object, if a
    /// manifest is present.
    fn c2pa_manifest_stream_object_id(&self) -> Option<ObjectId> {
        let file_spec_ref = self.c2pa_file_spec_object_id()?;

        self.document
            .get_object(file_spec_ref)
            .ok()?
            .as_dict()
            .ok()?
            .get(b"EF")
            .ok()?
            .as_dict()
            .ok()?
            .get(b"F")
            .ok()?
            .as_reference()
            .ok()
    }

    /// Returns the [Object::ObjectId] of the C2PA File Spec Reference, if it is present in the
    /// PDF's associated files array.
    fn c2pa_file_spec_object_id(&self) -> Option<ObjectId> {
        self.associated_files().ok()?.iter().find_map(|value| {
            let Ok(reference) = value.as_reference() else {
                return None;
            };

            let name = self
                .document
                .get_object(reference)
                .and_then(Object::as_dict)
                .and_then(|dict| dict.get_deref(AF_RELATIONSHIP_KEY, &self.document))
                .and_then(Object::as_name)
                .ok()?;

            (name == C2PA_RELATIONSHIP).then_some(reference)
        })
    }

    /// Removes the C2PA File Spec Reference if it exists in the Associated Files [Object::Array] of
    /// PDF's catalog. This will return an [Err] if the PDF doesn't contain a C2PA File Spec
    /// Reference.
    fn remove_c2pa_file_spec_reference(&mut self) -> Result<(), Error> {
        let c2pa_file_spec_reference = self
            .c2pa_file_spec_object_id()
            .ok_or(Error::FindingC2PAFileSpec)?;

        self.document
            .catalog_mut()?
            .get_mut(ASSOCIATED_FILE_KEY)?
            .as_array_mut()?
            .retain(|v| {
                let Ok(reference) = v.as_reference() else {
                    return true;
                };

                reference != c2pa_file_spec_reference
            });

        Ok(())
    }

    /// Adds the C2PA `Annotation` to the PDF.
    ///
    /// ### Note:
    /// The `FileAttachment` annotation is added to the first page of the PDF in the lower
    /// left-hand corner. The `FileAttachment`'s location is not defined in the spec as of version
    /// `1.3`.
    fn add_file_attachment_annotation(
        &mut self,
        file_spec_reference: ObjectId,
    ) -> Result<(), Error> {
        let annotation = dictionary! {
            "Type" => Name("Annot".into()),
            "Contents" => Object::string_literal(CONTENT_CREDS),
            "Name" => Object::string_literal(CONTENT_CREDS),
            SUBTYPE_KEY => Name("FileAttachment".into()),
            "FS" => Reference(file_spec_reference),
            // Places annotation in the lower left-hand corner. The icon will be 10x10.
            "Rect" => vec![0.into(), 0.into(), 10.into(), 10.into()],
        };

        // Add C2PA annotation as an indirect object.
        let annotation_ref = self.document.add_object(annotation);

        // Find the reference to the first page of the PDF.
        let first_page_ref = self
            .document
            .page_iter()
            .next()
            .ok_or(Error::AddingAnnotation)?;

        // Get a mutable ref to the first page as a Dictionary object.
        let first_page = self
            .document
            .get_object_mut(first_page_ref)?
            .as_dict_mut()?;

        // Ensures the /Annots array exists on the page object.
        if !first_page.has(ANNOTATIONS_KEY) {
            first_page.set(ANNOTATIONS_KEY, Array(vec![]))
        }

        // Follows a reference to the indirect annotations array, if it exists.
        let annotation_object = first_page.get_mut(ANNOTATIONS_KEY)?;
        let annotations = if let Ok(v) = annotation_object.as_reference() {
            self.document.get_object_mut(v)?
        } else {
            annotation_object
        }
        .as_array_mut()?;

        annotations.push(Reference(annotation_ref));
        Ok(())
    }

    /// Creates, or appends to, the Associated File (`AF`) array the embedded file spec reference of the
    /// C2PA data.
    fn push_associated_file(&mut self, embedded_file_spec_ref: ObjectId) -> Result<(), Error> {
        let catalog = self.document.catalog_mut()?;
        if catalog.get_mut(ASSOCIATED_FILE_KEY).is_err() {
            // Add associated files array to catalog if it isn't already present.
            catalog.set(ASSOCIATED_FILE_KEY, vec![]);
        }

        let associated_files = catalog.get_mut(ASSOCIATED_FILE_KEY)?;
        let associated_files = match associated_files.as_reference() {
            Ok(object_id) => self.document.get_object_mut(object_id)?,
            _ => associated_files,
        }
        .as_array_mut()?;

        associated_files.push(Reference(embedded_file_spec_ref));

        Ok(())
    }

    /// Adds the `Embedded File Specification` to the PDF document. Returns the [Reference]
    /// to the added `Embedded File Specification`.
    ///
    /// Sets `Subtype` and `AFRelationship` on this dictionary per C2PA spec §A.4.1: "The
    /// embedded file specification dictionary shall have a Subtype key whose value is
    /// `application/c2pa` and an AFRelationship key ... whose value is `C2PA_Manifest`."
    fn add_embedded_file_specification(&mut self, file_stream_ref: ObjectId) -> ObjectId {
        let embedded_file_stream = dictionary! {
            AF_RELATIONSHIP_KEY => Name(C2PA_RELATIONSHIP.into()),
            SUBTYPE_KEY => C2PA_MIME_TYPE,
            "Desc" => Object::string_literal(CONTENT_CREDS),
            "F" => Object::string_literal(CONTENT_CREDS),
            "EF" => dictionary! {
                "F" => Reference(file_stream_ref),
            },
            TYPE_KEY => Name("FileSpec".into()),
            "UF" => Object::string_literal(CONTENT_CREDS),
        };

        self.document.add_object(embedded_file_stream)
    }

    /// Adds the provided `bytes` as a `StreamDictionary` to the PDF document. Returns the
    /// [Reference] of the added [Object].
    fn add_c2pa_embedded_file_stream(&mut self, bytes: Vec<u8>) -> ObjectId {
        let stream = Stream::new(dictionary! {}, bytes);

        self.document.add_object(stream)
    }

    /// Remove the C2PA Manifest `Annotation` from the PDF.
    fn remove_manifest_from_annotations(&mut self) -> Result<(), Error> {
        for (_, page_id) in self.document.get_pages() {
            let page = self.document.get_object_mut(page_id)?.as_dict_mut()?;

            // Pages with no annotations at all have nothing to remove; skip them
            // instead of failing the whole removal (e.g. manifests attached only
            // via `/AF`, with no `/Names` or per-page `/Annots` reference).
            let Ok(annots) = page.get_mut(ANNOTATIONS_KEY) else {
                continue;
            };

            annots.as_array_mut()?.retain(|obj| {
                obj.as_dict()
                    .and_then(|annot| annot.get(TYPE_KEY))
                    .and_then(Object::as_name)
                    .map(|str| str::from_utf8(str) != Ok(CONTENT_CREDS))
                    .unwrap_or(true)
            });
        }

        Ok(())
    }

    /// Removes the manifest from the PDF's embedded files collection.
    fn remove_manifest_from_embedded_files(&mut self) -> Result<(), Error> {
        let Ok(names) = self.document.catalog_mut()?.get_mut(NAMES_KEY) else {
            return Err(Error::NoManifest);
        };

        // Follows the reference to the /Names Dictionary.
        let names_dictionary = match names.as_reference() {
            Ok(object_id) => self.document.get_object_mut(object_id)?.as_dict_mut()?,
            _ => names.as_dict_mut()?,
        };

        // Follows the reference to the /EmbeddedFiles Dictionary.
        let embedded_files_object = names_dictionary.get_mut(EMBEDDED_FILES_KEY)?;
        let embedded_files_dictionary = match embedded_files_object.as_reference() {
            Ok(object_id) => self.document.get_object_mut(object_id)?.as_dict_mut()?,
            _ => embedded_files_object.as_dict_mut()?,
        };

        // Gets the /Names array from the /EmbeddedFiles Dictionary. This will contain the reference
        // to the C2PA manifest.
        let names_vector_object = embedded_files_dictionary.get_mut(NAMES_KEY)?;
        let names_vector = match names_vector_object.as_reference() {
            Ok(object_id) => self.document.get_object_mut(object_id)?.as_array_mut()?,
            _ => names_vector_object.as_array_mut()?,
        };

        // Find the "Content Credentials" marker name in the /Names Array.
        let content_creds_marker_idx = names_vector
            .iter()
            .position(|value| {
                value
                    .as_str()
                    .map(|value| str::from_utf8(value) == Ok(CONTENT_CREDS))
                    .unwrap_or_default()
            })
            .ok_or(Error::UnableToFindEmbeddedFileManifest)?;

        let content_creds_reference_idx = content_creds_marker_idx + 1;
        if content_creds_reference_idx >= names_vector.len() {
            return Err(Error::UnableToFindEmbeddedFileManifest);
        }

        // Delete the "Content Credentials" marker object and the reference to the C2PA
        // manifest in the PDF's embedded files.
        names_vector.drain(content_creds_marker_idx..=content_creds_reference_idx);

        Ok(())
    }
}

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

    use super::*;

    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);

    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
    use wasm_bindgen_test::*;

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_loads_pdf_from_bytes() {
        let bytes = include_bytes!("../../tests/fixtures/basic.pdf");
        let pdf_result = Pdf::from_bytes(bytes);
        assert!(pdf_result.is_ok());
    }

    #[test]
    fn test_rejects_pdf_with_oversized_xref_stream() {
        use std::io::Cursor;

        use flate2::{write::ZlibEncoder, Compression};

        const XREF_ENTRY_COUNT: usize = 10_000_000;
        const XREF_ENTRY_SIZE: usize = 7;

        let mut pdf = b"%PDF-1.5\n".to_vec();
        let catalog_offset = pdf.len() as u32;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
        let xref_offset = pdf.len() as u32;

        let mut xref_data = vec![0; XREF_ENTRY_COUNT * XREF_ENTRY_SIZE];
        xref_data[5..7].copy_from_slice(&u16::MAX.to_be_bytes());
        for (id, offset) in [(1, catalog_offset), (2, xref_offset)] {
            let entry_start = id * XREF_ENTRY_SIZE;
            xref_data[entry_start] = 1;
            xref_data[entry_start + 1..entry_start + 5].copy_from_slice(&offset.to_be_bytes());
        }

        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(&xref_data).unwrap();
        let compressed_xref = encoder.finish().unwrap();

        pdf.extend_from_slice(
            format!(
                "2 0 obj\n<< /Type /XRef /Size {XREF_ENTRY_COUNT} /W [1 4 2] \
                 /Index [0 {XREF_ENTRY_COUNT}] /Root 1 0 R /Filter /FlateDecode \
                 /Length {} >>\nstream\n",
                compressed_xref.len()
            )
            .as_bytes(),
        );
        pdf.extend_from_slice(&compressed_xref);
        pdf.extend_from_slice(
            format!("\nendstream\nendobj\nstartxref\n{xref_offset}\n%%EOF\n").as_bytes(),
        );

        assert!(matches!(
            Pdf::from_bytes(&pdf),
            Err(Error::UnableToReadPdf(_))
        ));
        assert!(matches!(
            Pdf::from_reader(Cursor::new(pdf)),
            Err(Error::UnableToReadPdf(_))
        ));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_loads_pdf_from_bytes_with_invalid_file() {
        let bytes = include_bytes!("../../tests/fixtures/XCA.jpg");
        let pdf_result = Pdf::from_bytes(bytes);
        assert!(matches!(pdf_result, Err(Error::UnableToReadPdf(_))));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_is_password_protected() {
        let bytes = include_bytes!("../../tests/fixtures/basic-password.pdf");
        let pdf_result = Pdf::from_bytes(bytes).unwrap();
        assert!(pdf_result.is_password_protected());

        let bytes = include_bytes!("../../tests/fixtures/basic.pdf");
        let pdf = Pdf::from_bytes(bytes).unwrap();
        assert!(!pdf.is_password_protected());
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_has_c2pa_manifest_on_file_without_manifest() {
        let bytes = include_bytes!("../../tests/fixtures/basic.pdf");
        let pdf = Pdf::from_bytes(bytes).unwrap();
        assert!(!pdf.has_c2pa_manifest())
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_has_c2pa_manifest_on_file_with_manifest() {
        let bytes = include_bytes!("../../tests/fixtures/basic.pdf");
        let mut pdf = Pdf::from_bytes(bytes).unwrap();
        assert!(!pdf.has_c2pa_manifest());

        pdf.write_manifest_as_annotation(vec![0u8, 1u8]).unwrap();
        assert!(pdf.has_c2pa_manifest());
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_adds_embedded_file_spec_to_pdf_stream() {
        let bytes = include_bytes!("../../tests/fixtures/express.pdf");
        let mut pdf = Pdf::from_bytes(bytes).unwrap();
        let object_count_before_add = pdf.document.objects.len();

        let bytes = vec![10u8];
        let id = pdf.add_c2pa_embedded_file_stream(bytes.clone());

        // Object added to the PDF's object collection.
        assert_eq!(object_count_before_add + 1, pdf.document.objects.len());

        // We are able to find the object.
        let stream = pdf.document.get_object(id);
        assert_eq!(stream.unwrap().as_stream().unwrap().content, bytes);
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_write_manifest_as_annotation() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/express.pdf")).unwrap();
        assert!(!pdf.has_c2pa_manifest());
        pdf.write_manifest_as_annotation(vec![10u8, 20u8]).unwrap();
        assert!(pdf.has_c2pa_manifest());
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_write_manifest_bytes_to_pdf_with_existing_annotations() {
        let mut pdf =
            Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic-annotation.pdf")).unwrap();
        pdf.write_manifest_as_annotation(vec![10u8, 20u8]).unwrap();
        assert!(pdf.has_c2pa_manifest());
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_add_manifest_to_embedded_files() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        pdf.write_manifest_as_embedded_file(vec![10u8, 20u8])
            .unwrap();

        assert!(pdf.has_c2pa_manifest());
    }

    // C2PA spec §A.4.1: "The embedded file specification dictionary shall have a
    // Subtype key whose value is application/c2pa and an AFRelationship key ...
    // whose value is C2PA_Manifest."
    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_file_specification_has_spec_required_subtype_and_af_relationship() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        pdf.write_manifest_as_embedded_file(vec![10u8, 20u8])
            .unwrap();

        let file_spec_ref = pdf.c2pa_file_spec_object_id().unwrap();
        let file_spec = pdf
            .document
            .get_object(file_spec_ref)
            .unwrap()
            .as_dict()
            .unwrap();

        assert_eq!(
            file_spec.get(SUBTYPE_KEY).unwrap().as_name().unwrap(),
            b"application/c2pa"
        );
        assert_eq!(
            file_spec
                .get(AF_RELATIONSHIP_KEY)
                .unwrap()
                .as_name()
                .unwrap(),
            C2PA_RELATIONSHIP
        );
    }

    // A manifest recorded via a compressed xref entry (stored inside an
    // `/ObjStm`) has no byte offset in the outer file. This must surface as a
    // distinct error, never as "no manifest".
    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_manifest_object_offset_errors_on_compressed_xref_entry() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        pdf.write_manifest_as_embedded_file(vec![10u8, 20u8])
            .unwrap();

        let (id, _generation) = pdf.c2pa_manifest_stream_object_id().unwrap();
        pdf.document.reference_table.entries.insert(
            id,
            lopdf::xref::XrefEntry::Compressed {
                container: 1,
                index: 0,
            },
        );

        assert!(matches!(
            pdf.manifest_object_offset(),
            Err(Error::ManifestObjectNotByteAddressable)
        ));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_add_manifest_to_embedded_files_attachments_present() {
        let mut pdf =
            Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic-attachments.pdf")).unwrap();
        pdf.write_manifest_as_embedded_file(vec![10u8, 20u8])
            .unwrap();

        assert!(pdf.has_c2pa_manifest());
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_save_to() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        assert!(!pdf.has_c2pa_manifest());

        pdf.write_manifest_as_annotation(vec![10u8]).unwrap();
        assert!(pdf.has_c2pa_manifest());

        let mut saved_bytes = vec![];
        pdf.save_to(&mut saved_bytes).unwrap();

        let saved_pdf = Pdf::from_bytes(&saved_bytes).unwrap();
        assert!(saved_pdf.has_c2pa_manifest());
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_reads_manifest_bytes_for_embedded_files_manifest() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/express.pdf")).unwrap();
        assert!(!pdf.has_c2pa_manifest());

        let manifest_bytes = vec![0u8, 1u8, 1u8, 2u8, 3u8];
        pdf.write_manifest_as_embedded_file(manifest_bytes.clone())
            .unwrap();

        assert!(pdf.has_c2pa_manifest());
        assert!(matches!(
            pdf.read_manifest_bytes(),
            Ok(Some(manifests)) if manifests[0] == manifest_bytes
        ));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_reads_manifest_bytes_for_annotation_manifest() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        assert!(!pdf.has_c2pa_manifest());

        let manifest_bytes = vec![0u8, 1u8, 1u8, 2u8, 3u8];
        pdf.write_manifest_as_annotation(manifest_bytes.clone())
            .unwrap();

        assert!(pdf.has_c2pa_manifest());
        assert!(matches!(
            pdf.read_manifest_bytes(),
            Ok(Some(manifests)) if manifests[0] == manifest_bytes
        ));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_read_manifest_bytes_from_pdf_without_bytes_returns_none() {
        let pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        assert!(!pdf.has_c2pa_manifest());
        assert!(matches!(pdf.read_manifest_bytes(), Ok(None)));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_read_manifest_bytes_from_pdf_with_other_af_relationship_returns_none() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        pdf.document
            .catalog_mut()
            .unwrap()
            .set(ASSOCIATED_FILE_KEY, vec![Reference((100, 0))]);

        assert!(matches!(pdf.read_manifest_bytes(), Ok(None)));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_read_pdf_with_associated_file_that_is_not_manifest() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        pdf.document
            .catalog_mut()
            .unwrap()
            .set(ASSOCIATED_FILE_KEY, Reference((100, 0)));

        assert!(matches!(pdf.read_manifest_bytes(), Ok(None)));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_read_xmp_on_pdf_with_none() {
        let pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic-no-xmp.pdf")).unwrap();
        assert_eq!(pdf.read_xmp(), None);
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_read_xmp_on_pdf_with_some_metadata() {
        let pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        assert!(pdf.read_xmp().is_some());
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_write_xmp_on_pdf_with_no_existing_metadata() {
        let mut pdf =
            Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic-no-xmp.pdf")).unwrap();
        assert_eq!(pdf.read_xmp(), None);

        pdf.write_xmp("test xmp content".to_string()).unwrap();
        assert_eq!(pdf.read_xmp(), Some("test xmp content".to_string()));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_write_xmp_on_pdf_with_existing_metadata() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        assert!(pdf.read_xmp().is_some());

        pdf.write_xmp("replacement xmp content".to_string())
            .unwrap();
        assert_eq!(pdf.read_xmp(), Some("replacement xmp content".to_string()));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_write_xmp_round_trips_through_save_to() {
        let mut pdf =
            Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic-no-xmp.pdf")).unwrap();
        pdf.write_xmp("test xmp content".to_string()).unwrap();

        let mut saved_bytes = vec![];
        pdf.save_to(&mut saved_bytes).unwrap();

        let saved_pdf = Pdf::from_bytes(&saved_bytes).unwrap();
        assert_eq!(saved_pdf.read_xmp(), Some("test xmp content".to_string()));
    }

    // A `Stream` is only valid PDF syntax as a top-level indirect object —
    // writing one as a direct dictionary value serializes as `stream` /
    // `endstream` nested inside another object's dictionary, which isn't
    // valid PDF grammar. If `/Metadata` is ever a malformed direct (non
    // -reference) value rather than the reference it's supposed to be,
    // `write_xmp` must still go through a fresh indirect object rather than
    // overwriting that value in place with a `Stream`.
    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_write_xmp_replaces_malformed_direct_metadata_value() {
        let mut pdf =
            Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic-no-xmp.pdf")).unwrap();
        pdf.document
            .catalog_mut()
            .unwrap()
            .set(METADATA_KEY, dictionary! {});

        pdf.write_xmp("test xmp content".to_string()).unwrap();
        assert_eq!(pdf.read_xmp(), Some("test xmp content".to_string()));

        // Must still be valid, reparseable PDF: `/Metadata` is now a proper
        // indirect reference, not the `Stream` written in place as a direct
        // value that malformed grammar would produce.
        let metadata = pdf.document.catalog().unwrap().get(METADATA_KEY).unwrap();
        assert!(metadata.as_reference().is_ok());

        let mut saved_bytes = vec![];
        pdf.save_to(&mut saved_bytes).unwrap();

        let saved_pdf = Pdf::from_bytes(&saved_bytes).unwrap();
        assert_eq!(saved_pdf.read_xmp(), Some("test xmp content".to_string()));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_remove_manifest_bytes_from_file_without_c2pa_returns_error() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();

        assert!(matches!(
            pdf.remove_manifest_bytes(),
            Err(Error::NoManifest)
        ));
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_remove_manifest_from_file_with_annotation_based_manifest() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        let manifest_bytes = vec![0u8, 1u8, 1u8, 2u8, 3u8];
        pdf.write_manifest_as_annotation(manifest_bytes.clone())
            .unwrap();

        assert!(pdf.has_c2pa_manifest());
        assert!(pdf.remove_manifest_bytes().is_ok());
        assert!(!pdf.has_c2pa_manifest());
    }

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn test_remove_manifest_from_file_with_embedded_file_based_manifest() {
        let mut pdf = Pdf::from_bytes(include_bytes!("../../tests/fixtures/basic.pdf")).unwrap();
        let manifest_bytes = vec![0u8, 1u8, 1u8, 2u8, 3u8];

        pdf.write_manifest_as_embedded_file(manifest_bytes.clone())
            .unwrap();

        assert!(pdf.has_c2pa_manifest());
        assert!(pdf.remove_manifest_bytes().is_ok());
        assert!(!pdf.has_c2pa_manifest());
    }
}