vortix 0.4.0

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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Daemon IPC server loop (plan 015 phase D U18 / plan 010).
//!
//! Single-client-at-a-time. Accept → peer-UID check → read frame →
//! dispatch → write response → loop until client disconnects.
//! Multi-client support is follow-up scope.

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

use crate::vortix_core::engine::EngineHandle;
use crate::vortix_core::ipc::{
    decode_frame, encode_frame, FrameError, IpcError, IpcOp, IpcRequest, IpcResponse, IpcResult,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{UnixListener, UnixStream};

/// The daemon server. Holds the socket binding, engine handle, and
/// the effective UID captured at bind time for peer-UID enforcement.
pub struct DaemonServer {
    socket_path: PathBuf,
    listener: UnixListener,
    engine_handle: Option<Arc<EngineHandle>>,
    /// The effective UID of the daemon process at bind time. Every
    /// accepted client is checked against this value via
    /// `SO_PEERCRED` (Linux) / `getpeereid(2)` (macOS) and rejected
    /// if they do not match. This is the security boundary that
    /// prevents a local UID escalation from compromising the daemon
    /// even when the socket file's mode 0600 has been bypassed.
    daemon_uid: u32,
}

impl DaemonServer {
    /// Bind the daemon socket. Cleans up any stale file at the path.
    ///
    /// The returned server has no engine handle attached; clients see
    /// structured "engine handle not initialized" errors for
    /// `Execute`/`Snapshot`/`Subscribe`. Use [`Self::with_engine_handle`]
    /// to attach a `EngineHandle::Local` so dispatch routes through the
    /// real FSM actor.
    ///
    /// # Errors
    ///
    /// Returns `io::Error` when the parent directory is unwritable or
    /// the bind itself fails.
    pub fn bind(socket_path: PathBuf) -> std::io::Result<Self> {
        // Best-effort cleanup of a stale socket from a crashed previous run.
        let _ = std::fs::remove_file(&socket_path);
        let listener = UnixListener::bind(&socket_path)?;
        // Restrict access — only the daemon's owning UID should be
        // able to connect at the filesystem level. SO_PEERCRED /
        // getpeereid auth (below, on each accept) is the in-depth
        // guard on top of this.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&socket_path)?.permissions();
            perms.set_mode(0o600);
            std::fs::set_permissions(&socket_path, perms)?;
        }
        // SAFETY: `geteuid` is a vDSO-fast syscall on Linux and a
        // trivial syscall on macOS. It cannot fail and has no
        // pointer arguments.
        #[allow(unsafe_code)]
        let daemon_uid = unsafe { libc::geteuid() };
        Ok(Self {
            socket_path,
            listener,
            engine_handle: None,
            daemon_uid,
        })
    }

    /// Attach an engine handle so dispatch routes `Execute`/`Snapshot`/
    /// `Subscribe` through it. Without this, the daemon responds with
    /// structured "engine handle not initialized" errors so clients see
    /// typed wire errors instead of empty responses or connection drops.
    #[must_use]
    pub fn with_engine_handle(mut self, handle: EngineHandle) -> Self {
        self.engine_handle = Some(Arc::new(handle));
        self
    }

    /// Path to the bound socket.
    #[must_use]
    pub fn socket_path(&self) -> &Path {
        &self.socket_path
    }

    /// The daemon's own effective UID, captured at bind time. Used
    /// to authenticate connecting clients on each accept.
    #[must_use]
    pub fn daemon_uid(&self) -> u32 {
        self.daemon_uid
    }

    /// Accept loop. Returns when the listener is dropped or SIGTERM
    /// arrives (caller handles signal observation; this future
    /// terminates cleanly via `select!` from the caller).
    pub async fn run(self) -> std::io::Result<()> {
        eprintln!("vortix daemon: listening on {}", self.socket_path.display());
        if self.engine_handle.is_none() {
            tracing::warn!(
                "daemon started without an engine handle — Execute/Snapshot/Subscribe will return Internal errors"
            );
        }
        let daemon_uid = self.daemon_uid;
        loop {
            match self.listener.accept().await {
                Ok((stream, _addr)) => {
                    let handle = self.engine_handle.clone();
                    if let Err(e) = handle_client(stream, daemon_uid, handle).await {
                        eprintln!("vortix daemon: client session ended: {e}");
                    }
                }
                Err(e) => {
                    eprintln!("vortix daemon: accept failed: {e}");
                    // Brief backoff before re-accepting to avoid
                    // tight loop on persistent failure.
                    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                }
            }
        }
    }
}

