wsc 0.8.3

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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
/// Rekor transparency log client for keyless signing
///
/// This module provides integration with the Rekor transparency log,
/// which provides a tamper-proof record of signatures and certificates.
///
/// # Example
///
/// ```no_run
/// use wsc::keyless::{RekorClient, FulcioCertificate};
///
/// // Create a Rekor client
/// let client = RekorClient::new();
///
/// // Create a mock certificate (in real use, get from Fulcio)
/// let certificate = FulcioCertificate {
///     cert_chain: vec!["-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----".to_string()],
///     leaf_cert: "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----".to_string(),
///     public_key: vec![0u8; 32],
/// };
///
/// // Upload an entry to the transparency log
/// let artifact_hash = vec![0u8; 32]; // SHA256 hash of artifact
/// let signature = vec![0u8; 64]; // Ed25519 signature
///
/// match client.upload_entry(&artifact_hash, &signature, &certificate) {
///     Ok(entry) => {
///         println!("Entry uploaded successfully!");
///         println!("UUID: {}", entry.uuid);
///         println!("Log Index: {}", entry.log_index);
///         println!("Integrated Time: {}", entry.integrated_time);
///     }
///     Err(e) => eprintln!("Failed to upload entry: {}", e),
/// }
/// ```
use crate::error::WSError;
use crate::signature::keyless::fulcio::FulcioCertificate;
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Sentinel UUID value indicating Rekor upload was skipped.
///
/// Modules signed with this sentinel **cannot pass keyless verification** (DD-2).
/// Used only for testing or development; production signing must always upload to Rekor.
pub const REKOR_SKIPPED_UUID: &str = "skipped";

/// Returns true if a Rekor entry represents a skipped upload (not a real log entry).
pub fn is_rekor_skipped(entry: &RekorEntry) -> bool {
    entry.uuid.is_empty() || entry.uuid == REKOR_SKIPPED_UUID
}

/// Rekor log entry returned from the transparency log
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RekorEntry {
    /// Log entry UUID
    pub uuid: String,
    /// Log index
    pub log_index: u64,
    /// Base64-encoded entry body (needed for SET verification)
    pub body: String,
    /// Log ID (needed for SET verification)
    pub log_id: String,
    /// Inclusion proof (for verification) - JSON serialized
    pub inclusion_proof: Vec<u8>,
    /// Signed Entry Timestamp - base64-encoded signature
    pub signed_entry_timestamp: String,
    /// Integrated time timestamp (RFC3339)
    pub integrated_time: String,
}

/// Request payload for Rekor log entry upload
#[derive(Debug, Serialize)]
struct RekorUploadRequest {
    kind: String,
    #[serde(rename = "apiVersion")]
    api_version: String,
    spec: RekorSpec,
}

#[derive(Debug, Serialize)]
struct RekorSpec {
    signature: RekorSignature,
    data: RekorData,
}

#[derive(Debug, Serialize)]
struct RekorSignature {
    content: String,
    #[serde(rename = "publicKey")]
    public_key: RekorPublicKey,
}

#[derive(Debug, Serialize)]
struct RekorPublicKey {
    content: String,
}

#[derive(Debug, Serialize)]
struct RekorData {
    hash: RekorHash,
}

#[derive(Debug, Serialize)]
struct RekorHash {
    algorithm: String,
    value: String,
}

/// Response from Rekor log entry upload
/// The response is a map where the key is the UUID and value contains the entry details
#[derive(Debug, Deserialize)]
struct RekorUploadResponse {
    #[serde(flatten)]
    entries: HashMap<String, RekorEntryResponse>,
}

#[derive(Debug, Deserialize)]
struct RekorEntryResponse {
    #[serde(rename = "logIndex")]
    log_index: u64,
    #[allow(dead_code)]
    body: String, // Base64-encoded body (not currently used but part of API response)
    #[serde(rename = "integratedTime")]
    integrated_time: i64,
    #[serde(rename = "logID")]
    #[allow(dead_code)]
    log_id: String, // Log ID (not currently used but part of API response)
    verification: Option<RekorVerification>,
}

