isis-report-lib 0.3.0

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! Tamper-evident report signing and verification (v1).
//!
//! A `%ISIS-SIGNATURE {json}` block is appended after the PDF `%%EOF`.
//! Verification strips the block(s), re-hashes the original bytes and checks
//! the signature. Two modes: `hmac-sha256` (shared secret) and `ed25519`
//! (public-key verification, feature `sign`).

use std::collections::BTreeMap;
use std::sync::LazyLock;

use chrono::{SecondsFormat, Utc};
use hmac::{Hmac, Mac};
use indexmap::IndexMap;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;

use crate::error::{Error, Result};
use crate::pyops;
use crate::value::Value;

/// Envelope marker appended to signed PDFs.
pub const MARKER: &[u8] = b"%ISIS-SIGNATURE ";
/// Current signature envelope version.
pub const SIGNATURE_VERSION: u32 = 1;
/// Minimum HMAC key length accepted when signing.
pub const HMAC_MIN_KEY_BYTES: usize = 32;

/// Signature algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignatureAlg {
    /// HMAC-SHA256 with a shared secret.
    HmacSha256,
    /// Ed25519 with a private key.
    Ed25519,
}

impl SignatureAlg {
    /// Envelope name (`hmac-sha256` or `ed25519`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::HmacSha256 => "hmac-sha256",
            Self::Ed25519 => "ed25519",
        }
    }

    /// Parse an envelope name.
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "hmac-sha256" => Some(Self::HmacSha256),
            "ed25519" => Some(Self::Ed25519),
            _ => None,
        }
    }
}

impl std::fmt::Display for SignatureAlg {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Verification outcome (`valid` plus machine-readable details).
#[derive(Debug, Clone, Default)]
pub struct SignatureInfo {
    /// Whether the signature matched.
    pub valid: bool,
    /// Human-readable outcome reason.
    pub reason: String,
    /// Algorithm from the envelope.
    pub alg: Option<String>,
    /// SHA-256 of the signed bytes.
    pub sha256: Option<String>,
    /// Key id used for verification.
    pub key_id: Option<String>,
    /// Envelope issue timestamp.
    pub issued_at: Option<String>,
    /// Extra envelope fields.
    pub details: IndexMap<String, Value>,
}

/// Verification key material.
#[derive(Debug, Clone, Copy)]
pub enum KeyMaterial<'a> {
    /// One key.
    Single(&'a [u8]),
    /// Try each key in order.
    List(&'a [Vec<u8>]),
    /// Try by key id first, then every key.
    Keyring(&'a IndexMap<String, Vec<u8>>),
}

impl SignatureInfo {
    fn invalid(reason: impl Into<String>) -> Self {
        Self {
            valid: false,
            reason: reason.into(),
            ..Default::default()
        }
    }
}

/// Generate a random shared secret (at least 32 bytes).
pub fn generate_hmac_key(nbytes: usize) -> Result<Vec<u8>> {
    if nbytes < HMAC_MIN_KEY_BYTES {
        return Err(Error::option(format!(
            "HMAC keys must be at least {HMAC_MIN_KEY_BYTES} bytes, got {nbytes}"
        )));
    }
    let mut key = vec![0u8; nbytes];
    getrandom::fill(&mut key).map_err(|error| Error::message(format!("Cannot generate a random key: {error}")))?;
    Ok(key)
}

/// Generate `(private_pem, public_pem)` for Ed25519 signatures.
#[cfg(feature = "sign")]
pub fn generate_ed25519_keypair() -> Result<(Vec<u8>, Vec<u8>)> {
    use ed25519_dalek::pkcs8::{spki::EncodePublicKey, EncodePrivateKey};
    use ed25519_dalek::SigningKey;
    use pkcs8::LineEnding;

    let mut seed = [0u8; 32];
    getrandom::fill(&mut seed).map_err(|error| Error::message(format!("Cannot generate a random key: {error}")))?;
    let signing_key = SigningKey::from_bytes(&seed);
    let private = signing_key
        .to_pkcs8_pem(LineEnding::LF)
        .map_err(|error| Error::message(format!("Cannot encode the private key: {error}")))?;
    let public = signing_key
        .verifying_key()
        .to_public_key_pem(LineEnding::LF)
        .map_err(|error| Error::message(format!("Cannot encode the public key: {error}")))?;
    Ok((private.as_bytes().to_vec(), public.into_bytes()))
}

/// Generate an Ed25519 keypair (feature disabled).
#[cfg(not(feature = "sign"))]
pub fn generate_ed25519_keypair() -> Result<(Vec<u8>, Vec<u8>)> {
    Err(Error::FeatureDisabled(
        "Ed25519 signatures require the 'sign' feature (ed25519-dalek)",
    ))
}

fn sha256_hex(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    hex::encode(hasher.finalize())
}

fn json_escape_ascii(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);
    out.push('"');
    for ch in value.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0c}' => out.push_str("\\f"),
            ch if (ch as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", ch as u32)),
            ch if ch.is_ascii() => out.push(ch),
            ch => {
                let code = ch as u32;
                if code <= 0xFFFF {
                    out.push_str(&format!("\\u{code:04x}"));
                } else {
                    let code = code - 0x10000;
                    let high = 0xD800 + (code >> 10);
                    let low = 0xDC00 + (code & 0x3FF);
                    out.push_str(&format!("\\u{high:04x}\\u{low:04x}"));
                }
            }
        }
    }
    out.push('"');
    out
}

