vortix 0.3.1

Terminal UI for WireGuard and OpenVPN with real-time telemetry and leak guarding
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
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
//! Platform aggregate — runtime-selectable per-OS port dispatcher (plan 003 U3/U5).
//!
//! The five capability ports defined in `vortix-core::ports::*` each get a
//! lightweight `*Kind` enum carrier here. The real variants are unit tags
//! (zero-cost markers) that dispatch to the static trait impls in
//! `vortix-platform-{macos,linux}`; the `Mock(...)` variant carries scripted
//! state for tests.
//!
//! ## Why the aggregate lives in `vortix`, not `vortix-core`
//!
//! Plan #003 originally located the aggregate in `vortix-core`, but vortix-core
//! must not depend on the platform impl crates (those crates already depend on
//! vortix-core for the trait definitions — that's a Cargo dependency cycle).
//! The binary crate is the natural meeting point: it already depends on
//! everything, so the aggregate composes cleanly here.

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

use crate::vortix_core::ports::killswitch::{KillswitchError, Result as KsResult};

#[cfg(target_os = "linux")]
use crate::vortix_platform_linux as platform_impl;
#[cfg(target_os = "macos")]
use crate::vortix_platform_macos as platform_impl;
#[cfg(target_os = "windows")]
use crate::vortix_platform_windows as platform_impl;

// ───────────────────────────────────────────────────────────────────────────
// Mock state shells
// ───────────────────────────────────────────────────────────────────────────

/// Scriptable mock for the `Killswitch` port.
#[derive(Debug, Default, Clone)]
pub struct MockKillswitch {
    state: Arc<Mutex<MockKillswitchState>>,
}

#[derive(Debug, Default)]
struct MockKillswitchState {
    /// Optional canned error returned by the next `enable_blocking` call.
    pub fail_enable: Option<String>,
    /// Optional canned error returned by the next `disable_blocking` call.
    pub fail_disable: Option<String>,
    /// Whether `enable_blocking` was called at least once.
    pub enabled: bool,
    /// Whether `disable_blocking` was called at least once.
    pub disabled: bool,
}

impl MockKillswitch {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Script `enable_blocking` to fail with the given message.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned.
    pub fn fail_next_enable(&self, msg: impl Into<String>) {
        self.state.lock().unwrap().fail_enable = Some(msg.into());
    }

    /// Returns whether `enable_blocking` was called at least once.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned.
    #[must_use]
    pub fn was_enabled(&self) -> bool {
        self.state.lock().unwrap().enabled
    }

    /// Returns whether `disable_blocking` was called at least once.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned.
    #[must_use]
    pub fn was_disabled(&self) -> bool {
        self.state.lock().unwrap().disabled
    }

    fn enable_blocking(&self, _iface: &str, _server: Option<&str>) -> KsResult<()> {
        let mut s = self.state.lock().unwrap();
        if let Some(msg) = s.fail_enable.take() {
            return Err(KillswitchError::CommandFailed(msg));
        }
        s.enabled = true;
        Ok(())
    }

    fn disable_blocking(&self) -> KsResult<()> {
        let mut s = self.state.lock().unwrap();
        if let Some(msg) = s.fail_disable.take() {
            return Err(KillswitchError::CommandFailed(msg));
        }
        s.disabled = true;
        Ok(())
    }
}

/// Scriptable mock for the `DnsResolver` port.
#[derive(Debug, Default, Clone)]
pub struct MockDns {
    /// Canned response from `get_dns_server`. `None` returns `None`.
    pub dns: Option<String>,
}

/// Scriptable mock for the `Interface` port.
#[derive(Debug, Default, Clone)]
pub struct MockInterface {
    /// If true, `check_wireguard_interface` always returns true.
    pub wg_present: bool,
}

/// Scriptable mock for the `NetworkStats` port.
#[derive(Debug, Default, Clone)]
pub struct MockNetworkStats {
    pub bytes_in: u64,
    pub bytes_out: u64,
}

/// Scriptable mock for the `RouteTable` port.
#[derive(Debug, Default, Clone)]
pub struct MockRouteTable {
    pub gateway: Option<String>,
}

