hardware-enclave 0.2.2

Hardware-backed key management — macOS Secure Enclave, Windows TPM 2.0, Linux TPM/keyring — plus in-process memory protection
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
#![allow(dead_code, unused_imports, unused_qualifications, unreachable_patterns)]
//! Timeout utilities for subprocess execution and blocking reads.
//!
//! Cross-platform helpers to prevent enclave apps from hanging on
//! unresponsive subprocesses, bridge calls, or slow OS operations.

use std::io::{self, BufRead, BufReader, Read};
use std::process::{Child, ExitStatus, Output, Stdio};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};

/// Result of a bounded subprocess operation.
#[derive(Debug)]
pub enum TimeoutResult<T> {
    /// Operation completed within the deadline.
    Completed(T),
    /// Operation exceeded the deadline and the child was killed.
    TimedOut,
}

impl<T> TimeoutResult<T> {
    pub fn into_option(self) -> Option<T> {
        match self {
            TimeoutResult::Completed(v) => Some(v),
            TimeoutResult::TimedOut => None,
        }
    }

    pub fn is_timed_out(&self) -> bool {
        matches!(self, TimeoutResult::TimedOut)
    }
}

/// Poll interval for `try_wait`-based timeout loops.
const POLL_INTERVAL: Duration = Duration::from_millis(50);

/// Wait for a child process to exit, or return `TimedOut` after `timeout`
/// elapses. On timeout, the caller is responsible for killing the child.
pub fn wait_with_timeout(
    child: &mut Child,
    timeout: Duration,
) -> io::Result<TimeoutResult<ExitStatus>> {
    let start = Instant::now();
    loop {
        match child.try_wait()? {
            Some(status) => return Ok(TimeoutResult::Completed(status)),
            None => {
                if start.elapsed() >= timeout {
                    return Ok(TimeoutResult::TimedOut);
                }
                thread::sleep(POLL_INTERVAL);
            }
        }
    }
}

/// Run a child to completion, collecting stdout/stderr, bounded by `timeout`.
/// On timeout the child is killed and `TimedOut` is returned.
///
/// The child must already be configured via `.stdout(Stdio::piped())` etc.
/// if you want to capture output.
pub fn wait_output_with_timeout(
    mut child: Child,
    timeout: Duration,
) -> io::Result<TimeoutResult<Output>> {
    // Drain stdout/stderr on threads so the child's OS pipe buffers don't
    // fill up and deadlock before we hit the timeout.
    let stdout_thread = child.stdout.take().map(|mut s| {
        thread::Builder::new()
            .name("enclaveapp-child-stdout".into())
            .spawn(move || -> io::Result<Vec<u8>> {
                let mut buf = Vec::new();
                s.read_to_end(&mut buf)?;
                Ok(buf)
            })
    });
    let stderr_thread = child.stderr.take().map(|mut s| {
        thread::Builder::new()
            .name("enclaveapp-child-stderr".into())
            .spawn(move || -> io::Result<Vec<u8>> {
                let mut buf = Vec::new();
                s.read_to_end(&mut buf)?;
                Ok(buf)
            })
    });

    match wait_with_timeout(&mut child, timeout)? {
        TimeoutResult::Completed(status) => {
            let stdout = match stdout_thread {
                Some(Ok(t)) => t.join().unwrap_or_else(|_| Ok(Vec::new()))?,
                _ => Vec::new(),
            };
            let stderr = match stderr_thread {
                Some(Ok(t)) => t.join().unwrap_or_else(|_| Ok(Vec::new()))?,
                _ => Vec::new(),
            };
            Ok(TimeoutResult::Completed(Output {
                status,
                stdout,
                stderr,
            }))
        }
        TimeoutResult::TimedOut => {
            drop(child.kill());
            drop(child.wait());
            Ok(TimeoutResult::TimedOut)
        }
    }
}

/// Spawn a command with piped stdout/stderr and run it to completion
/// bounded by `timeout`.
pub fn run_with_timeout(
    mut cmd: std::process::Command,
    timeout: Duration,
) -> io::Result<TimeoutResult<Output>> {
    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
    let child = cmd.spawn()?;
    wait_output_with_timeout(child, timeout)
}

/// Spawn a command (inheriting stdout/stderr) and wait for its exit status
/// bounded by `timeout`. Kills the child on timeout.
pub fn run_status_with_timeout(
    mut cmd: std::process::Command,
    timeout: Duration,
) -> io::Result<TimeoutResult<ExitStatus>> {
    let mut child = cmd.spawn()?;
    match wait_with_timeout(&mut child, timeout)? {
        TimeoutResult::Completed(status) => Ok(TimeoutResult::Completed(status)),
        TimeoutResult::TimedOut => {
            drop(child.kill());
            drop(child.wait());
            Ok(TimeoutResult::TimedOut)
        }
    }
}

