wsc 0.8.2

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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
//! Keyless signing orchestration
//!
//! This module provides the main entry point for keyless signing, orchestrating:
//! 1. Ephemeral key generation
//! 2. OIDC token acquisition
//! 3. Fulcio certificate issuance
//! 4. Module signing
//! 5. Rekor transparency log upload
//!
//! # Environment variables
//!
//! - `WSC_EXPECTED_OIDC_ISSUER` — expected OIDC issuer URL. When set
//!   non-empty, validation is performed against this value (overrides
//!   `KeylessConfig::expected_issuer`). When **unset**, falls through to
//!   `KeylessConfig::expected_issuer`. An **empty** value (`""`) is now
//!   treated as "fall through to programmatic config", **not** as an implicit
//!   disable (audit H-4).
//! - `WSC_DISABLE_OIDC_ISSUER_CHECK` — set to `1` to explicitly disable issuer
//!   validation. This is the only way to silence the validation; previously a
//!   missing env var silently disabled the check.
//! - `WSC_REQUIRE_CERT_PINNING` — set to `1` to require certificate pinning.
//! - `WSC_SIGSTORE_STAGING` — set to `1` to use Sigstore staging endpoints.

use super::{
    FulcioClient, KeylessSignature, OidcProvider, RekorClient, RekorEntry, RekorKeyring,
    detect_oidc_provider, rekor,
};
use crate::{Module, WSError, SectionLike, audit};
use ecdsa::SigningKey;
use p256::ecdsa::Signature;
use sha2::{Digest, Sha256};

/// Configuration for keyless signing
#[derive(Default)]
pub struct KeylessConfig {
    /// Fulcio server URL (uses default if None)
    pub fulcio_url: Option<String>,
    /// Rekor server URL (uses default if None)
    pub rekor_url: Option<String>,
    /// Skip Rekor upload (testing only — NOT for production)
    ///
    /// **WARNING:** Modules signed with `skip_rekor=true` CANNOT pass keyless
    /// verification. The verifier enforces fail-closed (DD-2) and rejects any
    /// signature without a valid Rekor transparency log entry.
    ///
    /// Use only for local development and testing. For production CI/CD
    /// pipelines, always upload to Rekor.
    pub skip_rekor: bool,
    /// Use Sigstore staging environment instead of production
    ///
    /// When true, uses:
    /// - fulcio.staging.sigstore.dev
    /// - rekor.staging.sigstore.dev
    ///
    /// Can also be set via WSC_SIGSTORE_STAGING=1 environment variable.
    pub use_staging: bool,
    /// Custom certificate pins for Fulcio (overrides defaults)
    ///
    /// SHA256 fingerprints in hex format (64 characters each).
    /// If empty, uses built-in production/staging pins.
    pub fulcio_pins: Vec<String>,
    /// Custom certificate pins for Rekor (overrides defaults)
    ///
    /// SHA256 fingerprints in hex format (64 characters each).
    /// If empty, uses built-in production/staging pins.
    pub rekor_pins: Vec<String>,
    /// Require strict certificate pinning enforcement
    ///
    /// When true, operations will fail if certificate pinning cannot be enforced
    /// due to HTTP client limitations.
    ///
    /// Can also be set via WSC_REQUIRE_CERT_PINNING=1 environment variable.
    pub require_cert_pinning: bool,
    /// Expected OIDC issuer URL for signing operations
    ///
    /// When set, the OIDC token's issuer is validated against this value before
    /// sending it to Fulcio. This provides defense-in-depth against CI pipeline
    /// misconfiguration where the wrong identity provider is used.
    ///
    /// Can also be set via WSC_EXPECTED_OIDC_ISSUER environment variable.
    ///
    /// Example: `https://token.actions.githubusercontent.com` for GitHub Actions.
    pub expected_issuer: Option<String>,
    /// Optional proof cache for Rekor inclusion proofs (Phase 4.1).
    /// When set, verified proofs are cached for availability resilience.
    pub proof_cache: Option<std::sync::Arc<dyn super::proof_cache::ProofCacheBackend>>,
}


/// Resolve the effective expected OIDC issuer for validation (audit H-4).
///
/// Pure function over the inputs so the precedence rules can be unit-tested
/// without environment-variable mutation. Returns `Ok(Some(issuer))` when
/// validation should be performed against `issuer`, `Ok(None)` when validation
/// is disabled or no expected value is configured. The boolean tuple element
/// is `true` iff validation was explicitly disabled.
///
/// Precedence:
/// 1. `disable_env == Some("1")` -> `(None, true)` (explicit disable).
/// 2. `expected_env` set non-empty -> `(Some(env), false)`.
/// 3. `expected_env` empty/unset -> fall through to `programmatic`.
pub(crate) fn resolve_expected_issuer(
    expected_env: Option<&str>,
    disable_env: Option<&str>,
    programmatic: Option<&str>,
) -> (Option<String>, bool) {
    if disable_env == Some("1") {
        return (None, true);
    }
    let env = expected_env.filter(|s| !s.is_empty());
    let chosen = env
        .map(str::to_string)
        .or_else(|| programmatic.map(str::to_string));
    (chosen, false)
}