impl Drop for DaemonServer {
    fn drop(&mut self) {
        // Unlink the socket file on shutdown so the next daemon start
        // doesn't trip over a stale file.
        let _ = std::fs::remove_file(&self.socket_path);
    }
}

/// Handle one client connection. Reads framed requests, dispatches
/// them, writes framed responses. Returns when the client disconnects.
///
/// Before any dispatching, the peer's UID is checked against the
/// daemon's own UID via `SO_PEERCRED` (Linux) / `getpeereid` (macOS).
/// A mismatched peer receives a single `IpcError::Unauthorized` frame
/// (best-effort) and the connection is closed.
async fn handle_client(
    mut stream: UnixStream,
    daemon_uid: u32,
    engine_handle: Option<Arc<EngineHandle>>,
) -> Result<(), DaemonError> {
    // Peer-UID enforcement runs before any frame is read so an
    // unauthorized client never gets the chance to drive dispatch.
    match get_peer_uid(&stream) {
        Ok(peer_uid) if peer_uid == daemon_uid => { /* authorized; fall through */ }
        Ok(peer_uid) => {
            tracing::warn!(peer_uid, daemon_uid, "rejecting client with UID mismatch");
            // Best-effort notify-and-close: write a single
            // Unauthorized frame so the client surfaces a typed
            // error rather than an opaque EOF.
            let resp = IpcResponse {
                id: 0,
                result: Err(IpcError::Unauthorized),
            };
            if let Ok(frame) = encode_frame(&resp) {
                let _ = stream.write_all(&frame).await;
                let _ = stream.shutdown().await;
            }
            return Ok(());
        }
        Err(e) => {
            tracing::warn!(error = %e, "peer-UID lookup failed; closing connection");
            let resp = IpcResponse {
                id: 0,
                result: Err(IpcError::Internal(format!("peer-UID lookup failed: {e}"))),
            };
            if let Ok(frame) = encode_frame(&resp) {
                let _ = stream.write_all(&frame).await;
                let _ = stream.shutdown().await;
            }
            return Ok(());
        }
    }

    let mut buf = Vec::with_capacity(4096);
    let mut read_pos = 0usize;
    loop {
        // Read into buf.
        let mut chunk = [0u8; 4096];
        let n = stream.read(&mut chunk).await?;
        if n == 0 {
            // EOF — client closed.
            return Ok(());
        }
        buf.extend_from_slice(&chunk[..n]);

        // Drain as many full frames as we have.
        loop {
            match decode_frame::<IpcRequest>(&buf[read_pos..]) {
                Ok(None) => break, // need more bytes
                Ok(Some((req, consumed))) => {
                    read_pos += consumed;
                    let resp = dispatch(req, engine_handle.as_deref()).await;
                    let frame = encode_frame(&resp).map_err(DaemonError::Frame)?;
                    stream.write_all(&frame).await?;
                }
                Err(e) => return Err(DaemonError::Frame(e)),
            }
        }
        // Compact the buffer when we've consumed a meaningful chunk.
        if read_pos > 0 && read_pos >= buf.len() / 2 {
            buf.drain(..read_pos);
            read_pos = 0;
        }
    }
}

