write_signed.rs

Le fichier Rust de l'exemple « Un document signé avec un certificat de démonstration ». Une page qui porte une signature numérique, rompue par le moindre changement du fichier, faite avec un certificat qui n'existe que pour la démonstration. Chaque commande qui a servi à faire la clé et la signature est imprimée sur la page, avec celle qui la vérifie sans cette bibliothèque.

Rust 892 lignes

À quoi sert cet exemple

Un contrat envoyé par courriel peut être modifié en chemin — un montant, une date, une clause — sans que rien sur la page ne le montre. Une signature numérique, elle, le montre. C'est un nombre calculé sur chaque octet du fichier avec une clé privée, et le logiciel de lecture le recalcule à l'ouverture : si un seul octet a bougé, il annonce que la signature est rompue.

Ce que montre cet exemple

  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
//! Writes a document carrying a digital signature, made with a demonstration
//! certificate, and states on its page every command that made it.
//!
//! The library assembles the signature but for the one operation the private
//! key performs, which it hands to a function of the caller's. Here that
//! function runs the `openssl` program, so the key stays in a file the library
//! never opens:
//!
//! 1. the key and its certificate were made once, from the repository's root,
//!    by the command [`KEY_COMMAND`] states, and are committed under `keys/`;
//! 2. the certificate is handed to the library as DER, which
//!    [`CERTIFICATE_COMMAND`] writes out of the committed PEM file;
//! 3. the library reserves room in the file for the signature, takes the
//!    SHA-256 digest of every byte around that room, and hands the function
//!    the DER of the signed attributes naming that digest; the function pipes
//!    them to [`SIGN_COMMAND`], whose output is their RSA PKCS #1 v1.5
//!    signature;
//! 4. the library wraps that signature and the certificate into the CMS
//!    structure of a `PAdES` B-B signature and writes it, in hexadecimal, into
//!    the room between the two runs of bytes `/ByteRange` names.
//!
//! [`CHECK_COMMAND`] is what checks the file without this library: it is handed
//! the two runs joined into one file and the structure decoded into another.
//!
//! The certificate is a demonstration one, trusted by nobody, and its private
//! key is committed beside it, under `keys/`: the signature shows the file has
//! not changed, and says nothing about who signed it. 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 commands, the
//! signer's name and the moment of signing are not: a command is typed as it
//! stands, and the name is the one the certificate carries.
//!
//! Usage: `cargo run --example write_signed -- tmp/signed.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_signed`

use std::env;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{
    CadesSigner, Document, Error, FieldBorder, Font, FontHandle, Page, Rgb, Signature,
    SignatureAppearance, SignatureField, 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;

use language::Language;

/// 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 repository's root, which every command is run from.
fn root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..")
}

/// The command that made the demonstration key and its certificate, as the page
/// sets it over three lines. The example does not run it: its output is
/// committed.
const KEY_COMMAND: [&str; 3] = [
    "openssl req -x509 -newkey rsa:2048 -nodes -days 3650",
    "    -subj \"/CN=hqf-pdf demonstration signer\"",
    "    -keyout keys/demonstration_signer.key -out keys/demonstration_signer.crt",
];

/// The command that writes the certificate as DER, run from the repository's
/// root.
const CERTIFICATE_COMMAND: [&str; 6] = [
    "openssl",
    "x509",
    "-in",
    "keys/demonstration_signer.crt",
    "-outform",
    "DER",
];

/// The command that signs what it reads on its standard input with the
/// demonstration key, run from the repository's root.
const SIGN_COMMAND: [&str; 5] = [
    "openssl",
    "dgst",
    "-sha256",
    "-sign",
    "keys/demonstration_signer.key",
];

/// The command that checks the signature without this library, as the page sets
/// it over two lines.
const CHECK_COMMAND: [&str; 2] = [
    "openssl cms -verify -binary -inform DER -in signature.der -content covered.bin",
    "    -CAfile keys/demonstration_signer.crt -purpose any",
];

/// The name the certificate carries, which the signature states and the box on
/// the page shows.
const SIGNER: &str = "hqf-pdf demonstration signer";

/// When the document is signed, as the signature states it.
const SIGNED_AT: &str = "2026-09-13T08:00:00+00:00";

