wsc 0.9.0

WebAssembly Signature Component - WASM signing and verification toolkit
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
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
use crate::error::WSError;
use crate::wasm_module::varint;
use serde_json;
use std::io::{Cursor, Write};
use x509_parser::prelude::*;

// Re-export RekorEntry from the rekor module
use super::cert_verifier::CertificatePool;
pub use super::rekor::RekorEntry;
use super::rekor_verifier::RekorKeyring;

/// Binary format version for keyless signatures
pub const KEYLESS_VERSION: u8 = 0x02;

/// Signature type identifier for keyless signatures
pub const KEYLESS_SIG_TYPE: u8 = 0x02;

/// Standard signature type identifier
pub const STANDARD_SIG_TYPE: u8 = 0x01;

/// Maximum accepted depth of an embedded X.509 certificate chain.
///
/// Real-world Fulcio chains are length 2–3 (leaf + intermediate(s) + root).
/// Industry CAs ship at most 4–5. We cap at 8 — generous headroom while
/// rejecting adversarial 1000-cert chains that would trigger heap exhaustion
/// in `x509_parser` / WebPKI before any signature work begins.
pub const MAX_CHAIN_DEPTH: usize = 8;

/// Keyless signature custom section format
///
/// Binary format (extends existing wasmsig format):
/// ```text
/// [version: u8 = 0x02]              // New version for keyless
/// [sig_type: u8 = 0x02]             // 0x01 = standard, 0x02 = keyless
/// [signature_len: varint]
/// [signature: bytes]
/// [cert_chain_count: u8]
/// [cert_1_len: varint]
/// [cert_1: bytes]
/// ...
/// [rekor_entry_len: varint]
/// [rekor_entry: JSON bytes]
/// [module_hash_len: varint]
/// [module_hash: bytes]
/// ```
#[derive(Debug, Clone)]
pub struct KeylessSignature {
    /// Ed25519 signature over the module hash
    pub signature: Vec<u8>,
    /// X.509 certificate chain from Fulcio (PEM format)
    pub cert_chain: Vec<String>,
    /// Rekor transparency log entry
    pub rekor_entry: RekorEntry,
    /// SHA256 hash of the WASM module that was signed
    pub module_hash: Vec<u8>,
}

impl KeylessSignature {
    /// Create a new keyless signature
    pub fn new(
        signature: Vec<u8>,
        cert_chain: Vec<String>,
        rekor_entry: RekorEntry,
        module_hash: Vec<u8>,
    ) -> Self {
        Self {
            signature,
            cert_chain,
            rekor_entry,
            module_hash,
        }
    }