/// Look up the peer UID on an accepted Unix-domain socket connection.
///
/// Linux uses `SO_PEERCRED` (returns `struct ucred` with pid/uid/gid).
/// macOS uses `getpeereid(2)` (returns uid + gid directly). Both are
/// syscall-level primitives with no portable abstraction in `std` or
/// `tokio`, hence the platform cfg gating lives here rather than in a
/// `vortix-platform-*` crate.
#[cfg(unix)]
#[allow(unsafe_code)]
fn get_peer_uid(stream: &UnixStream) -> std::io::Result<u32> {
    use std::os::unix::io::AsRawFd;
    let fd = stream.as_raw_fd();

    // xtask:allow-platform-cfg: SO_PEERCRED/getpeereid are syscall-level primitives, no abstraction layer available.
    #[cfg(target_os = "linux")]
    {
        // SAFETY: `getsockopt` writes at most `len` bytes into the
        // pointer we provide. We zero-initialize a `ucred` (a POD
        // struct of three integers) and pass its size; the kernel
        // either fills it and returns 0, or returns -1 and sets
        // errno without touching the buffer.
        unsafe {
            let mut cred: libc::ucred = std::mem::zeroed();
            let mut len = libc::socklen_t::try_from(std::mem::size_of::<libc::ucred>()).expect(
                "ucred size fits in socklen_t (a small POD struct on every supported target)",
            );
            let rc = libc::getsockopt(
                fd,
                libc::SOL_SOCKET,
                libc::SO_PEERCRED,
                std::ptr::addr_of_mut!(cred).cast::<libc::c_void>(),
                std::ptr::from_mut(&mut len),
            );
            if rc != 0 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(cred.uid)
        }
    }

    // xtask:allow-platform-cfg: SO_PEERCRED/getpeereid are syscall-level primitives, no abstraction layer available.
    #[cfg(target_os = "macos")]
    {
        // SAFETY: `getpeereid` writes exactly one `uid_t` and one
        // `gid_t` into the two out-pointers we provide. We pass
        // pointers to stack locals of the correct types.
        unsafe {
            let mut uid: libc::uid_t = 0;
            let mut gid: libc::gid_t = 0;
            let rc = libc::getpeereid(
                fd,
                std::ptr::from_mut(&mut uid),
                std::ptr::from_mut(&mut gid),
            );
            if rc != 0 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(uid)
        }
    }

    // xtask:allow-platform-cfg: SO_PEERCRED/getpeereid are syscall-level primitives, no abstraction layer available.
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        let _ = fd;
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "peer-UID lookup not supported on this unix variant",
        ))
    }
}

/// Route one `IpcRequest` to the engine handle (if attached) and build
/// the response envelope.
///
/// `Subscribe` is acknowledged synchronously — turning the connection
/// into a streaming event channel is follow-up scope (the wire contract
/// reserves it). For now clients can correlate the `Subscribed` ack and
/// then poll `Snapshot` until the streaming half lands.
async fn dispatch(req: IpcRequest, engine_handle: Option<&EngineHandle>) -> IpcResponse {
    let result = match req.op {
        IpcOp::Execute(cmd) => match engine_handle {
            Some(h) => match h.execute_command(cmd).await {
                Ok(_ack) => Ok(IpcResult::Accepted),
                Err(e) => Err(IpcError::Internal(format!("engine error: {e}"))),
            },
            None => Err(IpcError::Internal(
                "engine handle not initialized in daemon".into(),
            )),
        },
        IpcOp::Snapshot => match engine_handle {
            Some(h) => match h.snapshot().await {
                // v1-compat: populate `Snapshot { state }` with the
                // primary's Connection (or Disconnected when no
                // primary). New v2 callers should switch to
                // `RegistrySnapshot` once they upgrade — see plan
                // #001 U22. Today the EngineHandle exposes a single
                // FSM (D1 wired the single-tunnel handle in the
                // daemon); the registry-aware variant lands when a
                // follow-up unit threads the registry into the
                // daemon's accept loop.
                Ok(snap) => Ok(IpcResult::Snapshot { state: snap.state }),
                Err(e) => Err(IpcError::Internal(format!("snapshot error: {e}"))),
            },
            None => Err(IpcError::Internal(
                "engine handle not initialized in daemon".into(),
            )),
        },
        IpcOp::Subscribe => {
            // v1: ack only. Promoting this connection into an event
            // stream (server-pushed `IpcResponse`-like envelopes after
            // the ack) is a follow-up unit — the wire contract reserves
            // it but no client consumes it today.
            if engine_handle.is_some() {
                tracing::warn!(
                    "daemon: Subscribe acknowledged but streaming half is not yet implemented — clients should poll Snapshot until the streaming unit lands"
                );
                Ok(IpcResult::Subscribed)
            } else {
                Err(IpcError::Internal(
                    "engine handle not initialized in daemon".into(),
                ))
            }
        }
        IpcOp::Shutdown => Ok(IpcResult::ShuttingDown),
    };
    IpcResponse { id: req.id, result }
}

