blueprint-remote-providers 0.2.0-alpha.2

Remote service providers for Tangle Blueprints
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
//! Secure bridge for Blueprint Manager <-> Remote Instance communication
//!
//! Provides secure, authenticated tunneling between the local Blueprint auth proxy
//! and remote instances across cloud providers.

use crate::core::error::{Error, Result};
use crate::deployment::tracker::DeploymentRecord;
use blueprint_core::{info, warn};
use blueprint_std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};
use serde::{Deserialize, Serialize};

/// Configuration for secure bridge
#[derive(Debug, Clone)]
pub struct SecureBridgeConfig {
    /// Enable mTLS for production deployments
    pub enable_mtls: bool,
    /// Connection timeout in seconds
    pub connect_timeout_secs: u64,
    /// Idle connection timeout in seconds
    pub idle_timeout_secs: u64,
    /// Maximum concurrent connections per endpoint
    pub max_connections_per_endpoint: usize,
}

impl Default for SecureBridgeConfig {
    fn default() -> Self {
        Self {
            enable_mtls: true,
            connect_timeout_secs: 30,
            idle_timeout_secs: 300,
            max_connections_per_endpoint: 10,
        }
    }
}

/// Remote endpoint configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteEndpoint {
    /// Cloud instance ID
    pub instance_id: String,
    /// Hostname or IP address
    pub host: String,
    /// Port for blueprint service
    pub port: u16,
    /// Use TLS for connection
    pub use_tls: bool,
    /// Service ID for routing
    pub service_id: u64,
    /// Blueprint ID for identification
    pub blueprint_id: u64,
}

/// Secure bridge for remote communication
pub struct SecureBridge {
    config: SecureBridgeConfig,
    endpoints: Arc<RwLock<HashMap<u64, RemoteEndpoint>>>,
    client: reqwest::Client,
}

impl SecureBridge {
    /// Validate certificate format and basic security properties
    fn validate_certificate_format(cert_data: &[u8], cert_type: &str) -> Result<()> {
        let cert_str = String::from_utf8(cert_data.to_vec())
            .map_err(|_| Error::ConfigurationError(format!("{cert_type} must be valid UTF-8")))?;

        // Basic PEM format validation
        if !cert_str.contains("-----BEGIN") || !cert_str.contains("-----END") {
            return Err(Error::ConfigurationError(format!(
                "{cert_type} must be in PEM format"
            )));
        }

        // Validate certificate is not obviously invalid
        if cert_data.len() < 100 {
            return Err(Error::ConfigurationError(format!(
                "{cert_type} appears to be too short to be valid"
            )));
        }

        // Check for common certificate types
        let valid_headers = [
            "-----BEGIN CERTIFICATE-----",
            "-----BEGIN PRIVATE KEY-----",
            "-----BEGIN RSA PRIVATE KEY-----",
            "-----BEGIN EC PRIVATE KEY-----",
        ];

        if !valid_headers.iter().any(|header| cert_str.contains(header)) {
            return Err(Error::ConfigurationError(format!(
                "{cert_type} does not contain recognized PEM headers"
            )));
        }

        // Certificate validation capabilities available for production use

        Ok(())
    }

    /// Create new secure bridge
    pub async fn new(config: SecureBridgeConfig) -> Result<Self> {
        let mut client_builder = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(config.connect_timeout_secs))
            .tcp_keepalive(std::time::Duration::from_secs(60));