// ───────────────────────────────────────────────────────────────────────────
// Per-port enum carriers
// ───────────────────────────────────────────────────────────────────────────

/// Static-dispatch carrier for the `Killswitch` port.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum KillswitchKind {
    #[cfg(target_os = "macos")]
    Macos,
    #[cfg(target_os = "linux")]
    Linux,
    #[cfg(target_os = "windows")]
    Windows,
    Mock(MockKillswitch),
}

impl KillswitchKind {
    /// Engage the kill switch.
    ///
    /// # Errors
    ///
    /// See [`KillswitchError`].
    ///
    /// # Panics
    ///
    /// The mock variant may panic if its internal mutex is poisoned.
    pub fn enable_blocking(
        &self,
        vpn_interface: &str,
        vpn_server_ip: Option<&str>,
    ) -> KsResult<()> {
        use crate::vortix_core::ports::killswitch::Killswitch;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::PfFirewall::enable_blocking(vpn_interface, vpn_server_ip),
            #[cfg(target_os = "linux")]
            Self::Linux => {
                platform_impl::IptablesFirewall::enable_blocking(vpn_interface, vpn_server_ip)
            }
            #[cfg(target_os = "windows")]
            Self::Windows => {
                platform_impl::WindowsFirewall::enable_blocking(vpn_interface, vpn_server_ip)
            }
            Self::Mock(m) => m.enable_blocking(vpn_interface, vpn_server_ip),
        }
    }

    /// Disengage the kill switch.
    ///
    /// # Errors
    ///
    /// See [`KillswitchError`].
    ///
    /// # Panics
    ///
    /// The mock variant may panic if its internal mutex is poisoned.
    pub fn disable_blocking(&self) -> KsResult<()> {
        use crate::vortix_core::ports::killswitch::Killswitch;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::PfFirewall::disable_blocking(),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::IptablesFirewall::disable_blocking(),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsFirewall::disable_blocking(),
            Self::Mock(m) => m.disable_blocking(),
        }
    }
}

/// Static-dispatch carrier for the `DnsResolver` port.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DnsResolverKind {
    #[cfg(target_os = "macos")]
    Macos,
    #[cfg(target_os = "linux")]
    Linux,
    #[cfg(target_os = "windows")]
    Windows,
    Mock(MockDns),
}

impl DnsResolverKind {
    /// Get the current system DNS server.
    #[must_use]
    pub fn get_dns_server(&self) -> Option<String> {
        use crate::vortix_core::ports::dns::DnsResolver;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::MacDns::get_dns_server(),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::LinuxDns::get_dns_server(),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsDns::get_dns_server(),
            Self::Mock(m) => m.dns.clone(),
        }
    }
}

/// Static-dispatch carrier for the `Interface` port.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum InterfaceKind {
    #[cfg(target_os = "macos")]
    Macos,
    #[cfg(target_os = "linux")]
    Linux,
    #[cfg(target_os = "windows")]
    Windows,
    Mock(MockInterface),
}

impl InterfaceKind {
    /// Whether a `WireGuard` interface exists for this profile name.
    #[must_use]
    pub fn check_wireguard_interface(&self, name: &str) -> bool {
        use crate::vortix_core::ports::interface::Interface;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::MacInterface::check_wireguard_interface(name),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::LinuxInterface::check_wireguard_interface(name),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsInterface::check_wireguard_interface(name),
            Self::Mock(m) => m.wg_present,
        }
    }

    /// Resolve the real interface name for a `WireGuard` profile.
    #[must_use]
    pub fn resolve_wireguard_interface(&self, name: &str) -> Option<String> {
        use crate::vortix_core::ports::interface::Interface;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::MacInterface::resolve_wireguard_interface(name),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::LinuxInterface::resolve_wireguard_interface(name),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsInterface::resolve_wireguard_interface(name),
            Self::Mock(m) => {
                if m.wg_present {
                    Some(name.to_string())
                } else {
                    None
                }
            }
        }
    }

    /// PID of the `WireGuard` user-space process managing the interface.
    #[must_use]
    pub fn get_wireguard_pid(&self, interface: &str) -> Option<u32> {
        use crate::vortix_core::ports::interface::Interface;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::MacInterface::get_wireguard_pid(interface),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::LinuxInterface::get_wireguard_pid(interface),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsInterface::get_wireguard_pid(interface),
            Self::Mock(_) => None,
        }
    }

    /// `(ip, mtu)` for the interface.
    #[must_use]
    pub fn get_interface_info(&self, interface: &str) -> (String, String) {
        use crate::vortix_core::ports::interface::Interface;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::MacInterface::get_interface_info(interface),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::LinuxInterface::get_interface_info(interface),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsInterface::get_interface_info(interface),
            Self::Mock(_) => (String::new(), String::new()),
        }
    }
}