#[derive(Debug)]
pub enum DaemonError {
    Io(std::io::Error),
    Frame(FrameError),
}

impl std::fmt::Display for DaemonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "IO error on client session: {e}"),
            Self::Frame(e) => write!(f, "frame protocol error: {e}"),
        }
    }
}

impl std::error::Error for DaemonError {}

impl From<std::io::Error> for DaemonError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

#[cfg(all(test, unix))]
#[allow(unsafe_code)]
mod tests {
    use super::*;
    use crate::vortix_core::engine::input::UserCommand;
    use crate::vortix_core::engine::state::Connection;
    use crate::vortix_core::profile::ProfileId;
    use tokio::net::UnixStream as TokioUnixStream;

    // ===== D1 dispatch tests =====

    #[tokio::test]
    async fn dispatch_execute_without_handle_returns_internal_error() {
        let req = IpcRequest {
            id: 1,
            op: IpcOp::Execute(UserCommand::Connect {
                profile_id: ProfileId::new("corp"),
            }),
        };
        let resp = dispatch(req, None).await;
        assert_eq!(resp.id, 1);
        match resp.result {
            Err(IpcError::Internal(msg)) => assert!(msg.contains("engine handle not initialized")),
            other => panic!("expected Internal error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn dispatch_snapshot_without_handle_returns_internal_error() {
        let req = IpcRequest {
            id: 2,
            op: IpcOp::Snapshot,
        };
        let resp = dispatch(req, None).await;
        assert_eq!(resp.id, 2);
        assert!(matches!(resp.result, Err(IpcError::Internal(_))));
    }

    #[tokio::test]
    async fn dispatch_subscribe_without_handle_returns_internal_error() {
        let req = IpcRequest {
            id: 3,
            op: IpcOp::Subscribe,
        };
        let resp = dispatch(req, None).await;
        assert_eq!(resp.id, 3);
        assert!(matches!(resp.result, Err(IpcError::Internal(_))));
    }

    #[tokio::test]
    async fn dispatch_shutdown_does_not_require_engine_handle() {
        let req = IpcRequest {
            id: 4,
            op: IpcOp::Shutdown,
        };
        let resp = dispatch(req, None).await;
        assert_eq!(resp.id, 4);
        assert!(matches!(resp.result, Ok(IpcResult::ShuttingDown)));
    }

    #[tokio::test]
    async fn dispatch_snapshot_with_handle_returns_disconnected_initially() {
        let handle = EngineHandle::for_test();
        let req = IpcRequest {
            id: 5,
            op: IpcOp::Snapshot,
        };
        let resp = dispatch(req, Some(&handle)).await;
        match resp.result {
            Ok(IpcResult::Snapshot { state }) => {
                assert!(matches!(state, Connection::Disconnected { .. }));
            }
            other => panic!("expected Snapshot, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn dispatch_execute_connect_with_handle_returns_accepted() {
        let handle = EngineHandle::for_test();
        let req = IpcRequest {
            id: 6,
            op: IpcOp::Execute(UserCommand::Connect {
                profile_id: ProfileId::new("corp"),
            }),
        };
        let resp = dispatch(req, Some(&handle)).await;
        assert!(matches!(resp.result, Ok(IpcResult::Accepted)));
    }

    #[tokio::test]
    async fn dispatch_subscribe_with_handle_returns_subscribed_ack() {
        let handle = EngineHandle::for_test();
        let req = IpcRequest {
            id: 7,
            op: IpcOp::Subscribe,
        };
        let resp = dispatch(req, Some(&handle)).await;
        assert!(matches!(resp.result, Ok(IpcResult::Subscribed)));
    }

    // ===== D2 peer-UID enforcement tests =====

    /// Helper: pick a unique temp socket path.
    fn fresh_socket_path() -> PathBuf {
        let mut p = std::env::temp_dir();
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        p.push(format!("vortix-test-{}-{nanos}.sock", std::process::id()));
        p
    }

    #[tokio::test]
    async fn peer_uid_matches_daemon_uid_for_same_process() {
        // Same-process connect: UID matches, dispatch fires normally.
        let socket = fresh_socket_path();
        let server = DaemonServer::bind(socket.clone()).expect("bind");
        let daemon_uid = server.daemon_uid();
        // SAFETY: trivial syscall, see DaemonServer::bind.
        let process_uid = unsafe { libc::geteuid() };
        assert_eq!(daemon_uid, process_uid, "daemon UID captured correctly");

        let handle = tokio::spawn(server.run());

        let mut client = loop {
            match TokioUnixStream::connect(&socket).await {
                Ok(s) => break s,
                Err(_) => tokio::time::sleep(std::time::Duration::from_millis(10)).await,
            }
        };

        // Shutdown is the simplest op — dispatched regardless of engine handle.
        let req = IpcRequest {
            id: 7,
            op: IpcOp::Shutdown,
        };
        let frame = encode_frame(&req).expect("encode");
        client.write_all(&frame).await.expect("write");

        let mut buf = vec![0u8; 4096];
        let n = client.read(&mut buf).await.expect("read");
        let (resp, _) = decode_frame::<IpcResponse>(&buf[..n])
            .expect("decode ok")
            .expect("complete frame");
        assert_eq!(resp.id, 7);
        assert!(matches!(resp.result, Ok(IpcResult::ShuttingDown)));

        handle.abort();
        let _ = std::fs::remove_file(&socket);
    }

    #[tokio::test]
    async fn unauthorized_path_emits_unauthorized_frame_without_dispatch() {
        // Force the rejection branch by passing a daemon_uid the
        // peer can never match (u32::MAX is never a real UID).
        let (server_end, mut client_end) = TokioUnixStream::pair().expect("socketpair");

        let fake_daemon_uid = u32::MAX;
        let server_task =
            tokio::spawn(async move { handle_client(server_end, fake_daemon_uid, None).await });

        let mut buf = vec![0u8; 4096];
        let n = client_end.read(&mut buf).await.expect("read");
        let (resp, _) = decode_frame::<IpcResponse>(&buf[..n])
            .expect("decode ok")
            .expect("complete frame");
        assert_eq!(resp.id, 0, "unauthorized frame uses id=0");
        assert!(matches!(resp.result, Err(IpcError::Unauthorized)));

        let outcome = server_task.await.expect("join");
        assert!(outcome.is_ok());
    }

    #[tokio::test]
    async fn get_peer_uid_returns_current_process_uid_on_socketpair() {
        let (a, _b) = TokioUnixStream::pair().expect("socketpair");
        let uid = get_peer_uid(&a).expect("peer uid lookup");
        // SAFETY: trivial syscall, see DaemonServer::bind.
        let me = unsafe { libc::geteuid() };
        assert_eq!(uid, me);
    }

    // ===== U22 multi-tunnel command dispatch =====

    #[tokio::test]
    async fn dispatch_execute_disconnect_all_routes_through_engine_handle() {
        let handle = EngineHandle::for_test();
        // Connect first so disconnect has something to act on.
        let connect_req = IpcRequest {
            id: 10,
            op: IpcOp::Execute(UserCommand::Connect {
                profile_id: ProfileId::new("corp"),
            }),
        };
        let _ = dispatch(connect_req, Some(&handle)).await;

        let req = IpcRequest {
            id: 11,
            op: IpcOp::Execute(UserCommand::Disconnect { profile_id: None }),
        };
        let resp = dispatch(req, Some(&handle)).await;
        assert_eq!(resp.id, 11);
        assert!(matches!(resp.result, Ok(IpcResult::Accepted)));
    }

    #[tokio::test]
    async fn dispatch_execute_disconnect_specific_routes_through_engine_handle() {
        let handle = EngineHandle::for_test();
        let req = IpcRequest {
            id: 12,
            op: IpcOp::Execute(UserCommand::Disconnect {
                profile_id: Some(ProfileId::new("corp")),
            }),
        };
        let resp = dispatch(req, Some(&handle)).await;
        assert!(matches!(resp.result, Ok(IpcResult::Accepted)));
    }

    #[tokio::test]
    async fn dispatch_execute_reconnect_all_routes_through_engine_handle() {
        let handle = EngineHandle::for_test();
        let req = IpcRequest {
            id: 13,
            op: IpcOp::Execute(UserCommand::Reconnect { profile_id: None }),
        };
        let resp = dispatch(req, Some(&handle)).await;
        assert!(matches!(resp.result, Ok(IpcResult::Accepted)));
    }

    #[tokio::test]
    async fn dispatch_execute_force_disconnect_specific_routes_through_engine_handle() {
        let handle = EngineHandle::for_test();
        let req = IpcRequest {
            id: 14,
            op: IpcOp::Execute(UserCommand::ForceDisconnect {
                profile_id: Some(ProfileId::new("corp")),
            }),
        };
        let resp = dispatch(req, Some(&handle)).await;
        assert!(matches!(resp.result, Ok(IpcResult::Accepted)));
    }

    #[test]
    fn v1_disconnect_unit_form_does_not_decode_against_v2_op() {
        // A v1 client sending `{"kind":"execute","Execute":"Disconnect"}`
        // (legacy unit-variant payload) must NOT silently mis-parse on
        // the v2 server. Verify against IpcOp::Execute(UserCommand) end
        // to end.
        let v1_envelope = r#"{"kind":"execute","Execute":"Disconnect"}"#;
        let parsed: Result<IpcOp, _> = serde_json::from_str(v1_envelope);
        assert!(
            parsed.is_err(),
            "v1 unit-variant Disconnect should be rejected by v2 IpcOp decoder, got {parsed:?}"
        );
    }

    #[test]
    fn v2_disconnect_struct_form_round_trips_through_ipc_op() {
        let op = IpcOp::Execute(UserCommand::Disconnect { profile_id: None });
        let json = serde_json::to_string(&op).expect("serialize");
        let back: IpcOp = serde_json::from_str(&json).expect("deserialize");
        match back {
            IpcOp::Execute(UserCommand::Disconnect { profile_id: None }) => {}
            other => panic!("v2 Disconnect{{None}} round-trip mismatch: {other:?}"),
        }
    }

    #[test]
    fn ipc_error_conflict_round_trips() {
        use crate::vortix_core::engine::registry::Conflict;
        let err = IpcError::Conflict {
            conflict: Conflict::DefaultRouteTakeover {
                current: ProfileId::new("corp"),
                new: ProfileId::new("home"),
            },
        };
        let json = serde_json::to_string(&err).expect("serialize");
        let back: IpcError = serde_json::from_str(&json).expect("deserialize");
        match back {
            IpcError::Conflict {
                conflict: Conflict::DefaultRouteTakeover { current, new },
            } => {
                assert_eq!(current.as_str(), "corp");
                assert_eq!(new.as_str(), "home");
            }
            other => panic!("expected Conflict round-trip, got {other:?}"),
        }
    }

    #[test]
    fn ipc_result_registry_snapshot_round_trips() {
        use crate::vortix_core::state::KillSwitchState;
        let r = IpcResult::RegistrySnapshot {
            tunnels: vec![],
            primary: None,
            killswitch: KillSwitchState::Disabled,
        };
        let json = serde_json::to_string(&r).expect("serialize");
        let back: IpcResult = serde_json::from_str(&json).expect("deserialize");
        match back {
            IpcResult::RegistrySnapshot {
                tunnels,
                primary,
                killswitch,
            } => {
                assert!(tunnels.is_empty());
                assert!(primary.is_none());
                assert_eq!(killswitch, KillSwitchState::Disabled);
            }
            other => panic!("expected RegistrySnapshot, got {other:?}"),
        }
    }
}