barbacane-wasm 0.7.0

WASM plugin runtime for Barbacane API gateway
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
//! HTTP client for outbound requests from WASM plugins.
//!
//! Provides connection pooling, TLS, timeouts, and circuit breaker support.

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use parking_lot::RwLock;
use reqwest::{Certificate, Client, Identity};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig, CircuitState};
use barbacane_plugin_sdk::types::base64_body;

/// TLS configuration for upstream mTLS connections.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TlsConfig {
    /// Path to PEM-encoded client certificate.
    #[serde(default)]
    pub client_cert: Option<PathBuf>,
    /// Path to PEM-encoded client private key.
    #[serde(default)]
    pub client_key: Option<PathBuf>,
    /// Path to PEM-encoded CA certificate for server verification.
    #[serde(default)]
    pub ca: Option<PathBuf>,
}

impl TlsConfig {
    /// Returns true if any TLS configuration is specified.
    pub fn is_configured(&self) -> bool {
        self.client_cert.is_some() || self.client_key.is_some() || self.ca.is_some()
    }

    /// Validate that if client_cert is set, client_key must also be set (and vice versa).
    pub fn validate(&self) -> Result<(), TlsConfigError> {
        match (&self.client_cert, &self.client_key) {
            (Some(_), None) => Err(TlsConfigError::MissingClientKey),
            (None, Some(_)) => Err(TlsConfigError::MissingClientCert),
            _ => Ok(()),
        }
    }

    /// Create a cache key for this TLS configuration.
    fn cache_key(&self) -> TlsCacheKey {
        TlsCacheKey {
            client_cert: self.client_cert.clone(),
            client_key: self.client_key.clone(),
            ca: self.ca.clone(),
        }
    }
}

