camel-component-api 0.54.0

Component API trait and registry 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
//! Shared [`ServerTlsSource`] — builds a validated [`rustls::ServerConfig`] from
//! PEM cert/key files, optionally with mTLS client CA verification.
//!
//! This deduplicates ~40 lines of PEM parsing that each of gRPC, HTTP, and WS
//! components implement separately. The individual components still own ALPN
//! configuration — `build_server_config` intentionally leaves ALPN empty so the
//! caller can set it after construction.

use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use camel_api::CamelError;
use rustls::ServerConfig;

/// File-based TLS source for rustls server-side configuration.
///
/// Reads PEM-encoded cert+key from the filesystem. When `client_ca_path` is
/// set, the server requires (and verifies) a client certificate (mTLS).
#[derive(Debug, Clone)]
pub struct ServerTlsSource {
    /// Path to the PEM-encoded server certificate chain.
    pub cert_path: PathBuf,
    /// Path to the PEM-encoded private key for the server certificate.
    pub key_path: PathBuf,
    /// Optional path to a PEM-encoded CA certificate for client verification.
    /// When set, mTLS is enabled (clients must present a cert signed by this CA).
    pub client_ca_path: Option<PathBuf>,
}

impl ServerTlsSource {
    /// Build a [`rustls::ServerConfig`] from the PEM files.
    ///
    /// Returns `EndpointCreationFailed` on any I/O, PEM parse, or rustls
    /// configuration error.
    ///
    /// ALPN protocols are intentionally NOT set — callers add their own
    /// (e.g., `b"h2"` for gRPC) after construction.
    pub fn build_server_config(&self) -> Result<ServerConfig, CamelError> {
        // Read cert and key files as raw bytes.
        let cert_pem = std::fs::read(&self.cert_path).map_err(|e| {
            CamelError::EndpointCreationFailed(format!(
                "TLS cert file '{}': {e}",
                self.cert_path.display()
            ))
        })?;
        let key_pem = std::fs::read(&self.key_path).map_err(|e| {
            CamelError::EndpointCreationFailed(format!(
                "TLS key file '{}': {e}",
                self.key_path.display()
            ))
        })?;

        // Parse PEM certs.
        let certs: Vec<_> = rustls_pemfile::certs(&mut cert_pem.as_slice())
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| {
                CamelError::EndpointCreationFailed(format!("TLS cert parse error: {e}"))
            })?;

        // Parse PEM private key.
        let key = rustls_pemfile::private_key(&mut key_pem.as_slice())
            .map_err(|e| CamelError::EndpointCreationFailed(format!("TLS key parse error: {e}")))?
            .ok_or_else(|| {
                CamelError::EndpointCreationFailed("TLS: no private key found in key PEM".into())
            })?;

        // Explicit ring provider — rustls 0.23 requires this (the default
        // `ServerConfig::builder()` panics at runtime without a process-default).
        let provider = Arc::new(rustls::crypto::ring::default_provider());

        // Build the protocol-version-safe builder.
        let builder = rustls::ServerConfig::builder_with_provider(Arc::clone(&provider))
            .with_safe_default_protocol_versions()
            .map_err(|e| {
                CamelError::EndpointCreationFailed(format!("rustls protocol versions: {e}"))
            })?;

        // Branch: mTLS (client cert verification) or plain server auth.
        let config = match &self.client_ca_path {
            Some(ca_path) => {
                let ca_pem = std::fs::read(ca_path).map_err(|e| {
                    CamelError::EndpointCreationFailed(format!(
                        "TLS client CA file '{}': {e}",
                        ca_path.display()
                    ))
                })?;
                let ca_certs: Vec<_> = rustls_pemfile::certs(&mut ca_pem.as_slice())
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| {
                        CamelError::EndpointCreationFailed(format!("invalid client CA PEM: {e}"))
                    })?;
                let mut roots = rustls::RootCertStore::empty();
                for cert in ca_certs {
                    roots.add(cert).map_err(|e| {
                        CamelError::EndpointCreationFailed(format!("client CA root add: {e}"))
                    })?;
                }
                let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(
                    Arc::new(roots),
                    Arc::clone(&provider),
                )
                .build()
                .map_err(|e| {
                    CamelError::EndpointCreationFailed(format!("mTLS client cert verifier: {e}"))
                })?;
                builder
                    .with_client_cert_verifier(verifier)
                    .with_single_cert(certs, key)
                    .map_err(|e| {
                        CamelError::EndpointCreationFailed(format!("rustls ServerConfig: {e}"))
                    })?
            }
            None => builder
                .with_no_client_auth()
                .with_single_cert(certs, key)
                .map_err(|e| {
                    CamelError::EndpointCreationFailed(format!("rustls ServerConfig: {e}"))
                })?,
        };

        Ok(config)
    }
}

// ---------------------------------------------------------------------------
// TlsReloadHandler + TlsReloadRegistry
// ---------------------------------------------------------------------------

