revenant-sign-core 3.0.5

Cross-platform client library for ARX CoSign / DocuSign Signature Appliance electronic signatures via the OASIS DSS SOAP API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Core signing operations: detached CMS and embedded PDF signatures.
//!
//! Every function takes a [`SigningTransport`], so the signing logic stays
//! transport-agnostic -- the appliance holds the private key and returns a
//! CMS/PKCS#7 blob, and none of it is constructed client-side. The high-level,
//! config-resolving entry points (`sign`, `sign_detached`) live in
//! [`crate::api`].

use std::time::Duration;

use crate::appearance::{compute_optimal_height, compute_optimal_width, get_font};
use crate::constants::{PDF_MAGIC, SHA1_DIGEST_SIZE};
use crate::net::SigningTransport;
use crate::pdf::{
    compute_byterange_hash, insert_cms, prepare_pdf_with_sig_field, verify_embedded_signature,
    PageSpec, Position, PrepareOptions, PreparedPdf, SIG_HEIGHT, SIG_WIDTH,
};
use crate::signing_response::{check_response_over_content, check_response_over_digest};
use crate::{Result, RevenantError};

/// Placement and appearance options for an embedded PDF signature.
///
/// Bundles everything [`sign_pdf_embedded`] needs beyond the transport and
/// credentials. Construct from [`EmbeddedSignatureOptions::default`] and set the
/// fields that matter. `x`/`y`/`w`/`h` are `None` when unset: an unset `w`/`h`
/// auto-sizes to the display fields (visible signatures only), and `x`/`y` fall
/// back to the `position` preset unless *both* are given.
#[derive(Debug, Clone)]
pub struct EmbeddedSignatureOptions {
    /// The page to place the signature on.
    pub page: PageSpec,
    /// Placement preset, used unless both `x` and `y` are set.
    pub position: Position,
    /// Manual x-coordinate (PDF points, origin = bottom-left).
    pub x: Option<f64>,
    /// Manual y-coordinate (PDF points, origin = bottom-left).
    pub y: Option<f64>,
    /// Signature field width in PDF points; auto-sized when `None`.
    pub w: Option<f64>,
    /// Signature field height in PDF points; auto-sized when `None`.
    pub h: Option<f64>,
    /// The `/Reason` string.
    pub reason: String,
    /// Signer display name (for `/Name` and the default first field).
    pub name: Option<String>,
    /// Path to a PNG/JPEG signature image.
    pub image_path: Option<String>,
    /// Explicit ordered display strings; defaults to name + auto date.
    pub fields: Option<Vec<String>>,
    /// Whether the signature has a visual appearance.
    pub visible: bool,
    /// Font registry key (e.g. `"noto-sans"`, `"ghea-grapalat"`).
    pub font: Option<String>,
}

impl Default for EmbeddedSignatureOptions {
    fn default() -> Self {
        Self {
            page: PageSpec::Last,
            position: Position::BottomRight,
            x: None,
            y: None,
            w: None,
            h: None,
            reason: String::new(),
            name: None,
            image_path: None,
            fields: None,
            visible: true,
            font: None,
        }
    }
}

/// Reject input that does not look like a PDF (fail-loud, before the network).
fn validate_pdf(pdf: &[u8]) -> Result<()> {
    if pdf.is_empty() || !pdf.starts_with(PDF_MAGIC) {
        return Err(RevenantError::Pdf(
            "Input does not appear to be a PDF file.".to_owned(),
        ));
    }
    Ok(())
}

/// Sign a PDF and return a detached CMS/PKCS#7 signature.
///
/// The response is verified against the submitted bytes before it is returned:
/// a signature nobody could check is not a result worth handing back.
///
/// # Errors
///
/// Returns [`RevenantError::Pdf`] if the input is not a PDF,
/// [`RevenantError::SigningResponse`] if the response is not a signature over
/// `pdf`, or a transport error (auth, server, TLS) from the signing service.
pub fn sign_pdf_detached(
    pdf: &[u8],
    transport: &dyn SigningTransport,
    username: &str,
    password: &str,
    timeout: Duration,
) -> Result<Vec<u8>> {
    validate_pdf(pdf)?;
    let cms_der = transport.sign_pdf_detached(pdf, username, password, timeout)?;
    check_response_over_content(&cms_der, pdf, "sign_pdf_detached")?;
    Ok(cms_der)
}