/// Main keyless signing interface
pub struct KeylessSigner {
    config: KeylessConfig,
    oidc: Box<dyn OidcProvider>,
    fulcio: FulcioClient,
    rekor: RekorClient,
}

impl KeylessSigner {
    /// Create keyless signer with default config
    ///
    /// This will auto-detect the OIDC provider from environment variables
    /// and use the default Sigstore production servers.
    ///
    /// # Example
    /// ```no_run
    /// use wsc::keyless::KeylessSigner;
    ///
    /// let signer = KeylessSigner::new()?;
    /// # Ok::<(), wsc::WSError>(())
    /// ```
    pub fn new() -> Result<Self, WSError> {
        Self::with_config(KeylessConfig::default())
    }

    /// Create keyless signer with custom config
    ///
    /// # Example
    /// ```no_run
    /// use wsc::keyless::{KeylessSigner, KeylessConfig};
    ///
    /// let config = KeylessConfig {
    ///     fulcio_url: Some("https://fulcio.sigstore.dev".to_string()),
    ///     rekor_url: Some("https://rekor.sigstore.dev".to_string()),
    ///     skip_rekor: false,
    ///     ..Default::default()
    /// };
    /// let signer = KeylessSigner::with_config(config)?;
    /// # Ok::<(), wsc::WSError>(())
    /// ```
    pub fn with_config(config: KeylessConfig) -> Result<Self, WSError> {
        use super::cert_pinning::PinningConfig;

        // Check if strict certificate pinning is required
        let require_pinning = config.require_cert_pinning
            || std::env::var("WSC_REQUIRE_CERT_PINNING").unwrap_or_default() == "1";

        // Determine if staging environment should be used
        let use_staging = config.use_staging || PinningConfig::is_staging();

        // Log certificate pinning configuration
        let fulcio_pins = if !config.fulcio_pins.is_empty() {
            PinningConfig::custom(config.fulcio_pins.clone(), "fulcio (custom)".to_string())
        } else if use_staging {
            PinningConfig::fulcio_staging()
        } else {
            PinningConfig::fulcio_production()
        };

        let rekor_pins = if !config.rekor_pins.is_empty() {
            PinningConfig::custom(config.rekor_pins.clone(), "rekor (custom)".to_string())
        } else if use_staging {
            PinningConfig::rekor_staging()
        } else {
            PinningConfig::rekor_production()
        };

        log::info!(
            "Certificate pinning configured: Fulcio ({} pins for {}), Rekor ({} pins for {})",
            fulcio_pins.pin_count(),
            fulcio_pins.service_name(),
            rekor_pins.pin_count(),
            rekor_pins.service_name()
        );

        // Validate pinning configuration if required
        if require_pinning {
            if !fulcio_pins.is_enabled() || !rekor_pins.is_enabled() {
                return Err(WSError::CertificatePinningError(
                    "Certificate pinning required but no pins configured".to_string(),
                ));
            }
            log::info!("Certificate pinning enforcement enabled");
        }

        // Auto-detect OIDC provider
        let oidc = detect_oidc_provider()?;
        log::info!("Using OIDC provider: {}", oidc.name());

        // Create Fulcio client with appropriate URL
        let fulcio = if let Some(url) = &config.fulcio_url {
            FulcioClient::with_url(url.clone())
        } else if use_staging {
            FulcioClient::with_url("https://fulcio.staging.sigstore.dev".to_string())
        } else {
            FulcioClient::new()
        };

        // Create Rekor client with appropriate URL
        let rekor = if let Some(url) = &config.rekor_url {
            RekorClient::with_url(url.clone())
        } else if use_staging {
            RekorClient::with_url("https://rekor.staging.sigstore.dev".to_string())
        } else {
            RekorClient::new()
        };

        Ok(Self {
            config,
            oidc,
            fulcio,
            rekor,
        })
    }