/// Implemented by each TLS-terminating component.
/// Registered with [`TlsReloadRegistry::global()`] when a server first spawns.
#[async_trait]
pub trait TlsReloadHandler: Send + Sync {
    /// Returns true if this handler owns the (scheme, host, port).
    fn matches(&self, scheme: &str, host: &str, port: u16) -> bool;
    /// Re-read cert files and swap. Returns Err if cert invalid; old cert stays.
    async fn reload(&self) -> Result<(), CamelError>;
}

/// Process-global singleton registry of TLS reload handlers.
///
/// The global is reachable through two handles that wrap the same
/// allocation: [`TlsReloadRegistry::global()`] returns a `&'static`
/// reference and [`TlsReloadRegistry::global_arc()`] returns an
/// [`Arc`] clone — a registration made through either handle is
/// observable through the other. Isolated instances for tests come
/// from [`Default`], which never touches the process global.
///
/// Each TLS-terminating component registers its handler when it first
/// spawns, and unregisters on release/eviction.
#[derive(Default)]
pub struct TlsReloadRegistry {
    handlers: Mutex<Vec<Arc<dyn TlsReloadHandler>>>,
}

impl TlsReloadRegistry {
    /// Returns a reference to the process-global singleton.
    pub fn global() -> &'static TlsReloadRegistry {
        Self::backing().as_ref()
    }

    /// Returns an [`Arc`] handle to the process-global singleton.
    ///
    /// The `Arc` wraps the same allocation as [`global`](Self::global).
    pub fn global_arc() -> Arc<TlsReloadRegistry> {
        Self::backing().clone()
    }

    /// Single backing allocation behind both [`global`](Self::global)
    /// and [`global_arc`](Self::global_arc). The `&'static Arc` derefs
    /// to a `&'static TlsReloadRegistry`, so `global()`'s signature
    /// and instance identity are unchanged for all callers.
    fn backing() -> &'static Arc<TlsReloadRegistry> {
        static BACKING: std::sync::OnceLock<Arc<TlsReloadRegistry>> = std::sync::OnceLock::new();
        BACKING.get_or_init(|| Arc::new(TlsReloadRegistry::default()))
    }

    /// Register a handler so it can be found later via [`find`](Self::find).
    pub fn register(&self, handler: Arc<dyn TlsReloadHandler>) {
        let mut guard = self
            .handlers
            .lock()
            .expect("TlsReloadRegistry lock poisoned"); // allow-unwrap
        guard.push(handler);
    }

    /// Find the handler that matches (scheme, host, port), if any.
    pub fn find(&self, scheme: &str, host: &str, port: u16) -> Option<Arc<dyn TlsReloadHandler>> {
        let guard = self
            .handlers
            .lock()
            .expect("TlsReloadRegistry lock poisoned"); // allow-unwrap
        guard
            .iter()
            .find(|h| h.matches(scheme, host, port))
            .cloned()
    }

    /// Remove handlers matching (scheme, host, port). Called on server release/eviction.
    pub fn unregister(&self, scheme: &str, host: &str, port: u16) {
        let mut guard = self
            .handlers
            .lock()
            .expect("TlsReloadRegistry lock poisoned"); // allow-unwrap
        guard.retain(|h| !h.matches(scheme, host, port));
    }
}

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

    /// Helper: write a PEM string to a temp file and return the path.
    fn write_pem(pem: &str, name: &str) -> PathBuf {
        crate::test_support::tls::write_pem_tmp(name, pem)
    }

    #[test]
    fn build_server_config_valid_cert() {
        let (ca_pem, cert_pem, key_pem) = crate::test_support::tls::gen_server_cert();
        let _ca = write_pem(&ca_pem, "ca.pem");
        let cert = write_pem(&cert_pem, "cert.pem");
        let key = write_pem(&key_pem, "key.pem");

        let source = ServerTlsSource {
            cert_path: cert,
            key_path: key,
            client_ca_path: None,
        };

        let config = source.build_server_config().expect("valid cert+key");
        assert!(config.alpn_protocols.is_empty(), "ALPN should be empty");
    }

    #[test]
    fn build_server_config_mtls() {
        let (ca_pem, cert_pem, key_pem) = crate::test_support::tls::gen_server_cert();
        let ca = write_pem(&ca_pem, "mtls-ca.pem");
        let cert = write_pem(&cert_pem, "cert.pem");
        let key = write_pem(&key_pem, "key.pem");

        let source = ServerTlsSource {
            cert_path: cert,
            key_path: key,
            client_ca_path: Some(ca),
        };

        let config = source.build_server_config().expect("mTLS should work");
        assert!(config.alpn_protocols.is_empty());
        // mTLS is enabled — verifier should require client cert.
        // We can't easily assert the verifier type, but we can verify
        // the config uses a client-cert verifier by checking it was
        // built without errors.
    }

    #[test]
    fn build_server_config_mtls_bad_ca_rejected() {
        let (_, cert_pem, key_pem) = crate::test_support::tls::gen_server_cert();
        let cert = write_pem(&cert_pem, "cert.pem");
        let key = write_pem(&key_pem, "key.pem");

        // Write garbage as the CA PEM.
        let bad_ca = write_pem("not-a-valid-ca-certificate\n", "bad-ca.pem");

        let source = ServerTlsSource {
            cert_path: cert,
            key_path: key,
            client_ca_path: Some(bad_ca),
        };

        let err = source.build_server_config().unwrap_err();
        assert!(
            matches!(&err, CamelError::EndpointCreationFailed(_)),
            "expected EndpointCreationFailed, got {err:?}"
        );
    }

    #[test]
    fn build_server_config_missing_file() {
        let source = ServerTlsSource {
            cert_path: PathBuf::from("/nonexistent/cert.pem"),
            key_path: PathBuf::from("/nonexistent/key.pem"),
            client_ca_path: None,
        };

        let err = source.build_server_config().unwrap_err();
        assert!(
            matches!(&err, CamelError::EndpointCreationFailed(_)),
            "expected EndpointCreationFailed, got {err:?}"
        );
    }

    #[test]
    fn build_server_config_malformed_pem() {
        let cert = write_pem("garbage-content\n", "bad-cert.pem");
        let key = write_pem("also-garbage\n", "bad-key.pem");

        let source = ServerTlsSource {
            cert_path: cert,
            key_path: key,
            client_ca_path: None,
        };

        let err = source.build_server_config().unwrap_err();
        assert!(
            matches!(&err, CamelError::EndpointCreationFailed(_)),
            "expected EndpointCreationFailed, got {err:?}"
        );
    }
}

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

    struct FakeHandler {
        scheme: String,
        host: String,
        port: u16,
    }

    #[async_trait::async_trait]
    impl TlsReloadHandler for FakeHandler {
        fn matches(&self, scheme: &str, host: &str, port: u16) -> bool {
            self.scheme == scheme && self.host == host && self.port == port
        }
        async fn reload(&self) -> Result<(), CamelError> {
            Ok(())
        }
    }

    #[test]
    fn registry_find_returns_matching_handler() {
        let reg = TlsReloadRegistry::default();
        reg.register(Arc::new(FakeHandler {
            scheme: "grpcs".into(),
            host: "0.0.0.0".into(),
            port: 9090,
        }));
        assert!(reg.find("grpcs", "0.0.0.0", 9090).is_some());
        assert!(reg.find("https", "0.0.0.0", 9090).is_none());
    }

    #[test]
    fn registry_find_returns_none_when_empty() {
        let reg = TlsReloadRegistry::default();
        assert!(reg.find("grpcs", "0.0.0.0", 9090).is_none());
    }

    #[test]
    fn registry_unregister_removes_handler() {
        let reg = TlsReloadRegistry::default();
        reg.register(Arc::new(FakeHandler {
            scheme: "grpcs".into(),
            host: "0.0.0.0".into(),
            port: 9090,
        }));
        assert!(reg.find("grpcs", "0.0.0.0", 9090).is_some());
        reg.unregister("grpcs", "0.0.0.0", 9090);
        assert!(reg.find("grpcs", "0.0.0.0", 9090).is_none());
    }

    #[test]
    fn global_and_global_arc_share_instance() {
        const SCHEME: &str = "tlsseam-shared";
        const HOST: &str = "shared.invalid";
        const PORT: u16 = 64401;

        let arc = TlsReloadRegistry::global_arc();
        assert!(std::ptr::eq(TlsReloadRegistry::global(), arc.as_ref()));

        arc.register(Arc::new(FakeHandler {
            scheme: SCHEME.into(),
            host: HOST.into(),
            port: PORT,
        }));
        assert!(
            TlsReloadRegistry::global()
                .find(SCHEME, HOST, PORT)
                .is_some(),
            "registration via global_arc must be visible through global()"
        );
        TlsReloadRegistry::global().unregister(SCHEME, HOST, PORT);
        assert!(
            TlsReloadRegistry::global()
                .find(SCHEME, HOST, PORT)
                .is_none(),
            "cleanup must leave no residue for sibling tests"
        );
    }

    #[test]
    fn default_instance_is_isolated_from_global() {
        const SCHEME: &str = "tlsseam-isolated";
        const HOST: &str = "isolated.invalid";
        const PORT: u16 = 64402;

        let global = TlsReloadRegistry::global();
        global.register(Arc::new(FakeHandler {
            scheme: SCHEME.into(),
            host: HOST.into(),
            port: PORT,
        }));
        let fresh = TlsReloadRegistry::default();
        assert!(
            fresh.find(SCHEME, HOST, PORT).is_none(),
            "Default instance must not see global registrations"
        );
        // Cleanup so sibling tests see no residue.
        global.unregister(SCHEME, HOST, PORT);
        assert!(global.find(SCHEME, HOST, PORT).is_none());
    }
}