/// Sign a pre-computed 20-byte SHA-1 hash.
///
/// Signs the hash bytes themselves. What a service does with a submitted digest
/// is service-defined and observed to vary: some sign it as a pre-computed
/// digest, others hash it again and sign it as ordinary content. Only the first
/// kind yields a signature that can be attached to the document the hash came
/// from, so the response is checked to be a genuine signature and a warning is
/// logged when it does not bind the submitted digest. To sign a document, pass
/// the document to [`sign_data`].
///
/// # Errors
///
/// Returns [`RevenantError::Other`] if the hash is not exactly
/// [`SHA1_DIGEST_SIZE`] bytes, [`RevenantError::SigningResponse`] if the
/// response is not a verifiable signature, or a transport error from the
/// signing service.
pub fn sign_hash(
    hash: &[u8],
    transport: &dyn SigningTransport,
    username: &str,
    password: &str,
    timeout: Duration,
) -> Result<Vec<u8>> {
    if hash.len() != SHA1_DIGEST_SIZE {
        return Err(RevenantError::Other(format!(
            "Expected {SHA1_DIGEST_SIZE}-byte SHA-1 hash, got {} bytes.",
            hash.len()
        )));
    }
    let cms_der = transport.sign_hash(hash, username, password, timeout)?;
    check_response_over_digest(&cms_der, hash, "sign_hash")?;
    Ok(cms_der)
}

/// Sign arbitrary data; the server hashes it and returns a CMS/PKCS#7 signature.
///
/// The response is verified against `data` before it is returned.
///
/// # Errors
///
/// Returns [`RevenantError::Other`] on empty input,
/// [`RevenantError::SigningResponse`] if the response is not a signature over
/// `data`, or a transport error from the signing service.
pub fn sign_data(
    data: &[u8],
    transport: &dyn SigningTransport,
    username: &str,
    password: &str,
    timeout: Duration,
) -> Result<Vec<u8>> {
    if data.is_empty() {
        return Err(RevenantError::Other("Cannot sign empty data.".to_owned()));
    }
    let cms_der = transport.sign_data(data, username, password, timeout)?;
    check_response_over_content(&cms_der, data, "sign_data")?;
    Ok(cms_der)
}