    /// Sign a WASM module using keyless signing
    ///
    /// This method performs the complete keyless signing flow:
    /// 1. Generates an ephemeral ECDSA P-256 keypair
    /// 2. Obtains an OIDC identity token
    /// 3. Requests a short-lived certificate from Fulcio
    /// 4. Signs the module hash with the ephemeral key
    /// 5. Uploads the signature to Rekor transparency log
    /// 6. Embeds the keyless signature in the module
    ///
    /// # Arguments
    /// * `module` - The WASM module to sign
    ///
    /// # Returns
    /// * `(Module, KeylessSignature)` - The signed module and the keyless signature
    ///
    /// # Example
    /// ```no_run
    /// use wsc::{Module, keyless::KeylessSigner};
    ///
    /// let module = Module::deserialize_from_file("module.wasm")?;
    /// let signer = KeylessSigner::new()?;
    /// let (signed_module, signature) = signer.sign_module(module)?;
    ///
    /// signed_module.serialize_to_file("signed.wasm")?;
    /// println!("Signed by: {}", signature.get_identity()?);
    /// println!("Rekor entry: {}", signature.rekor_entry.uuid);
    /// # Ok::<(), wsc::WSError>(())
    /// ```
    pub fn sign_module(&self, module: Module) -> Result<(Module, KeylessSignature), WSError> {
        log::info!("Starting keyless signing process");

        // Generate correlation ID for audit trail
        let correlation_id = audit::new_correlation_id();

        // Step 1: Generate ephemeral keypair
        // SECURITY: Ephemeral key zeroization (addresses Issue #14)
        //
        // The SigningKey contains a SecretKey which implements ZeroizeOnDrop.
        // When the signing_key variable goes out of scope at the end of this function,
        // its Drop implementation will securely zeroize the private key bytes in memory.
        // This protects against:
        // - Memory dumps and crash files
        // - Swap file exposure
        // - Process memory inspection via debuggers
        // - Cold boot attacks (DRAM remanence)
        //
        // The zeroization happens automatically even in panic/error scenarios because
        // Rust's drop mechanism is exception-safe.
        log::debug!("Generating ephemeral ECDSA P-256 keypair");
        let signing_key =
            SigningKey::<p256::NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);
        let verifying_key = signing_key.verifying_key();

        // Encode public key in uncompressed form (0x04 || x || y)
        let public_key_bytes = verifying_key.to_encoded_point(false);
        let public_key = public_key_bytes.as_bytes();

        // Step 2: Get OIDC token
        log::debug!("Obtaining OIDC token from {}", self.oidc.name());
        let oidc_token = self.oidc.get_token()?;
        log::info!("OIDC token obtained for identity: {}", oidc_token.identity);

        // Step 2b: Validate OIDC issuer if expected issuer is configured (UCA-12 defense).
        //
        // Audit H-4: clean up the previous 3-state env-var override.
        //
        // Resolution rules:
        //   1. If `WSC_DISABLE_OIDC_ISSUER_CHECK=1`, disable validation
        //      (loud warning) — this is the ONLY way to disable. Previously
        //      an unset/empty env var silently disabled the check.
        //   2. Else if `WSC_EXPECTED_OIDC_ISSUER` is set non-empty, use it.
        //   3. Else if `WSC_EXPECTED_OIDC_ISSUER` is set but empty, fall
        //      through to programmatic config (treated as "no env override").
        //   4. Else use `KeylessConfig::expected_issuer`.
        let env_expected = std::env::var("WSC_EXPECTED_OIDC_ISSUER").ok();
        let env_disable = std::env::var("WSC_DISABLE_OIDC_ISSUER_CHECK").ok();
        let (expected_issuer, disable_check) = resolve_expected_issuer(
            env_expected.as_deref(),
            env_disable.as_deref(),
            self.config.expected_issuer.as_deref(),
        );

        if disable_check {
            log::warn!(
                "OIDC issuer validation DISABLED via WSC_DISABLE_OIDC_ISSUER_CHECK=1. \
                 Token issuer: {}",
                oidc_token.issuer
            );
        } else if let Some(ref expected) = expected_issuer {
            // Normalize trailing slashes for comparison (AS-13 defense)
            let expected_normalized = expected.trim_end_matches('/');
            let actual_normalized = oidc_token.issuer.trim_end_matches('/');
            if actual_normalized != expected_normalized {
                return Err(WSError::OidcError(format!(
                    "OIDC issuer mismatch: expected '{}', got '{}'. \
                     Check your CI pipeline OIDC configuration.",
                    expected, oidc_token.issuer
                )));
            }
            log::info!("OIDC issuer validated: {}", oidc_token.issuer);
        } else {
            log::warn!(
                "No OIDC issuer validation configured. Set KeylessConfig::expected_issuer or \
                 WSC_EXPECTED_OIDC_ISSUER for defense-in-depth, or set \
                 WSC_DISABLE_OIDC_ISSUER_CHECK=1 to silence this warning. \
                 Token issuer: {}",
                oidc_token.issuer
            );
        }