/// Blocking reader of `read_line` with a timeout. Spawns a worker thread
/// that owns the reader and sends each line over a channel.
///
/// The worker continues reading until EOF/error and cannot be cancelled
/// once started — intended for cases where the reader is owned by the
/// caller for the remainder of the session.
#[derive(Debug)]
pub struct LineReaderWithTimeout {
    rx: mpsc::Receiver<io::Result<String>>,
    _thread: thread::JoinHandle<()>,
}

impl LineReaderWithTimeout {
    /// Build a line reader with no per-line size cap. The worker reads
    /// until a newline regardless of length — only suitable for
    /// readers under our own control. Untrusted-peer cases (the WSL
    /// bridge, anything across a process boundary) should use
    /// [`Self::with_max_line_bytes`] so a malicious or malfunctioning
    /// peer can't drive unbounded heap allocation.
    pub fn new<R: Read + Send + 'static>(reader: R) -> Self {
        Self::spawn(reader, None)
    }

    /// Build a line reader that aborts (returns `InvalidData`) if a
    /// single line exceeds `max_line_bytes` before its terminating
    /// newline. Use this whenever the peer is across a trust boundary
    /// — it bounds the worst-case allocation per line at
    /// `max_line_bytes` rather than at the peer's discretion.
    pub fn with_max_line_bytes<R: Read + Send + 'static>(reader: R, max_line_bytes: usize) -> Self {
        Self::spawn(reader, Some(max_line_bytes))
    }

    fn spawn<R: Read + Send + 'static>(reader: R, max_line_bytes: Option<usize>) -> Self {
        let (tx, rx) = mpsc::channel();
        let thread = thread::Builder::new()
            .name("enclaveapp-line-reader".into())
            .spawn(move || {
                let mut buf_reader = BufReader::new(reader);
                loop {
                    let result = match max_line_bytes {
                        Some(max) => read_line_bounded(&mut buf_reader, max),
                        None => {
                            let mut line = String::new();
                            match buf_reader.read_line(&mut line) {
                                Ok(0) => Ok(None),
                                Ok(_) => Ok(Some(line)),
                                Err(e) => Err(e),
                            }
                        }
                    };
                    match result {
                        Ok(None) => break, // EOF
                        Ok(Some(line)) => {
                            if tx.send(Ok(line)).is_err() {
                                break;
                            }
                        }
                        Err(e) => {
                            drop(tx.send(Err(e)));
                            break;
                        }
                    }
                }
            })
            .expect("spawn line reader thread");
        Self {
            rx,
            _thread: thread,
        }
    }

    /// Receive the next line, or return `TimedOut` after `timeout`.
    /// Returns `Completed(Err(_))` on read error and `Completed(Ok(""))`
    /// on EOF.
    pub fn recv_line(&self, timeout: Duration) -> TimeoutResult<io::Result<String>> {
        match self.rx.recv_timeout(timeout) {
            Ok(result) => TimeoutResult::Completed(result),
            Err(mpsc::RecvTimeoutError::Timeout) => TimeoutResult::TimedOut,
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                TimeoutResult::Completed(Ok(String::new()))
            }
        }
    }
}

/// Read a single line into a `String`, returning `Ok(None)` on EOF
/// before any byte arrives, `Ok(Some(line))` when a newline is hit
/// (with the newline included, matching `BufRead::read_line`), or
/// `Err` if the line exceeds `max_bytes` before a newline. The cap
/// is on the line content excluding any oversize byte that wasn't
/// consumed.
///
/// Public so it can be exercised by fuzz harnesses; production
/// callers should normally use `LineReaderWithTimeout::with_max_line_bytes`
/// instead, which adds the timeout-aware worker thread on top.
pub fn read_line_bounded<R: BufRead>(
    reader: &mut R,
    max_bytes: usize,
) -> io::Result<Option<String>> {
    let mut buf: Vec<u8> = Vec::new();
    loop {
        let available = match reader.fill_buf() {
            Ok(b) => b,
            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(e),
        };
        if available.is_empty() {
            // EOF
            return if buf.is_empty() {
                Ok(None)
            } else {
                String::from_utf8(buf)
                    .map(Some)
                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
            };
        }
        // Up to `max_bytes` of remaining capacity, consume bytes
        // through the next newline if one exists in that slice.
        let remaining = max_bytes.saturating_sub(buf.len());
        let usable = &available[..available.len().min(remaining + 1)];
        if let Some(pos) = usable.iter().position(|&b| b == b'\n') {
            buf.extend_from_slice(&usable[..=pos]);
            reader.consume(pos + 1);
            return String::from_utf8(buf)
                .map(Some)
                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e));
        }
        // No newline in the usable slice. Either we have headroom
        // (remaining > 0) and just consume what we have, or we've
        // hit the cap with no newline — that's a hard error, and we
        // do NOT consume the offending bytes (so the caller could
        // resync if they had any way to, though in practice the
        // session is dead).
        if remaining == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("line exceeds {max_bytes}-byte cap before newline"),
            ));
        }
        let take = remaining.min(available.len());
        buf.extend_from_slice(&available[..take]);
        reader.consume(take);
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic)]
mod pure_tests {
    use super::*;
    use std::io::{self, Cursor};

