harborshield 0.1.0

A Rust port of Whalewall, to automate management of firewall rules for Docker containers
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
pub mod compose;
pub mod config;
pub mod container;
pub mod error;
pub mod network;

use crate::docker::container::{Container, Tracker};
use crate::docker::network::NetworkGatewayInfo;
use crate::{Error, Result};
use bollard::ClientVersion;
use bollard::{Docker, models::EventMessage};
use bon::bon;
use futures::stream::StreamExt;
use std::collections::HashMap;
use std::env;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::timeout;
use tracing::debug;

#[cfg(test)]
mod tests;

#[derive(Debug, Clone)]
enum ConnectionInfo {
    Socket(String),
    Http(String),
    Ssl {
        url: String,
        cert_path: String,
        verify: bool,
    },
    Default,
}

pub struct DockerClient {
    client: Docker,
    timeout_duration: Duration,
    api_version: Option<String>,
    connection_info: ConnectionInfo,
    pub network_gateway_cache: Arc<Mutex<HashMap<String, NetworkGatewayInfo>>>,
    pub container_tracker: Arc<Tracker>,
}

#[bon]
impl DockerClient {
    #[builder]
    pub fn new(
        #[builder(default = Duration::from_secs(30))] timeout_duration: Duration,
    ) -> Result<Self> {
        // Check for API version override first
        let api_version_override = env::var("DOCKER_API_VERSION").ok();

        // Check DOCKER_HOST environment variable
        let (client, connection_info) = if let Ok(docker_host) = env::var("DOCKER_HOST") {
            // Check if TLS is required
            let tls_verify = env::var("DOCKER_TLS_VERIFY")
                .unwrap_or_default()
                .eq_ignore_ascii_case("1")
                || env::var("DOCKER_TLS_VERIFY")
                    .unwrap_or_default()
                    .eq_ignore_ascii_case("true");

            if docker_host.starts_with("unix://") || docker_host.starts_with("/") {
                // Unix socket connection
                let client =
                    Docker::connect_with_socket(&docker_host, 120, bollard::API_DEFAULT_VERSION)
                        .map_err(|e| Error::Docker(e))?;
                (client, ConnectionInfo::Socket(docker_host))
            } else if tls_verify || docker_host.starts_with("tcp://") {
                // TCP connection - check if TLS is needed
                let cert_path = env::var("DOCKER_CERT_PATH").unwrap_or_else(|_| {
                    // Default to ~/.docker if not specified
                    let home = env::var("HOME").unwrap_or_else(|_| "/root".to_string());
                    format!("{}/.docker", home)
                });

                // Check if cert files exist - if they do, use TLS
                let cert_path_obj = Path::new(&cert_path);
                let has_certs = cert_path_obj.join("ca.pem").exists()
                    && cert_path_obj.join("cert.pem").exists()
                    && cert_path_obj.join("key.pem").exists();

                if tls_verify || has_certs {
                    let client = Self::connect_with_tls(&docker_host, &cert_path, tls_verify)?;
                    (
                        client,
                        ConnectionInfo::Ssl {
                            url: docker_host,
                            cert_path,
                            verify: tls_verify,
                        },
                    )
                } else {
                    // TCP without TLS
                    let url = if docker_host.starts_with("http://") {
                        docker_host.to_string()
                    } else {
                        docker_host.replace("tcp://", "http://")
                    };
                    let client = Docker::connect_with_http(&url, 120, bollard::API_DEFAULT_VERSION)
                        .map_err(|e| Error::Docker(e))?;
                    (client, ConnectionInfo::Http(url))
                }
            } else {
                // HTTP connection
                let client =
                    Docker::connect_with_http(&docker_host, 120, bollard::API_DEFAULT_VERSION)
                        .map_err(|e| Error::Docker(e))?;
                (client, ConnectionInfo::Http(docker_host))
            }
        } else {
            // Default connection
            let client = Docker::connect_with_socket_defaults().map_err(|e| Error::Docker(e))?;
            (client, ConnectionInfo::Default)
        };

        // Handle API version
        if let Some(version) = api_version_override {
            Self::create_with_specific_version_sync(connection_info, &version, timeout_duration)
        } else {
            // Return client without negotiation - it will be done lazily or explicitly
            Ok(Self {
                client,
                timeout_duration,
                api_version: None,
                connection_info,
                network_gateway_cache: Arc::new(Mutex::new(HashMap::new())),
                container_tracker: Arc::new(Tracker::builder().build()),
            })
        }
    }