#[derive(Debug, Deserialize)]
struct RekorVerification {
    #[serde(rename = "inclusionProof")]
    inclusion_proof: Option<RekorInclusionProof>,
    #[serde(rename = "signedEntryTimestamp")]
    signed_entry_timestamp: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct RekorInclusionProof {
    hashes: Vec<String>,
    #[serde(rename = "logIndex")]
    log_index: u64,
    #[serde(rename = "rootHash")]
    root_hash: String,
    #[serde(rename = "treeSize")]
    tree_size: u64,
}

/// Rekor client for transparency log operations
pub struct RekorClient {
    /// Rekor server URL (default: https://rekor.sigstore.dev)
    base_url: String,
    #[cfg(not(target_os = "wasi"))]
    client: ureq::Agent,
}

impl RekorClient {
    /// Create client with default Rekor server
    ///
    /// # Certificate Pinning
    ///
    /// Certificate pinning is ENFORCED by default using embedded pins for Sigstore
    /// production infrastructure. Custom pins can be set via `WSC_REKOR_PINS`.
    /// Set `WSC_REQUIRE_CERT_PINNING=1` to fail if pinning cannot be configured.
    pub fn new() -> Self {
        Self::with_url("https://rekor.sigstore.dev".to_string())
    }

    /// Create client with custom Rekor server
    ///
    /// # Certificate Pinning
    ///
    /// Certificate pinning is ENFORCED when configured via `WSC_REKOR_PINS`.
    /// Set `WSC_REQUIRE_CERT_PINNING=1` to fail if pinning cannot be configured.
    pub fn with_url(base_url: String) -> Self {
        #[cfg(not(target_os = "wasi"))]
        {
            use super::transport::create_agent_with_optional_pinning;
            use super::cert_pinning::PinningConfig;

            // Create pinning configuration for Rekor
            let pinning = Some(PinningConfig::rekor());

            // Create agent with certificate pinning (or fall back to standard TLS)
            let agent = match create_agent_with_optional_pinning(pinning) {
                Ok(agent) => agent,
                Err(e) => {
                    // Log error but don't panic - fall back to standard agent
                    log::error!("Failed to create pinned agent for Rekor: {}. Using standard TLS.", e);
                    super::transport::create_standard_agent()
                }
            };

            Self {
                base_url,
                client: agent,
            }
        }

        #[cfg(target_os = "wasi")]
        {
            Self { base_url }
        }
    }

    /// Upload signature to Rekor transparency log
    ///
    /// # Arguments
    /// * `artifact_hash` - SHA256 hash of signed artifact (32 bytes)
    /// * `signature` - Signature bytes (DER-encoded for ECDSA)
    /// * `certificate` - Certificate from Fulcio
    ///
    /// # Returns
    /// * `RekorEntry` - The transparency log entry
    pub fn upload_entry(
        &self,
        artifact_hash: &[u8],
        signature: &[u8],
        certificate: &FulcioCertificate,
    ) -> Result<RekorEntry, WSError> {
        // Validate hash length
        if artifact_hash.len() != 32 {
            return Err(WSError::RekorError(
                "Artifact hash must be 32 bytes (SHA-256 for ECDSA)".to_string(),
            ));
        }

        // Convert hash to hex string
        let hash_hex = artifact_hash
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>();

        // Encode signature and certificate chain as base64
        let signature_b64 = BASE64.encode(signature);

        // Join certificate chain into single PEM block
        let cert_chain_pem = certificate.cert_chain.join("\n");
        let cert_b64 = BASE64.encode(cert_chain_pem.as_bytes());

        // Build request payload
        let request = RekorUploadRequest {
            kind: "hashedrekord".to_string(),
            api_version: "0.0.1".to_string(),
            spec: RekorSpec {
                signature: RekorSignature {
                    content: signature_b64,
                    public_key: RekorPublicKey { content: cert_b64 },
                },
                data: RekorData {
                    hash: RekorHash {
                        // ECDSA signatures use SHA-256 per Rekor hashedrekord spec
                        algorithm: "sha256".to_string(),
                        value: hash_hex,
                    },
                },
            },
        };

        // Send request (different implementations for native vs WASI)
        #[cfg(not(target_os = "wasi"))]
        {
            self.upload_entry_native(request)
        }

        #[cfg(target_os = "wasi")]
        {
            self.upload_entry_wasi(request)
        }
    }