    /// Serialize to bytes for WASM custom section
    ///
    /// # Binary Format
    ///
    /// The serialized format is:
    /// - Version byte (0x02)
    /// - Signature type byte (0x02 for keyless)
    /// - Signature length (varint) + signature bytes
    /// - Certificate chain count (u8)
    /// - For each certificate: length (varint) + PEM bytes
    /// - Rekor entry length (varint) + JSON bytes
    /// - Module hash length (varint) + hash bytes
    pub fn to_bytes(&self) -> Result<Vec<u8>, WSError> {
        let mut buffer = Vec::new();

        // Write version
        buffer
            .write_all(&[KEYLESS_VERSION])
            .map_err(|e| WSError::KeylessFormatError(format!("Failed to write version: {}", e)))?;

        // Write signature type
        buffer.write_all(&[KEYLESS_SIG_TYPE]).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to write signature type: {}", e))
        })?;

        // Write signature
        varint::put_slice(&mut buffer, &self.signature).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to write signature: {}", e))
        })?;

        // Write certificate chain count
        let cert_count = self.cert_chain.len();
        if cert_count > 255 {
            return Err(WSError::KeylessFormatError(format!(
                "Certificate chain too long: {} (max 255)",
                cert_count
            )));
        }
        buffer.write_all(&[cert_count as u8]).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to write cert count: {}", e))
        })?;

        // Write each certificate
        for (i, cert_pem) in self.cert_chain.iter().enumerate() {
            varint::put_slice(&mut buffer, cert_pem.as_bytes()).map_err(|e| {
                WSError::KeylessFormatError(format!("Failed to write certificate {}: {}", i, e))
            })?;
        }

        // Serialize Rekor entry to JSON
        let rekor_json = serde_json::to_vec(&self.rekor_entry).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to serialize Rekor entry: {}", e))
        })?;

        // Write Rekor entry
        varint::put_slice(&mut buffer, &rekor_json).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to write Rekor entry: {}", e))
        })?;

        // Write module hash
        varint::put_slice(&mut buffer, &self.module_hash).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to write module hash: {}", e))
        })?;

        Ok(buffer)
    }

    /// Deserialize from WASM custom section bytes
    ///
    /// # Arguments
    ///
    /// * `bytes` - Raw bytes from the WASM custom section
    ///
    /// # Returns
    ///
    /// A parsed `KeylessSignature` or an error if the format is invalid
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, WSError> {
        let mut reader = Cursor::new(bytes);

        // Read and verify version
        let mut version = [0u8; 1];
        std::io::Read::read_exact(&mut reader, &mut version)
            .map_err(|e| WSError::KeylessFormatError(format!("Failed to read version: {}", e)))?;
        if version[0] != KEYLESS_VERSION {
            return Err(WSError::KeylessFormatError(format!(
                "Unsupported version: {} (expected {})",
                version[0], KEYLESS_VERSION
            )));
        }

        // Read and verify signature type
        let mut sig_type = [0u8; 1];
        std::io::Read::read_exact(&mut reader, &mut sig_type).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to read signature type: {}", e))
        })?;
        if sig_type[0] != KEYLESS_SIG_TYPE {
            return Err(WSError::KeylessFormatError(format!(
                "Unsupported signature type: {} (expected {})",
                sig_type[0], KEYLESS_SIG_TYPE
            )));
        }

        // Read signature
        let signature = varint::get_slice(&mut reader)
            .map_err(|e| WSError::KeylessFormatError(format!("Failed to read signature: {}", e)))?;

        // Read certificate chain count
        let mut cert_count = [0u8; 1];
        std::io::Read::read_exact(&mut reader, &mut cert_count).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to read certificate count: {}", e))
        })?;

        // Read certificates
        let mut cert_chain = Vec::new();
        for i in 0..cert_count[0] {
            let cert_bytes = varint::get_slice(&mut reader).map_err(|e| {
                WSError::KeylessFormatError(format!("Failed to read certificate {}: {}", i, e))
            })?;
            let cert_pem = String::from_utf8(cert_bytes).map_err(|e| {
                WSError::KeylessFormatError(format!("Certificate {} is not valid UTF-8: {}", i, e))
            })?;
            cert_chain.push(cert_pem);
        }

        // Read Rekor entry
        let rekor_json = varint::get_slice(&mut reader).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to read Rekor entry: {}", e))
        })?;
        let rekor_entry: RekorEntry = serde_json::from_slice(&rekor_json).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to parse Rekor entry JSON: {}", e))
        })?;

        // Read module hash
        let module_hash = varint::get_slice(&mut reader).map_err(|e| {
            WSError::KeylessFormatError(format!("Failed to read module hash: {}", e))
        })?;

        Ok(Self {
            signature,
            cert_chain,
            rekor_entry,
            module_hash,
        })
    }

    /// Extract identity from the leaf certificate
    ///
    /// The identity is typically stored in the Subject Alternative Name (SAN) extension,
    /// which contains the email, URI, or other identity from the OIDC token.
    ///
    /// # Returns
    ///
    /// The identity string (e.g., "user@example.com", "https://github.com/user/repo")
    pub fn get_identity(&self) -> Result<String, WSError> {
        if self.cert_chain.is_empty() {
            return Err(WSError::CertificateError(
                "No certificates in chain".to_string(),
            ));
        }

        // Parse the leaf certificate (first in chain)
        let leaf_pem = &self.cert_chain[0];
        let (_, pem) = parse_x509_pem(leaf_pem.as_bytes())
            .map_err(|e| WSError::CertificateError(format!("Failed to parse PEM: {}", e)))?;

        let cert = pem.parse_x509().map_err(|e| {
            WSError::CertificateError(format!("Failed to parse X.509 certificate: {}", e))
        })?;

        // Look for Subject Alternative Name extension
        if let Some(san_ext) =
            cert.get_extension_unique(&oid_registry::OID_X509_EXT_SUBJECT_ALT_NAME)?
            && let ParsedExtension::SubjectAlternativeName(san) = san_ext.parsed_extension() {
                // Try different SAN types in order of preference
                for name in &san.general_names {
                    match name {
                        GeneralName::RFC822Name(email) => {
                            return Ok(email.to_string());
                        }
                        GeneralName::URI(uri) => {
                            return Ok(uri.to_string());
                        }
                        GeneralName::DNSName(dns) => {
                            return Ok(dns.to_string());
                        }
                        _ => continue,
                    }
                }
            }

        // Fall back to subject common name if no SAN found
        for rdn in cert.subject().iter() {
            for attr in rdn.iter() {
                if attr.attr_type() == &oid_registry::OID_X509_COMMON_NAME
                    && let Ok(cn) = attr.as_str() {
                        return Ok(cn.to_string());
                    }
            }
        }

        Err(WSError::CertificateError(
            "No identity found in certificate".to_string(),
        ))
    }

    /// Extract issuer from the leaf certificate
    ///
    /// The issuer identifies the OIDC provider that issued the identity token
    /// (e.g., "https://accounts.google.com", "https://token.actions.githubusercontent.com").
    ///
    /// For Fulcio certificates, this is stored in a custom OID extension.
    ///
    /// # Returns
    ///
    /// The issuer URL string
    pub fn get_issuer(&self) -> Result<String, WSError> {
        if self.cert_chain.is_empty() {
            return Err(WSError::CertificateError(
                "No certificates in chain".to_string(),
            ));
        }

        // Parse the leaf certificate (first in chain)
        let leaf_pem = &self.cert_chain[0];
        let (_, pem) = parse_x509_pem(leaf_pem.as_bytes())
            .map_err(|e| WSError::CertificateError(format!("Failed to parse PEM: {}", e)))?;

        let cert = pem.parse_x509().map_err(|e| {
            WSError::CertificateError(format!("Failed to parse X.509 certificate: {}", e))
        })?;

        // Sigstore/Fulcio uses custom OIDs for OIDC issuer:
        // - 1.3.6.1.4.1.57264.1.1 (v1, deprecated but still common)
        // - 1.3.6.1.4.1.57264.1.8 (v2, Issuer V2)
        const OIDC_ISSUER_V1: &[u64] = &[1, 3, 6, 1, 4, 1, 57264, 1, 1];
        const OIDC_ISSUER_V2: &[u64] = &[1, 3, 6, 1, 4, 1, 57264, 1, 8];

        // Try to find the OIDC issuer in certificate extensions
        for ext in cert.extensions() {
            let oid_components: Vec<u64> = match ext.oid.iter() {
                Some(iter) => iter.collect(),
                None => continue,
            };

            // Check for OIDC Issuer v1 or v2
            if oid_components == OIDC_ISSUER_V1 || oid_components == OIDC_ISSUER_V2 {
                // The extension value is a UTF8String containing the issuer URL
                // It may be wrapped in ASN.1 encoding, try to extract the string
                let value = ext.value;

                // Try to parse as ASN.1 UTF8String first
                if let Ok((_, utf8_str)) = der_parser::der::parse_der_utf8string(value) {
                    if let Ok(s) = utf8_str.as_str() {
                        return Ok(s.to_string());
                    }
                }

                // Fallback: try to interpret raw bytes as UTF-8
                if let Ok(s) = std::str::from_utf8(value) {
                    return Ok(s.to_string());
                }
            }
        }

        // Fallback: extract certificate issuer common name
        // This is not the OIDC issuer, but provides some information
        for rdn in cert.issuer().iter() {
            for attr in rdn.iter() {
                if attr.attr_type() == &oid_registry::OID_X509_COMMON_NAME
                    && let Ok(cn) = attr.as_str()
                {
                    return Ok(cn.to_string());
                }
            }
        }

        Err(WSError::CertificateError(
            "No OIDC issuer found in certificate".to_string(),
        ))
    }

    /// Verify the certificate chain
    ///
    /// This performs full RFC 5280 certificate chain validation:
    /// - Validates certificate chain up to Fulcio root CA
    /// - Checks certificate signatures at each level
    /// - Verifies validity periods match Rekor integrated_time
    /// - Validates certificate extensions (Key Usage, Extended Key Usage)
    ///
    /// # Returns
    ///
    /// Ok if the certificate chain is valid, error otherwise
    ///
    /// # Security
    ///
    /// Uses WebPKI (rustls-webpki) for cryptographic verification.
    /// Trust anchors are embedded from Sigstore TUF repository.
    pub fn verify_cert_chain(&self) -> Result<(), WSError> {
        if self.cert_chain.is_empty() {
            return Err(WSError::CertificateError(
                "Empty certificate chain".to_string(),
            ));
        }

        // SECURITY: bound chain depth before invoking x509_parser/WebPKI.
        // An adversarial 1000-cert chain would otherwise trigger heap
        // exhaustion during PEM/DER decoding.
        if self.cert_chain.len() > MAX_CHAIN_DEPTH {
            return Err(WSError::ChainTooDeep(MAX_CHAIN_DEPTH));
        }

        // Load Fulcio trusted roots
        let cert_pool = CertificatePool::from_embedded_trust_root().map_err(|e| {
            WSError::CertificateError(format!("Failed to load trusted roots: {}", e))
        })?;

        // Parse integrated_time from Rekor entry (RFC3339 format)
        let integrated_time =
            chrono::DateTime::parse_from_rfc3339(&self.rekor_entry.integrated_time).map_err(
                |e| WSError::CertificateError(format!("Failed to parse integrated_time: {}", e)),
            )?;

        let integrated_time_unix = integrated_time.timestamp();

        // Verify the leaf certificate (first in chain)
        // The leaf certificate must chain up to a trusted Fulcio root CA
        let leaf_cert_pem = self
            .cert_chain
            .first()
            .ok_or_else(|| WSError::CertificateError("No leaf certificate in chain".to_string()))?;

        cert_pool
            .verify_pem_cert(leaf_cert_pem.as_bytes(), integrated_time_unix)
            .map_err(|e| {
                WSError::CertificateError(format!("Certificate verification failed: {}", e))
            })?;

        log::debug!("Certificate chain verified successfully");
        Ok(())
    }

    /// Verify the Rekor inclusion proof
    ///
    /// This performs complete Rekor transparency log verification:
    /// - Verifies the Merkle tree inclusion proof
    /// - Checks the signed entry timestamp (SET)
    /// - Validates against Rekor's public key
    /// - Verifies checkpoint signatures when available
    ///
    /// # Security
    ///
    /// This ensures that the signature was actually logged in Rekor's
    /// transparency log, providing non-repudiation and auditability.
    ///
    /// # Returns
    ///
    /// Ok if the inclusion proof is valid, error otherwise
    pub fn verify_rekor_inclusion(&self) -> Result<(), WSError> {
        log::debug!(
            "Verifying Rekor inclusion proof for entry {}",
            self.rekor_entry.uuid
        );

        // Load Rekor public keys from embedded trust root
        let keyring = RekorKeyring::from_embedded_trust_root()
            .map_err(|e| WSError::RekorError(format!("Failed to load Rekor public keys: {}", e)))?;

        // Verify the inclusion proof using the full verification implementation
        // This performs:
        // 1. Merkle tree inclusion proof verification (RFC 6962)
        // 2. Signed Entry Timestamp (SET) verification
        // 3. Checkpoint signature verification (if available)
        keyring.verify_inclusion_proof(&self.rekor_entry)?;

        log::debug!("Rekor inclusion proof verified successfully");
        Ok(())
    }
}

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

    fn create_test_signature() -> KeylessSignature {
        let signature = vec![1, 2, 3, 4, 5];
        let cert_chain = vec![
            "-----BEGIN CERTIFICATE-----\ntest cert 1\n-----END CERTIFICATE-----".to_string(),
            "-----BEGIN CERTIFICATE-----\ntest cert 2\n-----END CERTIFICATE-----".to_string(),
        ];
        let rekor_entry = RekorEntry {
            uuid: "test-uuid-1234".to_string(),
            log_index: 42,
            body: "eyJ0ZXN0IjoidmFsdWUifQ==".to_string(),
            log_id: "test-log-id".to_string(),
            inclusion_proof: vec![10, 20, 30, 40],
            signed_entry_timestamp: "c2lnbmF0dXJl".to_string(),
            integrated_time: "2024-01-01T00:00:00Z".to_string(),
        };
        let module_hash = vec![0xde, 0xad, 0xbe, 0xef];

        KeylessSignature::new(signature, cert_chain, rekor_entry, module_hash)
    }

    #[test]
    fn test_serialization_roundtrip() {
        let sig = create_test_signature();

        // Serialize to bytes
        let bytes = sig.to_bytes().expect("Serialization failed");

        // Verify format markers
        assert_eq!(bytes[0], KEYLESS_VERSION);
        assert_eq!(bytes[1], KEYLESS_SIG_TYPE);

        // Deserialize back
        let deserialized = KeylessSignature::from_bytes(&bytes).expect("Deserialization failed");

        // Verify all fields match
        assert_eq!(deserialized.signature, sig.signature);
        assert_eq!(deserialized.cert_chain, sig.cert_chain);
        assert_eq!(deserialized.rekor_entry.uuid, sig.rekor_entry.uuid);
        assert_eq!(
            deserialized.rekor_entry.log_index,
            sig.rekor_entry.log_index
        );
        assert_eq!(
            deserialized.rekor_entry.inclusion_proof,
            sig.rekor_entry.inclusion_proof
        );
        assert_eq!(
            deserialized.rekor_entry.integrated_time,
            sig.rekor_entry.integrated_time
        );
        assert_eq!(deserialized.module_hash, sig.module_hash);
    }

    #[test]
    fn test_empty_cert_chain() {
        let mut sig = create_test_signature();
        sig.cert_chain = vec![];

        let bytes = sig.to_bytes().expect("Serialization should succeed");
        let deserialized =
            KeylessSignature::from_bytes(&bytes).expect("Deserialization should succeed");

        assert_eq!(deserialized.cert_chain.len(), 0);
    }

    #[test]
    fn test_single_cert_chain() {
        let mut sig = create_test_signature();
        sig.cert_chain =
            vec!["-----BEGIN CERTIFICATE-----\nsingle\n-----END CERTIFICATE-----".to_string()];

        let bytes = sig.to_bytes().expect("Serialization should succeed");
        let deserialized =
            KeylessSignature::from_bytes(&bytes).expect("Deserialization should succeed");

        assert_eq!(deserialized.cert_chain.len(), 1);
        assert_eq!(deserialized.cert_chain[0], sig.cert_chain[0]);
    }

    #[test]
    fn test_max_cert_chain() {
        let mut sig = create_test_signature();
        // Create 255 certificates (max allowed)
        sig.cert_chain = (0..255)
            .map(|i| {
                format!(
                    "-----BEGIN CERTIFICATE-----\ncert {}\n-----END CERTIFICATE-----",
                    i
                )
            })
            .collect();

        let bytes = sig.to_bytes().expect("Serialization should succeed");
        let deserialized =
            KeylessSignature::from_bytes(&bytes).expect("Deserialization should succeed");

        assert_eq!(deserialized.cert_chain.len(), 255);
    }

    #[test]
    fn test_too_many_certs() {
        let mut sig = create_test_signature();
        // Create 256 certificates (one too many)
        sig.cert_chain = (0..256)
            .map(|i| {
                format!(
                    "-----BEGIN CERTIFICATE-----\ncert {}\n-----END CERTIFICATE-----",
                    i
                )
            })
            .collect();

        let result = sig.to_bytes();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            WSError::KeylessFormatError(_)
        ));
    }

    #[test]
    fn test_invalid_version() {
        let sig = create_test_signature();
        let mut bytes = sig.to_bytes().expect("Serialization failed");

        // Corrupt version byte
        bytes[0] = 0xFF;

        let result = KeylessSignature::from_bytes(&bytes);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            WSError::KeylessFormatError(_)
        ));
    }

    #[test]
    fn test_invalid_signature_type() {
        let sig = create_test_signature();
        let mut bytes = sig.to_bytes().expect("Serialization failed");

        // Corrupt signature type byte
        bytes[1] = STANDARD_SIG_TYPE;

        let result = KeylessSignature::from_bytes(&bytes);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            WSError::KeylessFormatError(_)
        ));
    }

    #[test]
    fn test_truncated_data() {
        let sig = create_test_signature();
        let bytes = sig.to_bytes().expect("Serialization failed");

        // Try to deserialize truncated data
        let truncated = &bytes[0..5];
        let result = KeylessSignature::from_bytes(truncated);
        assert!(result.is_err());
    }

    #[test]
    fn test_rekor_entry_json_serialization() {
        let entry = RekorEntry {
            uuid: "test-uuid".to_string(),
            log_index: 123,
            body: "eyJ0ZXN0IjoidmFsdWUifQ==".to_string(),
            log_id: "test-log-id".to_string(),
            inclusion_proof: vec![1, 2, 3],
            signed_entry_timestamp: "c2lnbmF0dXJl".to_string(),
            integrated_time: "2024-01-01T12:00:00Z".to_string(),
        };

        let json = serde_json::to_string(&entry).expect("JSON serialization failed");
        let deserialized: RekorEntry =
            serde_json::from_str(&json).expect("JSON deserialization failed");

        assert_eq!(deserialized.uuid, entry.uuid);
        assert_eq!(deserialized.log_index, entry.log_index);
        assert_eq!(deserialized.body, entry.body);
        assert_eq!(deserialized.log_id, entry.log_id);
        assert_eq!(deserialized.inclusion_proof, entry.inclusion_proof);
        assert_eq!(
            deserialized.signed_entry_timestamp,
            entry.signed_entry_timestamp
        );
        assert_eq!(deserialized.integrated_time, entry.integrated_time);
    }

    #[test]
    fn test_verify_cert_chain_rejects_invalid() {
        let sig = create_test_signature();
        // Real implementation should reject fake test certificates
        // (create_test_signature uses dummy PEM data, not real Fulcio certs)
        assert!(sig.verify_cert_chain().is_err());

        // Empty chain should also be rejected
        let mut empty_sig = sig.clone();
        empty_sig.cert_chain = vec![];
        assert!(empty_sig.verify_cert_chain().is_err());
    }

    #[test]
    fn test_verify_rekor_inclusion_rejects_invalid() {
        let sig = create_test_signature();
        // The test data has invalid Rekor entry, so verification should fail
        // This proves that real verification is happening (not just a stub)
        let result = sig.verify_rekor_inclusion();
        assert!(
            result.is_err(),
            "Expected verification to fail with invalid test data"
        );

        // Verify we get a Rekor error (not some other error type)
        match result {
            Err(WSError::RekorError(_)) => {} // Expected
            Err(e) => panic!("Expected RekorError, got: {:?}", e),
            Ok(_) => panic!("Expected verification to fail"),
        }
    }

    #[test]
    fn test_get_identity_no_certs() {
        let mut sig = create_test_signature();
        sig.cert_chain = vec![];

        let result = sig.get_identity();
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WSError::CertificateError(_)));
    }

    #[test]
    fn test_get_issuer_no_certs() {
        let mut sig = create_test_signature();
        sig.cert_chain = vec![];

        let result = sig.get_issuer();
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WSError::CertificateError(_)));
    }

    #[test]
    fn test_large_signature() {
        let mut sig = create_test_signature();
        // Create a large signature (64 bytes, typical for Ed25519)
        sig.signature = vec![0x42; 64];

        let bytes = sig.to_bytes().expect("Serialization failed");
        let deserialized = KeylessSignature::from_bytes(&bytes).expect("Deserialization failed");

        assert_eq!(deserialized.signature.len(), 64);
        assert_eq!(deserialized.signature, sig.signature);
    }

    #[test]
    fn test_verify_cert_chain_rejects_too_deep() {
        // A 100-cert synthetic chain must be rejected before any x509 parsing.
        // This exercises the MAX_CHAIN_DEPTH guard in verify_cert_chain.
        let mut sig = create_test_signature();
        sig.cert_chain = (0..100)
            .map(|i| {
                format!(
                    "-----BEGIN CERTIFICATE-----\nfake-cert-{}\n-----END CERTIFICATE-----",
                    i
                )
            })
            .collect();

        let result = sig.verify_cert_chain();
        match result {
            Err(WSError::ChainTooDeep(max)) => assert_eq!(max, MAX_CHAIN_DEPTH),
            Err(other) => panic!("expected ChainTooDeep, got {:?}", other),
            Ok(_) => panic!("expected ChainTooDeep, got Ok"),
        }
    }

    #[test]
    fn test_verify_cert_chain_at_max_depth_proceeds_to_parser() {
        // A chain of MAX_CHAIN_DEPTH bogus PEMs must NOT be rejected by the
        // depth check; it should fall through to PEM/X.509 parsing and fail
        // there. This proves the bound is at MAX_CHAIN_DEPTH+1, not below.
        let mut sig = create_test_signature();
        sig.cert_chain = (0..MAX_CHAIN_DEPTH)
            .map(|i| {
                format!(
                    "-----BEGIN CERTIFICATE-----\nfake-cert-{}\n-----END CERTIFICATE-----",
                    i
                )
            })
            .collect();

        let result = sig.verify_cert_chain();
        // Must not be rejected by depth guard
        assert!(!matches!(result, Err(WSError::ChainTooDeep(_))));
        // But it must still fail (these aren't real Fulcio certs)
        assert!(result.is_err());
    }

    #[test]
    fn test_large_module_hash() {
        let mut sig = create_test_signature();
        // Create a SHA-256 hash (32 bytes)
        sig.module_hash = vec![0xFF; 32];

        let bytes = sig.to_bytes().expect("Serialization failed");
        let deserialized = KeylessSignature::from_bytes(&bytes).expect("Deserialization failed");

        assert_eq!(deserialized.module_hash.len(), 32);
        assert_eq!(deserialized.module_hash, sig.module_hash);
    }
}