/// The same moment, as the box on the page shows it.
const SIGNED_AT_SHOWN: &str = "2026-09-13 08:00 UTC";

/// The name of the signature field.
const FIELD: &str = "approval";

/// 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 steps are set at, in points.
const BODY_SIZE: f64 = 10.5;

/// The size a section heading is set at, in points.
const SECTION_SIZE: f64 = 13.0;

/// The size a command is set at, in points.
const COMMAND_SIZE: f64 = 8.5;

/// The signature box, under the body: its lower-left corner, its width and its
/// height, in points.
const BOX: (f64, f64, f64, f64) = (LEFT, 579.0, 260.0, 44.0);

/// How far the heading over the steps sits below the last line of the body, the
/// signature box standing between the two, in points.
const PAST_THE_BOX: f64 = 92.0;

/// The size the lines in the signature box are set at, in points.
const BOX_SIZE: f64 = 9.0;

/// The grey of the frame around the signature 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 commands, the signer's name and the moment 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,
    /// What the signature covers.
    covers: [&'static str; 3],
    /// What a demonstration certificate proves, and what it does not.
    proves: [&'static str; 4],
    /// Why the document was signed, as the signature states it.
    reason: &'static str,
    /// What stands before the moment of signing in the signature box.
    signed_label: &'static str,
    /// What stands over the steps that made the signature.
    made_heading: &'static str,
    /// The first step: the key and its certificate.
    made_key: &'static str,
    /// The second step: the certificate as DER.
    made_certificate: &'static str,
    /// The third step: what the key signs.
    made_signature: [&'static str; 3],
    /// The fourth step: where the signature lands in the file.
    made_structure: [&'static str; 2],
    /// What stands over the way to check the file.
    check_heading: &'static str,
    /// What to hand the check.
    check: [&'static str; 4],
}

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 signed document, and how it was signed",
    covers: [
        "This file carries a digital signature. It covers every byte of the file",
        "but the place it is written in: one byte changed anywhere breaks it, and",
        "reading software says so.",
    ],
    proves: [
        "The certificate is a demonstration one: it was made for this example,",
        "and it names no person and no company. The signature proves the file",
        "has not changed; it proves nothing about who signed it, since nobody",
        "vouches for this certificate.",
    ],
    reason: "Shows how a document is signed",
    signed_label: "Signed",
    made_heading: "How it was signed",
    made_key: "1. The key and its certificate were made once, from the repository's root:",
    made_certificate: "2. The library is handed the certificate as DER, which this writes:",
    made_signature: [
        "3. The library leaves room in the file for the signature, takes the digest",
        "of every byte around it, and hands the program the attributes to sign.",
        "The key signs them, and never reaches the library:",
    ],
    made_structure: [
        "4. The library wraps that signature and the certificate into the structure",
        "a PAdES signature carries, and writes it into the room it left.",
    ],
    check_heading: "Checking it without this library",
    check: [
        "The file's /ByteRange names the two runs of bytes the signature covers,",
        "and /Contents holds the structure between them, in hexadecimal. Join",
        "the two runs into covered.bin, decode the structure into signature.der,",
        "and run:",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Un document signé, et comment il l'a été",
    covers: [
        "Ce fichier porte une signature numérique. Elle couvre chaque octet du",
        "fichier sauf la place où elle est écrite : un seul octet changé, où que",
        "ce soit, la rompt, et le logiciel de lecture le dit.",
    ],
    proves: [
        "Le certificat est un certificat de démonstration : il a été fait pour",
        "cet exemple, et il ne nomme ni personne ni entreprise. La signature",
        "prouve que le fichier n'a pas changé ; elle ne prouve rien de qui l'a",
        "signé, puisque personne ne se porte garant de ce certificat.",
    ],
    reason: "Montre comment un document est signé",
    signed_label: "Signé le",
    made_heading: "Comment il a été signé",
    made_key: "1. La clé et son certificat ont été faits une fois, depuis la racine du dépôt :",
    made_certificate: "2. La bibliothèque reçoit le certificat en DER, que ceci écrit :",
    made_signature: [
        "3. La bibliothèque laisse dans le fichier la place de la signature, calcule",
        "l'empreinte de chaque octet autour, et donne au programme les attributs à",
        "signer. La clé les signe, et n'entre jamais dans la bibliothèque :",
    ],
    made_structure: [
        "4. La bibliothèque enveloppe cette signature et le certificat dans la",
        "structure qu'une signature PAdES porte, et l'écrit dans la place laissée.",
    ],
    check_heading: "Le vérifier sans cette bibliothèque",
    check: [
        "Le /ByteRange du fichier nomme les deux plages d'octets que la signature",
        "couvre, et /Contents contient la structure entre elles, en hexadécimal.",
        "Joignez les deux plages dans covered.bin, décodez la structure dans",
        "signature.der, puis lancez :",
    ],
};

/// 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); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// 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,
    /// A section heading.
    Section,
    /// The first line of a step, or of the text over a command.
    Step,
    /// A line carrying on a step.
    StepCarriedOn,
    /// A line of a 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_BOX,
            (_, Self::Section) => 30.0,
            (_, Self::Paragraph) | (Self::Section, _) => 22.0,
            (Self::Command, Self::Command) => 12.0,
            (_, Self::Command) => 14.0,
            (Self::Command, _) => 19.0,
            _ => 15.0,
        }
    }
}

/// Every line the page draws, 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(
        words
            .covers
            .iter()
            .map(|line| ((*line).to_owned(), Kind::Body)),
    );
    for (index, line) in words.proves.iter().enumerate() {
        let kind = if index == 0 {
            Kind::Paragraph
        } else {
            Kind::Body
        };
        all.push(((*line).to_owned(), kind));
    }
    all.push((words.made_heading.to_owned(), Kind::Section));
    all.push((words.made_key.to_owned(), Kind::Step));
    all.extend(
        KEY_COMMAND
            .iter()
            .map(|line| ((*line).to_owned(), Kind::Command)),
    );
    all.push((words.made_certificate.to_owned(), Kind::Step));
    all.push((CERTIFICATE_COMMAND.join(" "), Kind::Command));
    for (index, line) in words.made_signature.iter().enumerate() {
        let kind = if index == 0 {
            Kind::Step
        } else {
            Kind::StepCarriedOn
        };
        all.push(((*line).to_owned(), kind));
    }
    all.push((SIGN_COMMAND.join(" "), Kind::Command));
    for (index, line) in words.made_structure.iter().enumerate() {
        let kind = if index == 0 {
            Kind::Step
        } else {
            Kind::StepCarriedOn
        };
        all.push(((*line).to_owned(), kind));
    }
    all.push((words.check_heading.to_owned(), Kind::Section));
    for (index, line) in words.check.iter().enumerate() {
        let kind = if index == 0 {
            Kind::Step
        } else {
            Kind::StepCarriedOn
        };
        all.push(((*line).to_owned(), kind));
    }
    all.extend(
        CHECK_COMMAND
            .iter()
            .map(|line| ((*line).to_owned(), Kind::Command)),
    );
    all
}