    /// Native implementation using ureq
    #[cfg(not(target_os = "wasi"))]
    fn upload_entry_native(&self, request: RekorUploadRequest) -> Result<RekorEntry, WSError> {
        let url = format!("{}/api/v1/log/entries", self.base_url);

        let json_request = serde_json::to_string(&request)
            .map_err(|e| WSError::RekorError(format!("Failed to serialize request: {}", e)))?;

        // Agent configured with http_status_as_error(false), so we always get Ok(Response)
        let response = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .send(json_request.as_bytes())
            .map_err(|e| WSError::RekorError(format!("Failed to upload entry: {}", e)))?;

        // Check status code
        let status = response.status();
        if status != 201 {
            let error_text = response
                .into_body()
                .read_to_string()
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(WSError::RekorError(format!(
                "Upload failed with status {}: {}",
                status, error_text
            )));
        }

        // Parse response
        let body = response
            .into_body()
            .read_to_string()
            .map_err(|e| WSError::RekorError(format!("Failed to read response body: {}", e)))?;

        // SECURITY (audit H-5): all empty-field rejection handled in the
        // shared helper so synthetic responses can be unit-tested.
        build_rekor_entry_from_response(&body)
    }

    /// WASI implementation using wasi::http
    #[cfg(target_os = "wasi")]
    fn upload_entry_wasi(&self, request: RekorUploadRequest) -> Result<RekorEntry, WSError> {
        use wasi::http::outgoing_handler;
        use wasi::http::types::{Fields, Method, OutgoingBody, OutgoingRequest, Scheme};
        use wasi::io::streams::StreamError;

        let url = format!("{}/api/v1/log/entries", self.base_url);

        // Parse URL
        let url_parts: Vec<&str> = url.split("://").collect();
        if url_parts.len() != 2 {
            return Err(WSError::RekorError("Invalid URL format".to_string()));
        }

        let scheme = if url_parts[0] == "https" {
            Scheme::Https
        } else {
            Scheme::Http
        };

        let remaining: Vec<&str> = url_parts[1].splitn(2, '/').collect();
        let authority = remaining[0].to_string();
        let path_and_query = if remaining.len() > 1 {
            format!("/{}", remaining[1])
        } else {
            "/".to_string()
        };

        // Create request
        let headers = Fields::new();
        headers.set(&"Content-Type".to_string(), &[b"application/json".to_vec()]);

        let outgoing_request = OutgoingRequest::new(headers);
        outgoing_request.set_scheme(Some(&scheme));
        outgoing_request.set_authority(Some(&authority));
        outgoing_request.set_path_with_query(Some(&path_and_query));
        outgoing_request.set_method(&Method::Post);

        // Serialize request body
        let request_json = serde_json::to_vec(&request)
            .map_err(|e| WSError::RekorError(format!("Failed to serialize request: {}", e)))?;

        let outgoing_body = outgoing_request
            .body()
            .map_err(|_| WSError::RekorError("Failed to get request body".to_string()))?;
        {
            let outgoing_stream = outgoing_body
                .write()
                .map_err(|_| WSError::RekorError("Failed to write request body".to_string()))?;
            outgoing_stream
                .blocking_write_and_flush(&request_json)
                .map_err(|e| WSError::RekorError(format!("Failed to send request: {:?}", e)))?;
        }
        OutgoingBody::finish(outgoing_body, None)
            .map_err(|_| WSError::RekorError("Failed to finish request body".to_string()))?;

        // Send request
        let future_response = outgoing_handler::handle(outgoing_request, None)
            .map_err(|_| WSError::RekorError("Failed to send HTTP request".to_string()))?;
        let incoming_response = future_response
            .get()
            .ok_or_else(|| WSError::RekorError("No response received".to_string()))?
            .map_err(|_| WSError::RekorError("Request failed".to_string()))??;

        // Check status
        let status = incoming_response.status();
        if status != 201 {
            return Err(WSError::RekorError(format!(
                "Upload failed with status {}",
                status
            )));
        }

        // Read response body
        let incoming_body = incoming_response
            .consume()
            .map_err(|_| WSError::RekorError("Failed to get response body".to_string()))?;
        let incoming_stream = incoming_body
            .stream()
            .map_err(|_| WSError::RekorError("Failed to get response stream".to_string()))?;

        let mut response_bytes = Vec::new();
        loop {
            match incoming_stream.blocking_read(4096) {
                Ok(chunk) => {
                    if chunk.is_empty() {
                        break;
                    }
                    response_bytes.extend_from_slice(&chunk);
                }
                Err(StreamError::Closed) => break,
                Err(e) => {
                    return Err(WSError::RekorError(format!("Stream error: {:?}", e)));
                }
            }
        }

        // SECURITY (audit H-5): all empty-field rejection handled in the
        // shared helper.
        let body_str = std::str::from_utf8(&response_bytes)
            .map_err(|e| WSError::RekorError(format!("Invalid UTF-8 in response: {}", e)))?;
        build_rekor_entry_from_response(body_str)
    }