fn canonical_value(value: &Value) -> String {
    match value {
        Value::Null => "null".to_string(),
        Value::Bool(value) => value.to_string(),
        Value::Int(value) => value.to_string(),
        Value::UInt(value) => value.to_string(),
        Value::Float(value) => {
            if value.is_finite() {
                pyops::py_float_str(*value)
            } else {
                "null".to_string()
            }
        }
        Value::Decimal(value) => json_escape_ascii(&value.to_string()),
        Value::String(value) => json_escape_ascii(value),
        Value::Date(value) => json_escape_ascii(&value.format("%Y-%m-%d").to_string()),
        Value::DateTime(value) => json_escape_ascii(&value.to_rfc3339()),
        Value::Array(values) => format!("[{}]", values.iter().map(canonical_value).collect::<Vec<_>>().join(",")),
        Value::Object(values) => {
            let sorted: BTreeMap<&String, &Value> = values.iter().collect();
            let parts: Vec<String> = sorted
                .iter()
                .map(|(key, value)| format!("{}:{}", json_escape_ascii(key), canonical_value(value)))
                .collect();
            format!("{{{}}}", parts.join(","))
        }
    }
}

fn canonical_json(value: &Value) -> Vec<u8> {
    canonical_value(value).into_bytes()
}

type SignatureEnvelopes = Vec<IndexMap<String, Value>>;

fn split_blocks(signed: &[u8]) -> Result<(Vec<u8>, SignatureEnvelopes)> {
    let Some(start) = signed.windows(5).position(|window| window == b"%%EOF") else {
        return Err(Error::signature("Not a PDF (missing %%EOF marker): cannot sign or verify."));
    };
    let mut end = start + 5;
    while end < signed.len() && signed[end] != b'\n' {
        end += 1;
    }
    if end < signed.len() {
        end += 1;
    }
    let original = signed[..end].to_vec();
    let mut envelopes = Vec::new();
    for line in signed[end..].split(|byte| *byte == b'\n') {
        let line = line.strip_suffix(b"\r").unwrap_or(line);
        if !line.starts_with(MARKER) {
            continue;
        }
        let payload = &line[MARKER.len()..];
        let parsed: serde_json::Value =
            serde_json::from_slice(payload).map_err(|error| Error::signature(format!("Corrupt signature block: {error}")))?;
        let value = Value::from_json(parsed);
        if let Value::Object(object) = value {
            envelopes.push(object);
        }
    }
    Ok((original, envelopes))
}

