camel-component-http 0.28.0

HTTP client component for rust-camel
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
use serde::Deserialize;

use camel_component_api::CamelError;

#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct HttpConfig {
    #[serde(default = "default_connect_timeout_ms")]
    pub connect_timeout_ms: u64,
    #[serde(default = "default_pool_max_idle_per_host")]
    pub pool_max_idle_per_host: usize,
    #[serde(default = "default_pool_idle_timeout_ms")]
    pub pool_idle_timeout_ms: u64,
    #[serde(default)]
    pub follow_redirects: bool,
    #[serde(default)]
    pub max_redirects: Option<usize>,
    #[serde(default = "default_response_timeout_ms")]
    pub response_timeout_ms: u64,
    #[serde(default = "default_read_timeout_ms")]
    pub read_timeout_ms: u64,
    #[serde(default = "default_max_body_size")]
    pub max_body_size: usize,
    #[serde(default = "default_max_response_bytes")]
    pub max_response_bytes: usize,
    #[serde(default = "default_max_request_body")]
    pub max_request_body: usize,
    #[serde(default)]
    pub allow_internal: bool,
    #[serde(default)]
    pub blocked_hosts: Vec<String>,
    #[serde(default)]
    pub ok_status_code_range: Option<String>,
    #[serde(default)]
    pub tls: Option<TlsConfig>,
    #[serde(default)]
    pub proxy_url: Option<String>,
}

/// TLS configuration for HTTP/HTTPS client connections.
#[derive(Clone, PartialEq, Deserialize)]
pub struct TlsConfig {
    /// Enables TLS customization for client connections.
    pub enabled: bool,
    /// Verifies peer certificates when true. Defaults to true.
    #[serde(default = "default_verify_peer")]
    pub verify_peer: bool,
    /// Optional path to custom CA certificate bundle (PEM or DER).
    #[serde(default)]
    pub ca_cert_path: Option<String>,
    /// Optional path to client certificate for mTLS (PEM).
    #[serde(default)]
    pub client_cert_path: Option<String>,
    /// Optional path to client private key for mTLS (PEM).
    #[serde(default)]
    pub client_key_path: Option<String>,
    /// If true, skips certificate verification (discouraged).
    #[serde(default)]
    pub insecure: bool,
}

fn default_verify_peer() -> bool {
    true
}

impl Default for TlsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            verify_peer: default_verify_peer(),
            ca_cert_path: None,
            client_cert_path: None,
            client_key_path: None,
            insecure: false,
        }
    }
}

// Manual Debug redacts the mTLS path fields (client key, client cert, CA
// bundle). A derived Debug would expose them and leak credential paths
// (ADR-0051). Mirrors ServerTlsConfig and HttpAuth redaction patterns.
impl std::fmt::Debug for TlsConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TlsConfig")
            .field("enabled", &self.enabled)
            .field("verify_peer", &self.verify_peer)
            .field("ca_cert_path", &"[REDACTED]")
            .field("client_cert_path", &"[REDACTED]")
            .field("client_key_path", &"[REDACTED]")
            .field("insecure", &self.insecure)
            .finish()
    }
}

/// Server-side TLS configuration for HTTP consumer endpoints.
///
/// When present, the HTTP server binds with TLS via `axum_server::from_tcp_rustls`.
/// When absent, the server binds plain HTTP via `axum::serve`.
#[derive(Clone)]
pub struct ServerTlsConfig {
    /// Path to the PEM-encoded server certificate chain.
    pub cert_path: String,
    /// Path to the PEM-encoded server private key.
    pub key_path: String,
}

impl std::fmt::Debug for ServerTlsConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServerTlsConfig")
            .field("cert_path", &"[REDACTED]")
            .field("key_path", &"[REDACTED]")
            .finish()
    }
}

fn default_connect_timeout_ms() -> u64 {
    5_000
}

fn default_pool_max_idle_per_host() -> usize {
    100
}

fn default_pool_idle_timeout_ms() -> u64 {
    90_000
}

fn default_response_timeout_ms() -> u64 {
    30_000
}

fn default_read_timeout_ms() -> u64 {
    30_000
}

fn default_max_body_size() -> usize {
    10_485_760
}

fn default_max_response_bytes() -> usize {
    10_485_760
}

fn default_max_request_body() -> usize {
    2_097_152
}