        // Configure TLS settings with production-grade certificate validation
        if config.enable_mtls {
            // Production mTLS certificate configuration
            info!("mTLS enabled for secure bridge - strict certificate validation");

            // Load client certificate and private key for mTLS
            let cert_path = std::env::var("BLUEPRINT_CLIENT_CERT_PATH")
                .unwrap_or_else(|_| "/etc/blueprint/certs/client.crt".to_string());
            let key_path = std::env::var("BLUEPRINT_CLIENT_KEY_PATH")
                .unwrap_or_else(|_| "/etc/blueprint/certs/client.key".to_string());
            let ca_path = std::env::var("BLUEPRINT_CA_CERT_PATH")
                .unwrap_or_else(|_| "/etc/blueprint/certs/ca.crt".to_string());

            // PRODUCTION SECURITY: Enforce certificate presence in production
            let is_production = std::env::var("BLUEPRINT_ENV")
                .unwrap_or_else(|_| "development".to_string())
                == "production";

            if is_production
                && (!std::path::Path::new(&cert_path).exists()
                    || !std::path::Path::new(&key_path).exists()
                    || !std::path::Path::new(&ca_path).exists())
            {
                return Err(Error::ConfigurationError(
                    "Production deployment requires mTLS certificates at configured paths".into(),
                ));
            }

            if std::path::Path::new(&cert_path).exists()
                && std::path::Path::new(&key_path).exists()
                && std::path::Path::new(&ca_path).exists()
            {
                // Read certificate files
                let client_cert = std::fs::read(&cert_path).map_err(|e| {
                    Error::ConfigurationError(format!("Failed to read client cert: {e}"))
                })?;
                let client_key = std::fs::read(&key_path).map_err(|e| {
                    Error::ConfigurationError(format!("Failed to read client key: {e}"))
                })?;
                let ca_cert = std::fs::read(&ca_path).map_err(|e| {
                    Error::ConfigurationError(format!("Failed to read CA cert: {e}"))
                })?;

                // Validate certificate formats before use
                Self::validate_certificate_format(&client_cert, "client certificate")?;
                Self::validate_certificate_format(&client_key, "client private key")?;
                Self::validate_certificate_format(&ca_cert, "CA certificate")?;

                // Create identity by combining cert and key into single PEM buffer
                let mut combined_pem = Vec::new();
                combined_pem.extend_from_slice(&client_cert);
                combined_pem.extend_from_slice(b"\n");
                combined_pem.extend_from_slice(&client_key);

                let identity = reqwest::Identity::from_pem(&combined_pem).map_err(|e| {
                    Error::ConfigurationError(format!("Failed to create identity: {e}"))
                })?;
                let ca_cert = reqwest::Certificate::from_pem(&ca_cert).map_err(|e| {
                    Error::ConfigurationError(format!("Failed to parse CA cert: {e}"))
                })?;

                client_builder = client_builder
                    .identity(identity)
                    .add_root_certificate(ca_cert)
                    .use_rustls_tls()
                    .tls_built_in_root_certs(false); // Only trust our CA

                info!("mTLS certificates loaded and validated successfully");
            } else if is_production {
                return Err(Error::ConfigurationError(
                    "mTLS certificates required for production deployment".into(),
                ));
            } else {
                warn!("mTLS certificates not found - using system certs for development");
                client_builder = client_builder.use_rustls_tls();
            }
        } else {
            let is_production = std::env::var("BLUEPRINT_ENV")
                .unwrap_or_else(|_| "development".to_string())
                == "production";

            if is_production {
                return Err(Error::ConfigurationError(
                    "mTLS cannot be disabled in production environment".into(),
                ));
            }

            client_builder = client_builder.danger_accept_invalid_certs(true);
            warn!("mTLS disabled - DEVELOPMENT ONLY");
        }

        let client = client_builder
            .build()
            .map_err(|e| Error::ConfigurationError(format!("Failed to create HTTP client: {e}")))?;