    /// Verify inclusion proof and SET for a Rekor entry
    ///
    /// This performs full cryptographic verification:
    /// 1. Signed Entry Timestamp (SET) verification using ECDSA P-256
    /// 2. Merkle tree inclusion proof verification (RFC 6962)
    ///
    /// # Arguments
    /// * `entry` - The Rekor log entry to verify
    ///
    /// # Returns
    /// `Ok(true)` if verification succeeds, `Err(WSError)` otherwise
    ///
    /// # Security
    /// This ensures that:
    /// - Rekor accepted and timestamped the entry (SET signature)
    /// - The entry exists in the transparency log (inclusion proof)
    /// - The transparency log is cryptographically sound (Merkle tree)
    pub fn verify_inclusion(&self, entry: &RekorEntry) -> Result<bool, WSError> {
        use super::rekor_verifier::RekorKeyring;

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

        // Perform full verification (SET + inclusion proof)
        keyring.verify_entry(entry)?;

        Ok(true)
    }
}

impl Default for RekorClient {
    fn default() -> Self {
        Self::new()
    }
}

/// Build a `RekorEntry` from a parsed Rekor upload response (audit H-5).
///
/// Pure helper so the empty-SET / empty-inclusion-proof rejection rules can be
/// unit-tested with a synthetic JSON payload. Rejects (returns Err) any
/// response that:
///
/// - has no entries map
/// - omits the `verification` object
/// - omits the inclusion proof
/// - has a structurally-empty inclusion proof (no hashes or empty root)
/// - omits or has an empty `signedEntryTimestamp`
///
/// These rejections happen BEFORE any caching or downstream verification, so a
/// caller cannot accidentally cache a partial/invalid entry.
fn build_rekor_entry_from_response(body: &str) -> Result<RekorEntry, WSError> {
    let response_data: RekorUploadResponse = serde_json::from_str(body)
        .map_err(|e| WSError::RekorError(format!("Failed to parse response: {}", e)))?;

    if response_data.entries.is_empty() {
        return Err(WSError::RekorError(
            "No entry returned in response".to_string(),
        ));
    }

    let (uuid, entry_data) = response_data
        .entries
        .into_iter()
        .next()
        .ok_or_else(|| WSError::RekorError("Empty response from Rekor".to_string()))?;

    let verification = entry_data.verification.ok_or_else(|| {
        WSError::RekorError(
            "Rekor response missing 'verification' object — refusing to return entry".to_string(),
        )
    })?;

    let raw_inclusion_proof = verification.inclusion_proof.ok_or_else(|| {
        WSError::RekorError(
            "Rekor response missing inclusion proof — refusing to return entry".to_string(),
        )
    })?;
    if raw_inclusion_proof.hashes.is_empty() || raw_inclusion_proof.root_hash.is_empty() {
        return Err(WSError::RekorError(
            "Rekor response has structurally-empty inclusion proof (no hashes or empty root)"
                .to_string(),
        ));
    }
    let inclusion_proof = serde_json::to_vec(&raw_inclusion_proof)
        .map_err(|e| WSError::RekorError(format!("Failed to serialize inclusion proof: {}", e)))?;

    let signed_entry_timestamp = match verification.signed_entry_timestamp {
        Some(set) if !set.is_empty() => set,
        _ => {
            return Err(WSError::RekorError(
                "Rekor response missing or empty signed entry timestamp".to_string(),
            ));
        }
    };

    Ok(RekorEntry {
        uuid,
        log_index: entry_data.log_index,
        body: entry_data.body,
        log_id: entry_data.log_id,
        inclusion_proof,
        signed_entry_timestamp,
        integrated_time: format_timestamp(entry_data.integrated_time),
    })
}

/// Format Unix timestamp to RFC3339 string
fn format_timestamp(timestamp: i64) -> String {
    use time::{OffsetDateTime, format_description::well_known::Rfc3339};

    match OffsetDateTime::from_unix_timestamp(timestamp) {
        Ok(dt) => dt
            .format(&Rfc3339)
            .unwrap_or_else(|_| timestamp.to_string()),
        Err(_) => timestamp.to_string(),
    }
}

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