        // Step 3: Create proof of possession
        // Sign the 'sub' claim from the OIDC token
        // Per Fulcio spec: proof_of_possession is "a signature over the `sub` claim"
        // The SigningKey::sign() method handles hashing internally
        log::debug!("Creating proof of possession");
        let sub_claim = oidc_token.get_sub_claim()?;

        use ecdsa::signature::Signer;
        let proof: Signature = signing_key.sign(sub_claim.as_bytes());

        // Step 4: Request certificate from Fulcio
        log::debug!("Requesting certificate from Fulcio");
        let certificate =
            self.fulcio
                .get_certificate(&oidc_token, public_key, &proof.to_bytes())?;
        log::info!(
            "Certificate obtained with {} certs in chain",
            certificate.cert_chain.len()
        );

        // Step 5: Compute module hash and sign it
        // Use SHA-256 for ECDSA signatures per Rekor hashedrekord spec
        log::debug!("Computing module hash (SHA-256)");
        let mut module_bytes = Vec::new();
        module.serialize(&mut module_bytes)?;

        // For hashedrekord, we need to sign the pre-computed hash using DigestSigner
        // Create hasher and sign it before finalizing
        log::debug!("Signing module hash");
        let mut module_hasher = Sha256::new();
        module_hasher.update(&module_bytes);

        use ecdsa::signature::DigestSigner;
        let signature: Signature = signing_key.sign_digest(module_hasher.clone());

        // Also get the hash value for Rekor upload
        let module_hash = module_hasher.finalize();
        let artifact_hash = format!("sha256:{}", hex::encode(&module_hash));

        // Log signing attempt (we now have identity and artifact hash)
        audit::log_signing_attempt(
            &correlation_id,
            &artifact_hash,
            Some(&oidc_token.identity),
        );

        // Step 7: Upload to Rekor (if not skipped)
        let rekor_entry = if self.config.skip_rekor {
            log::error!(
                "WARNING: Rekor upload skipped. The produced module CANNOT pass keyless \
                 verification (DD-2 fail-closed policy). Use only for testing."
            );
            eprintln!(
                "\n⚠ WARNING: Rekor upload skipped — this module cannot pass keyless verification.\n"
            );
            // Create a dummy entry for testing
            RekorEntry {
                uuid: rekor::REKOR_SKIPPED_UUID.to_string(),
                log_index: 0,
                body: String::new(),
                log_id: String::new(),
                inclusion_proof: vec![],
                signed_entry_timestamp: String::new(),
                integrated_time: chrono::Utc::now().to_rfc3339(),
            }
        } else {
            log::debug!("Uploading signature to Rekor");
            let entry =
                self.rekor
                    .upload_entry(&module_hash, &signature.to_bytes(), &certificate)?;
            log::info!(
                "Rekor entry created: {} (index: {})",
                entry.uuid,
                entry.log_index
            );
            entry
        };

        // Step 8: Create keyless signature
        log::debug!("Creating keyless signature");
        let keyless_sig = KeylessSignature::new(
            signature.to_bytes().to_vec(),
            certificate.cert_chain.clone(),
            rekor_entry,
            module_hash.to_vec(),
        );

        // Step 9: Embed signature in module
        log::debug!("Embedding signature in module");
        let signed_module = self.embed_signature(module, &keyless_sig)?;

        // Log signing success
        audit::log_signing_success(
            &correlation_id,
            &artifact_hash,
            Some(&oidc_token.identity),
            Some(&keyless_sig.rekor_entry.uuid),
            None, // certificate fingerprint (TODO: extract from cert)
        );

        log::info!("Keyless signing completed successfully");
        Ok((signed_module, keyless_sig))
    }

    /// Embed a keyless signature into a WASM module
    ///
    /// This creates a custom section named "signature" with the serialized
    /// keyless signature data.
    fn embed_signature(
        &self,
        module: Module,
        signature: &KeylessSignature,
    ) -> Result<Module, WSError> {
        let signature_bytes = signature.to_bytes()?;
        log::debug!("Embedding keyless signature: {} bytes", signature_bytes.len());

        // Use Module's existing attach_signature mechanism
        module.attach_signature(&signature_bytes)
    }
}

/// Keyless signature verification
pub struct KeylessVerifier {
    config: KeylessConfig,
}

/// Result of keyless signature verification
#[derive(Debug, Clone)]
pub struct KeylessVerificationResult {
    /// The identity (email/subject) from the certificate
    pub identity: String,
    /// The OIDC issuer URL
    pub issuer: String,
    /// The Rekor log index
    pub rekor_log_index: u64,
    /// The Rekor entry UUID
    pub rekor_uuid: String,
}