/// TLS configuration errors.
#[derive(Debug, Error)]
pub enum TlsConfigError {
    #[error("client_cert specified but client_key is missing")]
    MissingClientKey,
    #[error("client_key specified but client_cert is missing")]
    MissingClientCert,
    #[error("failed to read certificate file: {0}")]
    ReadCertificate(#[source] std::io::Error),
    #[error("failed to read key file: {0}")]
    ReadKey(#[source] std::io::Error),
    #[error("failed to read CA file: {0}")]
    ReadCa(#[source] std::io::Error),
    #[error("failed to parse PEM identity: {0}")]
    ParseIdentity(#[source] reqwest::Error),
    #[error("failed to parse CA certificate: {0}")]
    ParseCaCert(#[source] reqwest::Error),
}

/// Cache key for TLS-configured clients.
#[derive(Debug, Clone, PartialEq, Eq)]
struct TlsCacheKey {
    client_cert: Option<PathBuf>,
    client_key: Option<PathBuf>,
    ca: Option<PathBuf>,
}

impl Hash for TlsCacheKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.client_cert.hash(state);
        self.client_key.hash(state);
        self.ca.hash(state);
    }
}

/// HTTP client with connection pooling and circuit breaker support.
#[derive(Clone)]
pub struct HttpClient {
    /// Default client (no mTLS).
    client: Client,
    /// Cached clients with specific TLS configurations.
    tls_clients: Arc<RwLock<HashMap<TlsCacheKey, Client>>>,
    /// Base config for creating new clients.
    base_config: HttpClientConfig,
    circuit_breakers: Arc<RwLock<HashMap<String, CircuitBreaker>>>,
    default_timeout: Duration,
    allow_plaintext: bool,
}

impl HttpClient {
    /// Create a new HTTP client.
    pub fn new(config: HttpClientConfig) -> Result<Self, HttpClientError> {
        let client = Client::builder()
            .pool_max_idle_per_host(config.pool_max_idle_per_host)
            .pool_idle_timeout(config.pool_idle_timeout)
            .connect_timeout(config.connect_timeout)
            .timeout(config.default_timeout)
            .build()
            .map_err(HttpClientError::BuildError)?;

        let default_timeout = config.default_timeout;
        let allow_plaintext = config.allow_plaintext;

        Ok(Self {
            client,
            tls_clients: Arc::new(RwLock::new(HashMap::new())),
            base_config: config,
            circuit_breakers: Arc::new(RwLock::new(HashMap::new())),
            default_timeout,
            allow_plaintext,
        })
    }

    /// Get or create a client with the specified TLS configuration.
    fn get_or_create_tls_client(&self, tls_config: &TlsConfig) -> Result<Client, HttpClientError> {
        let cache_key = tls_config.cache_key();

        // Check if we already have a client for this config
        {
            let clients = self.tls_clients.read();
            if let Some(client) = clients.get(&cache_key) {
                return Ok(client.clone());
            }
        }

        // Create a new client with TLS config
        let client = self.build_tls_client(tls_config)?;

        // Cache it
        {
            let mut clients = self.tls_clients.write();
            clients.insert(cache_key, client.clone());
        }

        Ok(client)
    }

    /// Build a new client with the specified TLS configuration.
    fn build_tls_client(&self, tls_config: &TlsConfig) -> Result<Client, HttpClientError> {
        tls_config.validate().map_err(HttpClientError::TlsConfig)?;

        let mut builder = Client::builder()
            .pool_max_idle_per_host(self.base_config.pool_max_idle_per_host)
            .pool_idle_timeout(self.base_config.pool_idle_timeout)
            .connect_timeout(self.base_config.connect_timeout)
            .timeout(self.base_config.default_timeout);

        // Add client certificate (mTLS)
        if let (Some(cert_path), Some(key_path)) = (&tls_config.client_cert, &tls_config.client_key)
        {
            let cert_pem = std::fs::read(cert_path)
                .map_err(|e| HttpClientError::TlsConfig(TlsConfigError::ReadCertificate(e)))?;
            let key_pem = std::fs::read(key_path)
                .map_err(|e| HttpClientError::TlsConfig(TlsConfigError::ReadKey(e)))?;

            // Combine cert and key for Identity::from_pem
            let mut pem = cert_pem;
            pem.extend_from_slice(&key_pem);

            let identity = Identity::from_pem(&pem)
                .map_err(|e| HttpClientError::TlsConfig(TlsConfigError::ParseIdentity(e)))?;

            builder = builder.identity(identity);
        }

        // Add custom CA certificate
        if let Some(ca_path) = &tls_config.ca {
            let ca_pem = std::fs::read(ca_path)
                .map_err(|e| HttpClientError::TlsConfig(TlsConfigError::ReadCa(e)))?;

            let ca_cert = Certificate::from_pem(&ca_pem)
                .map_err(|e| HttpClientError::TlsConfig(TlsConfigError::ParseCaCert(e)))?;

            builder = builder.add_root_certificate(ca_cert);
        }

        builder.build().map_err(HttpClientError::BuildError)
    }

    /// Make an HTTP request.
    pub async fn call(&self, request: HttpRequest) -> Result<HttpResponse, HttpClientError> {
        self.call_with_tls(request, None).await
    }

    /// Send a streaming HTTP request and return the raw upstream response.
    ///
    /// Applies the same URL validation, plaintext checks, and circuit breaker
    /// as `call`, but returns the `reqwest::Response` directly so the caller
    /// can stream the response body chunk by chunk (e.g. via `bytes_stream()`).
    ///
    /// The circuit breaker is only updated on connection-level errors; success
    /// recording is left to the caller after streaming completes.
    pub async fn stream_raw(
        &self,
        request: HttpRequest,
    ) -> Result<reqwest::Response, HttpClientError> {
        let url = request
            .url
            .parse::<reqwest::Url>()
            .map_err(|e| HttpClientError::InvalidUrl(e.to_string()))?;

        if url.scheme() == "http" && !self.allow_plaintext {
            return Err(HttpClientError::PlaintextNotAllowed);
        }

        let host = url
            .host_str()
            .ok_or_else(|| HttpClientError::InvalidUrl("missing host".into()))?
            .to_string();

        let circuit_state = self.get_circuit_state(&host);
        if circuit_state == crate::circuit_breaker::CircuitState::Open {
            return Err(HttpClientError::CircuitOpen(host));
        }

        let method = request
            .method
            .parse::<reqwest::Method>()
            .map_err(|e| HttpClientError::InvalidMethod(e.to_string()))?;

        let timeout = request.timeout.unwrap_or(self.default_timeout);

        let mut req_builder = self.client.request(method, url).timeout(timeout);

        for (key, value) in &request.headers {
            req_builder = req_builder.header(key.as_str(), value.as_str());
        }

        if let Some(body) = request.body {
            req_builder = req_builder.body(body);
        }

        match req_builder.send().await {
            Ok(response) => Ok(response),
            Err(e) => {
                self.record_failure(&host);
                if e.is_timeout() {
                    Err(HttpClientError::Timeout)
                } else if e.is_connect() {
                    Err(HttpClientError::ConnectionFailed(e.to_string()))
                } else {
                    Err(HttpClientError::RequestFailed(e.to_string()))
                }
            }
        }
    }

    /// Make an HTTP request with optional TLS configuration for mTLS.
    pub async fn call_with_tls(
        &self,
        request: HttpRequest,
        tls_config: Option<&TlsConfig>,
    ) -> Result<HttpResponse, HttpClientError> {
        // Validate URL scheme
        let url = request
            .url
            .parse::<reqwest::Url>()
            .map_err(|e| HttpClientError::InvalidUrl(e.to_string()))?;

        if url.scheme() == "http" && !self.allow_plaintext {
            return Err(HttpClientError::PlaintextNotAllowed);
        }

        // Extract host for circuit breaker
        let host = url
            .host_str()
            .ok_or_else(|| HttpClientError::InvalidUrl("missing host".into()))?
            .to_string();

        // Check circuit breaker
        let circuit_state = self.get_circuit_state(&host);
        if circuit_state == CircuitState::Open {
            return Err(HttpClientError::CircuitOpen(host));
        }

        // Get the appropriate client (default or TLS-configured)
        let client = match tls_config {
            Some(tls) if tls.is_configured() => self.get_or_create_tls_client(tls)?,
            _ => self.client.clone(),
        };

        // Build request
        let method = request
            .method
            .parse::<reqwest::Method>()
            .map_err(|e| HttpClientError::InvalidMethod(e.to_string()))?;

        let timeout = request.timeout.unwrap_or(self.default_timeout);

        let mut req_builder = client.request(method, url).timeout(timeout);

        // Add headers
        for (key, value) in &request.headers {
            req_builder = req_builder.header(key.as_str(), value.as_str());
        }

        // Add body
        if let Some(body) = request.body {
            req_builder = req_builder.body(body);
        }

        // Execute request
        let result = req_builder.send().await;

        match result {
            Ok(response) => {
                // Record success
                self.record_success(&host);

                let status = response.status().as_u16();
                let headers: HashMap<String, String> = response
                    .headers()
                    .iter()
                    .filter_map(|(k, v)| {
                        v.to_str()
                            .ok()
                            .map(|v| (k.as_str().to_lowercase(), v.to_string()))
                    })
                    .collect();

                let body = response
                    .bytes()
                    .await
                    .map_err(HttpClientError::ResponseReadError)?;

                Ok(HttpResponse {
                    status,
                    headers,
                    body: Some(body.to_vec()),
                })
            }
            Err(e) => {
                // Record failure
                self.record_failure(&host);

                if e.is_timeout() {
                    Err(HttpClientError::Timeout)
                } else if e.is_connect() {
                    Err(HttpClientError::ConnectionFailed(e.to_string()))
                } else {
                    Err(HttpClientError::RequestFailed(e.to_string()))
                }
            }
        }
    }

    /// Configure circuit breaker for a host.
    pub fn configure_circuit_breaker(&self, host: &str, config: CircuitBreakerConfig) {
        let mut breakers = self.circuit_breakers.write();
        breakers.insert(host.to_string(), CircuitBreaker::new(config));
    }

    fn get_circuit_state(&self, host: &str) -> CircuitState {
        let breakers = self.circuit_breakers.read();
        breakers
            .get(host)
            .map(|cb| cb.state())
            .unwrap_or(CircuitState::Closed)
    }

    fn record_success(&self, host: &str) {
        let mut breakers = self.circuit_breakers.write();
        if let Some(cb) = breakers.get_mut(host) {
            cb.record_success();
        }
    }

    fn record_failure(&self, host: &str) {
        let mut breakers = self.circuit_breakers.write();
        if let Some(cb) = breakers.get_mut(host) {
            cb.record_failure();
        }
    }
}

/// Configuration for the HTTP client.
#[derive(Debug, Clone)]
pub struct HttpClientConfig {
    /// Maximum idle connections per host.
    pub pool_max_idle_per_host: usize,
    /// Idle connection timeout.
    pub pool_idle_timeout: Duration,
    /// Connection timeout.
    pub connect_timeout: Duration,
    /// Default request timeout.
    pub default_timeout: Duration,
    /// Allow plaintext HTTP (development only).
    pub allow_plaintext: bool,
}

impl Default for HttpClientConfig {
    fn default() -> Self {
        Self {
            pool_max_idle_per_host: 10,
            pool_idle_timeout: Duration::from_secs(90),
            connect_timeout: Duration::from_secs(10),
            default_timeout: Duration::from_secs(30),
            allow_plaintext: false,
        }
    }
}

/// HTTP request from WASM plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpRequest {
    /// HTTP method (GET, POST, etc.)
    pub method: String,
    /// Full URL including scheme and host.
    pub url: String,
    /// Request headers.
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// Request body (optional, base64-encoded in JSON for WASM transport).
    #[serde(default, with = "base64_body")]
    pub body: Option<Vec<u8>>,
    /// Request timeout (optional, uses client default).
    #[serde(default, with = "option_duration_serde")]
    pub timeout: Option<Duration>,
}

/// HTTP response to WASM plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpResponse {
    /// HTTP status code.
    pub status: u16,
    /// Response headers.
    pub headers: HashMap<String, String>,
    /// Response body (optional, base64-encoded in JSON for WASM transport).
    #[serde(default, with = "base64_body")]
    pub body: Option<Vec<u8>>,
}

impl HttpResponse {
    /// Create an error response.
    pub fn error(status: u16, error_type: &str, title: &str, detail: &str) -> Self {
        let body = serde_json::json!({
            "type": error_type,
            "title": title,
            "status": status,
            "detail": detail
        });

        let mut headers = HashMap::new();
        headers.insert(
            "content-type".to_string(),
            "application/problem+json".to_string(),
        );

        Self {
            status,
            headers,
            body: Some(body.to_string().into_bytes()),
        }
    }
}

/// HTTP client errors.
#[derive(Debug, Error)]
pub enum HttpClientError {
    #[error("failed to build HTTP client: {0}")]
    BuildError(#[source] reqwest::Error),

    #[error("invalid URL: {0}")]
    InvalidUrl(String),

    #[error("invalid HTTP method: {0}")]
    InvalidMethod(String),

    #[error("plaintext HTTP not allowed")]
    PlaintextNotAllowed,

    #[error("circuit breaker open for host: {0}")]
    CircuitOpen(String),

    #[error("request timeout")]
    Timeout,

    #[error("connection failed: {0}")]
    ConnectionFailed(String),

    #[error("request failed: {0}")]
    RequestFailed(String),

    #[error("failed to read response: {0}")]
    ResponseReadError(#[source] reqwest::Error),

    #[error("TLS configuration error: {0}")]
    TlsConfig(#[source] TlsConfigError),
}

/// Custom serde for Option<Duration> in seconds.
mod option_duration_serde {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::time::Duration;

    pub fn serialize<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match duration {
            Some(d) => d.as_secs_f64().serialize(serializer),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<f64> = Option::deserialize(deserializer)?;
        Ok(opt.map(Duration::from_secs_f64))
    }
}

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

    #[test]
    fn test_config_default() {
        let config = HttpClientConfig::default();
        assert_eq!(config.pool_max_idle_per_host, 10);
        assert_eq!(config.default_timeout, Duration::from_secs(30));
        assert!(!config.allow_plaintext);
    }

    #[test]
    fn test_error_response() {
        let resp = HttpResponse::error(
            502,
            "urn:barbacane:error:upstream-unavailable",
            "Bad Gateway",
            "Failed to connect to upstream",
        );

        assert_eq!(resp.status, 502);
        assert_eq!(
            resp.headers.get("content-type"),
            Some(&"application/problem+json".to_string())
        );
    }

    #[test]
    fn test_tls_config_default() {
        let tls = TlsConfig::default();
        assert!(tls.client_cert.is_none());
        assert!(tls.client_key.is_none());
        assert!(tls.ca.is_none());
        assert!(!tls.is_configured());
    }

    #[test]
    fn test_tls_config_is_configured() {
        let mut tls = TlsConfig::default();
        assert!(!tls.is_configured());

        tls.client_cert = Some(PathBuf::from("/path/to/cert.pem"));
        assert!(tls.is_configured());

        tls.client_cert = None;
        tls.ca = Some(PathBuf::from("/path/to/ca.pem"));
        assert!(tls.is_configured());
    }

    #[test]
    fn test_tls_config_validate_success() {
        // Empty config is valid
        let tls = TlsConfig::default();
        assert!(tls.validate().is_ok());

        // CA only is valid
        let tls = TlsConfig {
            client_cert: None,
            client_key: None,
            ca: Some(PathBuf::from("/path/to/ca.pem")),
        };
        assert!(tls.validate().is_ok());

        // Both cert and key is valid
        let tls = TlsConfig {
            client_cert: Some(PathBuf::from("/path/to/cert.pem")),
            client_key: Some(PathBuf::from("/path/to/key.pem")),
            ca: None,
        };
        assert!(tls.validate().is_ok());
    }

    #[test]
    fn test_tls_config_validate_missing_key() {
        let tls = TlsConfig {
            client_cert: Some(PathBuf::from("/path/to/cert.pem")),
            client_key: None,
            ca: None,
        };
        let err = tls.validate().unwrap_err();
        assert!(matches!(err, TlsConfigError::MissingClientKey));
    }

    #[test]
    fn test_tls_config_validate_missing_cert() {
        let tls = TlsConfig {
            client_cert: None,
            client_key: Some(PathBuf::from("/path/to/key.pem")),
            ca: None,
        };
        let err = tls.validate().unwrap_err();
        assert!(matches!(err, TlsConfigError::MissingClientCert));
    }

    #[test]
    fn test_tls_config_serde() {
        let json = r#"{
            "client_cert": "/etc/certs/client.crt",
            "client_key": "/etc/certs/client.key",
            "ca": "/etc/certs/ca.crt"
        }"#;

        let tls: TlsConfig = serde_json::from_str(json).unwrap();
        assert_eq!(
            tls.client_cert,
            Some(PathBuf::from("/etc/certs/client.crt"))
        );
        assert_eq!(tls.client_key, Some(PathBuf::from("/etc/certs/client.key")));
        assert_eq!(tls.ca, Some(PathBuf::from("/etc/certs/ca.crt")));
    }

    #[test]
    fn test_tls_config_serde_partial() {
        let json = r#"{"ca": "/etc/certs/ca.crt"}"#;

        let tls: TlsConfig = serde_json::from_str(json).unwrap();
        assert!(tls.client_cert.is_none());
        assert!(tls.client_key.is_none());
        assert_eq!(tls.ca, Some(PathBuf::from("/etc/certs/ca.crt")));
    }

    // ── stream_raw validation ─────────────────────────────────────────────────

    #[tokio::test]
    async fn stream_raw_rejects_invalid_url() {
        let client = HttpClient::new(HttpClientConfig::default()).expect("client");
        let req = HttpRequest {
            method: "GET".into(),
            url: "not a url".into(),
            headers: Default::default(),
            body: None,
            timeout: None,
        };
        assert!(matches!(
            client.stream_raw(req).await,
            Err(HttpClientError::InvalidUrl(_))
        ));
    }

    #[tokio::test]
    async fn stream_raw_rejects_plaintext_when_disallowed() {
        let config = HttpClientConfig {
            allow_plaintext: false,
            ..Default::default()
        };
        let client = HttpClient::new(config).expect("client");
        let req = HttpRequest {
            method: "GET".into(),
            url: "http://example.com/api".into(),
            headers: Default::default(),
            body: None,
            timeout: None,
        };
        assert!(matches!(
            client.stream_raw(req).await,
            Err(HttpClientError::PlaintextNotAllowed)
        ));
    }

    #[tokio::test]
    async fn stream_raw_rejects_invalid_method() {
        let config = HttpClientConfig {
            allow_plaintext: true,
            ..Default::default()
        };
        let client = HttpClient::new(config).expect("client");
        let req = HttpRequest {
            method: "NOT A METHOD!!!".into(),
            url: "http://127.0.0.1:1/".into(),
            headers: Default::default(),
            body: None,
            timeout: None,
        };
        assert!(matches!(
            client.stream_raw(req).await,
            Err(HttpClientError::InvalidMethod(_))
        ));
    }

    #[tokio::test]
    async fn stream_raw_connection_refused() {
        let config = HttpClientConfig {
            allow_plaintext: true,
            ..Default::default()
        };
        let client = HttpClient::new(config).expect("client");
        let req = HttpRequest {
            method: "GET".into(),
            url: "http://127.0.0.1:1/".into(), // port 1: connection refused
            headers: Default::default(),
            body: None,
            timeout: None,
        };
        let err = client.stream_raw(req).await.unwrap_err();
        assert!(
            matches!(
                err,
                HttpClientError::ConnectionFailed(_) | HttpClientError::RequestFailed(_)
            ),
            "expected network error, got: {err:?}"
        );
    }

    #[tokio::test]
    async fn stream_raw_timeout() {
        use tokio::net::TcpListener;

        // Bind a listener but never accept — the client will time out.
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
        let addr = listener.local_addr().expect("local_addr");

        let config = HttpClientConfig {
            allow_plaintext: true,
            ..Default::default()
        };
        let client = HttpClient::new(config).expect("client");
        let req = HttpRequest {
            method: "GET".into(),
            url: format!("http://{addr}/slow"),
            headers: Default::default(),
            body: None,
            timeout: Some(Duration::from_millis(50)),
        };
        let err = client.stream_raw(req).await.unwrap_err();
        assert!(
            matches!(err, HttpClientError::Timeout),
            "expected Timeout, got: {err:?}"
        );

        drop(listener);
    }

    #[tokio::test]
    async fn stream_raw_successful_request() {
        use tokio::io::AsyncWriteExt;
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
        let addr = listener.local_addr().expect("local_addr");

        // Spawn a minimal HTTP server that returns a 200.
        tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.expect("accept");
            let mut buf = [0u8; 1024];
            let _ = tokio::io::AsyncReadExt::read(&mut socket, &mut buf).await;
            let response = "HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok";
            socket.write_all(response.as_bytes()).await.expect("write");
            socket.shutdown().await.expect("shutdown");
        });

