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 | //! Takes a finished file that carries no form and no place to sign, adds two
//! places to sign to it, and signs them one after the other, each signature
//! leaving the one before it covering what it covered.
//!
//! Five files, each the whole of the one before it followed by a section
//! appended after its last byte:
//!
//! 1. the file received: one page, written on its own, with no form;
//! 2. the same file with the two framed signature fields [`APPROVAL`] and
//! [`REVIEW`] added under the word its page sets over each, one section
//! each, through `IncrementalUpdate::to_bytes_with_signature_field`;
//! 3. that file with [`APPROVAL`] signed, through
//! `IncrementalUpdate::to_signed_bytes`;
//! 4. that file with [`REVIEW`] signed the same way, read afresh;
//! 5. that file with the demonstration certificate kept in its document
//! security store, filed under both signatures, through
//! `IncrementalUpdate::to_bytes_with_store`, so that both stay checkable
//! once the certificate has expired.
//!
//! The approval certifies the document, allowing forms to be filled in and the
//! fields left empty to be signed after it, and states where it was made and
//! how to reach its signer; the review is an ordinary signature in the older
//! PKCS #7 form. What each states of itself is printed as it is made.
//!
//! Both signatures are made with the demonstration signer `shared/signer.rs`
//! hands to `openssl`. The approval covers the third file whole but for the
//! room its own structure sits in, and nothing of the section the review
//! appends; the review covers the fourth. A signature made with an RSA key is
//! the same bytes every time it is made over the same bytes, so the example
//! writes the same file on every run.
//!
//! The page is written in the language `HQF_PDF_LANG` names. The command, the
//! signer's name and the moments of signing are not.
//!
//! Usage: `cargo run --example write_signed_twice -- tmp/signed_twice.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_signed_twice`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{
Certification, Document, Error, FieldBorder, Font, FontHandle, IncrementalUpdate, Page, Rgb,
SecurityStore, Signature, SignatureField, SignatureValidation, SubFilter,
};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
#[path = "shared/failure.rs"]
mod failure;
#[path = "shared/signer.rs"]
mod signer;
#[cfg(test)]
#[path = "shared/signature_check.rs"]
mod signature_check;
use language::Language;
use signer::{CHECK_COMMAND, SIGNER};
/// The font the example draws with when none is given on the command line: the
/// one committed for the tests, so that the example runs on any machine.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// The name of the field signed first.
const APPROVAL: &str = "approval";
/// The name of the field signed second.
const REVIEW: &str = "review";
/// When the approval is signed, as its signature states it.
const APPROVED_AT: &str = "2026-09-14T09:00:00+00:00";
/// When the review is signed, as its signature states it.
const REVIEWED_AT: &str = "2026-09-15T14:30:00+00:00";
/// When the validation data of both signatures is kept, as each entry of the
/// security store states it.
const KEPT_AT: &str = "2026-09-16T08:00:00+00:00";
/// The page the two fields are added to, counting from zero: the file's only
/// one.
const PAGE: usize = 0;
/// How far in from the left edge of the sheet every line is set, in points.
const LEFT: f64 = 72.0;
/// Where the baseline of the heading sits, in points up from the foot of the
/// sheet.
const HEADING_BASELINE: f64 = 770.0;
/// The size the heading is set at, in points.
const HEADING_SIZE: f64 = 18.0;
/// The size the body and the text over the command are set at, in points.
const BODY_SIZE: f64 = 10.5;
/// The size the section heading is set at, in points.
const SECTION_SIZE: f64 = 13.0;
/// The size the command is set at, in points.
const COMMAND_SIZE: f64 = 8.5;
/// The size the word over each box is set at, in points.
const LABEL_SIZE: f64 = 9.0;
/// How far the baseline of the word over a box sits above the box's top, in
/// points.
const LABEL_RISE: f64 = 6.0;
/// The two boxes, side by side under the body, each with its field's name: the
/// lower-left corner, the width and the height, in points.
const BOXES: [(&str, f64, f64, f64, f64); 2] = [
(APPROVAL, LEFT, 528.0, 200.0, 44.0),
(REVIEW, 323.0, 528.0, 200.0, 44.0),
];
/// How far the section heading sits below the last line of the body, the boxes
/// standing between the two, in points.
const PAST_THE_BOXES: f64 = 110.0;
/// The grey of the frame around each box, and its width in points.
const BORDER: Rgb = Rgb::gray(0.55);
const BORDER_WIDTH: f64 = 0.75;
/// The words the page is written in, one set per language.
///
/// The command, the signer's name and the moments of signing are not among
/// them.
#[derive(Debug)]
struct Words {
/// What the document is called, at the head of the page and in what the
/// file says of itself.
title: &'static str,
/// Where the file came from, and what was added to it.
received: [&'static str; 3],
/// What the demonstration key proves, and what it does not.
proves: [&'static str; 2],
/// How the two signatures went in, and what each covers.
added: [&'static str; 4],
/// The word over the box signed first.
approval_label: &'static str,
/// The word over the box signed second.
review_label: &'static str,
/// Why the approval was signed, as its signature states it.
approval_reason: &'static str,
/// Why the review was signed, as its signature states it.
review_reason: &'static str,
/// What stands over the way to check the file.
check_heading: &'static str,
/// What to hand the check.
check: [&'static str; 3],
/// What the last section keeps for checking the signatures later.
kept: [&'static str; 2],
}
impl Words {
/// The words the page is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The page in English.
const ENGLISH: Words = Words {
title: "A file received, then signed twice",
received: [
"This page stands for a file somebody else sent. It was written first,",
"on its own, with no form and no place to sign; the two framed boxes below",
"were added to it afterwards, and not one of its bytes has moved.",
],
proves: [
"Both signatures are made with the demonstration key committed in keys/:",
"they prove the bytes unchanged, and nothing about who signed them.",
],
added: [
"Each box went in as a section appended after the file's last byte. Then",
"the approval was signed, and the review after it, each in a section of",
"its own again. The review covers the whole file; the approval still covers",
"exactly the bytes it covered when it was made, and still verifies.",
],
approval_label: "Approval",
review_label: "Review",
approval_reason: "Approves the file received",
review_reason: "Reviews the approved file",
check_heading: "Checking both without this library",
check: [
"The file holds one /ByteRange per signature. For each, join its two runs",
"into covered.bin, decode the structure between them into signature.der,",
"and run:",
],
kept: [
"Last, a fifth section keeps the demonstration certificate in the file's",
"security store, filed under both signatures, so both stay checkable later.",
],
};
/// The page in French.
const FRENCH: Words = Words {
title: "Un fichier reçu, puis signé deux fois",
received: [
"Cette page tient lieu d’un fichier envoyé par quelqu’un d’autre. Il a",
"d’abord été écrit seul, sans formulaire ni place pour signer ; les deux",
"cadres ci-dessous y ont été ajoutés ensuite, sans déplacer un seul octet.",
],
proves: [
"Les deux signatures sont faites avec la clé de démonstration du dossier keys/ :",
"elles prouvent que les octets n’ont pas changé, et rien sur le signataire.",
],
added: [
"Chaque cadre est entré dans une section ajoutée après le dernier octet.",
"Puis l’approbation a été signée, et la relecture après elle, chacune dans",
"sa propre section, elle aussi. La relecture couvre tout le fichier ; l’approbation",
"couvre exactement les octets couverts à sa création, et se vérifie toujours.",
],
approval_label: "Approbation",
review_label: "Relecture",
approval_reason: "Approuve le fichier reçu",
review_reason: "Relit le fichier approuvé",
check_heading: "Les vérifier toutes deux sans cette bibliothèque",
check: [
"Le fichier contient un /ByteRange par signature. Pour chacun, concaténez ses",
"deux plages dans covered.bin, décodez la structure entre elles dans",
"signature.der, puis lancez :",
],
kept: [
"Enfin, une cinquième section conserve le certificat de démonstration, pour les deux",
"signatures, dans le magasin de sécurité du fichier : elles resteront vérifiables.",
],
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Een ontvangen bestand, tweemaal ondertekend",
received: [
"Deze pagina staat voor een bestand van iemand anders. Het is eerst geschreven, op",
"zichzelf, zonder formulier of tekenplek; de twee omkaderde vakken hieronder",
"zijn er later aan toegevoegd, en geen enkele byte ervan is verschoven.",
],
proves: [
"Beide handtekeningen zijn gemaakt met de demonstratiesleutel in keys/:",
"ze bewijzen dat de bytes niet veranderd zijn, en niets over wie tekende.",
],
added: [
"Elk vak kwam erin als een sectie na de laatste byte van het bestand. Daarna",
"werd de goedkeuring ondertekend, en de beoordeling erna, elk weer in een eigen",
"sectie. De beoordeling dekt het hele bestand; de goedkeuring dekt nog steeds",
"precies de bytes die ze dekte toen ze gezet werd, en klopt nog steeds.",
],
approval_label: "Goedkeuring",
review_label: "Beoordeling",
approval_reason: "Keurt het ontvangen bestand goed",
review_reason: "Beoordeelt het goedgekeurde bestand",
check_heading: "Beide controleren zonder deze bibliotheek",
check: [
"Per handtekening is er één /ByteRange. Voeg voor elk de twee reeksen samen",
"tot covered.bin, decodeer de structuur ertussen naar signature.der,",
"en voer uit:",
],
kept: [
"Ten slotte bewaart een vijfde sectie het demonstratiecertificaat in de",
"beveiligingsopslag, zodat beide handtekeningen later te controleren blijven.",
],
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "Um ficheiro recebido, depois assinado duas vezes",
received: [
"Esta página faz as vezes de um ficheiro que alguém enviou. Foi escrito primeiro,",
"sozinho, sem formulário nem lugar para assinar; as duas caixas emolduradas abaixo",
"foram-lhe acrescentadas depois, e nem um dos seus bytes se mexeu.",
],
proves: [
"As duas assinaturas são feitas com a chave de demonstração guardada em keys/:",
"provam que os bytes não mudaram, e nada sobre quem os assinou.",
],
added: [
"Cada caixa entrou numa secção acrescentada após o último byte do ficheiro. Depois",
"foi assinada a aprovação, e a revisão a seguir, cada uma de novo numa secção",
"própria. A revisão cobre o ficheiro inteiro; a aprovação continua a cobrir",
"exatamente os bytes que cobria quando foi feita, e continua a verificar-se.",
],
approval_label: "Aprovação",
review_label: "Revisão",
approval_reason: "Aprova o ficheiro recebido",
review_reason: "Revê o ficheiro aprovado",
check_heading: "Verificar as duas sem esta biblioteca",
check: [
"O ficheiro tem um /ByteRange por assinatura. Para cada uma, junte os dois troços",
"em covered.bin, descodifique a estrutura entre eles em signature.der,",
"e execute:",
],
kept: [
"Por fim, uma quinta secção guarda o certificado de demonstração no",
"arquivo de segurança, para as duas assinaturas continuarem verificáveis.",
],
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Un file ricevuto, poi firmato due volte",
received: [
"Questa pagina rappresenta un file inviato da qualcun altro. È stato scritto prima,",
"da solo, senza modulo né posto per firmare; i due riquadri incorniciati qui sotto",
"gli sono stati aggiunti dopo, e nemmeno uno dei suoi byte si è mosso.",
],
proves: [
"Entrambe le firme sono fatte con la chiave di dimostrazione registrata in keys/:",
"provano che i byte non sono cambiati, e nulla su chi li ha firmati.",
],
added: [
"Ogni riquadro è entrato come una sezione aggiunta dopo l’ultimo byte del file. Poi",
"è stata firmata l’approvazione, poi la revisione, ciascuna di nuovo in una sezione",
"propria. La revisione copre l’intero file; l’approvazione copre ancora",
"esattamente i byte che copriva quando è stata fatta, e si verifica ancora.",
],
approval_label: "Approvazione",
review_label: "Revisione",
approval_reason: "Approva il file ricevuto",
review_reason: "Rivede il file approvato",
check_heading: "Verificarle entrambe senza questa libreria",
check: [
"Il file ha un /ByteRange per firma. Per ciascuna, unite i suoi due tratti",
"in covered.bin, decodificate la struttura tra di essi in signature.der,",
"ed eseguite:",
],
kept: [
"Infine, una quinta sezione conserva il certificato di dimostrazione",
"nell’archivio di sicurezza, perché entrambe le firme restino verificabili.",
],
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Un archivo recibido, y luego firmado dos veces",
received: [
"Esta página representa un archivo que envió otra persona. Se escribió primero,",
"solo, sin formulario ni lugar para firmar; las dos cajas enmarcadas de abajo",
"se le añadieron después, y ni uno de sus bytes se ha movido.",
],
proves: [
"Las dos firmas se hacen con la clave de demostración guardada en keys/:",
"prueban que los bytes no cambiaron, y no prueban nada de quién las firmó.",
],
added: [
"Cada caja entró como una sección añadida tras el último byte del archivo. Luego",
"se firmó la aprobación, y la revisión después, cada una otra vez en una sección",
"propia. La revisión cubre el archivo entero; la aprobación sigue cubriendo",
"exactamente los bytes que cubría al hacerse, y sigue verificándose.",
],
approval_label: "Aprobación",
review_label: "Revisión",
approval_reason: "Aprueba el archivo recibido",
review_reason: "Revisa el archivo aprobado",
check_heading: "Comprobar las dos sin esta biblioteca",
check: [
"El archivo tiene un /ByteRange por firma. Para cada una, concatene sus dos tramos",
"en covered.bin, decodifique la estructura entre ellos en signature.der,",
"y ejecute:",
],
kept: [
"Por último, una quinta sección guarda el certificado de demostración en",
"el almacén de seguridad, para que ambas firmas sigan siendo verificables.",
],
};
/// The page in German.
const GERMAN: Words = Words {
title: "Eine erhaltene Datei, dann zweimal signiert",
received: [
"Diese Seite steht für eine Datei, die jemand anderes schickte. Sie entstand zuerst",
"für sich, ohne Formular und ohne Unterschriftsfeld; die beiden Kästen unten kamen",
"danach hinzu, und kein einziges ihrer Bytes hat sich verändert.",
],
proves: [
"Beide Signaturen stammen vom Vorführschlüssel aus keys/: Sie beweisen,",
"dass die Bytes unverändert sind, und nichts über die Unterzeichner.",
],
added: [
"Jeder Kasten kam als Abschnitt hinter das letzte Byte der Datei. Dann",
"wurde die Freigabe signiert, danach die Prüfung, jede wieder in einem",
"eigenen Abschnitt. Die Prüfung deckt die ganze Datei ab; die Freigabe deckt noch",
"genau die Bytes von damals und lässt sich weiterhin verifizieren.",
],
approval_label: "Freigabe",
review_label: "Prüfung",
approval_reason: "Gibt die erhaltene Datei frei",
review_reason: "Prüft die freigegebene Datei",
check_heading: "Beide ohne diese Bibliothek prüfen",
check: [
"Die Datei enthält je Signatur ein /ByteRange. Für jede die zwei Folgen",
"zu covered.bin zusammenfügen, die Struktur dazwischen zu signature.der",
"dekodieren und ausführen:",
],
kept: [
"Zuletzt legt ein fünfter Abschnitt das Vorführzertifikat im",
"Sicherheitsspeicher der Datei ab, damit beide Signaturen prüfbar bleiben.",
],
};
/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
(Language::English, &ENGLISH),
(Language::French, &FRENCH),
(Language::German, &GERMAN),
(Language::Spanish, &SPANISH),
(Language::Italian, &ITALIAN),
(Language::Portuguese, &PORTUGUESE),
(Language::Dutch, &DUTCH),
];
/// What a line of the page is, which sets its size and how far it sits below
/// the line before it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
/// The heading at the top of the page.
Heading,
/// A line of the body.
Body,
/// The first line of a paragraph of the body after the first.
Paragraph,
/// The section heading.
Section,
/// The first line of the text over the command.
Step,
/// A line carrying on the text over the command.
StepCarriedOn,
/// A line of the command.
Command,
}
impl Kind {
/// The size a line of this kind is set at, in points.
const fn size(self) -> f64 {
match self {
Self::Heading => HEADING_SIZE,
Self::Body | Self::Paragraph | Self::Step | Self::StepCarriedOn => BODY_SIZE,
Self::Section => SECTION_SIZE,
Self::Command => COMMAND_SIZE,
}
}
/// How far a line of this kind sits below the line before it, of kind
/// `before`, in points.
const fn drop_after(self, before: Self) -> f64 {
match (before, self) {
(Self::Heading, _) => 32.0,
(Self::Body, Self::Section) => PAST_THE_BOXES,
(_, Self::Paragraph) | (Self::Section, _) => 22.0,
(Self::Command, Self::Command) => 12.0,
(_, Self::Command) => 14.0,
_ => 15.0,
}
}
}
/// The lines of one block, the first of kind `first` and the others of kind
/// `rest`.
fn block(lines: &[&str], first: Kind, rest: Kind) -> Vec<(String, Kind)> {
lines
.iter()
.enumerate()
.map(|(index, line)| ((*line).to_owned(), if index == 0 { first } else { rest }))
.collect()
}
/// Every line the page draws down its left margin, in the order they are drawn,
/// with its kind.
fn lines(words: &Words) -> Vec<(String, Kind)> {
let mut all = vec![(words.title.to_owned(), Kind::Heading)];
all.extend(block(&words.received, Kind::Body, Kind::Body));
all.extend(block(&words.proves, Kind::Paragraph, Kind::Body));
all.extend(block(&words.added, Kind::Paragraph, Kind::Body));
all.push((words.check_heading.to_owned(), Kind::Section));
all.extend(block(&words.check, Kind::Step, Kind::StepCarriedOn));
all.extend(block(&CHECK_COMMAND, Kind::Command, Kind::Command));
all.extend(block(&words.kept, Kind::Paragraph, Kind::Body));
all
}
/// Every line the page draws down its left margin, in the order they are drawn:
/// what it says, the size it is set at, and where its baseline sits in points
/// up from the foot of the sheet.
fn drawing(words: &Words) -> Vec<(String, f64, f64)> {
let mut drawn = Vec::new();
let mut baseline = HEADING_BASELINE;
let mut before = None;
for (line, kind) in lines(words) {
if let Some(previous) = before {
baseline -= kind.drop_after(previous);
}
drawn.push((line, kind.size(), baseline));
before = Some(kind);
}
drawn
}
/// The word over each box, in the order of [`BOXES`]: what it says, and where
/// its baseline starts.
fn labels(words: &Words) -> [(&'static str, f64, f64); 2] {
let [(_, ax, ay, _, ah), (_, rx, ry, _, rh)] = BOXES;
[
(words.approval_label, ax, ay + ah + LABEL_RISE),
(words.review_label, rx, ry + rh + LABEL_RISE),
]
}
/// The page's text: every line set by its own origin, each in an object of its
/// own, the body first and the word over each box after it.
fn drawn(font: &FontHandle, words: &Words) -> Result<Content, Error> {
let mut content = Content::new();
let over_the_boxes = labels(words)
.into_iter()
.map(|(line, x, baseline)| (line.to_owned(), LABEL_SIZE, x, baseline));
let down_the_margin = drawing(words)
.into_iter()
.map(|(line, size, baseline)| (line, size, LEFT, baseline));
for (line, size, x, baseline) in down_the_margin.chain(over_the_boxes) {
content.begin_text();
content.set_font(font, size)?;
content.text_origin(x, baseline)?;
content.show_glyphs(&font.glyphs(&line));
content.end_text();
}
Ok(content)
}
/// The file received: one page, no form, no place to sign.
fn received(words: &Words, font: Font) -> Result<Vec<u8>, Error> {
let mut doc = Document::new();
doc.set_license(licence::licensed());
doc.set_info(Name::new("Title"), words.title);
let handle = doc.add_font(font);
let mut page = Page::a4();
page.content = drawn(&handle, words)?.into_bytes();
doc.add_page(page)?;
doc.to_bytes()
}
/// An update over `pdf`, under the examples' licence.
fn update(pdf: Vec<u8>) -> Result<IncrementalUpdate, Error> {
let mut update = IncrementalUpdate::new(pdf)?;
update.set_license(licence::licensed());
Ok(update)
}
/// The file with a framed, empty signature field over each box, each added in a
/// section of its own.
fn placed(received: Vec<u8>) -> Result<Vec<u8>, Error> {
let mut bytes = received;
for (name, x, y, width, height) in BOXES {
let field = SignatureField::new(name, x, y, width, height)
.border(FieldBorder::solid(BORDER, BORDER_WIDTH));
bytes = update(bytes)?.to_bytes_with_signature_field(PAGE, &field)?;
}
Ok(bytes)
}
/// Where the approval says it was signed.
const LOCATION: &str = "Paris";
/// How the approval says its signer is reached.
const CONTACT: &str = "contact@hqf-pdf.com";
/// What a signature states about itself: the field it fills, why, and when.
fn signature(field: &str, reason: &str, at: &str) -> Signature {
Signature::new(field)
.name(SIGNER)
.reason(reason)
.signed_at(at)
.sub_filter(SubFilter::EtsiCadesDetached)
}
/// What `certification` allows after it, as the terminal says it.
const fn allowed(certification: Option<Certification>) -> &'static str {
match certification {
None => "an ordinary signature, certifying nothing",
Some(Certification::NoChanges) => "certifies the document, allowing no change",
Some(Certification::FormFilling) => {
"certifies the document, allowing forms filled in and empty fields signed"
}
Some(Certification::Annotating) => {
"certifies the document, allowing forms, signatures and annotations"
}
Some(_) => "certifies the document",
}
}
/// The file with the approval signed: a certifying signature that allows the
/// review to be signed after it, and says where it was made and how to reach
/// its signer.
fn approved(placed: Vec<u8>, words: &Words) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let signed = signature(APPROVAL, words.approval_reason, APPROVED_AT)
.location(LOCATION)
.contact(CONTACT)
.certifies(Certification::FormFilling);
println!("{}: {}", signed.field(), allowed(signed.certification()));
Ok(update(placed)?.to_signed_bytes(&signed, &signer::demonstration()?)?)
}
/// The approved file with the review signed, in the older PKCS #7 form.
fn reviewed(approved: Vec<u8>, words: &Words) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let signed = signature(REVIEW, words.review_reason, REVIEWED_AT)
.sub_filter(SubFilter::AdbePkcs7Detached);
println!("{}: {}", signed.field(), allowed(signed.certification()));
Ok(update(approved)?.to_signed_bytes(&signed, &signer::demonstration()?)?)
}
/// The reviewed file with the demonstration certificate kept in its document
/// security store, filed under each of the two signatures.
fn kept(reviewed: Vec<u8>) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let certificate = signer::run(&signer::CERTIFICATE_COMMAND, &[])?;
let mut store = SecurityStore::new().certificate(certificate.clone());
for field in [APPROVAL, REVIEW] {
store = store.signature(
SignatureValidation::new(field)
.certificate(certificate.clone())
.created_at(KEPT_AT),
);
}
println!(
"security store: {} certificate, filed under {} signatures",
store.certificates().len(),
store.signatures().len()
);
Ok(update(reviewed)?.to_bytes_with_store(&store)?)
}
/// The file received, its two places added, both signed in turn, and the
/// certificate they were signed with kept in it.
fn signed_twice(words: &Words, font: Font) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let approved = approved(placed(received(words, font)?)?, words)?;
kept(reviewed(approved, words)?)
}
/// Writes `bytes` to `path`, making the directory it goes in if it is not
/// there, and says what was written.
fn written(path: &str, bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
if let Some(parent) = Path::new(path).parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, bytes)?;
println!("wrote {path}: {} bytes", bytes.len());
Ok(())
}
fn main() -> std::process::ExitCode {
failure::reported(run_example())
}
fn run_example() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let mut args = env::args().skip(1);
// A named file is written as named; the default one carries the language,
// so the two languages do not overwrite each other in `tmp/`.
let out = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("signed_twice")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let bytes = signed_twice(words, Font::parse(fs::read(&font_path)?)?)?;
written(&out, &bytes)
}
#[cfg(test)]
mod tests {
use hqf_pdf::{Document, Font, IncrementalUpdate};
use super::signature_check::{
byte_ranges, covered_and_signature, openssl_is_there, page_check, scratch,
};
use super::{
APPROVAL, APPROVED_AT, BOXES, CHECK_COMMAND, LABEL_SIZE, LEFT, REVIEW, REVIEWED_AT, WORDS,
Words, approved, default_font, drawing, kept, labels, language, placed, received, reviewed,
};
/// The width of the sheet, in points: A4, which the page is.
const SHEET_WIDTH: f64 = 595.276;
/// The room a line set from the left margin has before it reaches the
/// margin on the other side of the sheet.
const PAPER: f64 = SHEET_WIDTH - 2.0 * LEFT;
/// The lines two languages are allowed to write the same way. There are
/// none: the command and the signer's name are held outside the words.
const SPARED: [&str; 0] = [];
/// The committed font, parsed.
fn a_font() -> Font {
Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
.expect("the committed font parses")
}
/// The four files the example writes one after the other in the language of
/// `words`: received, with its places, approved, reviewed.
fn stages(words: &Words) -> [Vec<u8>; 4] {
let first = received(words, a_font()).expect("the file is written");
let second = placed(first.clone()).expect("the places are added");
let third = approved(second.clone(), words).expect("the approval is signed");
let fourth = reviewed(third.clone(), words).expect("the review is signed");
[first, second, third, fourth]
}
/// The seconds from 1970 to `at`, one of the two moments of signing, which
/// the check is told to judge the certificate at.
fn seconds(at: &str) -> u64 {
// 20 710 days from 1970-01-01 to 2026-09-14, and 20 711 to 2026-09-15.
match at {
APPROVED_AT => 20_710 * 86_400 + 9 * 3_600,
REVIEWED_AT => 20_711 * 86_400 + 14 * 3_600 + 30 * 60,
_ => panic!("{at} is not a moment the example signs at"),
}
}
#[test]
fn every_language_writes_the_page_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the page says these in more than one language: {untranslated:?}"
);
}
/// Nothing on the page is broken to a width: a line down the margin has the
/// paper, and the word over a box has the box.
#[test]
fn every_language_writes_lines_that_fit_the_room_they_have() {
let mut doc = Document::new();
let font = doc.add_font(a_font());
for (named, words) in WORDS {
for (line, size, _) in drawing(words) {
let measured = font.measure(&line, size);
assert!(
measured <= PAPER,
"the {} page draws {line:?} over {measured:.1} points, and \
it has {PAPER:.1}",
named.code()
);
}
for ((label, _, _), (_, _, _, width, _)) in labels(words).into_iter().zip(BOXES) {
let measured = font.measure(label, LABEL_SIZE);
assert!(
measured <= width,
"the {} page sets {label:?} over {measured:.1} points, on a box \
{width} wide",
named.code()
);
}
}
}
/// The page draws no line over the one below it, the words over the boxes
/// stand clear of the last line of the body, and the section heading stands
/// clear of the boxes.
#[test]
fn the_page_draws_no_line_over_the_one_below_it_nor_over_the_boxes() {
for (named, words) in WORDS {
let code = named.code();
let drawn = drawing(words);
for pair in drawn.windows(2) {
let (above, size, higher) = &pair[0];
let (below, _, lower) = &pair[1];
assert!(
higher - lower >= *size,
"the {code} page sets {above:?} at {higher} and {below:?} at \
{lower}, and the first is {size} points tall"
);
}
let body = words.received.len() + words.proves.len() + words.added.len();
let (last, size, above) = &drawn[body];
assert_eq!(last, words.added[3]);
for (label, _, baseline) in labels(words) {
assert!(
above - size >= baseline + LABEL_SIZE,
"the {code} page sets {last:?} at {above}, into {label:?} at \
{baseline}"
);
}
let (heading, size, below) = &drawn[body + 1];
assert_eq!(heading, words.check_heading);
for (name, _, bottom, _, _) in BOXES {
assert!(
below + size <= bottom,
"the {code} page sets {heading:?} at {below}, into the {name} \
box whose bottom is at {bottom}"
);
}
}
}
/// The page states the check it asks for, word for word.
#[test]
fn the_page_states_the_check() {
for (named, words) in WORDS {
let drawn: Vec<String> = drawing(words).into_iter().map(|line| line.0).collect();
for command in CHECK_COMMAND {
assert!(
drawn.iter().any(|line| line == command),
"the {} page does not state {command:?}",
named.code()
);
}
}
}
/// The file received carries no form and no place to sign; the two places
/// are added to it, each file is the whole of the one before it followed by
/// more, and nothing but the two places is offered to sign.
#[test]
fn the_places_are_added_to_a_file_with_no_form_after_every_byte_it_had() {
let words = Words::of(language::Language::English);
let received = received(words, a_font()).expect("the file is written");
let placed = placed(received.clone()).expect("the places are added");
let form = |pdf: &[u8]| pdf.windows(9).any(|window| window == b"/AcroForm");
assert!(!form(&received), "the file received carries a form");
assert!(
IncrementalUpdate::new(received.clone())
.expect("the file reads")
.signature_fields()
.expect("its fields read")
.is_empty()
);
assert!(placed.len() > received.len());
assert_eq!(&placed[..received.len()], received.as_slice());
assert!(form(&placed[received.len()..]));
assert_eq!(
IncrementalUpdate::new(placed)
.expect("the file reads")
.signature_fields()
.expect("its fields read"),
[APPROVAL, REVIEW]
);
}
/// Each signature goes in after every byte of the file it signs, and the
/// review leaves the approval's range where it was: the approval covers the
/// approved file to its last byte, the review covers the whole of the
/// reviewed one.
#[test]
fn each_signature_covers_the_file_it_signed_to_its_last_byte() {
if !openssl_is_there() {
return;
}
let [_, placed, approved, reviewed] = stages(Words::of(language::Language::English));
assert_eq!(&approved[..placed.len()], placed.as_slice());
assert_eq!(&reviewed[..approved.len()], approved.as_slice());
let approval = byte_ranges(&approved);
assert_eq!(approval.len(), 1, "the approved file carries one signature");
let ranges = byte_ranges(&reviewed);
assert_eq!(ranges.len(), 2, "the reviewed file carries two signatures");
assert_eq!(
ranges[0], approval[0],
"the review moved the approval's range"
);
for (range, file) in ranges.iter().zip([&approved, &reviewed]) {
let [start, _, second, length] = *range;
assert_eq!(start, 0);
assert_eq!(second + length, file.len());
}
}
/// `openssl cms -verify`, which shares no code with this library, verifies
/// both signatures of the file the example writes in every language, each
/// over the bytes its own range names; and once a byte of the section the
/// review appended changes, it refuses the review and still verifies the
/// approval, which never covered that section.
#[test]
fn the_check_verifies_both_signatures_and_a_change_after_the_first_breaks_the_second_alone() {
if !openssl_is_there() {
return;
}
for (named, words) in WORDS {
let code = named.code();
let dir = scratch("write-signed-twice", code);
let [_, _, approved, reviewed] = stages(words);
let ranges = byte_ranges(&reviewed);
let moments = [APPROVED_AT, REVIEWED_AT];
for (range, at) in ranges.iter().zip(moments) {
covered_and_signature(&dir, &reviewed, *range);
let (verified, said) = page_check(&dir, seconds(at));
assert!(
verified,
"openssl refused the {code} file's {at} one: {said}"
);
assert!(said.contains("Verification successful"), "{said}");
}
let mut tampered = reviewed.clone();
let past_the_approval = tampered.len() - 3;
assert!(past_the_approval >= approved.len());
tampered[past_the_approval] ^= 0x01;
covered_and_signature(&dir, &tampered, ranges[0]);
let (verified, said) = page_check(&dir, seconds(APPROVED_AT));
assert!(
verified,
"openssl refused the {code} file's approval over a change past it: {said}"
);
covered_and_signature(&dir, &tampered, ranges[1]);
let (verified, _) = page_check(&dir, seconds(REVIEWED_AT));
assert!(
!verified,
"openssl accepted the {code} file's review over changed bytes"
);
std::fs::remove_dir_all(dir).expect("the scratch directory is removed");
}
}
/// The same run twice writes the same file.
#[test]
fn the_example_writes_the_same_file_every_time() {
if !openssl_is_there() {
return;
}
let words = Words::of(language::Language::English);
let once = kept(stages(words)[3].clone()).expect("the store is written");
let again = kept(stages(words)[3].clone()).expect("the store is written");
assert_eq!(once, again);
}
/// The store goes in after every byte of the reviewed file, leaves both
/// ranges where they were, holds the certificate once, and files an entry
/// under each signature; `openssl cms -verify` still verifies both.
#[test]
fn the_store_follows_both_signatures_and_both_still_verify() {
if !openssl_is_there() {
return;
}
let words = Words::of(language::Language::English);
let [_, _, _, reviewed] = stages(words);
let stored = kept(reviewed.clone()).expect("the store is written");
assert_eq!(&stored[..reviewed.len()], reviewed.as_slice());
assert_eq!(byte_ranges(&stored), byte_ranges(&reviewed));
let appended = &stored[reviewed.len()..];
let holds = |needle: &[u8]| {
appended
.windows(needle.len())
.filter(|w| *w == needle)
.count()
};
assert_eq!(holds(b"/DSS"), 1);
assert_eq!(holds(b"/Certs"), 1);
assert_eq!(holds(b"/TU"), 2, "an entry under each signature");
let dir = scratch("write-signed-twice-kept", "en");
for (range, at) in byte_ranges(&stored).iter().zip([APPROVED_AT, REVIEWED_AT]) {
covered_and_signature(&dir, &stored, *range);
let (verified, said) = page_check(&dir, seconds(at));
assert!(verified, "openssl refused the {at} one: {said}");
}
std::fs::remove_dir_all(dir).expect("the scratch directory is removed");
}
}
|