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
591
592
593
594
595
596
597
pub mod error;
pub mod guard;

#[cfg(test)]
mod tests;

use crate::database::DB;
use crate::{Error, Result};
use bon::{Builder, bon};
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};

/// Tracks resources that need cleanup on cancellation or error
///
pub struct CleanupTracker {
    cleanup_tx: mpsc::Sender<CleanupRequest>,
    cleanup_handle: Option<JoinHandle<()>>,
    cancellation_token: CancellationToken,
}

#[derive(Debug, Clone)]
enum CleanupResource {
    NftablesRule {
        table: String,
        chain: String,
        handle: u64,
    },
    NftablesChain {
        table: String,
        chain: String,
    },
    NftablesSet {
        table: String,
        set: String,
    },
    DatabaseContainer {
        id: String,
    },
    HarborshieldFilterRules,
}

#[derive(Debug)]
enum CleanupRequest {
    Register(CleanupResource),
    Unregister(CleanupResource),
    CleanupAll,
    Shutdown,
}

#[bon]
impl CleanupTracker {
    #[builder]
    pub fn new(db: Arc<Mutex<DB>>) -> Self {
        let (cleanup_tx, mut cleanup_rx) = mpsc::channel::<CleanupRequest>(100);
        let cancellation_token = CancellationToken::new();
        let token_clone = cancellation_token.clone();

        let cleanup_handle = tokio::spawn(async move {
            let mut resources_vec = Vec::new();

            loop {
                tokio::select! {
                    Some(request) = cleanup_rx.recv() => {
                        match request {
                            CleanupRequest::Register(resource) => {
                                resources_vec.push(resource);
                                debug!("Registered resource for cleanup");
                            }
                            CleanupRequest::Unregister(resource) => {
                                resources_vec.retain(|r| !matches_resource(r, &resource));
                                debug!("Unregistered resource from cleanup");
                            }
                            CleanupRequest::CleanupAll => {
                                info!("Performing cleanup of all tracked resources");
                                for resource in &resources_vec {
                                    if let Err(e) = cleanup_resource(resource, &db).await {
                                        error!("Failed to cleanup resource: {}", e);
                                    }
                                }
                            }
                            CleanupRequest::Shutdown => {
                                debug!("Cleanup tracker shutting down");
                                break;
                            }
                        }
                    }
                    _ = token_clone.cancelled() => {
                        info!("Cleanup tracker cancelled, performing cleanup");
                        for resource in &resources_vec {
                            if let Err(e) = cleanup_resource(resource, &db).await {
                                error!("Failed to cleanup resource on cancellation: {}", e);
                            }
                        }
                        break;
                    }
                }
            }
        });

        Self {
            cleanup_tx,
            cleanup_handle: Some(cleanup_handle),
            cancellation_token,
        }
    }

    /// Register a nftables rule for cleanup
    pub async fn register_rule(&self, table: String, chain: String, handle: u64) -> Result<()> {
        self.cleanup_tx
            .send(CleanupRequest::Register(CleanupResource::NftablesRule {
                table,
                chain,
                handle,
            }))
            .await
            .map_err(|_| Error::invalid_state("Cleanup tracker closed", "open", "closed"))?;
        Ok(())
    }

    /// Register a nftables chain for cleanup
    pub async fn register_chain(&self, table: String, chain: String) -> Result<()> {
        self.cleanup_tx
            .send(CleanupRequest::Register(CleanupResource::NftablesChain {
                table,
                chain,
            }))
            .await
            .map_err(|_| Error::invalid_state("Cleanup tracker closed", "open", "closed"))?;
        Ok(())
    }

    /// Register a nftables set for cleanup
    pub async fn register_set(&self, table: String, set: String) -> Result<()> {
        self.cleanup_tx
            .send(CleanupRequest::Register(CleanupResource::NftablesSet {
                table,
                set,
            }))
            .await
            .map_err(|_| Error::invalid_state("Cleanup tracker closed", "open", "closed"))?;
        Ok(())
    }

    /// Register a database container for cleanup
    pub async fn register_db_container(&self, id: String) -> Result<()> {
        self.cleanup_tx
            .send(CleanupRequest::Register(
                CleanupResource::DatabaseContainer { id },
            ))
            .await
            .map_err(|_| Error::invalid_state("Cleanup tracker closed", "open", "closed"))?;
        Ok(())
    }