        Ok(Self {
            config,
            endpoints: Arc::new(RwLock::new(HashMap::new())),
            client,
        })
    }

    /// Validate endpoint for security - prevent SSRF attacks
    fn validate_endpoint_security(endpoint: &RemoteEndpoint) -> Result<()> {
        // SECURITY: Only allow localhost and private IP ranges for remote instances
        let host = &endpoint.host;

        // Parse IP address
        if let Ok(ip) = host.parse::<std::net::IpAddr>() {
            match ip {
                std::net::IpAddr::V4(ipv4) => {
                    if !ipv4.is_loopback() && !ipv4.is_private() {
                        return Err(Error::ConfigurationError(
                            "Remote endpoints must use localhost or private IP ranges only".into(),
                        ));
                    }
                }
                std::net::IpAddr::V6(ipv6) => {
                    if !ipv6.is_loopback() {
                        return Err(Error::ConfigurationError(
                            "Remote endpoints must use localhost for IPv6".into(),
                        ));
                    }
                }
            }
        } else {
            // If it's a hostname, only allow localhost variants
            if !host.starts_with("localhost") && host != "127.0.0.1" && host != "::1" {
                return Err(Error::ConfigurationError(
                    "Remote endpoints must use localhost hostname only".into(),
                ));
            }
        }

        // Validate port range (u16 max is 65535, so only check minimum)
        if endpoint.port < 1024 {
            return Err(Error::ConfigurationError("Port must be >= 1024".into()));
        }

        Ok(())
    }

    /// Register a remote endpoint with security validation
    pub async fn register_endpoint(&self, service_id: u64, endpoint: RemoteEndpoint) -> Result<()> {
        // SECURITY: Validate endpoint before registration
        Self::validate_endpoint_security(&endpoint)?;

        if let Ok(mut endpoints) = self.endpoints.write() {
            endpoints.insert(service_id, endpoint.clone());
            info!(
                "Registered secure remote endpoint for service {}: {}:{}",
                service_id, endpoint.host, endpoint.port
            );
            Ok(())
        } else {
            Err(Error::ConfigurationError(
                "Failed to acquire endpoint lock".into(),
            ))
        }
    }

    /// Remove an endpoint
    pub async fn remove_endpoint(&self, service_id: u64) {
        if let Ok(mut endpoints) = self.endpoints.write() {
            if endpoints.remove(&service_id).is_some() {
                info!("Removed remote endpoint for service {}", service_id);
            }
        }
    }

    /// Health check for remote endpoint
    pub async fn health_check(&self, service_id: u64) -> Result<bool> {
        let url = {
            let endpoints = self
                .endpoints
                .read()
                .map_err(|_| Error::ConfigurationError("Lock poisoned".to_string()))?;
            let endpoint = endpoints.get(&service_id).ok_or_else(|| {
                Error::ConfigurationError(format!("No endpoint for service {service_id}"))
            })?;

            format!(
                "{}://{}:{}/health",
                if endpoint.use_tls { "https" } else { "http" },
                endpoint.host,
                endpoint.port
            )
        }; // Lock is dropped here

        // Apply config-based timeout for health checks
        let health_request = self
            .client
            .get(&url)
            .timeout(std::time::Duration::from_secs(
                self.config.connect_timeout_secs,
            ));

        match health_request.send().await {
            Ok(response) => Ok(response.status().is_success()),
            Err(_) => {
                // SECURITY: Don't log detailed error information to prevent information disclosure
                warn!("Health check failed for service {}", service_id);
                Ok(false)
            }
        }
    }

    /// Forward authenticated request to remote endpoint
    pub async fn forward_request(
        &self,
        service_id: u64,
        method: &str,
        path: &str,
        headers: HashMap<String, String>,
        body: Vec<u8>,
    ) -> Result<(u16, HashMap<String, String>, Vec<u8>)> {
        let url = {
            let endpoints = self
                .endpoints
                .read()
                .map_err(|_| Error::ConfigurationError("Lock poisoned".to_string()))?;
            let endpoint = endpoints.get(&service_id).ok_or_else(|| {
                Error::ConfigurationError(format!("No endpoint for service {service_id}"))
            })?;

            format!(
                "{}://{}:{}{}",
                if endpoint.use_tls { "https" } else { "http" },
                endpoint.host,
                endpoint.port,
                path
            )
        }; // Lock is dropped here

        let mut request = match method.to_uppercase().as_str() {
            "GET" => self.client.get(&url),
            "POST" => self.client.post(&url),
            "PUT" => self.client.put(&url),
            "DELETE" => self.client.delete(&url),
            "PATCH" => self.client.patch(&url),
            _ => {
                return Err(Error::ConfigurationError(format!(
                    "Unsupported method: {method}"
                )));
            }
        };

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

        // Add body if provided
        if !body.is_empty() {
            request = request.body(body);
        }

        // Apply config-based timeout for requests
        let response = request
            .timeout(std::time::Duration::from_secs(
                self.config.connect_timeout_secs,
            ))
            .send()
            .await
            .map_err(|e| Error::ConfigurationError(format!("Request failed: {e}")))?;

        // Extract response
        let status = response.status().as_u16();
        let response_headers: HashMap<String, String> = response
            .headers()
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
            .collect();

        let response_body = response
            .bytes()
            .await
            .map_err(|e| Error::ConfigurationError(format!("Failed to read response: {e}")))?
            .to_vec();

        Ok((status, response_headers, response_body))
    }

    /// Update bridge from deployment record
    pub async fn update_from_deployment(&self, record: &DeploymentRecord) {
        if let Some(instance_id) = record.resource_ids.get("instance_id") {
            if let Some(public_ip) = record.resource_ids.get("public_ip") {
                let service_id = record.blueprint_id.parse::<u64>().unwrap_or(0);

                let endpoint = RemoteEndpoint {
                    instance_id: instance_id.clone(),
                    host: public_ip.clone(),
                    port: 8080, // Default blueprint service port
                    use_tls: true,
                    service_id,
                    blueprint_id: service_id,
                };

                let _ = self.register_endpoint(service_id, endpoint).await;
            }
        }
    }

    /// Get endpoint information for service
    pub async fn get_endpoint(&self, service_id: u64) -> Option<RemoteEndpoint> {
        let endpoints = self.endpoints.read().ok()?;
        endpoints.get(&service_id).cloned()
    }

    /// List all registered endpoints
    pub async fn list_endpoints(&self) -> Vec<(u64, RemoteEndpoint)> {
        match self.endpoints.read() {
            Ok(endpoints) => endpoints.iter().map(|(id, ep)| (*id, ep.clone())).collect(),
            Err(_) => vec![],
        }
    }

    /// Get bridge configuration (for monitoring/debugging)
    pub fn get_config(&self) -> &SecureBridgeConfig {
        &self.config
    }

    /// Check if endpoint registration is within connection limits
    pub async fn can_register_endpoint(&self, _service_id: u64) -> bool {
        // Check current endpoint count against config limits
        match self.endpoints.read() {
            Ok(endpoints) => endpoints.len() < self.config.max_connections_per_endpoint * 100, // Scale by factor for total limit
            Err(_) => false,
        }
    }
}

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

    #[tokio::test]
    async fn test_bridge_creation() {
        let config = SecureBridgeConfig {
            enable_mtls: false,
            ..Default::default()
        };

        let bridge = SecureBridge::new(config).await.unwrap();
        assert!(bridge.list_endpoints().await.is_empty());
    }

    #[tokio::test]
    async fn test_endpoint_management() {
        let config = SecureBridgeConfig {
            enable_mtls: false,
            ..Default::default()
        };

        let bridge = SecureBridge::new(config).await.unwrap();

        let endpoint = RemoteEndpoint {
            instance_id: "i-test123".to_string(),
            host: "localhost".to_string(),
            port: 8080,
            use_tls: true,
            service_id: 1,
            blueprint_id: 100,
        };

        // Register endpoint
        bridge.register_endpoint(1, endpoint.clone()).await.unwrap();
        assert_eq!(bridge.list_endpoints().await.len(), 1);

        // Get endpoint
        let retrieved = bridge.get_endpoint(1).await.unwrap();
        assert_eq!(retrieved.instance_id, "i-test123");

        // Remove endpoint
        bridge.remove_endpoint(1).await;
        assert!(bridge.list_endpoints().await.is_empty());
    }
}