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
// Derived from PDFium's fpdfsdk/fpdf_signature.cpp
// Original: Copyright 2020 The PDFium Authors
// Licensed under BSD-3-Clause / Apache-2.0
// See pdfium-upstream/LICENSE for the original license.
//! Digital signature field enumeration and metadata extraction.
//!
//! Corresponds to upstream `fpdf_signature.h` / `fpdf_signature.cpp`.
//!
//! This module provides **read-only** access to digital signatures embedded
//! in a PDF document. Cryptographic verification (PKCS#7/CMS) and signature
//! creation are out of scope.
use rpdfium_core::{Name, PdfSource};
use rpdfium_parser::{Object, ObjectStore};
use crate::error::{DocError, DocResult};
/// Maximum number of signature fields collected from a single document.
const MAX_SIGNATURES: usize = 1_000;
// ---------------------------------------------------------------------------
// DocMdpPermission
// ---------------------------------------------------------------------------
/// The DocMDP (Modification Detection and Prevention) permission level.
///
/// Corresponds to the `/P` integer in the DocMDP transform parameters.
/// See ISO 32000-2 §12.8.2.2.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DocMdpPermission {
/// No changes allowed (P=1).
NoChanges,
/// Form filling and signing only (P=2).
FormFillingAndSigning,
/// Annotations, form filling, and signing (P=3).
AnnotationFormFillingAndSigning,
}
impl DocMdpPermission {
/// Convert from the PDF `/P` integer value.
///
/// Returns `None` for values that are not 1, 2, or 3.
pub fn from_p_value(p: i64) -> Option<Self> {
match p {
1 => Some(Self::NoChanges),
2 => Some(Self::FormFillingAndSigning),
3 => Some(Self::AnnotationFormFillingAndSigning),
_ => None,
}
}
/// Convert back to the integer `/P` value.
pub fn as_u32(self) -> u32 {
match self {
Self::NoChanges => 1,
Self::FormFillingAndSigning => 2,
Self::AnnotationFormFillingAndSigning => 3,
}
}
}
// ---------------------------------------------------------------------------
// SignatureObject
// ---------------------------------------------------------------------------
/// A digital signature field parsed from a PDF's AcroForm.
///
/// Corresponds to the data obtainable via the eight
/// `FPDF_GetSignatureObject` / `FPDFSignatureObj_Get*` functions in
/// PDFium's `fpdf_signature.h`.
#[derive(Debug, Clone)]
pub struct SignatureObject {
contents: Option<Vec<u8>>,
byte_range: Vec<(u64, u64)>,
sub_filter: Option<String>,
reason: Option<String>,
time: Option<String>,
doc_mdp_permission: Option<DocMdpPermission>,
}
impl SignatureObject {
/// The raw DER-encoded PKCS#7/CMS signature bytes from `/Contents`.
///
/// Returns `None` if the field has no `/Contents` entry.
///
/// Corresponds to `FPDFSignatureObj_GetContents()`.
pub fn contents(&self) -> Option<&[u8]> {
self.contents.as_deref()
}
/// ADR-019 T2 alias for [`contents()`](Self::contents).
///
/// Corresponds to `FPDFSignatureObj_GetContents`.
#[inline]
pub fn signature_obj_get_contents(&self) -> Option<&[u8]> {
self.contents()
}
/// Deprecated — use [`signature_obj_get_contents()`](Self::signature_obj_get_contents).
///
/// Corresponds to `FPDFSignatureObj_GetContents`.
#[deprecated(
note = "use `signature_obj_get_contents()` — matches upstream `FPDFSignatureObj_GetContents`"
)]
#[inline]
pub fn get_contents(&self) -> Option<&[u8]> {
self.contents()
}
/// The byte ranges that the signature covers, as `(offset, length)` pairs.
///
/// The `/ByteRange` array is a flat sequence of integers interpreted as
/// pairs: `[offset0, length0, offset1, length1, ...]`. An odd number of
/// elements results in the trailing element being dropped.
///
/// Corresponds to `FPDFSignatureObj_GetByteRange()`.
pub fn byte_range(&self) -> &[(u64, u64)] {
&self.byte_range
}
/// ADR-019 T2 alias for [`byte_range()`](Self::byte_range).
///
/// Corresponds to `FPDFSignatureObj_GetByteRange`.
#[inline]
pub fn signature_obj_get_byte_range(&self) -> &[(u64, u64)] {
self.byte_range()
}
/// Deprecated — use [`signature_obj_get_byte_range()`](Self::signature_obj_get_byte_range).
///
/// Corresponds to `FPDFSignatureObj_GetByteRange`.
#[deprecated(
note = "use `signature_obj_get_byte_range()` — matches upstream `FPDFSignatureObj_GetByteRange`"
)]
#[inline]
pub fn get_byte_range(&self) -> &[(u64, u64)] {
self.byte_range()
}
/// The sub-filter name from `/SubFilter` (e.g. `"adbe.pkcs7.detached"`).
///
/// Returns `None` if the field has no `/SubFilter` entry.
///
/// Corresponds to `FPDFSignatureObj_GetSubFilter()`.
pub fn sub_filter(&self) -> Option<&str> {
self.sub_filter.as_deref()
}
/// ADR-019 T2 alias for [`sub_filter()`](Self::sub_filter).
///
/// Corresponds to `FPDFSignatureObj_GetSubFilter`.
#[inline]
pub fn signature_obj_get_sub_filter(&self) -> Option<&str> {
self.sub_filter()
}
/// Deprecated — use [`signature_obj_get_sub_filter()`](Self::signature_obj_get_sub_filter).
///
/// Corresponds to `FPDFSignatureObj_GetSubFilter`.
#[deprecated(
note = "use `signature_obj_get_sub_filter()` — matches upstream `FPDFSignatureObj_GetSubFilter`"
)]
#[inline]
pub fn get_sub_filter(&self) -> Option<&str> {
self.sub_filter()
}
/// The human-readable signing reason from `/Reason`.
///
/// Returns `None` if the field has no `/Reason` entry.
///
/// Corresponds to `FPDFSignatureObj_GetReason()`.
pub fn reason(&self) -> Option<&str> {
self.reason.as_deref()
}
/// ADR-019 T2 alias for [`reason()`](Self::reason).
///
/// Corresponds to `FPDFSignatureObj_GetReason`.
#[inline]
pub fn signature_obj_get_reason(&self) -> Option<&str> {
self.reason()
}
/// Deprecated — use [`signature_obj_get_reason()`](Self::signature_obj_get_reason).
///
/// Corresponds to `FPDFSignatureObj_GetReason`.
#[deprecated(
note = "use `signature_obj_get_reason()` — matches upstream `FPDFSignatureObj_GetReason`"
)]
#[inline]
pub fn get_reason(&self) -> Option<&str> {
self.reason()
}
/// The signing time string from `/M` (format: `"D:YYYYMMDDHHmmSSOHH'mm'"`).
///
/// Returns `None` if the field has no `/M` entry.
///
/// Corresponds to `FPDFSignatureObj_GetTime()`.
pub fn time(&self) -> Option<&str> {
self.time.as_deref()
}
/// ADR-019 T2 alias for [`time()`](Self::time).
///
/// Corresponds to `FPDFSignatureObj_GetTime`.
#[inline]
pub fn signature_obj_get_time(&self) -> Option<&str> {
self.time()
}
/// Deprecated — use [`signature_obj_get_time()`](Self::signature_obj_get_time).
///
/// Corresponds to `FPDFSignatureObj_GetTime`.
#[deprecated(
note = "use `signature_obj_get_time()` — matches upstream `FPDFSignatureObj_GetTime`"
)]
#[inline]
pub fn get_time(&self) -> Option<&str> {
self.time()
}
/// Deprecated — use [`signature_obj_get_time()`](Self::signature_obj_get_time).
#[deprecated(
note = "use `signature_obj_get_time()` — matches upstream `FPDFSignatureObj_GetTime`"
)]
#[inline]
pub fn signing_time(&self) -> Option<&str> {
self.time()
}
/// The DocMDP permission level, if a DocMDP transform is present.
///
/// Returns `None` if the signature does not include a DocMDP reference.
///
/// Corresponds to `FPDFSignatureObj_GetDocMDPPermission()`.
pub fn doc_mdp_permission(&self) -> Option<DocMdpPermission> {
self.doc_mdp_permission
}
/// ADR-019 T2 alias for [`doc_mdp_permission()`](Self::doc_mdp_permission).
///
/// Corresponds to `FPDFSignatureObj_GetDocMDPPermission`.
#[inline]
pub fn signature_obj_get_doc_mdp_permission(&self) -> Option<DocMdpPermission> {
self.doc_mdp_permission()
}
/// Deprecated — use [`signature_obj_get_doc_mdp_permission()`](Self::signature_obj_get_doc_mdp_permission).
///
/// Corresponds to `FPDFSignatureObj_GetDocMDPPermission`.
#[deprecated(
note = "use `signature_obj_get_doc_mdp_permission()` — matches upstream `FPDFSignatureObj_GetDocMDPPermission`"
)]
#[inline]
pub fn get_doc_mdp_permission(&self) -> Option<DocMdpPermission> {
self.doc_mdp_permission()
}
}
// ---------------------------------------------------------------------------
// collect_signatures
// ---------------------------------------------------------------------------
/// Collect all digital signature fields from the document's AcroForm.
///
/// Iterates the top-level `/AcroForm/Fields[]` array (non-recursive) and
/// collects every entry whose `/FT` is `/Sig`. Returns an empty `Vec` if the
/// document has no AcroForm or no signature fields.
///
/// Corresponds to `CollectSignatures()` in PDFium's `fpdf_signature.cpp`.
pub fn collect_signatures<S: PdfSource>(
catalog: &Object,
store: &ObjectStore<S>,
) -> DocResult<Vec<SignatureObject>> {
// Resolve the catalog dictionary.
let catalog_dict = store
.deep_resolve(catalog)
.map_err(|e| DocError::Parser(e.to_string()))?;
let catalog_dict = catalog_dict.as_dict().ok_or(DocError::UnexpectedType)?;
// Navigate to /AcroForm.
let acroform_obj = match catalog_dict.get(&Name::acro_form()) {
Some(obj) => obj,
None => return Ok(Vec::new()),
};
let acroform = store
.deep_resolve(acroform_obj)
.map_err(|e| DocError::Parser(e.to_string()))?;
let acroform_dict = match acroform.as_dict() {
Some(d) => d,
None => return Ok(Vec::new()),
};
// Get the top-level /Fields array.
let fields_obj = match acroform_dict.get(&Name::fields()) {
Some(obj) => obj,
None => return Ok(Vec::new()),
};
let fields_resolved = store
.deep_resolve(fields_obj)
.map_err(|e| DocError::Parser(e.to_string()))?;
let fields_arr = match fields_resolved.as_array() {
Some(arr) => arr,
None => return Ok(Vec::new()),
};
let mut signatures = Vec::new();
for field_ref in fields_arr {
if signatures.len() >= MAX_SIGNATURES {
break;
}
// Resolve the field dictionary.
let field_obj = store
.deep_resolve(field_ref)
.map_err(|e| DocError::Parser(e.to_string()))?;
let field_dict = match field_obj.as_dict() {
Some(d) => d,
None => continue,
};
// Check /FT == /Sig.
let ft = match field_dict.get(&Name::ft()) {
Some(obj) => obj,
None => continue,
};
let ft_resolved = store
.deep_resolve(ft)
.map_err(|e| DocError::Parser(e.to_string()))?;
let ft_name = match ft_resolved.as_name() {
Some(n) => n,
None => continue,
};
if *ft_name != Name::sig() {
continue;
}
// Resolve /V (the signature dictionary).
let v_obj = match field_dict.get(&Name::v()) {
Some(obj) => obj,
None => continue,
};
let sig_dict_obj = store
.deep_resolve(v_obj)
.map_err(|e| DocError::Parser(e.to_string()))?;
let sig_dict = match sig_dict_obj.as_dict() {
Some(d) => d,
None => continue,
};
let sig = parse_sig_dict(sig_dict, store)?;
signatures.push(sig);
}
Ok(signatures)
}
/// Parse a signature dictionary into a [`SignatureObject`].
fn parse_sig_dict<S: PdfSource>(
sig_dict: &std::collections::HashMap<Name, Object>,
store: &ObjectStore<S>,
) -> DocResult<SignatureObject> {
// /Contents — binary DER-encoded PKCS#7
let contents = sig_dict
.get(&Name::contents())
.and_then(|obj| store.deep_resolve(obj).ok())
.and_then(|obj| obj.as_string().map(|s| s.as_bytes().to_vec()));
// /ByteRange — flat integer array → [(offset, len)] pairs
let byte_range = sig_dict
.get(&Name::byte_range())
.and_then(|obj| store.deep_resolve(obj).ok())
.and_then(|obj| {
obj.as_array().map(|arr| {
arr.iter()
.filter_map(|item| {
store
.deep_resolve(item)
.ok()
.and_then(|o| o.as_i64())
.map(|v| v.max(0) as u64)
})
.collect::<Vec<u64>>()
})
})
.map(|flat| {
flat.chunks_exact(2)
.map(|pair| (pair[0], pair[1]))
.collect::<Vec<(u64, u64)>>()
})
.unwrap_or_default();
// /SubFilter — ASCII Name
let sub_filter = sig_dict
.get(&Name::sub_filter())
.and_then(|obj| store.deep_resolve(obj).ok())
.and_then(|obj| obj.as_name().map(|n| n.as_str().to_string()));
// /Reason — PDF text string
let reason = sig_dict
.get(&Name::reason())
.and_then(|obj| store.deep_resolve(obj).ok())
.and_then(|obj| obj.as_string().map(|s| s.to_string_lossy()));
// /M — PDF date string (ASCII)
let time = sig_dict
.get(&Name::m())
.and_then(|obj| store.deep_resolve(obj).ok())
.and_then(|obj| obj.as_string().map(|s| s.to_string_lossy()));
// /Reference[] — scan for DocMDP transform
let doc_mdp_permission = parse_doc_mdp(sig_dict, store);
Ok(SignatureObject {
contents,
byte_range,
sub_filter,
reason,
time,
doc_mdp_permission,
})
}
/// Scan `/Reference[]` for a DocMDP transform and extract the permission level.
fn parse_doc_mdp<S: PdfSource>(
sig_dict: &std::collections::HashMap<Name, Object>,
store: &ObjectStore<S>,
) -> Option<DocMdpPermission> {
let ref_obj = sig_dict.get(&Name::reference())?;
let ref_resolved = store.deep_resolve(ref_obj).ok()?;
let ref_arr = ref_resolved.as_array()?;
for entry_ref in ref_arr {
let entry_obj = store.deep_resolve(entry_ref).ok()?;
let entry_dict = entry_obj.as_dict()?;
// Check /TransformMethod == /DocMDP
let tm_obj = entry_dict.get(&Name::transform_method())?;
let tm_resolved = store.deep_resolve(tm_obj).ok()?;
let tm_name = tm_resolved.as_name()?;
if *tm_name != Name::doc_mdp() {
continue;
}
// Get /TransformParams/P
// Upstream uses GetIntegerFor("P", 2): absent /P defaults to 2
// (FormFillingAndSigning), then validates range 1–3.
let tp_obj = entry_dict.get(&Name::transform_params())?;
let tp_resolved = store.deep_resolve(tp_obj).ok()?;
let tp_dict = tp_resolved.as_dict()?;
let p_val = tp_dict
.get(&Name::p())
.and_then(|obj| store.deep_resolve(obj).ok())
.and_then(|obj| obj.as_i64())
.unwrap_or(2); // PDF spec default when /P is absent
return DocMdpPermission::from_p_value(p_val);
}
None
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::Arc;
use rpdfium_core::{Name, PdfString};
use rpdfium_parser::object::Object;
use rpdfium_parser::store::ObjectStore;
use super::*;
/// Build a raw PDF byte stream with the given extra objects appended and
/// an AcroForm pointing to `fields_refs` (object numbers).
fn build_pdf_with_sig(field_obj_num: u32) -> Vec<u8> {
// We construct minimal PDF objects by hand.
// Objects:
// 1 0 obj — Catalog (has /AcroForm 4 0 R)
// 2 0 obj — Pages
// 3 0 obj — Sig field (/FT /Sig, /V 5 0 R)
// 4 0 obj — AcroForm (/Fields [3 0 R])
// 5 0 obj — Sig dict (/Type /Sig, /Contents <DEADBEEF>,
// /ByteRange [0 10 20 30],
// /SubFilter /adbe.pkcs7.detached,
// /Reason (test reason),
// /M (D:20240101000000),
// /Reference [6 0 R])
// 6 0 obj — Ref dict (/TransformMethod /DocMDP,
// /TransformParams 7 0 R)
// 7 0 obj — TransformParams (/P 2)
let _ = field_obj_num; // used to select the field ref, but we hardcode obj 3
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.7\n");
let obj1_offset = pdf.len();
pdf.extend_from_slice(
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>\nendobj\n",
);
let obj2_offset = pdf.len();
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
let obj3_offset = pdf.len();
pdf.extend_from_slice(b"3 0 obj\n<< /FT /Sig /V 5 0 R /T (Signature1) >>\nendobj\n");
let obj4_offset = pdf.len();
pdf.extend_from_slice(b"4 0 obj\n<< /Fields [3 0 R] >>\nendobj\n");
let obj5_offset = pdf.len();
// /Contents with hex string, /ByteRange, /SubFilter, /Reason, /M, /Reference
pdf.extend_from_slice(
b"5 0 obj\n\
<< /Type /Sig\n\
/Contents <DEADBEEF>\n\
/ByteRange [0 10 20 30]\n\
/SubFilter /adbe.pkcs7.detached\n\
/Reason (test reason)\n\
/M (D:20240101000000)\n\
/Reference [6 0 R]\n\
>>\nendobj\n",
);
let obj6_offset = pdf.len();
pdf.extend_from_slice(
b"6 0 obj\n<< /TransformMethod /DocMDP /TransformParams 7 0 R >>\nendobj\n",
);
let obj7_offset = pdf.len();
pdf.extend_from_slice(b"7 0 obj\n<< /P 2 >>\nendobj\n");
let xref_offset = pdf.len();
pdf.extend_from_slice(b"xref\n");
pdf.extend_from_slice(b"0 8\n");
pdf.extend_from_slice(b"0000000000 65535 f \n");
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj1_offset).as_bytes());
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj2_offset).as_bytes());
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj3_offset).as_bytes());
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj4_offset).as_bytes());
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj5_offset).as_bytes());
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj6_offset).as_bytes());
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj7_offset).as_bytes());
pdf.extend_from_slice(b"trailer\n<< /Size 8 /Root 1 0 R >>\n");
pdf.extend_from_slice(format!("startxref\n{}\n%%%%EOF\n", xref_offset).as_bytes());
pdf
}
fn build_minimal_pdf(extra: &[u8]) -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.7\n");
let obj1_offset = pdf.len();
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let obj2_offset = pdf.len();
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
pdf.extend_from_slice(extra);
let xref_offset = pdf.len();
pdf.extend_from_slice(b"xref\n0 3\n");
pdf.extend_from_slice(b"0000000000 65535 f \n");
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj1_offset).as_bytes());
pdf.extend_from_slice(format!("{:010} 00000 n \n", obj2_offset).as_bytes());
pdf.extend_from_slice(b"trailer\n<< /Size 3 /Root 1 0 R >>\n");
pdf.extend_from_slice(format!("startxref\n{}\n%%%%EOF\n", xref_offset).as_bytes());
pdf
}
fn open_arc(data: Vec<u8>) -> (ObjectStore<Arc<[u8]>>, rpdfium_core::error::ObjectId) {
let arc: Arc<[u8]> = Arc::from(data);
let store = ObjectStore::open(arc, rpdfium_core::ParsingMode::Lenient).unwrap();
let cat_id = store.trailer().root;
(store, cat_id)
}
// -----------------------------------------------------------------------
// Unit tests using in-memory Object construction
// -----------------------------------------------------------------------
/// Build a SignatureObject by directly calling parse_sig_dict via a
/// manually constructed sig dict + empty store (Vec<u8> source).
fn make_empty_store() -> ObjectStore<Vec<u8>> {
let pdf = build_minimal_pdf(&[]);
ObjectStore::open(pdf, rpdfium_core::ParsingMode::Lenient).unwrap()
}
#[test]
fn test_no_acroform_returns_empty() {
// PDF has no /AcroForm → expect empty vec.
let pdf = build_minimal_pdf(&[]);
let (store, cat_id) = open_arc(pdf);
let cat = store.resolve(cat_id).unwrap();
let sigs = collect_signatures(cat, &store).unwrap();
assert!(sigs.is_empty());
}
#[test]
fn test_collects_one_signature() {
let pdf = build_pdf_with_sig(3);
let (store, cat_id) = open_arc(pdf);
let cat = store.resolve(cat_id).unwrap();
let sigs = collect_signatures(cat, &store).unwrap();
assert_eq!(sigs.len(), 1);
let sig = &sigs[0];
// contents
assert_eq!(sig.contents(), Some(&[0xDE, 0xAD, 0xBE, 0xEF][..]));
// byte_range
assert_eq!(sig.byte_range(), &[(0, 10), (20, 30)]);
// sub_filter
assert_eq!(sig.sub_filter(), Some("adbe.pkcs7.detached"));
// reason
assert_eq!(sig.reason(), Some("test reason"));
// time
assert_eq!(sig.time(), Some("D:20240101000000"));
// doc_mdp
assert_eq!(
sig.doc_mdp_permission(),
Some(DocMdpPermission::FormFillingAndSigning)
);
}
#[test]
fn test_empty_byte_range() {
// Build a sig dict without /ByteRange.
let mut sig_dict: HashMap<Name, Object> = HashMap::new();
sig_dict.insert(
Name::contents(),
Object::String(PdfString::from_bytes(vec![0xAA])),
);
let store = make_empty_store();
let sig = parse_sig_dict(&sig_dict, &store).unwrap();
assert_eq!(sig.byte_range(), &[]);
}
#[test]
fn test_odd_byte_range_truncates() {
// Odd number of elements → last one dropped.
let mut sig_dict: HashMap<Name, Object> = HashMap::new();
sig_dict.insert(
Name::byte_range(),
Object::Array(vec![
Object::Integer(0),
Object::Integer(10),
Object::Integer(20), // orphan — no pair
]),
);
let store = make_empty_store();
let sig = parse_sig_dict(&sig_dict, &store).unwrap();
// Only one complete pair: (0, 10); the 20 is dropped.
assert_eq!(sig.byte_range(), &[(0, 10)]);
}
#[test]
fn test_doc_mdp_none() {
// Sig dict without /Reference → None.
let sig_dict: HashMap<Name, Object> = HashMap::new();
let store = make_empty_store();
let sig = parse_sig_dict(&sig_dict, &store).unwrap();
assert_eq!(sig.doc_mdp_permission(), None);
}
#[test]
fn test_doc_mdp_level_2() {
assert_eq!(
DocMdpPermission::from_p_value(2),
Some(DocMdpPermission::FormFillingAndSigning)
);
}
#[test]
fn test_doc_mdp_level_3() {
assert_eq!(
DocMdpPermission::from_p_value(3),
Some(DocMdpPermission::AnnotationFormFillingAndSigning)
);
}
#[test]
fn test_invalid_p_value() {
assert_eq!(DocMdpPermission::from_p_value(99), None);
assert_eq!(DocMdpPermission::from_p_value(0), None);
assert_eq!(DocMdpPermission::from_p_value(-1), None);
}
#[test]
fn test_non_sig_fields_skipped() {
// Build a PDF with a Tx field (obj 3) and a Sig field (obj 4).
// Only the Sig field should be collected.
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.7\n");
let obj1_offset = pdf.len();
pdf.extend_from_slice(
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>\nendobj\n",
);
let obj2_offset = pdf.len();
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
// Tx field (should be skipped)
let obj3_offset = pdf.len();
pdf.extend_from_slice(b"3 0 obj\n<< /FT /Tx /T (TextField) /V (hello) >>\nendobj\n");
// Sig field
let obj4_offset = pdf.len();
pdf.extend_from_slice(b"4 0 obj\n<< /FT /Sig /V 6 0 R /T (Signature1) >>\nendobj\n");
// AcroForm with both fields
let obj5_offset = pdf.len();
pdf.extend_from_slice(b"5 0 obj\n<< /Fields [3 0 R 4 0 R] >>\nendobj\n");
// Sig dict for the Sig field
let obj6_offset = pdf.len();
pdf.extend_from_slice(
b"6 0 obj\n<< /Type /Sig /Contents <AABB> /SubFilter /test >>\nendobj\n",
);
let xref_offset = pdf.len();
pdf.extend_from_slice(b"xref\n0 7\n");
pdf.extend_from_slice(b"0000000000 65535 f \n");
for offset in &[
obj1_offset,
obj2_offset,
obj3_offset,
obj4_offset,
obj5_offset,
obj6_offset,
] {
pdf.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
}
pdf.extend_from_slice(b"trailer\n<< /Size 7 /Root 1 0 R >>\n");
pdf.extend_from_slice(format!("startxref\n{}\n%%%%EOF\n", xref_offset).as_bytes());
let (store, cat_id) = open_arc(pdf);
let cat = store.resolve(cat_id).unwrap();
let sigs = collect_signatures(cat, &store).unwrap();
assert_eq!(sigs.len(), 1, "only the Sig field should be collected");
assert_eq!(sigs[0].sub_filter(), Some("test"));
}
#[test]
fn test_doc_mdp_as_u32() {
assert_eq!(DocMdpPermission::NoChanges.as_u32(), 1);
assert_eq!(DocMdpPermission::FormFillingAndSigning.as_u32(), 2);
assert_eq!(
DocMdpPermission::AnnotationFormFillingAndSigning.as_u32(),
3
);
}
// -----------------------------------------------------------------------
// Gap #1: DocMDP /P default value
// -----------------------------------------------------------------------
#[test]
fn test_doc_mdp_missing_p_defaults_to_level_2() {
// /TransformParams dict exists but has no /P key.
// Upstream default: GetIntegerFor("P", 2) → FormFillingAndSigning.
let mut sig_dict: HashMap<Name, Object> = HashMap::new();
// /Reference [ << /TransformMethod /DocMDP /TransformParams << >> >> ]
let transform_params = Object::Dictionary(HashMap::new()); // empty — no /P
let mut ref_entry: HashMap<Name, Object> = HashMap::new();
ref_entry.insert(Name::transform_method(), Object::Name(Name::doc_mdp()));
ref_entry.insert(Name::transform_params(), transform_params);
sig_dict.insert(
Name::reference(),
Object::Array(vec![Object::Dictionary(ref_entry)]),
);
let store = make_empty_store();
let sig = parse_sig_dict(&sig_dict, &store).unwrap();
assert_eq!(
sig.doc_mdp_permission(),
Some(DocMdpPermission::FormFillingAndSigning),
"/P absent in /TransformParams should default to level 2"
);
}
// -----------------------------------------------------------------------
// Gap #3: Malformed field edge cases
// -----------------------------------------------------------------------
#[test]
fn test_contents_non_string_returns_none() {
// /Contents is an integer (not a string) → contents() should be None.
let mut sig_dict: HashMap<Name, Object> = HashMap::new();
sig_dict.insert(Name::contents(), Object::Integer(42));
let store = make_empty_store();
let sig = parse_sig_dict(&sig_dict, &store).unwrap();
assert_eq!(
sig.contents(),
None,
"/Contents as integer should yield None"
);
}
#[test]
fn test_byte_range_non_array_returns_empty() {
// /ByteRange is a dict (not an array) → byte_range() should be empty.
let mut sig_dict: HashMap<Name, Object> = HashMap::new();
sig_dict.insert(Name::byte_range(), Object::Dictionary(HashMap::new()));
let store = make_empty_store();
let sig = parse_sig_dict(&sig_dict, &store).unwrap();
assert!(
sig.byte_range().is_empty(),
"/ByteRange as dict should yield empty slice"
);
}
#[test]
fn test_reference_non_array_is_ignored() {
// /Reference is a single dict (not an array) → doc_mdp_permission() should be None.
let mut ref_entry: HashMap<Name, Object> = HashMap::new();
ref_entry.insert(Name::transform_method(), Object::Name(Name::doc_mdp()));
let mut tp: HashMap<Name, Object> = HashMap::new();
tp.insert(Name::p(), Object::Integer(1));
ref_entry.insert(Name::transform_params(), Object::Dictionary(tp));
let mut sig_dict: HashMap<Name, Object> = HashMap::new();
// Single dict instead of array — malformed per spec.
sig_dict.insert(Name::reference(), Object::Dictionary(ref_entry));
let store = make_empty_store();
let sig = parse_sig_dict(&sig_dict, &store).unwrap();
assert_eq!(
sig.doc_mdp_permission(),
None,
"/Reference as bare dict (not array) should yield None"
);
}
}