/// Static-dispatch carrier for the `NetworkStats` port.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum NetworkStatsKind {
    #[cfg(target_os = "macos")]
    Macos,
    #[cfg(target_os = "linux")]
    Linux,
    #[cfg(target_os = "windows")]
    Windows,
    Mock(MockNetworkStats),
}

impl NetworkStatsKind {
    /// Total bytes received and transmitted across all non-loopback interfaces.
    #[must_use]
    pub fn get_total_bytes(&self) -> (u64, u64) {
        use crate::vortix_core::ports::network_stats::NetworkStats;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::MacNetworkStats::get_total_bytes(),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::LinuxNetworkStats::get_total_bytes(),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsNetworkStats::get_total_bytes(),
            Self::Mock(m) => (m.bytes_in, m.bytes_out),
        }
    }
}

/// Static-dispatch carrier for the `RouteTable` port.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum RouteTableKind {
    #[cfg(target_os = "macos")]
    Macos,
    #[cfg(target_os = "linux")]
    Linux,
    #[cfg(target_os = "windows")]
    Windows,
    Mock(MockRouteTable),
}

impl RouteTableKind {
    /// IP of the current default gateway, if any.
    #[must_use]
    pub fn default_gateway(&self) -> Option<String> {
        use crate::vortix_core::ports::route_table::RouteTable;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::MacRouteTable::default_gateway(),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::LinuxRouteTable::default_gateway(),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsRouteTable::default_gateway(),
            Self::Mock(m) => m.gateway.clone(),
        }
    }
}

/// Scriptable mock for the `SocketAudit` port (plan 015 phase C).
#[derive(Debug, Default, Clone)]
pub struct MockSocketAudit {
    pub canned: Vec<crate::vortix_core::ports::socket_audit::SocketSnapshot>,
}

/// Static-dispatch carrier for the `SocketAudit` port (plan 015 phase C).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SocketAuditKind {
    #[cfg(target_os = "macos")]
    Macos,
    #[cfg(target_os = "linux")]
    Linux,
    #[cfg(target_os = "windows")]
    Windows,
    Mock(MockSocketAudit),
}

impl SocketAuditKind {
    /// Snapshot the current socket inventory.
    ///
    /// # Errors
    ///
    /// See `crate::vortix_core::ports::socket_audit::SocketAuditError`.
    pub fn snapshot(
        &self,
    ) -> crate::vortix_core::ports::socket_audit::SocketAuditResult<
        Vec<crate::vortix_core::ports::socket_audit::SocketSnapshot>,
    > {
        use crate::vortix_core::ports::socket_audit::SocketAudit;
        match self {
            #[cfg(target_os = "macos")]
            Self::Macos => platform_impl::LsofSocketAudit::snapshot(),
            #[cfg(target_os = "linux")]
            Self::Linux => platform_impl::ProcSocketAudit::snapshot(),
            #[cfg(target_os = "windows")]
            Self::Windows => platform_impl::WindowsSocketAudit::snapshot(),
            Self::Mock(m) => Ok(m.canned.clone()),
        }
    }
}

// ───────────────────────────────────────────────────────────────────────────
// The aggregate
// ───────────────────────────────────────────────────────────────────────────