    #[test]
    fn timeout_result_completed_into_option_is_some() {
        let r: TimeoutResult<i32> = TimeoutResult::Completed(42);
        assert_eq!(r.into_option(), Some(42));
    }

    #[test]
    fn timeout_result_timed_out_into_option_is_none() {
        let r: TimeoutResult<i32> = TimeoutResult::TimedOut;
        assert_eq!(r.into_option(), None);
    }

    #[test]
    fn timeout_result_completed_is_not_timed_out() {
        let r: TimeoutResult<i32> = TimeoutResult::Completed(1);
        assert!(!r.is_timed_out());
    }

    #[test]
    fn timeout_result_timed_out_is_timed_out() {
        let r: TimeoutResult<i32> = TimeoutResult::TimedOut;
        assert!(r.is_timed_out());
    }

    #[test]
    fn read_line_bounded_empty_reader_returns_none() {
        let mut cursor = Cursor::new(b"");
        let result = read_line_bounded(&mut cursor, 1024).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn read_line_bounded_single_line_with_newline() {
        let mut cursor = Cursor::new(b"hello\n");
        let result = read_line_bounded(&mut cursor, 1024).unwrap();
        assert_eq!(result.as_deref(), Some("hello\n"));
    }

    #[test]
    fn read_line_bounded_eof_without_newline() {
        let mut cursor = Cursor::new(b"hello");
        let result = read_line_bounded(&mut cursor, 1024).unwrap();
        assert_eq!(result.as_deref(), Some("hello"));
    }

    #[test]
    fn read_line_bounded_multiple_lines_reads_sequentially() {
        let mut cursor = Cursor::new(b"first\nsecond\n");
        let line1 = read_line_bounded(&mut cursor, 1024).unwrap();
        let line2 = read_line_bounded(&mut cursor, 1024).unwrap();
        let line3 = read_line_bounded(&mut cursor, 1024).unwrap();
        assert_eq!(line1.as_deref(), Some("first\n"));
        assert_eq!(line2.as_deref(), Some("second\n"));
        assert!(line3.is_none());
    }

    #[test]
    fn read_line_bounded_line_exceeds_cap_returns_invalid_data() {
        // 5 chars before the newline, cap is 3 → InvalidData
        let mut cursor = Cursor::new(b"hello\n");
        let err = read_line_bounded(&mut cursor, 3).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn read_line_bounded_line_at_exact_cap_succeeds() {
        // exactly 5 chars before newline, cap is 5 → Ok
        let mut cursor = Cursor::new(b"hello\n");
        let result = read_line_bounded(&mut cursor, 5).unwrap();
        assert_eq!(result.as_deref(), Some("hello\n"));
    }

    #[test]
    fn read_line_bounded_max_bytes_zero_newline_first_succeeds() {
        // cap=0, first byte is '\n' → consumed immediately → Ok("\n")
        let mut cursor = Cursor::new(b"\nhello");
        let result = read_line_bounded(&mut cursor, 0).unwrap();
        assert_eq!(result.as_deref(), Some("\n"));
    }

    #[test]
    fn read_line_bounded_max_bytes_zero_non_newline_first_is_error() {
        let mut cursor = Cursor::new(b"a\nhello");
        let err = read_line_bounded(&mut cursor, 0).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn read_line_bounded_utf8_content() {
        let input = "héllo\n";
        let mut cursor = Cursor::new(input.as_bytes());
        let result = read_line_bounded(&mut cursor, 128).unwrap();
        assert_eq!(result.as_deref(), Some("héllo\n"));
    }

    #[test]
    fn read_line_bounded_exactly_max_bytes_at_eof_no_newline() {
        let mut cursor = Cursor::new(b"abc");
        let result = read_line_bounded(&mut cursor, 3).unwrap();
        assert_eq!(result.as_deref(), Some("abc"));
    }

    #[test]
    fn read_line_bounded_large_cap_long_line() {
        let line: Vec<u8> = std::iter::repeat(b'x').take(100).chain([b'\n']).collect();
        let mut cursor = Cursor::new(line);
        let result = read_line_bounded(&mut cursor, 200).unwrap();
        let s = result.unwrap();
        assert_eq!(s.len(), 101);
        assert!(s.starts_with('x'));
        assert!(s.ends_with('\n'));
    }

    #[test]
    fn read_line_bounded_empty_line_newline_only() {
        let mut cursor = Cursor::new(b"\n");
        let result = read_line_bounded(&mut cursor, 1024).unwrap();
        assert_eq!(result.as_deref(), Some("\n"));
    }

    #[test]
    fn read_line_bounded_after_eof_returns_none() {
        let mut cursor = Cursor::new(b"hi\n");
        let _unused = read_line_bounded(&mut cursor, 1024).unwrap();
        let eof = read_line_bounded(&mut cursor, 1024).unwrap();
        assert!(eof.is_none());
    }

    #[test]
    fn read_line_bounded_only_newlines() {
        let mut cursor = Cursor::new(b"\n\n\n");
        let r1 = read_line_bounded(&mut cursor, 10).unwrap();
        let r2 = read_line_bounded(&mut cursor, 10).unwrap();
        let r3 = read_line_bounded(&mut cursor, 10).unwrap();
        let r4 = read_line_bounded(&mut cursor, 10).unwrap();
        assert_eq!(r1.as_deref(), Some("\n"));
        assert_eq!(r2.as_deref(), Some("\n"));
        assert_eq!(r3.as_deref(), Some("\n"));
        assert!(r4.is_none());
    }

    #[test]
    fn read_line_bounded_single_char_at_eof() {
        let mut cursor = Cursor::new(b"x");
        let result = read_line_bounded(&mut cursor, 1).unwrap();
        assert_eq!(result.as_deref(), Some("x"));
    }

    #[test]
    fn read_line_bounded_error_message_contains_cap() {
        let mut cursor = Cursor::new(b"toolongline\n");
        let err = read_line_bounded(&mut cursor, 5).unwrap_err();
        assert!(err.to_string().contains("5"));
    }
}

#[cfg(all(test, unix))]
#[allow(clippy::unwrap_used, clippy::panic, let_underscore_drop)]
mod tests {
    use super::*;
    use std::process::Command;

    #[cfg(unix)]
    #[test]
    fn run_with_timeout_completes_fast_command() {
        let result = run_with_timeout(
            {
                let mut c = Command::new("/bin/sh");
                c.args(["-c", "echo hello"]);
                c
            },
            Duration::from_secs(5),
        )
        .unwrap();
        match result {
            TimeoutResult::Completed(output) => {
                assert!(output.status.success());
                assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "hello");
            }
            TimeoutResult::TimedOut => panic!("fast command should not time out"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn run_with_timeout_kills_slow_command() {
        let start = Instant::now();
        let result = run_with_timeout(
            {
                let mut c = Command::new("/bin/sh");
                c.args(["-c", "sleep 10"]);
                c
            },
            Duration::from_millis(200),
        )
        .unwrap();
        assert!(result.is_timed_out());
        // Should fire well before the 10s sleep finishes
        assert!(start.elapsed() < Duration::from_secs(2));
    }

    #[cfg(unix)]
    #[test]
    fn line_reader_delivers_line_within_timeout() {
        use std::io::Write;
        let mut cmd = Command::new("/bin/sh");
        cmd.args(["-c", "cat"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped());
        let mut child = cmd.spawn().unwrap();
        let r = child.stdout.take().unwrap();
        let mut w = child.stdin.take().unwrap();
        let reader = LineReaderWithTimeout::new(r);
        writeln!(w, "hello world").unwrap();
        w.flush().unwrap();
        match reader.recv_line(Duration::from_secs(2)) {
            TimeoutResult::Completed(Ok(line)) => assert_eq!(line.trim(), "hello world"),
            other => panic!("unexpected result: {:?}", other),
        }
        // Close stdin so cat exits, then reap the child to avoid a zombie.
        drop(w);
        drop(child.wait());
    }

    #[cfg(unix)]
    #[test]
    fn bounded_line_reader_aborts_when_line_exceeds_cap() {
        // Feed 200 bytes followed by a newline through a bounded
        // reader with a 100-byte cap. The reader must surface an
        // InvalidData error rather than allocating the full 200.
        //
        // Use `seq 1 200 | xargs printf 'x%.0s'` rather than bash
        // brace expansion (`{1..200}`). `/bin/sh` on Linux runners
        // is `dash`, which doesn't expand `{1..200}` and produces a
        // single `x` — leading to a flaky pass on macOS (where
        // `/bin/sh` is bash) and a hard fail on the Linux CI runner.
        use std::io::Write;
        let mut cmd = Command::new("/bin/sh");
        cmd.args(["-c", "seq 1 200 | xargs printf 'x%.0s' && printf '\\n'"])
            .stdin(Stdio::null())
            .stdout(Stdio::piped());
        let mut child = cmd.spawn().unwrap();
        let stdout = child.stdout.take().unwrap();
        let reader = LineReaderWithTimeout::with_max_line_bytes(stdout, 100);
        match reader.recv_line(Duration::from_secs(2)) {
            TimeoutResult::Completed(Err(e)) => {
                assert_eq!(e.kind(), io::ErrorKind::InvalidData);
            }
            other => panic!("expected InvalidData, got: {:?}", other),
        }
        drop(child.kill());
        drop(child.wait());
        let _ = Write::flush(&mut io::stdout());
    }

    #[cfg(unix)]
    #[test]
    fn bounded_line_reader_accepts_line_within_cap() {
        use std::io::Write;
        let mut cmd = Command::new("/bin/sh");
        cmd.args(["-c", "printf 'short line\\n'"])
            .stdin(Stdio::null())
            .stdout(Stdio::piped());
        let mut child = cmd.spawn().unwrap();
        let stdout = child.stdout.take().unwrap();
        let reader = LineReaderWithTimeout::with_max_line_bytes(stdout, 1024);
        match reader.recv_line(Duration::from_secs(2)) {
            TimeoutResult::Completed(Ok(line)) => assert_eq!(line, "short line\n"),
            other => panic!("expected short line, got: {:?}", other),
        }
        drop(child.wait());
        let _ = Write::flush(&mut io::stdout());
    }

    #[cfg(unix)]
    #[test]
    fn line_reader_times_out_when_no_data() {
        let mut cmd = Command::new("/bin/sh");
        cmd.args(["-c", "sleep 10"]).stdout(Stdio::piped());
        let mut child = cmd.spawn().unwrap();
        let stdout = child.stdout.take().unwrap();
        let reader = LineReaderWithTimeout::new(stdout);
        let start = Instant::now();
        let result = reader.recv_line(Duration::from_millis(200));
        assert!(result.is_timed_out());
        assert!(start.elapsed() < Duration::from_secs(1));
        drop(child.kill());
        drop(child.wait());
    }

    #[cfg(unix)]
    #[test]
    fn run_status_with_timeout_completes_fast_command() {
        let mut cmd = Command::new("/bin/sh");
        cmd.args(["-c", "exit 0"]);
        let result = run_status_with_timeout(cmd, Duration::from_secs(5)).unwrap();
        match result {
            TimeoutResult::Completed(status) => assert!(status.success()),
            TimeoutResult::TimedOut => panic!("fast command should not time out"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn run_status_with_timeout_kills_slow_command() {
        let start = Instant::now();
        let mut cmd = Command::new("/bin/sh");
        cmd.args(["-c", "sleep 10"]);
        let result = run_status_with_timeout(cmd, Duration::from_millis(200)).unwrap();
        assert!(result.is_timed_out());
        assert!(start.elapsed() < Duration::from_secs(2));
    }

    #[test]
    fn line_reader_eof_disconnects_and_returns_empty_string() {
        // An immediately-empty reader causes the background thread to hit EOF
        // and exit, dropping the sender. The next recv_line must return
        // Completed(Ok("")) via the Disconnected arm rather than TimedOut.
        let reader = LineReaderWithTimeout::new(io::Cursor::new(b""));
        // Give the background thread time to reach EOF and exit.
        thread::sleep(Duration::from_millis(50));
        let result = reader.recv_line(Duration::from_millis(200));
        assert!(
            matches!(result, TimeoutResult::Completed(Ok(ref s)) if s.is_empty()),
            "expected Completed(Ok(\"\")) after sender disconnect, got: {result:?}"
        );
    }
}