mxc-sdk 1.1.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Nonce-authenticated localhost control server for the state-aware daemon.
//!
//! Supports `PING`, `STOP`, and single-flight `EXEC`; each connection runs in
//! its own task so long executions do not block liveness or shutdown requests.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{Mutex, MutexGuard, Notify, Semaphore};
use tokio::time::{timeout, Instant};

use mxc_sdk::windows_sandbox_lifecycle::bridge::{
    host_watchdog_deadline, reconnect_data_streams, stream_exec_on_guest, write_exit_frame,
    GuestConnection, HOST_WATCHDOG_GRACE,
};
use mxc_sdk::windows_sandbox_lifecycle::control_plane::{
    parse_client_protocol, IPC_ERR, IPC_ERR_BUSY, IPC_ERR_NOT_READY, IPC_ERR_PROTOCOL, IPC_EXEC,
    IPC_PING, IPC_PROTOCOL_VERSION, IPC_STOP,
};
use mxc_sdk::windows_sandbox_lifecycle::ipc_exec;

use mxc_sdk::windows_sandbox_common::auth::Nonce as GuestNonce;

/// Maximum time to wait for a client request line.
const CLIENT_READ_TIMEOUT: Duration = Duration::from_secs(10);

/// Maximum time to wait for the framed `ExecStart` request after the `EXEC`
/// auth line.
const EXEC_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

/// Hard cap on the pre-auth request line length.
const MAX_AUTH_LINE_BYTES: u64 = 1024;

/// Bound on concurrent pre-auth client connections.
const MAX_CONCURRENT_PREAUTH: usize = 32;

/// Bounded wait for a pre-auth concurrency permit before dropping a connection.
const PREAUTH_PERMIT_WAIT: std::time::Duration = std::time::Duration::from_secs(5);

/// Monotonic source of per-exec correlation ids (unique within this daemon).
static EXEC_COUNTER: AtomicU64 = AtomicU64::new(0);

/// The daemon's single held guest connection.
pub enum GuestSlot {
    Booting,
    Ready {
        conn: GuestConnection,
        addr: std::net::SocketAddr,
    },
    /// The held guest connection was lost or left indeterminate by a failed
    /// exec or a post-exec data-stream reconnect. This is terminal for the
    /// sandbox's session: there is no path back to `Ready`, because the daemon
    /// cannot safely re-establish its single held guest connection mid-session.
    /// Every subsequent `EXEC` fails fast with the recorded reason; the caller
    /// must `stop`/`deprovision` and re-provision. `STOP`/teardown still work.
    Unusable(String),
}

struct ReleasedGuestSlot(());

fn restore_and_release_guest_slot(
    mut slot: MutexGuard<'_, GuestSlot>,
    next: GuestSlot,
) -> ReleasedGuestSlot {
    *slot = next;
    drop(slot);
    ReleasedGuestSlot(())
}

async fn write_released_exit_frame(
    writer: &mut tokio::net::tcp::OwnedWriteHalf,
    _released: ReleasedGuestSlot,
    exit_code: i32,
    error_message: &str,
) -> Result<bool> {
    write_exit_frame(writer, exit_code, error_message).await
}

impl std::fmt::Debug for GuestSlot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GuestSlot::Booting => write!(f, "Booting"),
            GuestSlot::Ready { addr, .. } => write!(f, "Ready {{ addr: {addr} }}"),
            GuestSlot::Unusable(reason) => write!(f, "Unusable({reason:?})"),
        }
    }
}

/// Pure admission decision for an incoming EXEC.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdmissionDecision {
    Admit,
    Busy,
    NotReady,
    Unusable(String),
}

/// Pure single-flight admission classifier. See [`AdmissionDecision`].
pub fn classify_admission(slot_state: &GuestSlot, slot_held_elsewhere: bool) -> AdmissionDecision {
    if slot_held_elsewhere {
        return AdmissionDecision::Busy;
    }
    match slot_state {
        GuestSlot::Ready { .. } => AdmissionDecision::Admit,
        GuestSlot::Booting => AdmissionDecision::NotReady,
        GuestSlot::Unusable(reason) => AdmissionDecision::Unusable(reason.clone()),
    }
}