impl KeylessVerifier {
    /// Create a keyless verifier with default config (no proof cache).
    pub fn new() -> Self {
        Self {
            config: KeylessConfig::default(),
        }
    }

    /// Create a keyless verifier with custom config (e.g., with proof cache).
    pub fn with_config(config: KeylessConfig) -> Self {
        Self { config }
    }

    /// Extract keyless signature from a module's signature section
    pub fn extract_signature(module: &Module) -> Result<KeylessSignature, WSError> {
        // Find the signature section
        let sig_section = module.sections.iter().find(|s| s.is_signature_header());

        let sig_section = sig_section.ok_or(WSError::NoSignatures)?;

        // Get the payload
        let payload = match sig_section {
            crate::Section::Custom(custom) => custom.payload(),
            _ => return Err(WSError::NoSignatures),
        };

        // Try to parse as keyless signature
        KeylessSignature::from_bytes(payload)
    }

    /// Verify a keyless signature
    ///
    /// This method performs comprehensive verification:
    /// 1. Extracts the keyless signature from the module
    /// 2. Verifies the certificate chain against Fulcio roots
    /// 3. Verifies the Rekor SET (Signed Entry Timestamp)
    /// 4. Optionally validates identity and issuer claims
    ///
    /// When a proof cache is configured, verified Rekor proofs are cached
    /// so that subsequent verifications can succeed during transient Rekor
    /// outages. On cache miss AND Rekor unavailable, verification still
    /// fails (DD-2 fail-closed).
    ///
    /// # Arguments
    /// * `module` - The signed WASM module
    /// * `expected_identity` - Optional identity to verify (e.g., "user@example.com")
    /// * `expected_issuer` - Optional OIDC issuer to verify (e.g., "https://github.com/login/oauth")
    ///
    /// # Returns
    /// `KeylessVerificationResult` with signer details if verification succeeds
    ///
    /// # Example
    /// ```no_run
    /// use wsc::{Module, keyless::KeylessVerifier};
    ///
    /// let module = Module::deserialize_from_file("signed.wasm")?;
    /// let verifier = KeylessVerifier::new();
    /// let result = verifier.verify(
    ///     &module,
    ///     Some("user@example.com"),
    ///     Some("https://github.com/login/oauth")
    /// )?;
    /// println!("Signed by: {}", result.identity);
    /// # Ok::<(), wsc::WSError>(())
    /// ```
    pub fn verify(
        &self,
        module: &Module,
        expected_identity: Option<&str>,
        expected_issuer: Option<&str>,
    ) -> Result<KeylessVerificationResult, WSError> {
        log::info!("Starting keyless signature verification");

        // Generate correlation ID for audit trail
        let correlation_id = audit::new_correlation_id();

        // Step 1: Extract signature from module
        log::debug!("Extracting keyless signature from module");
        let keyless_sig = Self::extract_signature(module)?;

        // Compute artifact hash for audit logging
        let mut module_bytes = Vec::new();
        module.serialize(&mut module_bytes).ok();
        let module_hash = Sha256::digest(&module_bytes);
        let artifact_hash = format!("sha256:{}", hex::encode(&module_hash));

        // Log verification attempt
        audit::log_verification_attempt(&correlation_id, &artifact_hash);

        // Step 2: Verify certificate chain
        log::debug!("Verifying certificate chain against Fulcio roots");
        keyless_sig.verify_cert_chain()?;
        log::info!("Certificate chain verified successfully");

        // Step 3: Verify Rekor SET (Signed Entry Timestamp)
        // Fail-closed: Rekor verification is MANDATORY for keyless signatures (DD-2).
        // A missing or skipped Rekor entry means the signature lacks transparency
        // proof and MUST be rejected.
        if rekor::is_rekor_skipped(&keyless_sig.rekor_entry) {
            return Err(WSError::RekorError(
                "Rekor transparency log entry is required for keyless verification".into(),
            ));
        }

        // Check proof cache before network call
        let cache_key = {
            let hash_hex = hex::encode(&module_hash);
            super::proof_cache::CacheKey::from_hash(&hash_hex, &keyless_sig.rekor_entry.uuid)
        };
        let mut cache_hit = false;
        if let Some(ref cache) = self.config.proof_cache {
            if let Some(_cached_proof) = cache.get(&cache_key) {
                // Cache hit — proof was already validated when it was cached.
                // The certificate chain verification above still runs on every
                // call, so we only skip the Rekor network round-trip.
                log::info!("Using cached Rekor proof for {}", keyless_sig.rekor_entry.uuid);
                cache_hit = true;
            }
        }

        if !cache_hit {
            log::debug!("Verifying Rekor SET");
            let verifier = RekorKeyring::from_embedded_trust_root()?;
            verifier.verify_set(&keyless_sig.rekor_entry)?;
            log::info!("Rekor SET verified successfully");

            // After successful Rekor verification, cache the proof
            if let Some(ref cache) = self.config.proof_cache {
                let cached = super::proof_cache::cache_verified_proof(
                    &keyless_sig.rekor_entry,
                    std::time::Duration::from_secs(86400),
                );
                cache.insert(cache_key, cached);
            }
        }

        // Step 4: Extract identity and issuer from certificate
        let identity = keyless_sig.get_identity()?;
        let issuer = keyless_sig.get_issuer()?;

        // Step 5: Validate identity if expected
        if let Some(expected) = expected_identity {
            if identity != expected {
                return Err(WSError::CertificateError(format!(
                    "Identity mismatch: expected '{}', got '{}'",
                    expected, identity
                )));
            }
            log::info!("Identity verified: {}", identity);
        }

        // Step 6: Validate issuer if expected
        if let Some(expected) = expected_issuer {
            if issuer != expected {
                return Err(WSError::CertificateError(format!(
                    "Issuer mismatch: expected '{}', got '{}'",
                    expected, issuer
                )));
            }
            log::info!("Issuer verified: {}", issuer);
        }

        // Log verification success
        audit::log_verification_success(
            &correlation_id,
            &artifact_hash,
            Some(&identity),
            1, // signature count
        );

        log::info!("Keyless verification completed successfully");

        Ok(KeylessVerificationResult {
            identity,
            issuer,
            rekor_log_index: keyless_sig.rekor_entry.log_index,
            rekor_uuid: keyless_sig.rekor_entry.uuid,
        })
    }
}