    fn recreate_client(connection_info: &ConnectionInfo) -> Result<Docker> {
        match connection_info {
            ConnectionInfo::Socket(socket_path) => {
                Docker::connect_with_socket(socket_path, 120, bollard::API_DEFAULT_VERSION)
                    .map_err(|e| Error::Docker(e))
            }
            ConnectionInfo::Http(url) => {
                Docker::connect_with_http(url, 120, bollard::API_DEFAULT_VERSION)
                    .map_err(|e| Error::Docker(e))
            }
            ConnectionInfo::Ssl {
                url,
                cert_path,
                verify,
            } => Self::connect_with_tls(url, cert_path, *verify),
            ConnectionInfo::Default => {
                Docker::connect_with_socket_defaults().map_err(|e| Error::Docker(e))
            }
        }
    }

    fn create_with_specific_version_sync(
        connection_info: ConnectionInfo,
        version: &str,
        timeout_duration: Duration,
    ) -> Result<Self> {
        tracing::info!("Using DOCKER_API_VERSION: {}", version);

        // Normalize version format (handle both "1.41" and "v1.41")
        let normalized_version = if version.starts_with('v') {
            version.to_string()
        } else {
            format!("v{}", version)
        };

        // Since bollard uses compile-time API version, we can't dynamically change it
        // But we can validate and warn about compatibility
        let bollard_version = Self::get_bollard_version();
        let parse_version =
            |v: &str| -> Option<f32> { v.trim_start_matches('v').parse::<f32>().ok() };

        if let (Some(requested_v), Some(bollard_v)) = (
            parse_version(&normalized_version),
            parse_version(&bollard_version.to_string()),
        ) {
            if (requested_v - bollard_v).abs() > 0.1 {
                tracing::warn!(
                    "DOCKER_API_VERSION {} differs significantly from bollard's compile-time version {}. \
                    This may cause compatibility issues.",
                    normalized_version,
                    bollard_version
                );
            }
        }

        // Create client with default version (can't change compile-time constant)
        let client = Self::recreate_client(&connection_info)?;

        // Store the requested version for reference
        Ok(Self {
            client,
            timeout_duration,
            api_version: Some(normalized_version),
            connection_info,
            network_gateway_cache: Arc::new(Mutex::new(HashMap::new())),
            container_tracker: Arc::new(Tracker::builder().build()),
        })
    }

    pub fn api_version(&self) -> Option<&str> {
        self.api_version.as_deref()
    }

    /// Explicitly negotiate API version with the Docker daemon
    /// This consumes self and returns a new instance with negotiated version
    pub async fn negotiate_version(self) -> Result<Self> {
        let timeout_duration = self.timeout_duration;
        let connection_info = self.connection_info.clone();

        match timeout(timeout_duration, self.client.negotiate_version()).await {
            Ok(Ok(negotiated_client)) => {
                tracing::info!("Successfully negotiated Docker API version");
                Ok(Self {
                    client: negotiated_client,
                    timeout_duration,
                    api_version: None, // Version is handled internally by bollard
                    connection_info,
                    network_gateway_cache: Arc::new(Mutex::new(HashMap::new())),
                    container_tracker: Arc::new(Tracker::builder().build()),
                })
            }
            Ok(Err(e)) => {
                tracing::warn!(
                    "Failed to negotiate Docker API version: {}. Using default version.",
                    e
                );
                // Recreate the client since negotiate_version consumed it
                let client = Self::recreate_client(&connection_info)?;
                Ok(Self {
                    client,
                    timeout_duration,
                    api_version: None,
                    connection_info,
                    network_gateway_cache: Arc::new(Mutex::new(HashMap::new())),
                    container_tracker: Arc::new(Tracker::builder().build()),
                })
            }
            Err(_) => {
                tracing::warn!("Docker API version negotiation timed out. Using default version.");
                // Recreate the client since negotiate_version consumed it
                let client = Self::recreate_client(&connection_info)?;
                Ok(Self {
                    client,
                    timeout_duration,
                    api_version: None,
                    connection_info,
                    network_gateway_cache: Arc::new(Mutex::new(HashMap::new())),
                    container_tracker: Arc::new(Tracker::builder().build()),
                })
            }
        }
    }