/// Every line the page draws, 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 page's text: every line set by its own origin, each in an object of its
/// own.
fn drawn(font: &FontHandle, lines: &[(String, f64, f64)]) -> Result<Content, Error> {
    let mut content = Content::new();
    for (line, size, baseline) in lines {
        content.begin_text();
        content.set_font(font, *size)?;
        content.text_origin(LEFT, *baseline)?;
        content.show_glyphs(&font.glyphs(line));
        content.end_text();
    }
    Ok(content)
}

/// The signature box: a framed field that shows, once signed, who signed it and
/// when.
fn signature_box(font: &FontHandle, words: &Words) -> SignatureField {
    let (x, y, width, height) = BOX;
    let shown = SignatureAppearance::new(font.name(), BOX_SIZE)
        .line(SIGNER)
        .line(format!("{} {SIGNED_AT_SHOWN}", words.signed_label));
    SignatureField::new(FIELD, x, y, width, height)
        .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
        .appearance(shown)
}

/// The document and its one page, before it is signed.
fn document(words: &Words, font: Font) -> Result<Document, 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, &drawing(words))?.into_bytes();
    page.fields.push(signature_box(&handle, words).into());
    doc.add_page(page)?;
    Ok(doc)
}

/// What the signature states about itself.
fn signature(words: &Words) -> Signature {
    Signature::new(FIELD)
        .name(SIGNER)
        .reason(words.reason)
        .signed_at(SIGNED_AT)
        .sub_filter(SubFilter::EtsiCadesDetached)
}