    #[test]
    fn test_rekor_client_new() {
        let client = RekorClient::new();
        assert_eq!(client.base_url, "https://rekor.sigstore.dev");
    }

    #[test]
    fn test_rekor_client_with_url() {
        let custom_url = "https://custom.rekor.server".to_string();
        let client = RekorClient::with_url(custom_url.clone());
        assert_eq!(client.base_url, custom_url);
    }

    #[test]
    fn test_format_timestamp() {
        // Test a known timestamp: 2024-01-01 00:00:00 UTC
        let timestamp = 1704067200i64;
        let formatted = format_timestamp(timestamp);
        assert!(formatted.contains("2024"));
    }

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

        assert_eq!(entry.uuid, "test-uuid-123");
        assert_eq!(entry.log_index, 42);
        assert_eq!(entry.body, "eyJ0ZXN0IjoidmFsdWUifQ==");
        assert_eq!(entry.log_id, "test-log-id");
        assert_eq!(entry.inclusion_proof, vec![1, 2, 3, 4]);
        assert_eq!(entry.signed_entry_timestamp, "c2lnbmF0dXJl");
        assert_eq!(entry.integrated_time, "2024-01-01T00:00:00Z");
    }

    #[test]
    fn test_upload_entry_invalid_hash_length() {
        let client = RekorClient::new();

        // Create stub certificate
        let cert = FulcioCertificate {
            cert_chain: vec![
                "-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----".to_string(),
            ],
            leaf_cert: "-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----".to_string(),
            public_key: vec![0u8; 65],
        };

        // Test with invalid hash length (not 32 bytes for SHA-256)
        let invalid_hash = vec![0u8; 64]; // Wrong: SHA-512 size instead of SHA-256
        let signature = vec![0u8; 64];

        let result = client.upload_entry(&invalid_hash, &signature, &cert);
        assert!(result.is_err());

        if let Err(WSError::RekorError(msg)) = result {
            assert!(msg.contains("32 bytes"));
        } else {
            panic!("Expected RekorError");
        }
    }

    #[test]
    fn test_verify_inclusion_rejects_invalid() {
        let client = RekorClient::new();
        let entry = RekorEntry {
            uuid: "test-uuid".to_string(),
            log_index: 1,
            body: "eyJ0ZXN0IjoidmFsdWUifQ==".to_string(),
            log_id: "test-log-id".to_string(),
            inclusion_proof: vec![],
            signed_entry_timestamp: String::new(),
            integrated_time: "2024-01-01T00:00:00Z".to_string(),
        };

        // Real verification should reject this invalid entry
        let result = client.verify_inclusion(&entry);
        assert!(result.is_err(), "Should reject entry with no SET");
    }

    #[test]
    fn test_rekor_upload_request_serialization() {
        let request = RekorUploadRequest {
            kind: "hashedrekord".to_string(),
            api_version: "0.0.1".to_string(),
            spec: RekorSpec {
                signature: RekorSignature {
                    content: "c2lnbmF0dXJl".to_string(), // "signature" in base64
                    public_key: RekorPublicKey {
                        content: "Y2VydGlmaWNhdGU=".to_string(), // "certificate" in base64
                    },
                },
                data: RekorData {
                    hash: RekorHash {
                        algorithm: "sha256".to_string(),
                        value: "abcdef1234567890".to_string(),
                    },
                },
            },
        };

        let json = serde_json::to_string(&request).unwrap();

        // Verify JSON contains expected fields
        assert!(json.contains("hashedrekord"));
        assert!(json.contains("0.0.1"));
        assert!(json.contains("sha256"));
        assert!(json.contains("c2lnbmF0dXJl"));
    }

    #[test]
    fn test_rekor_upload_response_deserialization() {
        let json = r#"{
            "24296fb24b8ad77a123456789abcdef": {
                "logIndex": 12345,
                "body": "eyJhcGlWZXJzaW9uIjoiMC4wLjEifQ==",
                "integratedTime": 1704067200,
                "logID": "c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",
                "verification": {
                    "inclusionProof": {
                        "hashes": ["hash1", "hash2"],
                        "logIndex": 12345,
                        "rootHash": "root",
                        "treeSize": 100000
                    }
                }
            }
        }"#;

        let response: RekorUploadResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.entries.len(), 1);

        let (uuid, entry) = response.entries.into_iter().next().unwrap();
        assert!(uuid.starts_with("24296fb24b8ad77a"));
        assert_eq!(entry.log_index, 12345);
        assert_eq!(entry.integrated_time, 1704067200);
        assert!(entry.verification.is_some());
    }

    #[test]
    fn test_mock_rekor_entry_flow() {
        // This test demonstrates the expected flow with mock data
        let client = RekorClient::new();

        // Create mock certificate
        let cert = FulcioCertificate {
            cert_chain: vec![
                "-----BEGIN CERTIFICATE-----\nMIIBkTCCATegAwIBAgIUTest\n-----END CERTIFICATE-----"
                    .to_string(),
            ],
            leaf_cert:
                "-----BEGIN CERTIFICATE-----\nMIIBkTCCATegAwIBAgIUTest\n-----END CERTIFICATE-----"
                    .to_string(),
            public_key: vec![0u8; 65], // ECDSA P-256 uncompressed public key
        };

        // Create valid SHA256 hash (32 bytes)
        let artifact_hash = vec![0u8; 32];
        let signature = vec![0u8; 64]; // ECDSA signature (DER-encoded, approximate size)

        // Note: This will fail because we don't have a real Rekor server
        // But it demonstrates the API usage
        let result = client.upload_entry(&artifact_hash, &signature, &cert);

        // In a real integration test, we would mock the HTTP response
        // For now, we just verify the error is a Rekor error (connection failure)
        assert!(result.is_err());
    }

    // ============================================================================
    // SECURITY TESTS: Rekor response parsing — H-5
    // (reject empty SET / empty inclusion-proof BEFORE caching)
    // ============================================================================

    fn full_rekor_response_json() -> String {
        r#"{
            "abc123": {
                "logIndex": 7,
                "body": "ZHVtbXk=",
                "integratedTime": 1704067200,
                "logID": "deadbeef",
                "verification": {
                    "inclusionProof": {
                        "hashes": ["aa", "bb"],
                        "logIndex": 7,
                        "rootHash": "cc",
                        "treeSize": 10
                    },
                    "signedEntryTimestamp": "MEUCIQ=="
                }
            }
        }"#
        .to_string()
    }

    #[test]
    fn test_h5_full_response_accepted() {
        let entry = build_rekor_entry_from_response(&full_rekor_response_json())
            .expect("complete response must be accepted");
        assert_eq!(entry.uuid, "abc123");
        assert_eq!(entry.signed_entry_timestamp, "MEUCIQ==");
        assert!(!entry.inclusion_proof.is_empty());
    }

    #[test]
    fn test_h5_empty_set_rejected() {
        // SET present but empty: must reject (not silently default).
        let json = r#"{
            "abc123": {
                "logIndex": 7,
                "body": "ZHVtbXk=",
                "integratedTime": 1704067200,
                "logID": "deadbeef",
                "verification": {
                    "inclusionProof": {
                        "hashes": ["aa", "bb"],
                        "logIndex": 7,
                        "rootHash": "cc",
                        "treeSize": 10
                    },
                    "signedEntryTimestamp": ""
                }
            }
        }"#;
        let err = build_rekor_entry_from_response(json).expect_err("empty SET must reject");
        match err {
            WSError::RekorError(msg) => assert!(
                msg.to_lowercase().contains("signed entry timestamp"),
                "msg: {}",
                msg
            ),
            other => panic!("expected RekorError, got {:?}", other),
        }
    }

    #[test]
    fn test_h5_missing_set_rejected() {
        let json = r#"{
            "abc123": {
                "logIndex": 7,
                "body": "ZHVtbXk=",
                "integratedTime": 1704067200,
                "logID": "deadbeef",
                "verification": {
                    "inclusionProof": {
                        "hashes": ["aa"],
                        "logIndex": 7,
                        "rootHash": "cc",
                        "treeSize": 10
                    }
                }
            }
        }"#;
        assert!(matches!(
            build_rekor_entry_from_response(json),
            Err(WSError::RekorError(_))
        ));
    }

    #[test]
    fn test_h5_missing_inclusion_proof_rejected() {
        let json = r#"{
            "abc123": {
                "logIndex": 7,
                "body": "ZHVtbXk=",
                "integratedTime": 1704067200,
                "logID": "deadbeef",
                "verification": {
                    "signedEntryTimestamp": "MEUCIQ=="
                }
            }
        }"#;
        let err =
            build_rekor_entry_from_response(json).expect_err("missing inclusion proof must reject");
        match err {
            WSError::RekorError(msg) => assert!(msg.contains("inclusion proof"), "msg: {}", msg),
            other => panic!("expected RekorError, got {:?}", other),
        }
    }

    #[test]
    fn test_h5_empty_inclusion_proof_hashes_rejected() {
        // hashes vector is present but empty.
        let json = r#"{
            "abc123": {
                "logIndex": 7,
                "body": "ZHVtbXk=",
                "integratedTime": 1704067200,
                "logID": "deadbeef",
                "verification": {
                    "inclusionProof": {
                        "hashes": [],
                        "logIndex": 7,
                        "rootHash": "cc",
                        "treeSize": 10
                    },
                    "signedEntryTimestamp": "MEUCIQ=="
                }
            }
        }"#;
        let err = build_rekor_entry_from_response(json)
            .expect_err("structurally empty inclusion proof must reject");
        match err {
            WSError::RekorError(msg) => assert!(
                msg.to_lowercase().contains("structurally-empty"),
                "msg: {}",
                msg
            ),
            other => panic!("expected RekorError, got {:?}", other),
        }
    }

    #[test]
    fn test_h5_empty_root_hash_rejected() {
        let json = r#"{
            "abc123": {
                "logIndex": 7,
                "body": "ZHVtbXk=",
                "integratedTime": 1704067200,
                "logID": "deadbeef",
                "verification": {
                    "inclusionProof": {
                        "hashes": ["aa"],
                        "logIndex": 7,
                        "rootHash": "",
                        "treeSize": 10
                    },
                    "signedEntryTimestamp": "MEUCIQ=="
                }
            }
        }"#;
        assert!(matches!(
            build_rekor_entry_from_response(json),
            Err(WSError::RekorError(_))
        ));
    }

    #[test]
    fn test_h5_missing_verification_object_rejected() {
        let json = r#"{
            "abc123": {
                "logIndex": 7,
                "body": "ZHVtbXk=",
                "integratedTime": 1704067200,
                "logID": "deadbeef"
            }
        }"#;
        assert!(matches!(
            build_rekor_entry_from_response(json),
            Err(WSError::RekorError(_))
        ));
    }

    #[test]
    fn test_h5_no_entries_rejected() {
        let json = r#"{}"#;
        assert!(matches!(
            build_rekor_entry_from_response(json),
            Err(WSError::RekorError(_))
        ));
    }
}