/// Serve the control protocol until authenticated STOP/shutdown.
pub async fn run(
    listener: TcpListener,
    nonce: String,
    shutdown: Arc<Notify>,
    guest: Arc<Mutex<GuestSlot>>,
    guest_nonce: Arc<GuestNonce>,
) -> Result<()> {
    let nonce = Arc::new(nonce);
    let preauth_permits = Arc::new(Semaphore::new(MAX_CONCURRENT_PREAUTH));
    loop {
        tokio::select! {
            accepted = listener.accept() => {
                let (stream, peer) = match accepted {
                    Ok(sp) => sp,
                    Err(e) => {
                        // A transient accept() failure (e.g. a client that reset
                        // between the kernel completing the connection and our
                        // accept, or a momentary resource shortage) must not tear
                        // down the IPC server and, with it, the running sandbox.
                        // Log and keep serving; an authenticated STOP is the only
                        // intended way out of this loop.
                        eprintln!(
                            "[wsb-daemon] transient IPC accept error (continuing): {e:#}"
                        );
                        continue;
                    }
                };
                let permits = preauth_permits.clone();
                let acquire_result = tokio::time::timeout(
                    PREAUTH_PERMIT_WAIT,
                    permits.acquire_owned(),
                )
                .await;
                let permit = match acquire_result {
                    Ok(Ok(p)) => p,
                    Ok(Err(_)) => {
                        // Semaphore::acquire_owned only Errs on closed,
                        // which we never do.
                        eprintln!(
                            "[wsb-daemon] BUG: pre-auth semaphore closed; dropping {peer}"
                        );
                        drop(stream);
                        continue;
                    }
                    Err(_) => {
                        eprintln!(
                            "[wsb-daemon] pre-auth slot wait timed out after {:?}; dropping \
                             incoming IPC client {peer} ({MAX_CONCURRENT_PREAUTH} concurrent \
                             pre-auth tasks still in flight)",
                            PREAUTH_PERMIT_WAIT
                        );
                        drop(stream);
                        continue;
                    }
                };
                let nonce = nonce.clone();
                let guest = guest.clone();
                let shutdown = shutdown.clone();
                let guest_nonce = guest_nonce.clone();
                tokio::spawn(async move {
                    if let Err(e) = handle_client(stream, &nonce, &guest, &shutdown, &guest_nonce, permit).await {
                        eprintln!("[wsb-daemon] IPC client error: {e:#}");
                    }
                });
            }
            _ = shutdown.notified() => break,
        }
    }
    Ok(())
}

/// Read one request line, authenticate it, and dispatch on the verb.
async fn handle_client(
    stream: TcpStream,
    nonce: &str,
    guest: &Arc<Mutex<GuestSlot>>,
    shutdown: &Arc<Notify>,
    guest_nonce: &GuestNonce,
    permit: tokio::sync::OwnedSemaphorePermit,
) -> Result<()> {
    let (reader, mut writer) = stream.into_split();
    let mut reader = BufReader::new(reader);
    let mut line_bytes: Vec<u8> = Vec::with_capacity(128);
    let read_result = timeout(CLIENT_READ_TIMEOUT, async {
        let mut limited = (&mut reader).take(MAX_AUTH_LINE_BYTES);
        limited.read_until(b'\n', &mut line_bytes).await
    })
    .await
    .context("client read timed out")?
    .context("read client request")?;
    if read_result == 0 {
        return Ok(());
    }
    // A line that reached the cap without terminating with '\n' is treated as
    // malformed: do not waste the writer / a slot on it.
    let hit_cap = line_bytes.len() as u64 >= MAX_AUTH_LINE_BYTES && !line_bytes.ends_with(b"\n");
    if hit_cap {
        writer.write_all(b"ERR request too large\n").await.ok();
        return Ok(());
    }
    let line = match std::str::from_utf8(&line_bytes) {
        Ok(s) => s,
        Err(_) => {
            writer.write_all(b"ERR not utf8\n").await.ok();
            return Ok(());
        }
    };

    let trimmed = line.trim();
    // `EXEC` may carry a trailing IPC-protocol-version token: split into up to
    // three parts (verb, nonce, optional version). The nonce is a space-free
    // uuid, so it is always exactly the second token.
    let mut parts = trimmed.splitn(3, ' ');
    let verb = parts.next().unwrap_or("");
    let supplied = parts.next().unwrap_or("");
    let proto_token = parts.next().unwrap_or("");

    if supplied != nonce {
        writer.write_all(b"ERR auth\n").await.ok();
        return Ok(());
    }

    if verb == IPC_PING {
        writer.write_all(b"PONG\n").await.ok();
        Ok(())
    } else if verb == IPC_STOP {
        // Reply before notifying so the client sees the ack. STOP intentionally
        // never touches the guest mutex: shutdown must not be blocked by an
        // in-flight exec.
        writer.write_all(b"OK\n").await.ok();
        shutdown.notify_one();
        Ok(())
    } else if verb == IPC_EXEC {
        handle_exec(reader, writer, guest, guest_nonce, permit, proto_token).await
    } else {
        writer.write_all(b"ERR unknown command\n").await.ok();
        Ok(())
    }
}