fn sign_bytes(message: &[u8], key: &[u8], alg: SignatureAlg) -> Result<String> {
    match alg {
        SignatureAlg::HmacSha256 => {
            let mut mac = Hmac::<Sha256>::new_from_slice(key).map_err(|_| Error::signature("Invalid HMAC key"))?;
            mac.update(message);
            Ok(hex::encode(mac.finalize().into_bytes()))
        }
        SignatureAlg::Ed25519 => {
            #[cfg(feature = "sign")]
            {
                use ed25519_dalek::pkcs8::DecodePrivateKey;
                use ed25519_dalek::{Signer, SigningKey};
                let pem = std::str::from_utf8(key).map_err(|_| Error::signature("Ed25519 private key must be PEM text"))?;
                let signing_key =
                    SigningKey::from_pkcs8_pem(pem).map_err(|_| Error::signature("Ed25519 private key must be an Ed25519 PEM key"))?;
                Ok(hex::encode(signing_key.sign(message).to_bytes()))
            }
            #[cfg(not(feature = "sign"))]
            {
                let _ = message;
                Err(Error::FeatureDisabled(
                    "Ed25519 signatures require the 'sign' feature (ed25519-dalek)",
                ))
            }
        }
    }
}

fn verify_bytes(message: &[u8], signature_hex: &str, key: &[u8], alg: SignatureAlg) -> Result<bool> {
    match alg {
        SignatureAlg::HmacSha256 => {
            let mut mac = Hmac::<Sha256>::new_from_slice(key).map_err(|_| Error::signature("Invalid HMAC key"))?;
            mac.update(message);
            let expected = hex::encode(mac.finalize().into_bytes());
            Ok(bool::from(expected.as_bytes().ct_eq(signature_hex.as_bytes())))
        }
        SignatureAlg::Ed25519 => {
            #[cfg(feature = "sign")]
            {
                use ed25519_dalek::pkcs8::DecodePublicKey;
                use ed25519_dalek::{Signature, Verifier, VerifyingKey};
                let pem = std::str::from_utf8(key).map_err(|_| Error::signature("Ed25519 public key must be PEM text"))?;
                let verifying_key = VerifyingKey::from_public_key_pem(pem)
                    .map_err(|_| Error::signature("Ed25519 public key must be an Ed25519 PEM key"))?;
                let signature_bytes = hex::decode(signature_hex).map_err(|_| Error::signature("Signature is not valid hex"))?;
                let signature = Signature::from_slice(&signature_bytes).map_err(|_| Error::signature("Signature has an invalid length"))?;
                Ok(verifying_key.verify(message, &signature).is_ok())
            }
            #[cfg(not(feature = "sign"))]
            {
                let _ = (message, signature_hex, key);
                Err(Error::FeatureDisabled(
                    "Ed25519 signatures require the 'sign' feature (ed25519-dalek)",
                ))
            }
        }
    }
}

/// Append a signature block to PDF bytes (original bytes untouched).
pub fn sign_pdf(pdf: &[u8], key: &[u8], alg: SignatureAlg, key_id: Option<&str>, issued_at: Option<&str>) -> Result<Vec<u8>> {
    if alg == SignatureAlg::HmacSha256 && key.len() < HMAC_MIN_KEY_BYTES {
        return Err(Error::option(format!(
            "HMAC key must be at least {HMAC_MIN_KEY_BYTES} bytes, got {}; rotate to a new key",
            key.len()
        )));
    }
    let (original, _) = split_blocks(pdf)?;
    let issued_at = issued_at
        .map(str::to_string)
        .unwrap_or_else(|| Utc::now().to_rfc3339_opts(SecondsFormat::Secs, false));
    let mut envelope = IndexMap::new();
    envelope.insert("v".to_string(), Value::UInt(SIGNATURE_VERSION as u64));
    envelope.insert("alg".to_string(), Value::String(alg.as_str().to_string()));
    envelope.insert("sha256".to_string(), Value::String(sha256_hex(&original)));
    envelope.insert("issued_at".to_string(), Value::String(issued_at));
    if let Some(key_id) = key_id {
        envelope.insert("key_id".to_string(), Value::String(key_id.to_string()));
    }
    let signature = sign_bytes(&canonical_json(&Value::Object(envelope.clone())), key, alg)?;
    envelope.insert("sig".to_string(), Value::String(signature));
    let block = canonical_value(&Value::Object(envelope));
    let mut signed = original;
    signed.push(b'\n');
    signed.extend_from_slice(MARKER);
    signed.extend_from_slice(block.as_bytes());
    signed.push(b'\n');
    Ok(signed)
}