/// The platform aggregate — one field per capability port.
///
/// Constructed once at startup via [`Platform::detect_current`] and threaded
/// through the engine and CLI. Tests construct [`Platform::for_test`] which
/// uses `Mock(...)` variants for every port.
#[derive(Debug, Clone)]
pub struct Platform {
    pub killswitch: KillswitchKind,
    pub dns: DnsResolverKind,
    pub interface: InterfaceKind,
    pub network_stats: NetworkStatsKind,
    pub route_table: RouteTableKind,
    pub socket_audit: SocketAuditKind,
}

impl Platform {
    /// Construct the platform aggregate for the current OS.
    ///
    /// Today this just picks the right unit-tag variants for each port. Later
    /// units may need to run backend-detection probes here (e.g. iptables vs
    /// nftables) — currently those probes run inside the impl methods.
    #[must_use]
    pub fn detect_current() -> Self {
        #[cfg(target_os = "macos")]
        {
            Self {
                killswitch: KillswitchKind::Macos,
                dns: DnsResolverKind::Macos,
                interface: InterfaceKind::Macos,
                network_stats: NetworkStatsKind::Macos,
                route_table: RouteTableKind::Macos,
                socket_audit: SocketAuditKind::Macos,
            }
        }
        #[cfg(target_os = "linux")]
        {
            Self {
                killswitch: KillswitchKind::Linux,
                dns: DnsResolverKind::Linux,
                interface: InterfaceKind::Linux,
                network_stats: NetworkStatsKind::Linux,
                route_table: RouteTableKind::Linux,
                socket_audit: SocketAuditKind::Linux,
            }
        }
        #[cfg(target_os = "windows")]
        {
            Self {
                killswitch: KillswitchKind::Windows,
                dns: DnsResolverKind::Windows,
                interface: InterfaceKind::Windows,
                network_stats: NetworkStatsKind::Windows,
                route_table: RouteTableKind::Windows,
                socket_audit: SocketAuditKind::Windows,
            }
        }
    }

    /// Construct an all-mock platform for unit tests.
    #[must_use]
    pub fn for_test() -> Self {
        Self {
            killswitch: KillswitchKind::Mock(MockKillswitch::new()),
            dns: DnsResolverKind::Mock(MockDns::default()),
            interface: InterfaceKind::Mock(MockInterface::default()),
            network_stats: NetworkStatsKind::Mock(MockNetworkStats::default()),
            route_table: RouteTableKind::Mock(MockRouteTable::default()),
            socket_audit: SocketAuditKind::Mock(MockSocketAudit::default()),
        }
    }
}

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

    #[test]
    fn for_test_uses_mock_variants() {
        let p = Platform::for_test();
        assert!(matches!(p.killswitch, KillswitchKind::Mock(_)));
        assert!(matches!(p.dns, DnsResolverKind::Mock(_)));
        assert!(matches!(p.interface, InterfaceKind::Mock(_)));
        assert!(matches!(p.network_stats, NetworkStatsKind::Mock(_)));
        assert!(matches!(p.route_table, RouteTableKind::Mock(_)));
    }

    #[test]
    fn mock_killswitch_records_calls() {
        let mock = MockKillswitch::new();
        assert!(!mock.was_enabled());
        let ks = KillswitchKind::Mock(mock.clone());
        ks.enable_blocking("wg0", Some("1.2.3.4")).unwrap();
        assert!(mock.was_enabled());
        ks.disable_blocking().unwrap();
        assert!(mock.was_disabled());
    }

    #[test]
    fn mock_killswitch_scripts_failure() {
        let mock = MockKillswitch::new();
        mock.fail_next_enable("simulated iptables error");
        let ks = KillswitchKind::Mock(mock);
        let err = ks.enable_blocking("wg0", None).unwrap_err();
        assert!(matches!(err, KillswitchError::CommandFailed(_)));
    }

    #[test]
    fn mock_dns_returns_canned_value() {
        let dns = DnsResolverKind::Mock(MockDns {
            dns: Some("1.1.1.1".into()),
        });
        assert_eq!(dns.get_dns_server(), Some("1.1.1.1".into()));
    }

    #[test]
    fn mock_route_table_returns_canned_gateway() {
        let rt = RouteTableKind::Mock(MockRouteTable {
            gateway: Some("192.168.1.1".into()),
        });
        assert_eq!(rt.default_gateway(), Some("192.168.1.1".into()));
    }
}