    /// Register Harborshield filter rules for cleanup
    pub async fn register_harborshield_filter_rules(&self) -> Result<()> {
        self.cleanup_tx
            .send(CleanupRequest::Register(
                CleanupResource::HarborshieldFilterRules,
            ))
            .await
            .map_err(|_| Error::invalid_state("Cleanup tracker closed", "open", "closed"))?;
        Ok(())
    }

    /// Unregister a resource (when successfully committed)
    pub async fn unregister_rule(&self, table: String, chain: String, handle: u64) -> Result<()> {
        self.cleanup_tx
            .send(CleanupRequest::Unregister(CleanupResource::NftablesRule {
                table,
                chain,
                handle,
            }))
            .await
            .map_err(|_| Error::invalid_state("Cleanup tracker closed", "open", "closed"))?;
        Ok(())
    }

    /// Cleanup all tracked resources (on error/cancellation)
    pub async fn cleanup_all(&self) -> Result<()> {
        self.cleanup_tx
            .send(CleanupRequest::CleanupAll)
            .await
            .map_err(|_| Error::invalid_state("Cleanup tracker closed", "open", "closed"))?;
        Ok(())
    }

    /// Shutdown the cleanup tracker
    pub async fn shutdown(mut self) -> Result<()> {
        let _ = self.cleanup_tx.send(CleanupRequest::Shutdown).await;
        if let Some(handle) = self.cleanup_handle.take() {
            handle.await.map_err(|e| {
                Error::invalid_state(format!("Cleanup task failed: {}", e), "running", "failed")
            })?;
        }
        Ok(())
    }

    /// Get a child cancellation token
    pub fn child_token(&self) -> CancellationToken {
        self.cancellation_token.child_token()
    }

    /// Cancel all operations
    pub fn cancel(&self) {
        self.cancellation_token.cancel();
    }
}

impl Drop for CleanupTracker {
    fn drop(&mut self) {
        // Cancel the token to trigger cleanup
        self.cancellation_token.cancel();

        // Note: We can't await the handle in Drop since it's not async
        // The cleanup will happen in the background
        if self.cleanup_handle.is_some() {
            warn!(
                "CleanupTracker dropped without explicit shutdown - cleanup will happen in background"
            );
        }
    }
}

fn matches_resource(a: &CleanupResource, b: &CleanupResource) -> bool {
    match (a, b) {
        (
            CleanupResource::NftablesRule {
                table: t1,
                chain: c1,
                handle: h1,
            },
            CleanupResource::NftablesRule {
                table: t2,
                chain: c2,
                handle: h2,
            },
        ) => t1 == t2 && c1 == c2 && h1 == h2,
        (
            CleanupResource::NftablesChain {
                table: t1,
                chain: c1,
            },
            CleanupResource::NftablesChain {
                table: t2,
                chain: c2,
            },
        ) => t1 == t2 && c1 == c2,
        (
            CleanupResource::NftablesSet { table: t1, set: s1 },
            CleanupResource::NftablesSet { table: t2, set: s2 },
        ) => t1 == t2 && s1 == s2,
        (
            CleanupResource::DatabaseContainer { id: id1 },
            CleanupResource::DatabaseContainer { id: id2 },
        ) => id1 == id2,
        (CleanupResource::HarborshieldFilterRules, CleanupResource::HarborshieldFilterRules) => true,
        _ => false,
    }
}