impl Default for HttpConfig {
    fn default() -> Self {
        Self {
            connect_timeout_ms: default_connect_timeout_ms(),
            pool_max_idle_per_host: default_pool_max_idle_per_host(),
            pool_idle_timeout_ms: default_pool_idle_timeout_ms(),
            follow_redirects: false,
            max_redirects: None,
            response_timeout_ms: default_response_timeout_ms(),
            read_timeout_ms: default_read_timeout_ms(),
            max_body_size: default_max_body_size(),
            max_response_bytes: default_max_response_bytes(),
            max_request_body: default_max_request_body(),
            allow_internal: false,
            blocked_hosts: Vec::new(),
            ok_status_code_range: None,
            tls: None,
            proxy_url: None,
        }
    }
}

impl HttpConfig {
    pub fn validate(&self) -> Result<(), CamelError> {
        if let Some(max_redirects) = self.max_redirects
            && max_redirects > 20
        {
            return Err(CamelError::Config(
                "max_redirects must be <= 20".to_string(),
            ));
        }

        if let Some(range) = &self.ok_status_code_range {
            parse_ok_status_code_range(range)?;
        }

        if self.proxy_url.is_some() {
            return Err(CamelError::Config(
                "proxy_url is incompatible with SSRF DNS pinning and cannot be used".to_string(),
            ));
        }

        Ok(())
    }

    pub fn with_connect_timeout_ms(mut self, ms: u64) -> Self {
        self.connect_timeout_ms = ms;
        self
    }
    pub fn with_pool_max_idle_per_host(mut self, n: usize) -> Self {
        self.pool_max_idle_per_host = n;
        self
    }
    pub fn with_pool_idle_timeout_ms(mut self, ms: u64) -> Self {
        self.pool_idle_timeout_ms = ms;
        self
    }
    pub fn with_follow_redirects(mut self, follow: bool) -> Self {
        self.follow_redirects = follow;
        self
    }
    pub fn with_max_redirects(mut self, max_redirects: Option<usize>) -> Self {
        self.max_redirects = max_redirects;
        self
    }
    pub fn with_response_timeout_ms(mut self, ms: u64) -> Self {
        self.response_timeout_ms = ms;
        self
    }
    pub fn with_read_timeout_ms(mut self, ms: u64) -> Self {
        self.read_timeout_ms = ms;
        self
    }
    pub fn with_max_body_size(mut self, n: usize) -> Self {
        self.max_body_size = n;
        self
    }
    pub fn with_max_response_bytes(mut self, n: usize) -> Self {
        self.max_response_bytes = n;
        self
    }
    pub fn with_max_request_body(mut self, n: usize) -> Self {
        self.max_request_body = n;
        self
    }
    pub fn with_allow_internal(mut self, allow: bool) -> Self {
        self.allow_internal = allow;
        self
    }
    pub fn with_blocked_hosts(mut self, hosts: Vec<String>) -> Self {
        self.blocked_hosts = hosts;
        self
    }
    pub fn with_ok_status_code_range(mut self, range: Option<String>) -> Self {
        self.ok_status_code_range = range;
        self
    }
    pub fn with_tls(mut self, tls: Option<TlsConfig>) -> Self {
        self.tls = tls;
        self
    }
}