    /// Get the bollard library's compile-time API version
    fn get_bollard_version() -> &'static ClientVersion {
        bollard::API_DEFAULT_VERSION
    }

    /// Check if a feature is supported by the current API version
    pub fn is_feature_supported(&self, feature: &str, min_version: &str) -> Result<()> {
        if let Some(_api_version) = &self.api_version {
            let parse_version =
                |v: &str| -> Option<f32> { v.trim_start_matches('v').parse::<f32>().ok() };

            if let (Some(current_v), Some(min_v)) =
                (parse_version(_api_version), parse_version(min_version))
            {
                if current_v < min_v {
                    return Err(Error::config(format!(
                        "Unsupported Docker feature: {} (minimum version: {})",
                        feature, min_version
                    )));
                }
            }
        }
        Ok(())
    }

    fn connect_with_tls(docker_host: &str, cert_path: &str, _verify: bool) -> Result<Docker> {
        let cert_path = Path::new(cert_path);

        // Check if certificate files exist
        let ca_path = cert_path.join("ca.pem");
        let cert_file_path = cert_path.join("cert.pem");
        let key_path = cert_path.join("key.pem");

        if !ca_path.exists() || !cert_file_path.exists() || !key_path.exists() {
            return Err(Error::config_at(
                format!(
                    "TLS certificate files not found: ca.pem, cert.pem, and key.pem are required"
                ),
                cert_path.display().to_string(),
            ));
        }

        // Parse the Docker host URL
        let host = docker_host
            .strip_prefix("tcp://")
            .or_else(|| docker_host.strip_prefix("https://"))
            .unwrap_or(docker_host);

        // Convert to proper URL format for bollard
        let url = if host.starts_with("http") {
            host.to_string()
        } else {
            format!("https://{}", host)
        };

        // Use bollard's connect_with_ssl method
        Docker::connect_with_ssl(
            &url,
            &key_path,
            &cert_file_path,
            &ca_path,
            120,
            bollard::API_DEFAULT_VERSION,
        )
        .map_err(|e| Error::Docker(e))
    }

    pub async fn ping(&self) -> Result<()> {
        timeout(self.timeout_duration, self.client.ping())
            .await
            .map_err(|_| Error::timeout(self.timeout_duration, "ping Docker daemon"))?
            .map_err(|e| Error::Docker(e))?;
        Ok(())
    }

    pub async fn list_containers(&self) -> Result<Vec<bollard::models::ContainerSummary>> {
        use bollard::query_parameters::ListContainersOptionsBuilder;

        let options = ListContainersOptionsBuilder::default().all(false).build();

        timeout(
            self.timeout_duration,
            self.client.list_containers(Some(options)),
        )
        .await
        .map_err(|_| Error::timeout(self.timeout_duration, "list containers"))?
        .map_err(|e| Error::Docker(e))
    }

    pub async fn list_all_containers(&self) -> Result<Vec<bollard::models::ContainerSummary>> {
        use bollard::query_parameters::ListContainersOptionsBuilder;

        let options = ListContainersOptionsBuilder::default().all(true).build();

        timeout(
            self.timeout_duration,
            self.client.list_containers(Some(options)),
        )
        .await
        .map_err(|_| Error::timeout(self.timeout_duration, "list all containers"))?
        .map_err(|e| Error::Docker(e))
    }

    pub async fn try_get_container_by_id(&self, id: &str) -> Result<Container> {
        Ok(Container::from_inspect(self.inspect_container(id).await?)?)
    }

    pub async fn inspect_container(
        &self,
        id: &str,
    ) -> Result<bollard::models::ContainerInspectResponse> {
        use bollard::query_parameters::InspectContainerOptionsBuilder;

        let options = InspectContainerOptionsBuilder::default().build();

        timeout(
            self.timeout_duration,
            self.client.inspect_container(id, Some(options)),
        )
        .await
        .map_err(|_| Error::timeout(self.timeout_duration, "inspect container"))?
        .map_err(|e| Error::Docker(e))
    }

    pub async fn events(
        &self,
    ) -> Result<impl futures::stream::Stream<Item = Result<EventMessage>>> {
        self.events_with_retry().await
    }

    async fn events_with_retry(
        &self,
    ) -> Result<impl futures::stream::Stream<Item = Result<EventMessage>>> {
        use bollard::query_parameters::EventsOptionsBuilder;

        let mut filters = HashMap::new();
        filters.insert("type", vec!["container", "network"]);
        filters.insert(
            "event",
            vec![
                "create",
                "start",
                "die",
                "pause",
                "unpause",
                "rename",
                "connect",
                "disconnect",
            ],
        );

        let options = EventsOptionsBuilder::default().filters(&filters).build();

        let stream = self.client.events(Some(options));
        Ok(stream.map(|res| res.map_err(|e| Error::Docker(e))))
    }

    pub async fn pause_container(&self, id: &str) -> Result<()> {
        timeout(self.timeout_duration, self.client.pause_container(id))
            .await
            .map_err(|_| Error::timeout(self.timeout_duration, "pause container"))?
            .map_err(|e| Error::Docker(e))
    }

    pub async fn unpause_container(&self, id: &str) -> Result<()> {
        timeout(self.timeout_duration, self.client.unpause_container(id))
            .await
            .map_err(|_| Error::timeout(self.timeout_duration, "unpause container"))?
            .map_err(|e| Error::Docker(e))
    }

    pub async fn start_container(&self, id: &str) -> Result<()> {
        use bollard::query_parameters::StartContainerOptionsBuilder;

        let options = StartContainerOptionsBuilder::default().build();

        timeout(
            self.timeout_duration,
            self.client.start_container(id, Some(options)),
        )
        .await
        .map_err(|_| Error::timeout(self.timeout_duration, "start container"))?
        .map_err(|e| Error::Docker(e))
    }

    /// Get detailed version information about the Docker daemon
    pub async fn version_info(&self) -> Result<bollard::models::SystemVersion> {
        timeout(self.timeout_duration, self.client.version())
            .await
            .map_err(|_| Error::timeout(self.timeout_duration, "get version info"))?
            .map_err(|e| Error::Docker(e))
    }

    /// Check if the Docker daemon supports a specific API endpoint
    /// This is useful for gracefully handling newer features
    pub async fn check_api_endpoint(&self, endpoint: &str) -> bool {
        // For Unix sockets, we can't use reqwest directly, so fall back to version check
        if matches!(self.connection_info, ConnectionInfo::Socket(_)) {
            return self.check_api_endpoint_by_version(endpoint);
        }

        // Build the full endpoint URL based on the Docker connection
        let base_url = self.get_docker_base_url();
        let api_version = self.api_version.as_deref().unwrap_or("v1.41");
        let full_url = format!("{}/{}{}", base_url, api_version, endpoint);

        // Create an HTTP client based on connection type
        let client_result = match &self.connection_info {
            ConnectionInfo::Ssl { .. } => {
                // For SSL connections, we'd need to configure certificates
                // For now, fall back to version check
                return self.check_api_endpoint_by_version(endpoint);
            }
            _ => reqwest::Client::builder()
                .timeout(Duration::from_secs(5))
                .build(),
        };

        if let Ok(client) = client_result {
            // Make a HEAD request to check if the endpoint exists
            match client.head(&full_url).send().await {
                Ok(response) => {
                    // 2xx status codes indicate the endpoint exists
                    // 404 means it doesn't exist
                    // Other errors might be auth issues, so we fall back to version check
                    response.status().is_success()
                }
                Err(_) => {
                    // Fall back to version-based check if HEAD request fails
                    self.check_api_endpoint_by_version(endpoint)
                }
            }
        } else {
            // If we can't create the client, fall back to version check
            self.check_api_endpoint_by_version(endpoint)
        }
    }

    /// Get the base URL for the Docker daemon
    fn get_docker_base_url(&self) -> String {
        match &self.connection_info {
            ConnectionInfo::Socket(_) => {
                // For Unix sockets, Docker uses a special URL format
                // The actual endpoint will be handled by the HTTP client with socket support
                "http://localhost".to_string()
            }
            ConnectionInfo::Http(url) => url.clone(),
            ConnectionInfo::Ssl { url, .. } => url.clone(),
            ConnectionInfo::Default => {
                // Default Docker daemon URL
                "http://localhost:2375".to_string()
            }
        }
    }

    /// Check API endpoint support based on version compatibility
    fn check_api_endpoint_by_version(&self, endpoint: &str) -> bool {
        if let Some(_api_version) = &self.api_version {
            // Define minimum versions for various endpoints
            let endpoint_versions: HashMap<&str, &str> = HashMap::from([
                ("secrets", "v1.25"),
                ("configs", "v1.30"),
                ("plugins", "v1.24"),
                ("nodes", "v1.24"),
                ("services", "v1.24"),
                ("stacks", "v1.25"),
            ]);

            if let Some(&min_version) = endpoint_versions.get(endpoint) {
                return self.is_feature_supported(endpoint, min_version).is_ok();
            }
        }
        true // Assume supported if we can't determine
    }

    /// List all Docker networks
    pub async fn list_networks(&self) -> Result<Vec<bollard::models::Network>> {
        use bollard::query_parameters::ListNetworksOptionsBuilder;

        let options = ListNetworksOptionsBuilder::default().build();

        timeout(
            self.timeout_duration,
            self.client.list_networks(Some(options)),
        )
        .await
        .map_err(|_| Error::timeout(self.timeout_duration, "list networks"))?
        .map_err(|e| Error::Docker(e))
    }

    /// Inspect a specific Docker network
    pub async fn inspect_network(&self, network_id: &str) -> Result<bollard::models::Network> {
        use bollard::query_parameters::InspectNetworkOptionsBuilder;

        let options = InspectNetworkOptionsBuilder::default().build();

        timeout(
            self.timeout_duration,
            self.client.inspect_network(network_id, Some(options)),
        )
        .await
        .map_err(|_| Error::timeout(self.timeout_duration, "inspect network"))?
        .map_err(|e| Error::Docker(e))
    }

    /// Refresh network gateway information from Docker
    pub async fn refresh_network_gateways(&self) -> Result<()> {
        use crate::docker::network::extract_network_gateway;

        let networks = self.list_networks().await?;
        let mut gateway_cache = self.network_gateway_cache.lock().await;

        for network in networks {
            if let Ok(gateway_info) = extract_network_gateway(&network) {
                debug!(
                    "Found gateway info for network {}: {:?}",
                    gateway_info.network_name, gateway_info.gateway_ips
                );
                gateway_cache.insert(gateway_info.network_name.clone(), gateway_info);
            }
        }

        Ok(())
    }

    /// Get containers from Docker and sort by dependencies
    pub async fn get_sorted_containers(&self) -> Result<Vec<bollard::models::ContainerSummary>> {
        let mut containers = self.list_containers().await?;
        compose::sort_by_dependencies(&mut containers);
        Ok(containers)
    }
}