async fn cleanup_resource(resource: &CleanupResource, db: &Arc<Mutex<DB>>) -> Result<()> {
    match resource {
        CleanupResource::NftablesRule {
            table,
            chain,
            handle,
        } => {
            warn!(
                "Cleaning up nftables rule: table={}, chain={}, handle={}",
                table, chain, handle
            );

            // Try cleanup with retry logic
            let max_retries = 3;
            let mut attempt = 0;

            loop {
                attempt += 1;

                // Create a transaction to delete the rule
                let mut transaction =
                    crate::nftables::transaction::NftablesTransaction::builder().build();

                // Create a rule object with the handle for deletion
                let rule = nftables::schema::Rule {
                    family: nftables::types::NfFamily::IP,
                    table: std::borrow::Cow::Owned(table.clone()),
                    chain: std::borrow::Cow::Owned(chain.clone()),
                    handle: Some(*handle as u32),
                    expr: std::borrow::Cow::Borrowed(&[]),
                    index: None,
                    comment: None,
                };

                // Delete the rule
                transaction.delete(nftables::schema::NfListObject::Rule(rule));

                // Commit the transaction with retry
                match transaction.commit().await {
                    Ok(_) => {
                        info!(
                            "Successfully cleaned up nftables rule with handle {}",
                            handle
                        );
                        return Ok(());
                    }
                    Err(e) => {
                        if attempt >= max_retries {
                            error!(
                                "Failed to cleanup nftables rule after {} attempts: {}",
                                max_retries, e
                            );
                            return Err(e);
                        }
                        warn!("Attempt {} to cleanup nftables rule failed: {}", attempt, e);
                        tokio::time::sleep(tokio::time::Duration::from_millis(
                            100 * attempt as u64,
                        ))
                        .await;
                    }
                }
            }
        }
        CleanupResource::NftablesChain { table, chain } => {
            warn!(
                "Cleaning up nftables chain: table={}, chain={}",
                table, chain
            );

            // Try cleanup with retry logic
            let max_retries = 3;
            let mut attempt = 0;

            loop {
                attempt += 1;

                // Create a transaction to delete the chain
                let mut transaction =
                    crate::nftables::transaction::NftablesTransaction::builder().build();

                // First, flush all rules from the chain
                transaction.flush_chain(table, chain);

                // Then delete the chain itself
                let chain_obj = nftables::schema::Chain {
                    family: nftables::types::NfFamily::IP,
                    table: std::borrow::Cow::Owned(table.clone()),
                    name: std::borrow::Cow::Owned(chain.clone()),
                    newname: None,
                    handle: None,
                    _type: None,
                    hook: None,
                    prio: None,
                    dev: None,
                    policy: None,
                };

                transaction.delete(nftables::schema::NfListObject::Chain(chain_obj));

                // Commit the transaction
                match transaction.commit().await {
                    Ok(_) => {
                        info!("Successfully cleaned up nftables chain {}", chain);
                        return Ok(());
                    }
                    Err(e) => {
                        if attempt >= max_retries {
                            error!(
                                "Failed to cleanup nftables chain after {} attempts: {}",
                                max_retries, e
                            );
                            return Err(e);
                        }
                        warn!(
                            "Attempt {} to cleanup nftables chain failed: {}",
                            attempt, e
                        );
                        tokio::time::sleep(tokio::time::Duration::from_millis(
                            100 * attempt as u64,
                        ))
                        .await;
                    }
                }
            }
        }
        CleanupResource::NftablesSet { table, set } => {
            warn!("Cleaning up nftables set: table={}, set={}", table, set);

            // Try cleanup with retry logic
            let max_retries = 3;
            let mut attempt = 0;

            loop {
                attempt += 1;

                // Create a transaction to delete the set
                let mut transaction =
                    crate::nftables::transaction::NftablesTransaction::builder().build();

                // Create a set object for deletion
                let set_obj = Box::new(nftables::schema::Set {
                    family: nftables::types::NfFamily::IP,
                    table: std::borrow::Cow::Owned(table.clone()),
                    name: std::borrow::Cow::Owned(set.clone()),
                    handle: None,
                    set_type: nftables::schema::SetTypeValue::Single(
                        nftables::schema::SetType::Ipv4Addr,
                    ), // Dummy type for deletion
                    policy: None,
                    flags: None,
                    elem: None,
                    timeout: None,
                    gc_interval: None,
                    size: None,
                    comment: None,
                });

                transaction.delete(nftables::schema::NfListObject::Set(set_obj));

                // Commit the transaction
                match transaction.commit().await {
                    Ok(_) => {
                        info!("Successfully cleaned up nftables set {}", set);
                        return Ok(());
                    }
                    Err(e) => {
                        if attempt >= max_retries {
                            error!(
                                "Failed to cleanup nftables set after {} attempts: {}",
                                max_retries, e
                            );
                            return Err(e);
                        }
                        warn!("Attempt {} to cleanup nftables set failed: {}", attempt, e);
                        tokio::time::sleep(tokio::time::Duration::from_millis(
                            100 * attempt as u64,
                        ))
                        .await;
                    }
                }
            }
        }
        CleanupResource::DatabaseContainer { id } => {
            warn!("Cleaning up database container: id={}", id);

            // Lock the database
            let mut db_guard = db.lock().await;

            use crate::database::DbOp;

            // Define the operations to execute
            let ops = vec![
                DbOp::DeleteAddrsByContainer(id),
                DbOp::DeleteContainerAliases(id),
                DbOp::DeleteWaitingRules(id),
                DbOp::DeleteContainer(id),
            ];

            // Execute operations in transaction
            match db_guard.transaction().execute_ops(&ops).await {
                Ok(executed) => {
                    // Commit the transaction
                    executed.commit().await?;
                    info!("Successfully cleaned up database container {}", id);
                    Ok(())
                }
                Err(e) => {
                    error!("Failed to cleanup database container: {}", e);
                    Err(e)
                }
            }
        }
        CleanupResource::HarborshieldFilterRules => {
            warn!("Cleaning up all Harborshield rules from filter table");

            // First, get a list of all Harborshield chains (hs-* chains)
            let list_output = std::process::Command::new("nft")
                .args(&["-j", "list", "table", "ip", "filter"])
                .output()
                .map_err(|e| crate::Error::Config {
                    message: format!("Failed to list filter table: {}", e),
                    location: "cleanup_harborshield_filter_rules".to_string(),
                    suggestion: Some("Check nftables permissions".to_string()),
                })?;

            if !list_output.status.success() {
                warn!(
                    "Failed to list filter table: {}",
                    String::from_utf8_lossy(&list_output.stderr)
                );
                return Ok(()); // Don't fail cleanup if we can't list
            }

            let output_str = String::from_utf8_lossy(&list_output.stdout);

            // Parse JSON to find all chains starting with "hs-"
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&output_str) {
                if let Some(nftables) = json.get("nftables").and_then(|n| n.as_array()) {
                    let mut chains_to_delete = Vec::new();

                    for item in nftables {
                        if let Some(chain) = item.get("chain") {
                            if let Some(name) = chain.get("name").and_then(|n| n.as_str()) {
                                if name.starts_with("hs-") {
                                    chains_to_delete.push(name.to_string());
                                }
                            }
                        }
                    }

                    info!(
                        "Found {} Harborshield container chains to delete",
                        chains_to_delete.len()
                    );

                    // Delete each container chain
                    for chain_name in chains_to_delete {
                        // First flush the chain
                        let flush_result = std::process::Command::new("nft")
                            .args(&["flush", "chain", "ip", "filter", &chain_name])
                            .output();

                        if let Err(e) = flush_result {
                            warn!("Failed to flush chain {}: {}", chain_name, e);
                        }

                        // Then delete the chain
                        let delete_result = std::process::Command::new("nft")
                            .args(&["delete", "chain", "ip", "filter", &chain_name])
                            .output();

                        match delete_result {
                            Ok(output) => {
                                if output.status.success() {
                                    debug!("Successfully deleted chain {}", chain_name);
                                } else {
                                    warn!(
                                        "Failed to delete chain {}: {}",
                                        chain_name,
                                        String::from_utf8_lossy(&output.stderr)
                                    );
                                }
                            }
                            Err(e) => {
                                warn!("Failed to delete chain {}: {}", chain_name, e);
                            }
                        }
                    }
                }
            }

            // Also flush the main harborshield chain
            let flush_harborshield = std::process::Command::new("nft")
                .args(&["flush", "chain", "ip", "filter", "harborshield"])
                .output();

            if let Err(e) = flush_harborshield {
                warn!("Failed to flush harborshield chain: {}", e);
            }

            info!("Completed cleanup of Harborshield filter rules");
            Ok(())
        }
    }
}

/// Guard that automatically cleans up resources on drop
#[derive(Builder)]
pub struct CleanupGuard {
    tracker: Arc<CleanupTracker>,
    #[builder(default = false)]
    committed: bool,
}

impl CleanupGuard {
    /// Mark the operation as committed (no cleanup needed)
    pub fn commit(mut self) {
        self.committed = true;
    }
}

impl Drop for CleanupGuard {
    fn drop(&mut self) {
        if !self.committed {
            let tracker = self.tracker.clone();
            tokio::spawn(async move {
                if let Err(e) = tracker.cleanup_all().await {
                    error!("Failed to cleanup resources on guard drop: {}", e);
                }
            });
        }
    }
}