        let config = HttpClientConfig {
            allow_plaintext: true,
            ..Default::default()
        };
        let client = HttpClient::new(config).expect("client");
        let req = HttpRequest {
            method: "GET".into(),
            url: format!("http://{addr}/"),
            headers: Default::default(),
            body: None,
            timeout: None,
        };
        let resp = client
            .stream_raw(req)
            .await
            .expect("stream_raw should succeed");
        assert_eq!(resp.status(), 200);
        let body = resp.text().await.expect("body");
        assert_eq!(body, "ok");
    }

    #[test]
    fn test_tls_cache_key_equality() {
        let tls1 = TlsConfig {
            client_cert: Some(PathBuf::from("/path/to/cert.pem")),
            client_key: Some(PathBuf::from("/path/to/key.pem")),
            ca: None,
        };
        let tls2 = TlsConfig {
            client_cert: Some(PathBuf::from("/path/to/cert.pem")),
            client_key: Some(PathBuf::from("/path/to/key.pem")),
            ca: None,
        };
        let tls3 = TlsConfig {
            client_cert: Some(PathBuf::from("/other/cert.pem")),
            client_key: Some(PathBuf::from("/path/to/key.pem")),
            ca: None,
        };

        assert_eq!(tls1.cache_key(), tls2.cache_key());
        assert_ne!(tls1.cache_key(), tls3.cache_key());
    }