// Implement a simple RFC3339 timestamp for the dummy Rekor entry
mod chrono {
    pub struct Utc;
    impl Utc {
        pub fn now() -> DateTime {
            DateTime
        }
    }
    pub struct DateTime;
    impl DateTime {
        pub fn to_rfc3339(&self) -> String {
            // Use time crate's OffsetDateTime for proper RFC3339
            time::OffsetDateTime::now_utc()
                .format(&time::format_description::well_known::Rfc3339)
                .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string())
        }
    }
}

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

    #[test]
    fn test_keyless_config_default() {
        let config = KeylessConfig::default();
        assert!(config.fulcio_url.is_none());
        assert!(config.rekor_url.is_none());
        assert!(!config.skip_rekor);
        assert!(!config.use_staging);
        assert!(config.fulcio_pins.is_empty());
        assert!(config.rekor_pins.is_empty());
        assert!(!config.require_cert_pinning);
        assert!(config.expected_issuer.is_none());
        assert!(config.proof_cache.is_none());
    }

    #[test]
    fn test_keyless_config_custom() {
        let config = KeylessConfig {
            fulcio_url: Some("https://custom.fulcio.dev".to_string()),
            rekor_url: Some("https://custom.rekor.dev".to_string()),
            skip_rekor: true,
            ..Default::default()
        };
        assert!(config.fulcio_url.is_some());
        assert!(config.rekor_url.is_some());
        assert!(config.skip_rekor);
    }

    #[test]
    fn test_keyless_config_staging() {
        let config = KeylessConfig {
            use_staging: true,
            ..Default::default()
        };
        assert!(config.use_staging);
        assert!(config.fulcio_url.is_none()); // Will use staging URL
        assert!(config.rekor_url.is_none()); // Will use staging URL
    }

    #[test]
    fn test_keyless_config_custom_pins() {
        let config = KeylessConfig {
            fulcio_pins: vec!["a".repeat(64), "b".repeat(64)],
            rekor_pins: vec!["c".repeat(64)],
            ..Default::default()
        };
        assert_eq!(config.fulcio_pins.len(), 2);
        assert_eq!(config.rekor_pins.len(), 1);
    }

    #[test]
    fn test_keyless_config_require_cert_pinning() {
        let config = KeylessConfig {
            require_cert_pinning: true,
            ..Default::default()
        };
        assert!(config.require_cert_pinning);
    }

    #[test]
    fn test_keyless_config_expected_issuer() {
        let config = KeylessConfig {
            expected_issuer: Some("https://token.actions.githubusercontent.com".to_string()),
            ..Default::default()
        };
        assert_eq!(
            config.expected_issuer.as_deref(),
            Some("https://token.actions.githubusercontent.com")
        );
    }

    #[test]
    fn test_keyless_config_expected_issuer_default_is_none() {
        let config = KeylessConfig::default();
        assert!(config.expected_issuer.is_none());
    }

    // ============================================================================
    // SECURITY TESTS: OIDC issuer env-var precedence (audit H-4)
    // ============================================================================

    #[test]
    fn test_resolve_issuer_env_set_overrides_programmatic() {
        let (chosen, disabled) = resolve_expected_issuer(
            Some("https://env.example.com"),
            None,
            Some("https://prog.example.com"),
        );
        assert!(!disabled);
        assert_eq!(chosen.as_deref(), Some("https://env.example.com"));
    }

    #[test]
    fn test_resolve_issuer_env_empty_falls_through_to_programmatic() {
        // Audit H-4: empty env var must NOT silently disable validation; it
        // must fall through to the programmatic config.
        let (chosen, disabled) =
            resolve_expected_issuer(Some(""), None, Some("https://prog.example.com"));
        assert!(!disabled);
        assert_eq!(chosen.as_deref(), Some("https://prog.example.com"));
    }

    #[test]
    fn test_resolve_issuer_env_unset_uses_programmatic() {
        let (chosen, disabled) =
            resolve_expected_issuer(None, None, Some("https://prog.example.com"));
        assert!(!disabled);
        assert_eq!(chosen.as_deref(), Some("https://prog.example.com"));
    }

    #[test]
    fn test_resolve_issuer_explicit_disable() {
        // Audit H-4: only explicit WSC_DISABLE_OIDC_ISSUER_CHECK=1 disables.
        let (chosen, disabled) = resolve_expected_issuer(
            Some("https://env.example.com"),
            Some("1"),
            Some("https://prog.example.com"),
        );
        assert!(disabled);
        assert!(chosen.is_none());
    }

    #[test]
    fn test_resolve_issuer_disable_other_value_does_not_disable() {
        // Only "1" disables. "true", "yes", "0" must not.
        for v in &["true", "yes", "0", ""] {
            let (chosen, disabled) =
                resolve_expected_issuer(None, Some(*v), Some("https://prog.example.com"));
            assert!(!disabled, "value {:?} should not disable", v);
            assert_eq!(chosen.as_deref(), Some("https://prog.example.com"));
        }
    }

    #[test]
    fn test_resolve_issuer_no_config_anywhere() {
        let (chosen, disabled) = resolve_expected_issuer(None, None, None);
        assert!(!disabled);
        assert!(chosen.is_none());
    }

    #[test]
    fn test_keyless_signer_new_fails_without_oidc() {
        // This test will fail if no OIDC provider is detected
        // In CI environments without OIDC setup, this is expected
        let result = KeylessSigner::new();
        // Should either succeed (if OIDC is available) or fail with NoOidcProvider
        if let Err(e) = result {
            assert!(
                matches!(e, WSError::NoOidcProvider) || matches!(e, WSError::OidcError(_)),
                "Expected NoOidcProvider or OidcError, got: {:?}",
                e
            );
        }
    }

    #[test]
    fn test_keyless_verifier_no_signature() {
        // Create an empty module (no signature)
        let module = Module::default();
        let verifier = KeylessVerifier::new();
        let result = verifier.verify(&module, None, None);
        // Should fail with NoSignatures error
        assert!(result.is_err());
        assert!(matches!(result, Err(WSError::NoSignatures)));
    }

    // ============================================================================
    // SECURITY TESTS: Ephemeral Key Zeroization (Issue #14)
    // ============================================================================

    #[test]
    fn test_ephemeral_key_generation_and_drop() {
        // Test that ephemeral keys can be generated and dropped without issues
        // This verifies the basic zeroization mechanism works

        use ecdsa::SigningKey;
        use p256::NistP256;

        // Generate a key in a scope
        {
            let signing_key =
                SigningKey::<NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);
            let verifying_key = signing_key.verifying_key();

            // Verify we can use the key
            assert!(!verifying_key.to_encoded_point(false).as_bytes().is_empty());

            // signing_key goes out of scope here
            // Its internal SecretKey implements ZeroizeOnDrop
        }

        // If we reach here, Drop was called successfully
    }

    #[test]
    fn test_ephemeral_key_signing_operation() {
        // Test that we can perform signing operations and the key is still zeroized

        use ecdsa::{SigningKey, signature::Signer};
        use p256::{NistP256, ecdsa::Signature};

        let message = b"test message for signing";

        let signature: Signature = {
            // Generate key in inner scope
            let signing_key =
                SigningKey::<NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);

            // Sign the message
            let sig: Signature = signing_key.sign(message);

            // signing_key dropped here (zeroized)
            sig
        };

        // We have the signature but the key is gone (zeroized)
        assert_eq!(signature.to_bytes().len(), 64);
    }

    #[test]
    fn test_ephemeral_key_with_error_path() {
        // Test that ephemeral keys are zeroized even when errors occur

        use ecdsa::SigningKey;
        use p256::NistP256;

        fn operation_with_key() -> Result<Vec<u8>, WSError> {
            let signing_key =
                SigningKey::<NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);
            let verifying_key = signing_key.verifying_key();
            let public_bytes = verifying_key.to_encoded_point(false);

            // Simulate an error after using the key
            if !public_bytes.as_bytes().is_empty() {
                return Err(WSError::OidcError("Simulated error".to_string()));
            }

            Ok(public_bytes.as_bytes().to_vec())
        }

        let result = operation_with_key();
        assert!(result.is_err());

        // Key was zeroized despite error
    }

    #[test]
    fn test_ephemeral_key_multiple_operations() {
        // Test that we can generate multiple ephemeral keys sequentially
        // Each one should be zeroized before the next is created

        use ecdsa::{SigningKey, signature::Signer};
        use p256::{NistP256, ecdsa::Signature};

        let message = b"test message";
        let mut signatures = Vec::new();

        for _ in 0..5 {
            let sig: Signature = {
                let signing_key =
                    SigningKey::<NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);
                signing_key.sign(message)
                // key zeroized here
            };
            signatures.push(sig);
        }

        assert_eq!(signatures.len(), 5);
        // All 5 keys were created and zeroized sequentially
    }

    #[test]
    fn test_ephemeral_key_scope_limitation() {
        // Test that ephemeral keys don't escape their intended scope
        // This is a compile-time guarantee but we document the behavior

        use ecdsa::SigningKey;
        use p256::NistP256;

        let public_key_bytes = {
            let signing_key =
                SigningKey::<NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);
            let verifying_key = signing_key.verifying_key();

            // Extract public key (safe to keep)
            verifying_key.to_encoded_point(false).as_bytes().to_vec()

            // signing_key dropped/zeroized here
        };

        // We can keep the public key, but the private key is gone
        assert!(!public_key_bytes.is_empty());

        // This would not compile (key doesn't escape scope):
        // let leaked_key = signing_key; // ERROR: signing_key not in scope
    }

    #[test]
    fn test_ephemeral_key_with_digest_signing() {
        // Test that digest signing (as used in actual keyless signing) works
        // and keys are still properly zeroized

        use ecdsa::{SigningKey, signature::DigestSigner};
        use p256::{NistP256, ecdsa::Signature};
        use sha2::{Digest, Sha256};

        let data = b"data to hash and sign";

        let signature: Signature = {
            let signing_key =
                SigningKey::<NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);

            // Create digest
            let mut hasher = Sha256::new();
            hasher.update(data);

            // Sign the digest (this is what sign_module does)
            signing_key.sign_digest(hasher)

            // signing_key zeroized here
        };

        assert_eq!(signature.to_bytes().len(), 64);
    }

    #[test]
    fn test_ephemeral_key_verifying_key_extraction() {
        // Test that we can extract the verifying key before the signing key is dropped
        // This pattern is used in sign_module

        use ecdsa::SigningKey;
        use p256::NistP256;

        let (verifying_key_bytes, signature_made) = {
            let signing_key =
                SigningKey::<NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);

            // Extract verifying key (this is safe to keep)
            let verifying_key = signing_key.verifying_key();
            let vk_bytes = verifying_key.to_encoded_point(false).as_bytes().to_vec();

            // Use the signing key
            use ecdsa::signature::Signer;
            use p256::ecdsa::Signature;
            let sig: Signature = signing_key.sign(b"test");

            (vk_bytes, sig.to_bytes().len() == 64)

            // signing_key zeroized here
        };

        // We kept the public key and verified a signature was made
        assert!(!verifying_key_bytes.is_empty());
        assert!(signature_made);
    }

    #[test]
    fn test_ephemeral_key_move_semantics() {
        // Test that moving keys between scopes works correctly with zeroization

        use ecdsa::SigningKey;
        use p256::NistP256;

        fn consume_key(key: SigningKey<NistP256>) -> usize {
            let vk = key.verifying_key();
            vk.to_encoded_point(false).as_bytes().len()
            // key dropped and zeroized here
        }

        let signing_key =
            SigningKey::<NistP256>::random(&mut p256::elliptic_curve::rand_core::OsRng);

        let len = consume_key(signing_key);
        // signing_key was moved into consume_key and zeroized there

        assert!(len > 0);
    }
}