/// Runs the command `arguments` names from the repository's root, handing it
/// `input` on its standard input, and returns what it writes on its standard
/// output, or what it said on failing.
fn run(arguments: &[&str], input: &[u8]) -> Result<Vec<u8>, String> {
    let (program, rest) = arguments.split_first().ok_or("no command was named")?;
    let mut child = Command::new(program)
        .args(rest)
        .current_dir(root())
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|error| format!("{program} could not be run: {error}"))?;
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(input)
            .map_err(|error| format!("{program} was not handed its input: {error}"))?;
    }
    let out = child
        .wait_with_output()
        .map_err(|error| format!("{program} did not finish: {error}"))?;
    if !out.status.success() {
        return Err(format!(
            "{} failed: {}",
            arguments.join(" "),
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    Ok(out.stdout)
}

/// The document signed with the demonstration key, through `openssl`.
fn signed(words: &Words, font: Font) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let certificate = run(&CERTIFICATE_COMMAND, &[])?;
    let signer = CadesSigner::new([certificate], |attributes: &[u8]| {
        run(&SIGN_COMMAND, attributes).map_err(|what| Error::SigningFailed { what })
    })?;
    Ok(document(words, font)?.to_signed_bytes(&signature(words), &signer)?)
}

/// 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")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let bytes = signed(words, Font::parse(fs::read(&font_path)?)?)?;
    written(&out, &bytes)
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};
    use std::process::Command;

    use hqf_pdf::{Document, Font};

    use super::{
        BOX, CERTIFICATE_COMMAND, CHECK_COMMAND, KEY_COMMAND, LEFT, SIGN_COMMAND, SIGNED_AT,
        SIGNER, WORDS, Words, default_font, drawing, language, root, run, signed,
    };

    /// 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 commands 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 signed file the example writes in the language of `words`.
    fn written(words: &Words) -> Vec<u8> {
        signed(words, a_font()).expect("the document is signed")
    }

    /// Whether `openssl` is there to judge what was written, refusing to let
    /// the measurement pass for a success where it must be.
    ///
    /// Under Linux — the system every check of this repository is run on — a
    /// missing program is a failure. Elsewhere the measurement is named as NOT
    /// RUN and the test ends, which the run's output carries.
    ///
    /// # Panics
    ///
    /// Panics under Linux when `openssl` is not installed.
    #[cfg(target_os = "linux")]
    fn openssl_is_there() -> bool {
        assert!(
            installed(),
            "openssl is not installed, and it is what signs this document"
        );
        true
    }

    #[cfg(not(target_os = "linux"))]
    fn openssl_is_there() -> bool {
        if installed() {
            return true;
        }
        println!("NOT RUN: openssl is not on this machine, so nothing was signed");
        false
    }

    /// Whether `openssl` is on the machine.
    fn installed() -> bool {
        Command::new("openssl")
            .arg("version")
            .output()
            .is_ok_and(|out| out.status.success())
    }

    #[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 longer than the paper
    /// runs off the edge of it.
    #[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()
                );
            }
        }
    }

    /// The page draws no line over the one below it, and the signature box
    /// stands clear of the last line of the body above it and of the heading
    /// below it.
    #[test]
    fn the_page_draws_no_line_over_the_one_below_it_nor_over_the_box() {
        let (_, box_bottom, _, box_height) = BOX;
        let box_top = box_bottom + box_height;
        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.covers.len() + words.proves.len();
            let (last, size, above) = &drawn[body];
            assert_eq!(last, words.proves[3]);
            assert!(
                above - size >= box_top,
                "the {code} page sets {last:?} at {above}, into the box whose top \
                 is at {box_top}"
            );
            let (heading, size, below) = &drawn[body + 1];
            assert_eq!(heading, words.made_heading);
            assert!(
                below + size <= box_bottom,
                "the {code} page sets {heading:?} at {below}, into the box whose \
                 bottom is at {box_bottom}"
            );
        }
    }

    /// The commands the example runs are the ones the page states, word for
    /// word, beside the one that made the key and the one that checks the file,
    /// and each names a file that is committed.
    #[test]
    fn the_page_states_the_commands_the_example_runs_on_files_that_are_there() {
        for (named, words) in WORDS {
            let drawn: Vec<String> = drawing(words).into_iter().map(|line| line.0).collect();
            let stated = [CERTIFICATE_COMMAND.join(" "), SIGN_COMMAND.join(" ")]
                .into_iter()
                .chain(KEY_COMMAND.iter().map(|line| (*line).to_owned()))
                .chain(CHECK_COMMAND.iter().map(|line| (*line).to_owned()));
            for command in stated {
                assert!(
                    drawn.contains(&command),
                    "the {} page does not state {command:?}",
                    named.code()
                );
            }
        }
        for file in [CERTIFICATE_COMMAND[3], SIGN_COMMAND[4]] {
            assert!(root().join(file).is_file(), "{file} is not committed");
        }
        assert!(KEY_COMMAND.join(" ").contains(CERTIFICATE_COMMAND[3]));
        assert!(KEY_COMMAND.join(" ").contains(SIGN_COMMAND[4]));
        assert!(CHECK_COMMAND.join(" ").contains(CERTIFICATE_COMMAND[3]));
    }

    /// The committed certificate names the signer the page shows and nobody
    /// else, and the committed key is the one it certifies.
    #[test]
    fn the_committed_key_is_the_one_the_certificate_names_the_demonstration_signer_for() {
        if !openssl_is_there() {
            return;
        }
        let subject = run(
            &[
                "openssl",
                "x509",
                "-in",
                CERTIFICATE_COMMAND[3],
                "-noout",
                "-subject",
                "-issuer",
            ],
            &[],
        )
        .expect("the certificate reads");
        assert_eq!(
            String::from_utf8_lossy(&subject),
            format!("subject=CN = {SIGNER}\nissuer=CN = {SIGNER}\n")
        );
        assert!(KEY_COMMAND.join(" ").contains(&format!("/CN={SIGNER}\"")));

        let certified = run(
            &[
                "openssl",
                "x509",
                "-in",
                CERTIFICATE_COMMAND[3],
                "-noout",
                "-modulus",
            ],
            &[],
        )
        .expect("the certificate reads");
        let held = run(
            &[
                "openssl",
                "rsa",
                "-in",
                SIGN_COMMAND[4],
                "-noout",
                "-modulus",
            ],
            &[],
        )
        .expect("the key reads");
        assert!(certified.starts_with(b"Modulus="));
        assert_eq!(certified, held, "the key is not the certificate's");
    }

    /// The same document signed twice is the same file: an RSA PKCS #1 v1.5
    /// signature over the same bytes is the same signature.
    #[test]
    fn the_same_document_signed_twice_is_the_same_file() {
        if !openssl_is_there() {
            return;
        }
        let words = Words::of(language::Language::English);
        assert_eq!(written(words), written(words));
    }

    /// A directory of its own for one case.
    fn scratch(case: &str) -> PathBuf {
        let mut at = std::env::temp_dir();
        at.push(format!(
            "hqf-pdf-write-signed-{}-{case}",
            std::process::id()
        ));
        std::fs::create_dir_all(&at).expect("the scratch directory is made");
        at
    }

    /// The four numbers of the file's `/ByteRange`, read off its bytes.
    fn byte_range(pdf: &[u8]) -> [usize; 4] {
        let at = pdf
            .windows(11)
            .position(|window| window == b"/ByteRange ")
            .expect("a /ByteRange");
        let open = at + pdf[at..].iter().position(|&byte| byte == b'[').expect("[");
        let close = open
            + pdf[open..]
                .iter()
                .position(|&byte| byte == b']')
                .expect("]");
        let numbers: Vec<usize> = std::str::from_utf8(&pdf[open + 1..close])
            .expect("digits")
            .split_whitespace()
            .map(|number| number.parse().expect("a number"))
            .collect();
        numbers.try_into().expect("four numbers")
    }

    /// Writes into `dir` what the page says to hand the check: the two runs of
    /// bytes `/ByteRange` names joined into `covered.bin`, and the structure
    /// `/Contents` holds, its zero padding taken off, into `signature.der`.
    fn covered_and_signature(dir: &Path, pdf: &[u8]) {
        let [first, first_len, second, second_len] = byte_range(pdf);
        let mut covered = pdf[first..first + first_len].to_vec();
        covered.extend_from_slice(&pdf[second..second + second_len]);

        let hex = &pdf[first + first_len + 1..second - 1];
        let bytes: Vec<u8> = hex
            .chunks_exact(2)
            .map(|pair| {
                u8::from_str_radix(std::str::from_utf8(pair).expect("hex"), 16).expect("hex digit")
            })
            .collect();
        assert_eq!(bytes[0], 0x30, "the structure is a SEQUENCE");
        let length = match bytes[1] {
            short @ 0..0x80 => usize::from(short) + 2,
            long => {
                let count = usize::from(long & 0x7F);
                bytes[2..2 + count]
                    .iter()
                    .fold(0, |len, &octet| (len << 8) | usize::from(octet))
                    + 2
                    + count
            }
        };
        assert!(
            bytes[length..].iter().all(|&byte| byte == 0),
            "only zero padding follows the structure"
        );
        std::fs::write(dir.join("covered.bin"), covered).expect("written");
        std::fs::write(dir.join("signature.der"), &bytes[..length]).expect("written");
    }

    /// The seconds from 1970 to the moment the document is signed, which the
    /// check is told to judge the certificate at.
    fn signed_at_seconds() -> String {
        assert_eq!(SIGNED_AT, "2026-09-13T08:00:00+00:00");
        // 20 709 days from 1970-01-01 to 2026-09-13, and eight hours.
        (20_709_u64 * 86_400 + 8 * 3_600).to_string()
    }

    /// Runs the check the page states in `dir`, the certificate named by its
    /// place in the repository, and says whether it verified and what it said.
    fn page_check(dir: &Path) -> (bool, String) {
        let stated = CHECK_COMMAND.join(" ");
        let mut arguments: Vec<String> = stated.split_whitespace().map(str::to_owned).collect();
        let certificate = arguments
            .iter()
            .position(|word| word == CERTIFICATE_COMMAND[3])
            .expect("the check names the certificate");
        arguments[certificate] = root()
            .join(CERTIFICATE_COMMAND[3])
            .to_string_lossy()
            .into_owned();
        arguments.extend(["-attime".to_owned(), signed_at_seconds()]);
        arguments.extend(["-out".to_owned(), "/dev/null".to_owned()]);
        let out = Command::new(&arguments[0])
            .args(&arguments[1..])
            .current_dir(dir)
            .output()
            .expect("openssl runs");
        (
            out.status.success(),
            String::from_utf8_lossy(&out.stderr).into_owned(),
        )
    }

    /// `openssl cms -verify`, which shares no code with this library, verifies
    /// the signature of the file the example writes in every language, run as
    /// the page states it; and refuses it once one covered byte changes.
    #[test]
    fn the_check_the_page_states_verifies_the_file_and_refuses_it_once_a_byte_changes() {
        if !openssl_is_there() {
            return;
        }
        for (named, words) in WORDS {
            let dir = scratch(named.code());
            let pdf = written(words);
            covered_and_signature(&dir, &pdf);

            let (verified, said) = page_check(&dir);
            assert!(
                verified,
                "openssl refused the {} file's signature: {said}",
                named.code()
            );
            assert!(said.contains("Verification successful"), "{said}");

            let covered = dir.join("covered.bin");
            let mut tampered = std::fs::read(&covered).expect("read");
            let middle = tampered.len() / 2;
            tampered[middle] ^= 0x01;
            std::fs::write(&covered, tampered).expect("written");
            let (verified, _) = page_check(&dir);
            assert!(
                !verified,
                "openssl accepted the {} file's signature over changed bytes",
                named.code()
            );

            std::fs::remove_dir_all(dir).expect("the scratch directory is removed");
        }
    }
}