pub(crate) fn parse_ok_status_code_range(range: &str) -> Result<(u16, u16), CamelError> {
    let (start_str, end_str) = range.split_once('-').ok_or_else(|| {
        CamelError::Config("ok_status_code_range must be in NNN-NNN format".to_string())
    })?;

    if start_str.len() != 3
        || end_str.len() != 3
        || !start_str.chars().all(|c| c.is_ascii_digit())
        || !end_str.chars().all(|c| c.is_ascii_digit())
    {
        return Err(CamelError::Config(
            "ok_status_code_range must be in NNN-NNN format".to_string(),
        ));
    }

    let start = start_str
        .parse::<u16>()
        .map_err(|_| CamelError::Config("ok_status_code_range start is invalid".to_string()))?;
    let end = end_str
        .parse::<u16>()
        .map_err(|_| CamelError::Config("ok_status_code_range end is invalid".to_string()))?;

    if start > end {
        return Err(CamelError::Config(
            "ok_status_code_range start must be <= end".to_string(),
        ));
    }

    Ok((start, end))
}

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

    #[test]
    fn test_http_config_defaults() {
        let cfg = HttpConfig::default();
        assert_eq!(cfg.connect_timeout_ms, 5_000);
        assert_eq!(cfg.pool_max_idle_per_host, 100);
        assert_eq!(cfg.pool_idle_timeout_ms, 90_000);
        assert!(!cfg.follow_redirects);
        assert_eq!(cfg.max_redirects, None);
        assert_eq!(cfg.response_timeout_ms, 30_000);
        assert_eq!(cfg.max_body_size, 10_485_760);
        assert_eq!(cfg.max_request_body, 2_097_152);
        assert!(!cfg.allow_internal);
        assert!(cfg.blocked_hosts.is_empty());
        assert!(cfg.tls.is_none());
        assert!(cfg.proxy_url.is_none());
    }

    #[test]
    fn test_http_config_builder() {
        let cfg = HttpConfig::default()
            .with_connect_timeout_ms(1_000)
            .with_pool_max_idle_per_host(50)
            .with_follow_redirects(true)
            .with_allow_internal(true)
            .with_blocked_hosts(vec!["evil.com".to_string()]);
        assert_eq!(cfg.connect_timeout_ms, 1_000);
        assert_eq!(cfg.pool_max_idle_per_host, 50);
        assert!(cfg.follow_redirects);
        assert!(cfg.allow_internal);
        assert_eq!(cfg.blocked_hosts, vec!["evil.com".to_string()]);
        assert_eq!(cfg.response_timeout_ms, 30_000);
    }

    #[test]
    fn test_rejects_max_redirects_over_limit() {
        let cfg = HttpConfig {
            max_redirects: Some(21),
            ..HttpConfig::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_accepts_valid_max_redirects() {
        let cfg = HttpConfig {
            max_redirects: Some(10),
            ..HttpConfig::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_rejects_malformed_status_range() {
        let cfg = HttpConfig {
            ok_status_code_range: Some("abc-xyz".into()),
            ..HttpConfig::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_accepts_valid_status_range() {
        let cfg = HttpConfig {
            ok_status_code_range: Some("200-299".into()),
            ..HttpConfig::default()
        };
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_rejects_proxy_url_with_invalid_url() {
        // The SSRF rejection fires regardless of URL well-formedness: a
        // garbage value and a well-formed value both fail the same way.
        let cfg = HttpConfig {
            proxy_url: Some("::not-a-proxy::".into()),
            ..HttpConfig::default()
        };
        let err = cfg.validate().expect_err("proxy_url must be rejected");
        assert!(
            err.to_string()
                .contains("incompatible with SSRF DNS pinning"),
            "expected SSRF rejection message, got: {err}"
        );
    }

    #[test]
    fn test_rejects_proxy_url_with_valid_url() {
        let cfg = HttpConfig {
            proxy_url: Some("http://proxy:8080".into()),
            ..HttpConfig::default()
        };
        let err = cfg
            .validate()
            .expect_err("valid proxy_url must also be rejected");
        assert!(
            err.to_string()
                .contains("incompatible with SSRF DNS pinning"),
            "expected SSRF rejection message, got: {err}"
        );
    }

    #[test]
    fn test_proxy_url_toml_deserialize_then_reject() {
        // The field is retained for serde backward-compat so existing TOML
        // configs still parse; validate() surfaces the SSRF incompatibility
        // instead of letting the value silently slip through.
        let toml_src = r#"
            connect_timeout_ms = 5000
            proxy_url = "http://proxy:8080"
        "#;
        let cfg: HttpConfig = toml::from_str(toml_src).expect("toml must deserialize");
        assert_eq!(cfg.proxy_url.as_deref(), Some("http://proxy:8080"));

        let err = cfg
            .validate()
            .expect_err("validate must reject deserialized proxy_url");
        assert!(
            err.to_string()
                .contains("incompatible with SSRF DNS pinning"),
            "expected SSRF rejection message, got: {err}"
        );
    }

    #[test]
    fn server_tls_config_debug_redacts_paths() {
        let cfg = super::ServerTlsConfig {
            cert_path: "/secret/cert.pem".to_string(),
            key_path: "/secret/key.pem".to_string(),
        };
        let debug = format!("{:?}", cfg);
        assert!(
            !debug.contains("/secret"),
            "paths must be redacted: {debug}"
        );
        assert!(debug.contains("REDACTED"), "must show REDACTED: {debug}");
    }

    #[test]
    fn tls_config_debug_redacts_paths() {
        let cfg = super::TlsConfig {
            enabled: true,
            verify_peer: true,
            ca_cert_path: Some("/secret/ca.pem".to_string()),
            client_cert_path: Some("/secret/cert.pem".to_string()),
            client_key_path: Some("/secret/key.pem".to_string()),
            insecure: false,
        };
        let debug = format!("{:?}", cfg);
        assert!(
            !debug.contains("/secret"),
            "sensitive paths must be redacted: {debug}"
        );
        assert!(debug.contains("REDACTED"), "must show REDACTED: {debug}");
        assert!(
            debug.contains("enabled: true"),
            "non-sensitive fields must stay visible: {debug}"
        );
    }
}