fn candidates<'a>(keys: KeyMaterial<'a>, key_id: Option<&str>) -> Result<Vec<&'a [u8]>> {
    match keys {
        KeyMaterial::Single(key) => Ok(vec![key]),
        KeyMaterial::List(keys) => {
            if keys.is_empty() {
                return Err(Error::signature("No verification keys provided (empty keyring)"));
            }
            Ok(keys.iter().map(Vec::as_slice).collect())
        }
        KeyMaterial::Keyring(keyring) => {
            if keyring.is_empty() {
                return Err(Error::signature("No verification keys provided (empty keyring)"));
            }
            let mut values: Vec<&[u8]> = keyring.values().map(Vec::as_slice).collect();
            if let Some(key_id) = key_id {
                if let Some(preferred) = keyring.get(key_id) {
                    values.retain(|value| *value != preferred.as_slice());
                    values.insert(0, preferred.as_slice());
                }
            }
            Ok(values)
        }
    }
}

/// Verify the latest signature block of a (possibly) signed PDF.
///
/// Never panics for malformed input — check `info.valid` and `info.reason`.
pub fn verify_pdf(signed: &[u8], keys: KeyMaterial<'_>, alg: SignatureAlg) -> SignatureInfo {
    let (original, envelopes) = match split_blocks(signed) {
        Ok(result) => result,
        Err(error) => return SignatureInfo::invalid(error.to_string()),
    };
    let Some(envelope) = envelopes.last() else {
        return SignatureInfo::invalid("no signature block found");
    };
    for name in ["v", "alg", "sha256", "sig"] {
        if !envelope.contains_key(name) {
            return SignatureInfo {
                valid: false,
                reason: format!("signature block is missing {name:?}"),
                details: [("envelope".to_string(), Value::Object(envelope.clone()))].into_iter().collect(),
                ..Default::default()
            };
        }
    }
    let Some(sig) = envelope.get("sig").and_then(Value::as_str) else {
        return SignatureInfo {
            valid: false,
            reason: "signature block has a non-string 'sig'".to_string(),
            details: [("envelope".to_string(), Value::Object(envelope.clone()))].into_iter().collect(),
            ..Default::default()
        };
    };
    let version = envelope.get("v").and_then(Value::as_i64).unwrap_or(-1);
    if version != SIGNATURE_VERSION as i64 {
        return SignatureInfo::invalid(format!("unsupported signature version: {version}"));
    }
    let Some(block_alg) = envelope.get("alg").and_then(Value::as_str) else {
        return SignatureInfo::invalid("signature block has a non-string 'alg'");
    };
    if block_alg != alg.as_str() {
        return SignatureInfo {
            valid: false,
            reason: format!("algorithm mismatch: block is {block_alg:?}, verifying with {:?}", alg.as_str()),
            alg: Some(block_alg.to_string()),
            ..Default::default()
        };
    }
    let Some(expected_hash) = envelope.get("sha256").and_then(Value::as_str) else {
        return SignatureInfo::invalid("signature block has a non-string 'sha256'");
    };
    if sha256_hex(&original) != expected_hash {
        return SignatureInfo {
            valid: false,
            reason: "content hash mismatch: file was modified after signing".to_string(),
            alg: Some(alg.as_str().to_string()),
            sha256: Some(expected_hash.to_string()),
            ..Default::default()
        };
    }
    let mut body = envelope.clone();
    body.shift_remove("sig");
    let message = canonical_json(&Value::Object(body));
    let key_id = envelope.get("key_id").and_then(Value::as_str);
    let keys = match candidates(keys, key_id) {
        Ok(keys) => keys,
        Err(error) => {
            return SignatureInfo {
                valid: false,
                reason: error.to_string(),
                alg: Some(alg.as_str().to_string()),
                ..Default::default()
            }
        }
    };
    let mut failures = 0usize;
    for key in keys {
        let short_hmac = alg == SignatureAlg::HmacSha256 && key.len() < HMAC_MIN_KEY_BYTES;
        match verify_bytes(&message, sig, key, alg) {
            Ok(true) => {
                let mut details = IndexMap::new();
                if short_hmac {
                    details.insert(
                        "warning".to_string(),
                        Value::String(format!("legacy HMAC key shorter than {HMAC_MIN_KEY_BYTES} bytes; rotate it")),
                    );
                }
                return SignatureInfo {
                    valid: true,
                    reason: "ok".to_string(),
                    alg: Some(alg.as_str().to_string()),
                    sha256: Some(expected_hash.to_string()),
                    key_id: key_id.map(str::to_string),
                    issued_at: envelope.get("issued_at").and_then(Value::as_str).map(str::to_string),
                    details,
                };
            }
            Ok(false) => failures += 1,
            Err(error) => {
                return SignatureInfo {
                    valid: false,
                    reason: error.to_string(),
                    alg: Some(alg.as_str().to_string()),
                    ..Default::default()
                }
            }
        }
    }
    if failures > 1 {
        SignatureInfo {
            valid: false,
            reason: format!("signature mismatch: no configured key verified the signature ({failures} tried)"),
            alg: Some(alg.as_str().to_string()),
            ..Default::default()
        }
    } else {
        SignatureInfo {
            valid: false,
            reason: "signature mismatch: wrong key or tampered envelope".to_string(),
            alg: Some(alg.as_str().to_string()),
            ..Default::default()
        }
    }
}