/// Sign a PDF with an embedded signature (hash-then-sign around the appliance).
///
/// The flow is: prepare the PDF with an empty signature field, extract the
/// ByteRange data (everything but the reserved `/Contents` hex), send it to the
/// transport for signing, splice the returned CMS back in, and verify the result
/// before returning it. A failed post-sign verification is an error -- a corrupt
/// signed PDF is never returned.
///
/// # Errors
///
/// Returns [`RevenantError::Pdf`] if the input is not a PDF, the geometry is
/// invalid, preparation/insertion fails, or post-sign verification fails; or a
/// transport error from the signing service.
pub fn sign_pdf_embedded(
    pdf: &[u8],
    transport: &dyn SigningTransport,
    username: &str,
    password: &str,
    timeout: Duration,
    options: &EmbeddedSignatureOptions,
) -> Result<Vec<u8>> {
    validate_pdf(pdf)?;

    let mut w = options.w.unwrap_or(SIG_WIDTH);
    let mut h = options.h.unwrap_or(SIG_HEIGHT);
    if w <= 0.0 || h <= 0.0 {
        return Err(RevenantError::Pdf(format!(
            "Signature dimensions must be positive, got w={w}, h={h}"
        )));
    }
    if let Some(x) = options.x.filter(|&x| x < 0.0) {
        return Err(RevenantError::Pdf(format!(
            "Signature x-coordinate must be non-negative, got {x}"
        )));
    }
    if let Some(y) = options.y.filter(|&y| y < 0.0) {
        return Err(RevenantError::Pdf(format!(
            "Signature y-coordinate must be non-negative, got {y}"
        )));
    }

    log::info!(
        "Signing PDF (embedded, {}): {} bytes, position={}",
        if options.visible {
            "visible"
        } else {
            "invisible"
        },
        pdf.len(),
        options.position.canonical_name(),
    );

    // Auto-size the field to the explicit display fields, for visible
    // signatures where the caller left the dimension unset.
    if options.visible {
        if let Some(fields) = options.fields.as_ref().filter(|f| !f.is_empty()) {
            let font = get_font(options.font.as_deref())?;
            let has_img = options.image_path.is_some();
            if options.w.is_none() {
                w = compute_optimal_width(fields, h, has_img, font);
                log::debug!("Adaptive signature width: {w:.1} pt");
            }
            if options.h.is_none() {
                h = compute_optimal_height(fields, w, has_img, font);
                log::debug!("Adaptive signature height: {h:.1} pt");
            }
        }
    }

    // Step 1: prepare the PDF with an empty signature field.
    let manual_xy = options.x.zip(options.y);
    let prepare_opts = PrepareOptions {
        page: options.page,
        position: options.position,
        manual_xy,
        size: (w, h),
        reason: &options.reason,
        name: options.name.as_deref(),
        image_path: options.image_path.as_deref(),
        fields: options.fields.clone(),
        visible: options.visible,
        font: options.font.as_deref(),
    };
    let PreparedPdf {
        bytes: prepared,
        contents_hex_offset: hex_start,
        contents_hex_len: hex_len,
    } = prepare_pdf_with_sig_field(pdf, &prepare_opts)?;

    // Step 2: extract the ByteRange data (everything except the hex placeholder;
    // +1 skips the closing '>').
    let mut br_data = Vec::with_capacity(prepared.len().saturating_sub(hex_len + 1));
    br_data.extend_from_slice(&prepared[..hex_start]);
    br_data.extend_from_slice(&prepared[hex_start + hex_len + 1..]);

    // Step 3: sign the ByteRange data.
    let cms_der = sign_data(&br_data, transport, username, password, timeout)?;

    // Step 4: splice the CMS into the reserved /Contents.
    let signed = insert_cms(&prepared, hex_start, hex_len, &cms_der)?;
    if signed.len() != prepared.len() {
        return Err(RevenantError::Pdf(format!(
            "insert_cms changed PDF size: {} -> {}",
            prepared.len(),
            signed.len()
        )));
    }

    // Step 5: verify before returning -- never emit a PDF whose signature we
    // have not proven. This is more than a splice self-test: the response came
    // from the network, so it is checked the same way an arbitrary signed PDF
    // would be. Structure and the ByteRange hash show the splice preserved the
    // signed bytes; the signature check shows the appliance actually signed
    // them, rather than returning something that merely hashes correctly.
    let br_hash = compute_byterange_hash(&prepared, hex_start, hex_len)?;
    let result = verify_embedded_signature(&signed, Some(&br_hash), None);
    if !result.valid() {
        let detail = result.details.join("\n  ");
        log::error!("Post-sign verification failed: {detail}");
        return Err(RevenantError::Pdf(format!(
            "Post-sign verification FAILED:\n  {detail}\nThe signed PDF may be corrupt -- not saved."
        )));
    }

    log::info!("Signed PDF complete: {} bytes", signed.len());
    Ok(signed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cms::{extract_signature_data, find_byteranges};
    use crate::testutil::{sign_cms_detached, TestSigner};

    const BLANK_LETTER: &[u8] = include_bytes!("pdf/testdata/blank_letter.pdf");

    fn timeout() -> Duration {
        Duration::from_secs(30)
    }

    /// A well-formed 203-byte DER SEQUENCE that is not a signature at all --
    /// the shape a compromised or impersonated service could return.
    fn fake_cms() -> Vec<u8> {
        let mut der = vec![0x30, 0x81, 0xC8];
        der.extend(std::iter::repeat_n(0xAB, 200));
        der
    }

    /// A transport that returns a scripted CMS for every signing call.
    struct FakeSigner {
        cms: Vec<u8>,
    }

    impl SigningTransport for FakeSigner {
        fn sign_data(&self, _: &[u8], _: &str, _: &str, _: Duration) -> Result<Vec<u8>> {
            Ok(self.cms.clone())
        }
        fn sign_hash(&self, _: &[u8], _: &str, _: &str, _: Duration) -> Result<Vec<u8>> {
            Ok(self.cms.clone())
        }
        fn sign_pdf_detached(&self, _: &[u8], _: &str, _: &str, _: Duration) -> Result<Vec<u8>> {
            Ok(self.cms.clone())
        }
    }

    fn signer() -> TestSigner {
        TestSigner
    }

    #[test]
    fn embedded_visible_roundtrips() {
        let opts = EmbeddedSignatureOptions {
            name: Some("Jane Signer".to_owned()),
            reason: "Approved".to_owned(),
            ..Default::default()
        };
        let signed =
            sign_pdf_embedded(BLANK_LETTER, &signer(), "u", "p", timeout(), &opts).unwrap();
        // The returned PDF carries exactly one signature, and the spliced CMS is
        // the signature the transport produced over that PDF's ByteRange.
        assert_eq!(find_byteranges(&signed).unwrap().len(), 1);
        let (signed_data, cms) = extract_signature_data(&signed).unwrap();
        assert_eq!(cms, sign_cms_detached(&signed_data));
    }

    #[test]
    fn embedded_rejects_a_response_that_is_not_a_signature() {
        // The advisory's own proof of concept: a transport that answers with
        // filler bytes shaped like DER. It must not yield a "signed" PDF.
        let transport = FakeSigner { cms: fake_cms() };
        let opts = EmbeddedSignatureOptions {
            name: Some("Jane Signer".to_owned()),
            ..Default::default()
        };
        let err =
            sign_pdf_embedded(BLANK_LETTER, &transport, "u", "p", timeout(), &opts).unwrap_err();
        // Caught where the response arrives, before anything is spliced.
        assert!(matches!(err, RevenantError::SigningResponse(_)), "{err}");
    }

    #[test]
    fn embedded_rejects_a_signature_over_someone_elses_bytes() {
        // A genuine signature -- over the wrong document. Structure and the
        // signer's own key check out, so only binding the signature to the
        // bytes we submitted catches it.
        let transport = FakeSigner {
            cms: sign_cms_detached(b"a different document entirely"),
        };
        let opts = EmbeddedSignatureOptions {
            name: Some("Jane Signer".to_owned()),
            ..Default::default()
        };
        let err =
            sign_pdf_embedded(BLANK_LETTER, &transport, "u", "p", timeout(), &opts).unwrap_err();
        assert!(matches!(err, RevenantError::SigningResponse(_)), "{err}");
    }

    #[test]
    fn embedded_invisible_roundtrips() {
        let opts = EmbeddedSignatureOptions {
            visible: false,
            name: Some("Invisible".to_owned()),
            ..Default::default()
        };
        let signed =
            sign_pdf_embedded(BLANK_LETTER, &signer(), "u", "p", timeout(), &opts).unwrap();
        assert_eq!(find_byteranges(&signed).unwrap().len(), 1);
    }

    #[test]
    fn embedded_autosizes_from_explicit_fields() {
        let opts = EmbeddedSignatureOptions {
            fields: Some(vec![
                "A very long signer display name that forces a wide box".to_owned(),
                "SSN: 1234567890".to_owned(),
            ]),
            ..Default::default()
        };
        // Auto-sizing must not break the round-trip.
        let signed =
            sign_pdf_embedded(BLANK_LETTER, &signer(), "u", "p", timeout(), &opts).unwrap();
        assert_eq!(find_byteranges(&signed).unwrap().len(), 1);
    }

    #[test]
    fn embedded_rejects_non_pdf() {
        let opts = EmbeddedSignatureOptions::default();
        let err =
            sign_pdf_embedded(b"not a pdf", &signer(), "u", "p", timeout(), &opts).unwrap_err();
        assert!(matches!(err, RevenantError::Pdf(_)));
    }

    #[test]
    fn embedded_rejects_nonpositive_dimensions() {
        let opts = EmbeddedSignatureOptions {
            w: Some(0.0),
            ..Default::default()
        };
        let err =
            sign_pdf_embedded(BLANK_LETTER, &signer(), "u", "p", timeout(), &opts).unwrap_err();
        assert!(matches!(err, RevenantError::Pdf(_)));
    }

    #[test]
    fn embedded_rejects_negative_coordinates() {
        let opts = EmbeddedSignatureOptions {
            x: Some(-1.0),
            y: Some(10.0),
            ..Default::default()
        };
        let err =
            sign_pdf_embedded(BLANK_LETTER, &signer(), "u", "p", timeout(), &opts).unwrap_err();
        assert!(matches!(err, RevenantError::Pdf(_)));
    }

    #[test]
    fn embedded_fails_on_corrupt_cms() {
        // Too-small CMS -> rejected as a response, so no corrupt PDF is built.
        let transport = FakeSigner {
            cms: vec![0x30, 0x02, 0xAB, 0xCD],
        };
        let opts = EmbeddedSignatureOptions {
            name: Some("X".to_owned()),
            ..Default::default()
        };
        let err =
            sign_pdf_embedded(BLANK_LETTER, &transport, "u", "p", timeout(), &opts).unwrap_err();
        assert!(matches!(err, RevenantError::SigningResponse(_)), "{err}");
    }

    #[test]
    fn embedded_fails_when_the_splice_is_tampered_with() {
        // The response itself is genuine, so the arrival-time gate passes; only
        // the post-sign check can catch a PDF edited after the CMS went in.
        let opts = EmbeddedSignatureOptions {
            name: Some("Jane Signer".to_owned()),
            ..Default::default()
        };
        let signed =
            sign_pdf_embedded(BLANK_LETTER, &signer(), "u", "p", timeout(), &opts).unwrap();
        let result = crate::pdf::verify_embedded_signature(&signed, None, None);
        assert!(result.valid(), "{:?}", result.details);

        let mut tampered = signed.clone();
        let victim = tampered.len() / 2;
        tampered[victim] ^= 0x01;
        let after = crate::pdf::verify_embedded_signature(&tampered, None, None);
        assert!(!after.valid(), "{:?}", after.details);
    }

    #[test]
    fn detached_signs_and_validates_input() {
        let cms = sign_pdf_detached(BLANK_LETTER, &signer(), "u", "p", timeout()).unwrap();
        assert_eq!(cms, sign_cms_detached(BLANK_LETTER));
        let err = sign_pdf_detached(b"nope", &signer(), "u", "p", timeout()).unwrap_err();
        assert!(matches!(err, RevenantError::Pdf(_)));
    }

    #[test]
    fn sign_hash_validates_length() {
        assert!(sign_hash(&[0u8; 20], &signer(), "u", "p", timeout()).is_ok());
        let err = sign_hash(&[0u8; 19], &signer(), "u", "p", timeout()).unwrap_err();
        assert!(matches!(err, RevenantError::Other(_)));
    }

    #[test]
    fn sign_data_rejects_empty() {
        assert!(sign_data(b"data", &signer(), "u", "p", timeout()).is_ok());
        let err = sign_data(b"", &signer(), "u", "p", timeout()).unwrap_err();
        assert!(matches!(err, RevenantError::Other(_)));
    }
}