    // ── base64 body serde (host ↔ WASM plugin compatibility) ─────────────

    /// Verify that HttpRequest serialized by a WASM plugin (base64 body)
    /// deserializes correctly on the host side.
    #[test]
    fn http_request_base64_body_roundtrip() {
        let binary_body: Vec<u8> = vec![0x89, 0x50, 0x4E, 0x47, 0xFF, 0xFE, 0x00, 0x01];
        let req = HttpRequest {
            method: "POST".into(),
            url: "https://example.com/upload".into(),
            headers: Default::default(),
            body: Some(binary_body.clone()),
            timeout: None,
        };

        let json = serde_json::to_string(&req).unwrap();
        // Body must be base64-encoded in JSON, not raw bytes
        assert!(
            !json.contains("\\u0089"),
            "body should be base64-encoded, not escaped unicode"
        );

        let decoded: HttpRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.body.unwrap(), binary_body);
    }

    /// Verify that HttpResponse serialized by the host (base64 body)
    /// deserializes correctly on the plugin side.
    #[test]
    fn http_response_base64_body_roundtrip() {
        let binary_body: Vec<u8> = vec![0x89, 0x50, 0x4E, 0x47, 0xFF, 0xFE, 0x00, 0x01];
        let resp = HttpResponse {
            status: 200,
            headers: Default::default(),
            body: Some(binary_body.clone()),
        };

        let json = serde_json::to_string(&resp).unwrap();
        let decoded: HttpResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.body.unwrap(), binary_body);
    }

    /// Verify None body serializes as null and deserializes back.
    #[test]
    fn http_request_null_body_roundtrip() {
        let req = HttpRequest {
            method: "GET".into(),
            url: "https://example.com".into(),
            headers: Default::default(),
            body: None,
            timeout: None,
        };

        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains(r#""body":null"#));

        let decoded: HttpRequest = serde_json::from_str(&json).unwrap();
        assert!(decoded.body.is_none());
    }

    /// Simulate what a WASM plugin sends: manually construct the JSON with
    /// a base64 string body and verify the host deserializes it correctly.
    #[test]
    fn http_request_deserialize_from_plugin_json() {
        use base64::Engine;
        let raw_bytes: Vec<u8> = vec![0x00, 0x01, 0x80, 0xFF];
        let b64 = base64::engine::general_purpose::STANDARD.encode(&raw_bytes);

        let json = format!(
            r#"{{
                "method": "POST",
                "url": "https://example.com/api",
                "body": "{b64}"
            }}"#
        );

        let req: HttpRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(req.body.unwrap(), raw_bytes);
    }

    /// Simulate what the host sends back: manually construct JSON with
    /// base64 body and verify plugin-side deserialization.
    #[test]
    fn http_response_deserialize_from_host_json() {
        use base64::Engine;
        let raw_bytes: Vec<u8> = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A];
        let b64 = base64::engine::general_purpose::STANDARD.encode(&raw_bytes);

        let json = format!(
            r#"{{
                "status": 200,
                "headers": {{}},
                "body": "{b64}"
            }}"#
        );

        let resp: HttpResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(resp.body.unwrap(), raw_bytes);
    }
}