/// Convenience: verify with a single key.
pub fn verify_pdf_with_key(signed: &[u8], key: &[u8], alg: SignatureAlg) -> SignatureInfo {
    verify_pdf(signed, KeyMaterial::Single(key), alg)
}

#[allow(dead_code)]
static _ASSERT_SEND_SYNC: LazyLock<()> = LazyLock::new(|| ());

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hmac_sign_and_verify() {
        let key = generate_hmac_key(32).unwrap();
        let pdf = b"%PDF-1.4\ntrailer\n%%EOF\n";
        let signed = sign_pdf(
            pdf,
            &key,
            SignatureAlg::HmacSha256,
            Some("portal-1"),
            Some("2024-01-01T00:00:00+00:00"),
        )
        .unwrap();
        let info = verify_pdf_with_key(&signed, &key, SignatureAlg::HmacSha256);
        assert!(info.valid, "{}", info.reason);
        assert_eq!(info.key_id.as_deref(), Some("portal-1"));
        assert_eq!(info.issued_at.as_deref(), Some("2024-01-01T00:00:00+00:00"));
    }

    #[test]
    fn tampering_invalidates() {
        let key = generate_hmac_key(32).unwrap();
        let pdf = b"%PDF-1.4\n%%EOF\n";
        let signed = sign_pdf(pdf, &key, SignatureAlg::HmacSha256, None, None).unwrap();
        let mut tampered = signed.clone();
        tampered[0] = b'X';
        let info = verify_pdf_with_key(&tampered, &key, SignatureAlg::HmacSha256);
        assert!(!info.valid);
        assert!(info.reason.contains("hash mismatch"));
    }

    #[test]
    fn malformed_input_never_panics() {
        let info = verify_pdf_with_key(b"not a pdf", b"x".repeat(32).as_slice(), SignatureAlg::HmacSha256);
        assert!(!info.valid);
        let info = verify_pdf_with_key(b"%PDF-1.4\n%%EOF\n", b"short".as_slice(), SignatureAlg::HmacSha256);
        assert!(!info.valid);
    }

    #[test]
    fn keyring_rotation_tries_key_id_first() {
        let old = generate_hmac_key(32).unwrap();
        let new = generate_hmac_key(32).unwrap();
        let pdf = b"%PDF-1.4\n%%EOF\n";
        let signed = sign_pdf(pdf, &new, SignatureAlg::HmacSha256, Some("new"), None).unwrap();
        let mut keyring = IndexMap::new();
        keyring.insert("old".to_string(), old);
        keyring.insert("new".to_string(), new);
        let info = verify_pdf(&signed, KeyMaterial::Keyring(&keyring), SignatureAlg::HmacSha256);
        assert!(info.valid, "{}", info.reason);
    }

    #[test]
    fn short_hmac_key_is_rejected_for_signing() {
        let error = sign_pdf(b"%PDF-1.4\n%%EOF\n", b"short", SignatureAlg::HmacSha256, None, None).unwrap_err();
        assert!(error.to_string().contains("at least 32 bytes"));
    }
}