/// Handle an `EXEC` after the auth line: read the framed [`ipc_exec::ExecStart`], acquire
/// the single-flight guest slot, emit a status line, and (on admission) stream
/// the guest's output back as [`ipc_exec`] frames.
async fn handle_exec(
    mut reader: BufReader<tokio::net::tcp::OwnedReadHalf>,
    mut writer: tokio::net::tcp::OwnedWriteHalf,
    guest: &Arc<Mutex<GuestSlot>>,
    guest_nonce: &GuestNonce,
    permit: tokio::sync::OwnedSemaphorePermit,
    proto_token: &str,
) -> Result<()> {
    // Reject a wire-protocol mismatch before any frame I/O: a client from a
    // different mxc install may frame its `ExecStart` differently, so we must
    // not parse it. An absent token is a pre-versioning client (legacy version).
    match parse_client_protocol(proto_token) {
        Some(v) if v == IPC_PROTOCOL_VERSION => {}
        Some(v) => {
            writer
                .write_all(
                    format!(
                        "{IPC_ERR} {IPC_ERR_PROTOCOL} client v{v} != daemon v{IPC_PROTOCOL_VERSION}\n"
                    )
                    .as_bytes(),
                )
                .await
                .ok();
            return Ok(());
        }
        None => {
            writer
                .write_all(
                    format!("{IPC_ERR} {IPC_ERR_PROTOCOL} malformed version token\n").as_bytes(),
                )
                .await
                .ok();
            return Ok(());
        }
    }

    let req = match timeout(
        EXEC_REQUEST_TIMEOUT,
        ipc_exec::read_exec_start_async(&mut reader),
    )
    .await
    {
        Ok(Ok(req)) => req,
        Ok(Err(e)) => {
            writer
                .write_all(format!("{IPC_ERR} bad request: {e}\n").as_bytes())
                .await
                .ok();
            return Ok(());
        }
        Err(_) => {
            writer
                .write_all(format!("{IPC_ERR} request timed out\n").as_bytes())
                .await
                .ok();
            return Ok(());
        }
    };

    let slot_guard = guest.try_lock();
    let decision = match &slot_guard {
        Ok(slot) => classify_admission(slot, false),
        Err(_) => AdmissionDecision::Busy,
    };
    match decision {
        AdmissionDecision::Busy => {
            writer
                .write_all(format!("{IPC_ERR} {IPC_ERR_BUSY}\n").as_bytes())
                .await
                .ok();
            return Ok(());
        }
        AdmissionDecision::NotReady => {
            writer
                .write_all(format!("{IPC_ERR} {IPC_ERR_NOT_READY}\n").as_bytes())
                .await
                .ok();
            return Ok(());
        }
        AdmissionDecision::Unusable(reason) => {
            writer
                .write_all(format!("{IPC_ERR} {reason}\n").as_bytes())
                .await
                .ok();
            return Ok(());
        }
        AdmissionDecision::Admit => {}
    }
    let mut slot = slot_guard.expect("slot_guard Ok matched on Admit branch");
    let taken = std::mem::replace(
        &mut *slot,
        GuestSlot::Unusable("exec interrupted".to_string()),
    );
    let (mut conn, addr) = match taken {
        GuestSlot::Ready { conn, addr } => (conn, addr),
        other => unreachable!(
            "classify_admission admitted a non-Ready slot variant: {:?}",
            other
        ),
    };

    if let Err(e) = writer.write_all(b"OK\n").await {
        // The client vanished before we ran anything; the guest is untouched,
        // so restore the slot as Ready for the next caller.
        *slot = GuestSlot::Ready { conn, addr };
        return Err(anyhow::Error::new(e).context("write OK status"));
    }

    drop(permit);

    let exec_id = format!("exec-{}", EXEC_COUNTER.fetch_add(1, Ordering::Relaxed));

    // Host-side watchdog: a frozen-but-alive guest (never sends Exit, never
    // closes its streams) would otherwise wedge the single-flight slot forever.
    // The deadline is honoured *inside* the relay loop at frame boundaries, so a
    // timeout can never truncate a data frame and desync the client's decode.
    // `None` == infinite budget (`timeout_ms == u32::MAX`), as in one-shot.
    let deadline =
        host_watchdog_deadline(req.timeout_ms, HOST_WATCHDOG_GRACE).map(|d| Instant::now() + d);
    let stream_result = stream_exec_on_guest(
        &mut conn,
        &exec_id,
        &req,
        &mut reader,
        &mut writer,
        deadline,
    )
    .await;
    match stream_result {
        Ok(outcome) if outcome.timed_out => {
            // Watchdog fired at a frame boundary: the guest connection is no
            // longer trustworthy, so mark the slot Unusable and hand the client
            // a clean terminal exit frame (no partial data frame precedes it).
            let msg = format!(
                "guest did not report completion within the host watchdog ({}ms guest \
                 timeout + {}s grace); the sandbox may be frozen",
                req.timeout_ms,
                HOST_WATCHDOG_GRACE.as_secs()
            );
            eprintln!("[wsb-daemon] exec {exec_id}: {msg}");
            let released = restore_and_release_guest_slot(slot, GuestSlot::Unusable(msg.clone()));
            if outcome.ipc_alive {
                if let Err(e) = write_released_exit_frame(&mut writer, released, -1, &msg).await {
                    eprintln!(
                        "[wsb-daemon] exec {exec_id}: failed to send watchdog exit frame: {e:#}"
                    );
                }
            } else {
                let _ = released;
            }
        }
        Ok(outcome) => {
            let reconnect =
                reconnect_data_streams(&mut conn, addr, outcome.control_residual, guest_nonce)
                    .await;
            let next_slot = match &reconnect {
                Ok(()) => GuestSlot::Ready { conn, addr },
                Err(e) => GuestSlot::Unusable(format!("stream reconnect failed: {e}")),
            };
            let released = restore_and_release_guest_slot(slot, next_slot);

            if outcome.ipc_alive {
                match write_released_exit_frame(
                    &mut writer,
                    released,
                    outcome.exit_code,
                    &outcome.error_message,
                )
                .await
                {
                    Ok(true) => {}
                    Ok(false) => eprintln!(
                        "[wsb-daemon] exec {exec_id}: client disconnected before exit frame"
                    ),
                    Err(e) => {
                        eprintln!("[wsb-daemon] exec {exec_id}: failed to encode exit frame: {e:#}")
                    }
                }
            } else {
                eprintln!(
                    "[wsb-daemon] exec {exec_id}: client disconnected mid-stream; guest reused"
                );
                let _ = released;
            }

            if let Err(e) = reconnect {
                eprintln!(
                    "[wsb-daemon] exec {exec_id}: completed (exit {}); stream reconnect failed, \
                     sandbox left unusable for future execs: {e:#}",
                    outcome.exit_code
                );
            }
        }
        Err(e) => {
            *slot = GuestSlot::Unusable(format!("exec failed: {e}"));
            eprintln!("[wsb-daemon] exec {exec_id}: failed: {e:#}");
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use mxc_sdk::windows_sandbox_common::auth::generate_nonce;
    use mxc_sdk::windows_sandbox_lifecycle::ipc_exec::ExecStart;
    use std::net::SocketAddr;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener as TokioTcpListener;

    #[tokio::test]
    async fn released_guest_slot_is_unlocked() {
        let guest = Mutex::new(GuestSlot::Booting);
        let slot = guest.lock().await;

        let _released =
            restore_and_release_guest_slot(slot, GuestSlot::Unusable("test".to_string()));

        assert!(guest.try_lock().is_ok());
    }

    // ===== pure single-flight admission classifier tests ====================

    #[test]
    fn classify_busy_when_lock_held_elsewhere_beats_any_state() {
        // The Busy branch must fire even when the slot itself is Ready /
        // Booting / Unusable. Verified for every variant we can build
        // (Booting and Unusable; Ready needs live sockets, see ready_slot
        // comment).
        assert_eq!(
            classify_admission(&GuestSlot::Booting, true),
            AdmissionDecision::Busy
        );
        assert_eq!(
            classify_admission(&GuestSlot::Unusable("anything".into()), true),
            AdmissionDecision::Busy
        );
    }

    #[test]
    fn classify_booting_yields_not_ready() {
        assert_eq!(
            classify_admission(&GuestSlot::Booting, false),
            AdmissionDecision::NotReady
        );
    }

    #[test]
    fn classify_unusable_propagates_reason_verbatim() {
        let decision = classify_admission(
            &GuestSlot::Unusable("stream reconnect failed: timeout".to_string()),
            false,
        );
        assert_eq!(
            decision,
            AdmissionDecision::Unusable("stream reconnect failed: timeout".to_string())
        );
    }

    #[test]
    fn classify_unusable_does_not_admit_even_with_empty_reason() {
        let decision = classify_admission(&GuestSlot::Unusable(String::new()), false);
        match decision {
            AdmissionDecision::Unusable(r) => assert_eq!(r, ""),
            other => panic!("expected Unusable with empty reason, got {other:?}"),
        }
    }

    // ===== daemon control_server integration tests ===========================
    //
    // These spin up `control_server::run` against an in-process tokio
    // TcpListener and drive it with handcrafted client connections so the
    // nonce auth / pre-auth bound / pre-auth concurrency / malformed-EXEC
    // surface is covered without the daemon binary, the guest agent, or a
    // real Windows Sandbox VM.
    //
    // We never put the guest slot into Ready (which would require live
    // sockets); EXEC tests therefore expect `ERR not ready` and assert that
    // admission ran on the right state.

    async fn bind_listener() -> (TokioTcpListener, SocketAddr) {
        let l = TokioTcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = l.local_addr().unwrap();
        (l, addr)
    }

    async fn read_to_string(stream: &mut tokio::net::TcpStream) -> String {
        let mut buf = Vec::new();
        let _ = tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut buf)).await;
        String::from_utf8(buf).unwrap_or_default()
    }

    /// Drive `run` in a background task with a freshly bound listener and a
    /// known nonce, then return the bound address plus a shutdown notify the
    /// caller can use to stop the server when the test is done.
    async fn spawn_test_server(
        starting_slot: GuestSlot,
    ) -> (SocketAddr, Arc<Notify>, tokio::task::JoinHandle<Result<()>>) {
        let (listener, addr) = bind_listener().await;
        let nonce = "test-nonce-deadbeef".to_string();
        let shutdown = Arc::new(Notify::new());
        let guest = Arc::new(Mutex::new(starting_slot));
        let guest_nonce = Arc::new(generate_nonce().expect("generate nonce"));
        let server_shutdown = shutdown.clone();
        let handle =
            tokio::spawn(
                async move { run(listener, nonce, server_shutdown, guest, guest_nonce).await },
            );
        // No sleep needed here. `TcpListener::bind` has already
        // succeeded synchronously on `127.0.0.1:0`; the OS keeps incoming
        // SYNs in the listen backlog (default ~128) until the spawned
        // `run` task calls `accept`, so the test's first
        // `TcpStream::connect` cannot race the accept loop -- it
        // succeeds at the TCP layer either way and gets serviced as
        // soon as the accept catches up.
        (addr, shutdown, handle)
    }

    #[tokio::test]
    async fn ping_with_correct_nonce_yields_pong() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(b"PING test-nonce-deadbeef\n").await.unwrap();
        s.shutdown().await.ok();
        assert_eq!(read_to_string(&mut s).await, "PONG\n");

        shutdown.notify_one();
        // Server may keep running until next accept; give it a chance to exit.
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn missing_nonce_yields_err_auth() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        // No nonce after the verb.
        s.write_all(b"PING\n").await.unwrap();
        s.shutdown().await.ok();
        assert_eq!(read_to_string(&mut s).await, "ERR auth\n");

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn bad_nonce_yields_err_auth() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(b"PING wrong-nonce\n").await.unwrap();
        s.shutdown().await.ok();
        assert_eq!(read_to_string(&mut s).await, "ERR auth\n");

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn oversized_pre_auth_line_yields_err_request_too_large() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        // Write 2 KiB without a newline - exceeds MAX_AUTH_LINE_BYTES (1024).
        // The daemon should respond with the bounded-read rejection and close.
        let payload = vec![b'A'; (MAX_AUTH_LINE_BYTES as usize) * 2];
        s.write_all(&payload).await.unwrap();
        s.shutdown().await.ok();
        let resp = read_to_string(&mut s).await;
        assert_eq!(
            resp, "ERR request too large\n",
            "expected bounded-read rejection; got {resp:?}"
        );

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn unknown_verb_yields_err_unknown_command() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(b"WHATEVER test-nonce-deadbeef\n")
            .await
            .unwrap();
        s.shutdown().await.ok();
        assert_eq!(read_to_string(&mut s).await, "ERR unknown command\n");

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn exec_against_booting_slot_yields_err_not_ready() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        // Send the auth line, then a valid ExecStart frame. The server's
        // admission classifier sees GuestSlot::Booting and must respond with
        // `ERR not ready` after consuming the request frame.
        s.write_all(b"EXEC test-nonce-deadbeef\n").await.unwrap();
        let start = ExecStart {
            script_code: "echo hi".to_string(),
            working_directory: String::new(),
            timeout_ms: 5_000,
        };
        let bytes = ipc_exec::encode_exec_start(&start).unwrap();
        s.write_all(&bytes).await.unwrap();
        s.shutdown().await.ok();
        let resp = read_to_string(&mut s).await;
        assert_eq!(
            resp,
            format!("{IPC_ERR} {IPC_ERR_NOT_READY}\n"),
            "got {resp:?}"
        );

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn exec_against_unusable_slot_propagates_reason() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Unusable(
            "stream reconnect failed: synthetic".to_string(),
        ))
        .await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(b"EXEC test-nonce-deadbeef\n").await.unwrap();
        let start = ExecStart {
            script_code: "echo hi".to_string(),
            working_directory: String::new(),
            timeout_ms: 5_000,
        };
        let bytes = ipc_exec::encode_exec_start(&start).unwrap();
        s.write_all(&bytes).await.unwrap();
        s.shutdown().await.ok();
        let resp = read_to_string(&mut s).await;
        assert_eq!(
            resp,
            format!("{IPC_ERR} stream reconnect failed: synthetic\n"),
            "got {resp:?}"
        );

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn malformed_exec_frame_yields_err_bad_request() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(b"EXEC test-nonce-deadbeef\n").await.unwrap();
        // Send a bogus length prefix that's not followed by valid JSON.
        // The length is well under MAX_IPC_FRAME so the daemon won't reject
        // on size; instead it should fail to decode the JSON and reply with
        // `ERR bad request: ...`.
        s.write_all(&5u32.to_le_bytes()).await.unwrap();
        s.write_all(b"badjs").await.unwrap();
        s.shutdown().await.ok();
        let resp = read_to_string(&mut s).await;
        assert!(
            resp.starts_with(&format!("{IPC_ERR} bad request:")),
            "expected ERR bad request prefix, got {resp:?}"
        );

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn exec_with_matching_protocol_version_reaches_admission() {
        // An explicit version token equal to the daemon's passes the handshake,
        // so admission runs and (against Booting) yields `ERR not ready`.
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(format!("EXEC test-nonce-deadbeef {IPC_PROTOCOL_VERSION}\n").as_bytes())
            .await
            .unwrap();
        let start = ExecStart {
            script_code: "echo hi".to_string(),
            working_directory: String::new(),
            timeout_ms: 5_000,
        };
        s.write_all(&ipc_exec::encode_exec_start(&start).unwrap())
            .await
            .unwrap();
        s.shutdown().await.ok();
        let resp = read_to_string(&mut s).await;
        assert_eq!(
            resp,
            format!("{IPC_ERR} {IPC_ERR_NOT_READY}\n"),
            "got {resp:?}"
        );

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn exec_with_mismatched_protocol_version_yields_err_protocol() {
        // A version the daemon does not speak is refused before any frame I/O.
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mismatch = IPC_PROTOCOL_VERSION + 1;
        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(format!("EXEC test-nonce-deadbeef {mismatch}\n").as_bytes())
            .await
            .unwrap();
        s.shutdown().await.ok();
        let resp = read_to_string(&mut s).await;
        assert_eq!(
            resp,
            format!(
                "{IPC_ERR} {IPC_ERR_PROTOCOL} client v{mismatch} != daemon v{IPC_PROTOCOL_VERSION}\n"
            ),
            "got {resp:?}"
        );

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn exec_with_malformed_protocol_token_yields_err_protocol() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(b"EXEC test-nonce-deadbeef notanumber\n")
            .await
            .unwrap();
        s.shutdown().await.ok();
        let resp = read_to_string(&mut s).await;
        assert_eq!(
            resp,
            format!("{IPC_ERR} {IPC_ERR_PROTOCOL} malformed version token\n"),
            "got {resp:?}"
        );

        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test]
    async fn stop_with_correct_nonce_replies_ok_and_shuts_down() {
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(b"STOP test-nonce-deadbeef\n").await.unwrap();
        s.shutdown().await.ok();
        assert_eq!(read_to_string(&mut s).await, "OK\n");

        // STOP fires the shutdown notify; server loop should exit
        // promptly without needing our manual notify.
        let result = tokio::time::timeout(Duration::from_secs(5), handle)
            .await
            .expect("server should exit within timeout after STOP");
        result.expect("join").expect("server returned Ok");
        let _ = shutdown;
    }

    #[tokio::test]
    async fn concurrent_exec_returns_err_busy() {
        // Drive two concurrent EXECs against a Booting slot. The slot mutex
        // is contended only during admission; even with Booting, the
        // try_lock pattern means we cannot reliably produce a `Busy` from
        // the outside without a Ready slot whose handler holds the lock for
        // a long time.
        //
        // Instead we hand-test the busy path by holding the mutex from a
        // separate task before sending the EXEC. The classifier sees
        // slot_held_elsewhere=true and returns Busy regardless of state.
        let (listener, addr) = bind_listener().await;
        let nonce = "test-nonce-deadbeef".to_string();
        let shutdown = Arc::new(Notify::new());
        let guest = Arc::new(Mutex::new(GuestSlot::Booting));
        let guest_nonce = Arc::new(generate_nonce().expect("generate nonce"));

        // Hold the mutex from this test thread so the EXEC handler's
        // try_lock fails. Use the same Arc so the contention is real.
        let holder = guest.clone();
        let server_shutdown = shutdown.clone();
        let handle =
            tokio::spawn(
                async move { run(listener, nonce, server_shutdown, guest, guest_nonce).await },
            );
        // Same reasoning as the spawn_test_server helper above:
        // the OS TCP backlog already absorbs the immediate connect, so
        // we don't need to give the spawned `run` task a head start.

        // Acquire the slot lock and HOLD it for the duration of the EXEC.
        let _held = holder.lock().await;

        let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
        s.write_all(b"EXEC test-nonce-deadbeef\n").await.unwrap();
        let start = ExecStart {
            script_code: "echo hi".to_string(),
            working_directory: String::new(),
            timeout_ms: 5_000,
        };
        let bytes = ipc_exec::encode_exec_start(&start).unwrap();
        s.write_all(&bytes).await.unwrap();
        s.shutdown().await.ok();
        let resp = read_to_string(&mut s).await;
        assert_eq!(
            resp,
            format!("{IPC_ERR} {IPC_ERR_BUSY}\n"),
            "expected ERR busy when slot is held elsewhere; got {resp:?}"
        );

        drop(_held);
        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
    }

    #[tokio::test(start_paused = true)]
    async fn pre_auth_concurrency_cap_drops_after_wait_timeout() {
        // Saturate MAX_CONCURRENT_PREAUTH (32) slots with slow-loris clients
        // that never send a newline, then attempt one more connection. The
        // 33rd connection now waits up to PREAUTH_PERMIT_WAIT for a permit
        // instead of being dropped instantly; under the saturating fixture the
        // wait elapses and the daemon drops the excess. Fast-forwards
        // virtual time so the test stays sub-second despite the 5s
        // production wait.
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        // Open MAX_CONCURRENT_PREAUTH slow-loris connections and hold them.
        let mut held: Vec<tokio::net::TcpStream> = Vec::new();
        for _ in 0..MAX_CONCURRENT_PREAUTH {
            let s = tokio::net::TcpStream::connect(addr).await.unwrap();
            held.push(s);
        }

        // Yield to let the daemon spin up handler tasks for all 32.
        tokio::task::yield_now().await;

        // The 33rd connection sits on `acquire_owned()` because all
        // permits are held. Connect, then advance virtual time past
        // PREAUTH_PERMIT_WAIT and read to EOF -- the daemon should drop
        // the socket once the wait timeout fires.
        let mut excess = tokio::net::TcpStream::connect(addr).await.unwrap();
        // Bump time a small amount past the production wait.
        tokio::time::advance(PREAUTH_PERMIT_WAIT + Duration::from_millis(100)).await;
        let resp = read_to_string(&mut excess).await;
        assert_eq!(
            resp, "",
            "excess connection should be dropped after PREAUTH_PERMIT_WAIT; got {resp:?}"
        );

        drop(held);
        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(5), handle).await;
    }

    #[tokio::test(start_paused = true)]
    async fn pre_auth_burst_within_wait_window_succeeds() {
        // Regression coverage: a brief burst that briefly exceeds
        // MAX_CONCURRENT_PREAUTH must NOT surface as a backend error. The
        // 33rd connection waits up to PREAUTH_PERMIT_WAIT; if even a
        // single held connection is released within that window, the 33rd
        // wins a permit and the daemon proceeds with the auth read
        // instead of dropping. We assert "proceeds" by sending a verb-less
        // line and observing the daemon's `ERR unknown` reply; an instant-drop
        // would instead close the socket silently (empty read).
        let (addr, shutdown, handle) = spawn_test_server(GuestSlot::Booting).await;

        // Saturate the cap with slow-loris clients we *will* release.
        let mut held: Vec<tokio::net::TcpStream> = Vec::new();
        for _ in 0..MAX_CONCURRENT_PREAUTH {
            held.push(tokio::net::TcpStream::connect(addr).await.unwrap());
        }
        tokio::task::yield_now().await;

        let mut excess = tokio::net::TcpStream::connect(addr).await.unwrap();
        // Release one held connection well inside the wait window. The
        // dropped TcpStream causes the daemon-side handle_client task to
        // return, which releases its permit; the 33rd connection's
        // acquire_owned() then completes and handle_client runs.
        tokio::time::advance(Duration::from_millis(50)).await;
        held.pop();
        // Yield repeatedly so the daemon's released-permit -> excess-wakes
        // chain has time to schedule under paused time.
        for _ in 0..10 {
            tokio::task::yield_now().await;
        }

        // Send a verb-less line so the daemon's auth-first guard
        // dispatches and replies with ERR unknown. (The point is just
        // that *something* came back -- the connection was not silently
        // dropped.)
        excess
            .write_all(b"junkverb fake-nonce\n")
            .await
            .expect("write should succeed once handler is reading");
        excess.shutdown().await.ok();
        let resp = read_to_string(&mut excess).await;
        assert!(
            !resp.is_empty(),
            "burst within wait window must reach the daemon's auth path, got empty (= silent drop)"
        );

        drop(held);
        shutdown.notify_one();
        let _ = tokio::time::timeout(Duration::from_secs(5), handle).await;
    }
}
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.