#[cfg(test)]
mod extra_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn algorithm_names_parse_and_display() {
        assert_eq!(SignatureAlg::parse("hmac-sha256"), Some(SignatureAlg::HmacSha256));
        assert_eq!(SignatureAlg::parse("ed25519"), Some(SignatureAlg::Ed25519));
        assert_eq!(SignatureAlg::parse("other"), None);
        assert_eq!(SignatureAlg::HmacSha256.to_string(), "hmac-sha256");
        assert_eq!(SignatureAlg::Ed25519.to_string(), "ed25519");
    }

    #[test]
    fn canonical_json_is_stable_and_escaped() {
        assert_eq!(
            json_escape_ascii("a\"b\\c\n\r\t\u{08}\u{0c}\u{01}"),
            "\"a\\\"b\\\\c\\n\\r\\t\\b\\f\\u0001\""
        );
        assert_eq!(json_escape_ascii("é😀"), "\"\\u00e9\\ud83d\\ude00\"");
        let value = Value::from_json(json!({"b": 1, "a": {"z": true, "y": null}}));
        let canonical = String::from_utf8(canonical_json(&value)).unwrap();
        assert_eq!(canonical, "{\"a\":{\"y\":null,\"z\":true},\"b\":1}");
        assert_eq!(
            canonical_value(&Value::from_json(json!([Value::Float(f64::NAN), Value::Float(1.5)]))),
            "[null,1.5]"
        );
        assert_eq!(canonical_value(&Value::Decimal(rust_decimal::Decimal::new(15, 1))), "\"1.5\"");
    }

    #[test]
    fn split_blocks_reports_missing_pdf_and_corrupt_blocks() {
        assert!(split_blocks(b"not a pdf").is_err());
        let mut corrupt = b"%PDF-1.4\n%%EOF\n".to_vec();
        corrupt.extend_from_slice(MARKER);
        corrupt.extend_from_slice(b"{not-json}\n");
        assert!(split_blocks(&corrupt).is_err());
        let signed = sign_pdf(b"%PDF-1.4\n%%EOF\n", &[7u8; 32], SignatureAlg::HmacSha256, None, None).unwrap();
        let (original, envelopes) = split_blocks(&signed).unwrap();
        assert!(original.starts_with(b"%PDF-1.4"));
        assert_eq!(envelopes.len(), 1);
        assert!(envelopes[0].contains_key("sig"));
    }

    #[test]
    fn verification_rejects_unsigned_and_algorithm_mismatch() {
        let key = [3u8; 32];
        let unsigned = verify_pdf(b"%PDF-1.4\n%%EOF\n", KeyMaterial::Single(&key), SignatureAlg::HmacSha256);
        assert!(!unsigned.valid);
        assert!(unsigned.reason.contains("no signature"));

        let signed = sign_pdf(b"%PDF-1.4\n%%EOF\n", &key, SignatureAlg::HmacSha256, Some("k"), None).unwrap();
        let mismatch = verify_pdf(&signed, KeyMaterial::Single(&key), SignatureAlg::Ed25519);
        assert!(!mismatch.valid);
        assert!(mismatch.reason.contains("algorithm"), "{}", mismatch.reason);

        let list = verify_pdf(
            &signed,
            KeyMaterial::List(&[[9u8; 32].to_vec(), key.to_vec()]),
            SignatureAlg::HmacSha256,
        );
        assert!(list.valid);
        let mut keyring = IndexMap::new();
        keyring.insert("k".to_string(), key.to_vec());
        assert!(verify_pdf(&signed, KeyMaterial::Keyring(&keyring), SignatureAlg::HmacSha256).valid);
    }

    fn signed_block(json: &str) -> Vec<u8> {
        let mut data = b"%PDF-1.4\n%%EOF\n".to_vec();
        data.extend_from_slice(MARKER);
        data.extend_from_slice(json.as_bytes());
        data.push(b'\n');
        data
    }

    #[test]
    fn key_errors_and_canonical_value_edges() {
        assert!(generate_hmac_key(31).is_err());
        assert_eq!(canonical_value(&Value::Null), "null");
        assert_eq!(
            canonical_value(&Value::Date(chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap())),
            "\"2024-01-01\""
        );
        assert_eq!(
            canonical_value(&Value::DateTime(
                chrono::DateTime::parse_from_rfc3339("2024-01-01T00:00:00+00:00").unwrap()
            )),
            "\"2024-01-01T00:00:00+00:00\""
        );

        let signed = sign_pdf(b"%PDF-1.4\n%%EOF\n", &[1u8; 32], SignatureAlg::HmacSha256, None, None).unwrap();
        let empty_list: Vec<Vec<u8>> = Vec::new();
        let info = verify_pdf(&signed, KeyMaterial::List(&empty_list), SignatureAlg::HmacSha256);
        assert!(!info.valid);
        assert!(info.reason.contains("empty keyring"));
        let empty_map = IndexMap::new();
        let info = verify_pdf(&signed, KeyMaterial::Keyring(&empty_map), SignatureAlg::HmacSha256);
        assert!(!info.valid);
        assert!(info.reason.contains("empty keyring"));

        let info = verify_pdf(&signed, KeyMaterial::Single(&[2u8; 32]), SignatureAlg::HmacSha256);
        assert!(!info.valid);
        assert!(info.reason.contains("signature mismatch"), "{}", info.reason);
    }

    #[test]
    fn malformed_envelopes_fail_closed() {
        let cases = [
            ("{}", "missing \"v\""),
            (r#"{"v":1}"#, "missing \"alg\""),
            (r#"{"v":1,"alg":"hmac-sha256"}"#, "missing \"sha256\""),
            (r#"{"v":1,"alg":"hmac-sha256","sha256":"x"}"#, "missing \"sig\""),
            (r#"{"v":1,"alg":"hmac-sha256","sha256":"x","sig":1}"#, "non-string 'sig'"),
            (
                r#"{"v":2,"alg":"hmac-sha256","sha256":"x","sig":"x"}"#,
                "unsupported signature version",
            ),
            (r#"{"v":1,"alg":1,"sha256":"x","sig":"x"}"#, "non-string 'alg'"),
            (r#"{"v":1,"alg":"hmac-sha256","sha256":1,"sig":"x"}"#, "non-string 'sha256'"),
        ];
        for (json, expected) in cases {
            let info = verify_pdf(&signed_block(json), KeyMaterial::Single(&[1u8; 32]), SignatureAlg::HmacSha256);
            assert!(!info.valid, "{json}");
            assert!(info.reason.contains(expected), "{json}: {}", info.reason);
        }
    }

    #[test]
    fn legacy_short_hmac_key_is_accepted_with_warning() {
        let key = b"short-key";
        let original = b"%PDF-1.4\n%%EOF\n";
        let mut envelope = IndexMap::new();
        envelope.insert("v".to_string(), Value::UInt(SIGNATURE_VERSION as u64));
        envelope.insert("alg".to_string(), Value::String("hmac-sha256".into()));
        envelope.insert("sha256".to_string(), Value::String(sha256_hex(original)));
        let signature = sign_bytes(&canonical_json(&Value::Object(envelope.clone())), key, SignatureAlg::HmacSha256).unwrap();
        envelope.insert("sig".to_string(), Value::String(signature));
        let mut signed = original.to_vec();
        signed.push(b'\n');
        signed.extend_from_slice(MARKER);
        signed.extend_from_slice(canonical_value(&Value::Object(envelope)).as_bytes());
        signed.push(b'\n');

        let info = verify_pdf(&signed, KeyMaterial::Single(key), SignatureAlg::HmacSha256);
        assert!(info.valid, "{}", info.reason);
        assert!(info.details.get("warning").and_then(Value::as_str).unwrap().contains("legacy"));
    }
}