dtshim 0.9.0

Run host commands from inside a Docker container: the in-container client
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
use std::{
    io::{self, BufReader, ErrorKind, Read, Write},
    net::Shutdown,
    process::ExitCode,
    sync::mpsc,
    thread,
};

use anyhow::{Context, Result, bail, ensure};
use dtshim_core::model::{Message, Start};

use crate::{
    codec::{read_message, write_message},
    socket::SessionSocket,
};

const SOCKET_BUFFER_LEN: usize = 16 * 1024;

pub(crate) fn run(stream: impl SessionSocket, start: Start) -> Result<ExitCode> {
    run_with_io(stream, start, io::stdin(), io::stdout(), io::stderr())
}

fn run_with_io(
    mut stream: impl SessionSocket,
    start: Start,
    stdin: impl Read + Send + 'static,
    stdout: impl Write,
    stderr: impl Write,
) -> Result<ExitCode> {
    let mut input = stream.try_clone().context("failed to clone socket")?;
    write_message(&mut stream, &Message::Start(start)).context("failed to send start message")?;

    let (input_error_tx, input_error_rx) = mpsc::channel();
    thread::Builder::new()
        .spawn(move || {
            if let Err(error) = send_input(&mut input, stdin) {
                let _ = input_error_tx.send(error);
                let _ = input.shutdown(Shutdown::Both);
            }
        })
        .context("failed to spawn stdin worker")?;

    let output = BufReader::with_capacity(SOCKET_BUFFER_LEN, stream);
    receive_output(output, stdout, stderr)
        .map_err(|output_error| input_error_rx.try_recv().unwrap_or(output_error))
}

fn send_input(socket: &mut impl Write, mut stdin: impl Read) -> Result<()> {
    let mut buf = [0; 8192];

    loop {
        let n = match stdin.read(&mut buf) {
            Err(error) if error.kind() == ErrorKind::Interrupted => continue,
            result => result.context("failed to read stdin")?,
        };

        match write_message(socket, &Message::Stdin(buf[..n].to_vec())) {
            Ok(()) if n > 0 => {}
            Ok(()) => return Ok(()),
            Err(error)
                if matches!(
                    error.kind(),
                    ErrorKind::BrokenPipe | ErrorKind::ConnectionReset
                ) =>
            {
                return Ok(());
            }
            Err(error) => return Err(error).context("failed to send stdin"),
        }
    }
}

fn receive_output(
    mut socket: impl Read,
    mut stdout: impl Write,
    mut stderr: impl Write,
) -> Result<ExitCode> {
    while let Some(message) =
        read_message(&mut socket).context("failed to receive server message")?
    {
        match message {
            Message::Stdout(data) => {
                stdout.write_all(&data).context("failed to write stdout")?;
                stdout.flush().context("failed to flush stdout")?;
            }
            Message::Stderr(data) => {
                stderr.write_all(&data).context("failed to write stderr")?;
                stderr.flush().context("failed to flush stderr")?;
            }
            Message::Code(code) => {
                let code = u8::try_from(code).context("invalid command exit code")?;
                return Ok(ExitCode::from(code));
            }
            Message::Signaled(signal) => {
                ensure!(
                    (1..128).contains(&signal),
                    "invalid termination signal: {signal}"
                );
                return Ok(ExitCode::from(128 + signal as u8));
            }
            Message::Failed(message) => bail!("command failed: {message}"),
            other @ (Message::Start(_) | Message::Stdin(_)) => {
                bail!("unexpected message from server: {other:?}")
            }
        }
    }

    bail!("server disconnected before sending command status")
}

#[cfg(test)]
mod tests {
    use std::{
        mem,
        net::{TcpListener, TcpStream},
        os::unix::net::UnixStream,
        sync::{Arc, Mutex},
        time::Duration,
    };

    use super::*;

    const TIMEOUT: Duration = Duration::from_secs(2);

    fn start() -> Start {
        Start {
            token: Some("secret".into()),
            command: "tool".into(),
            args: vec!["argument".into()],
            env: vec![("NAME".into(), "value".into())],
            cwd: "/work".into(),
        }
    }

    // The output and input halves, driven directly over recorded bytes.

    fn wire(messages: impl IntoIterator<Item = Message>) -> Vec<u8> {
        let mut wire = Vec::new();
        for message in messages {
            write_message(&mut wire, &message).unwrap();
        }
        wire
    }

    fn status(messages: impl IntoIterator<Item = Message>) -> Result<ExitCode> {
        receive_output(wire(messages).as_slice(), io::sink(), io::sink())
    }

    #[test]
    fn exit_codes_and_signals_are_validated() {
        for code in [0, 1, 255] {
            assert_eq!(
                status([Message::Code(code)]).unwrap(),
                ExitCode::from(code as u8)
            );
        }
        for code in [-1, 256, i32::MAX] {
            assert_eq!(
                status([Message::Code(code)]).unwrap_err().to_string(),
                "invalid command exit code"
            );
        }
        for signal in [1, 15, 127] {
            assert_eq!(
                status([Message::Signaled(signal)]).unwrap(),
                ExitCode::from(128 + signal as u8)
            );
        }
        for signal in [-1, 0, 128, i32::MAX] {
            assert_eq!(
                status([Message::Signaled(signal)]).unwrap_err().to_string(),
                format!("invalid termination signal: {signal}")
            );
        }
    }

    #[test]
    fn server_failures_unexpected_messages_and_early_disconnect_are_reported() {
        assert_eq!(
            status([Message::Failed("authentication failed".into())])
                .unwrap_err()
                .to_string(),
            "command failed: authentication failed"
        );
        for message in [Message::Start(start()), Message::Stdin(vec![])] {
            assert!(
                status([message])
                    .unwrap_err()
                    .to_string()
                    .starts_with("unexpected message from server:")
            );
        }
        assert_eq!(
            status([]).unwrap_err().to_string(),
            "server disconnected before sending command status"
        );
    }

    #[test]
    fn corrupt_server_frame_is_reported() {
        let error = receive_output(&[0, 0, 0, 1, 255][..], io::sink(), io::sink()).unwrap_err();
        assert_eq!(error.to_string(), "failed to receive server message");
    }

    struct FailedWriter {
        flush: bool,
    }

    impl Write for FailedWriter {
        fn write(&mut self, data: &[u8]) -> io::Result<usize> {
            if self.flush {
                Ok(data.len())
            } else {
                Err(io::Error::other("write failed"))
            }
        }

        fn flush(&mut self) -> io::Result<()> {
            Err(io::Error::other("flush failed"))
        }
    }

    #[test]
    fn output_write_and_flush_errors_identify_the_stream() {
        for (message, flush, expected) in [
            (Message::Stdout(vec![42]), false, "failed to write stdout"),
            (Message::Stdout(vec![42]), true, "failed to flush stdout"),
            (Message::Stderr(vec![42]), false, "failed to write stderr"),
            (Message::Stderr(vec![42]), true, "failed to flush stderr"),
        ] {
            let error = receive_output(
                wire([message]).as_slice(),
                FailedWriter { flush },
                FailedWriter { flush },
            )
            .unwrap_err();
            assert_eq!(error.to_string(), expected);
        }
    }

    struct BrokenSocket {
        kind: ErrorKind,
        attempts: usize,
    }

    impl Write for BrokenSocket {
        fn write(&mut self, _: &[u8]) -> io::Result<usize> {
            self.attempts += 1;
            Err(self.kind.into())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn stdin_forwarding_stops_quietly_once_the_server_stops_reading() {
        let input = [0; 20_000];
        for kind in [ErrorKind::BrokenPipe, ErrorKind::ConnectionReset] {
            let mut socket = BrokenSocket { kind, attempts: 0 };
            send_input(&mut socket, &input[..]).unwrap();
            assert_eq!(socket.attempts, 1, "{kind:?}");
        }
    }

    #[test]
    fn other_stdin_send_failures_are_errors() {
        let mut socket = BrokenSocket {
            kind: ErrorKind::Other,
            attempts: 0,
        };
        let error = send_input(&mut socket, &b"input"[..]).unwrap_err();
        assert_eq!(error.to_string(), "failed to send stdin");
    }

    // The whole session, over real sockets with a scripted server.

    fn socket_pair() -> (UnixStream, UnixStream) {
        let (client, server) = UnixStream::pair().unwrap();
        server.set_read_timeout(Some(TIMEOUT)).unwrap();
        server.set_write_timeout(Some(TIMEOUT)).unwrap();
        (client, server)
    }

    fn run_client(
        client: impl SessionSocket,
        stdin: impl Read + Send + 'static,
        stdout: impl Write + Send + 'static,
        stderr: impl Write + Send + 'static,
    ) -> Result<ExitCode> {
        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            let _ = tx.send(run_with_io(client, start(), stdin, stdout, stderr));
        });
        rx.recv_timeout(TIMEOUT)
            .expect("client session did not finish")
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum OutputStream {
        Stdout,
        Stderr,
    }

    type OutputLog = Arc<Mutex<Vec<(OutputStream, Vec<u8>)>>>;

    struct RecordingWriter {
        stream: OutputStream,
        data: Vec<u8>,
        log: OutputLog,
    }

    impl Write for RecordingWriter {
        fn write(&mut self, data: &[u8]) -> io::Result<usize> {
            let len = data.len().min(2);
            self.data.extend_from_slice(&data[..len]);
            Ok(len)
        }

        fn flush(&mut self) -> io::Result<()> {
            self.log
                .lock()
                .unwrap()
                .push((self.stream, mem::take(&mut self.data)));
            Ok(())
        }
    }

    #[test]
    fn forwards_start_stdin_eof_and_both_output_streams() {
        let (client, mut server) = socket_pair();
        let input = vec![0xff; 20_000];
        let expected_input = input.clone();
        let log = OutputLog::default();
        let stdout = RecordingWriter {
            stream: OutputStream::Stdout,
            data: Vec::new(),
            log: Arc::clone(&log),
        };
        let stderr = RecordingWriter {
            stream: OutputStream::Stderr,
            data: Vec::new(),
            log: Arc::clone(&log),
        };
        let server = thread::spawn(move || {
            let Some(Message::Start(request)) = read_message(&mut server).unwrap() else {
                panic!("expected start");
            };
            assert_eq!(request.token.as_deref(), Some("secret"));
            assert_eq!(request.command, "tool");
            assert_eq!(request.args, ["argument"]);
            assert_eq!(request.env, [("NAME".to_owned(), "value".to_owned())]);
            assert_eq!(request.cwd, "/work");

            for chunk in expected_input.chunks(8192).chain(std::iter::once(&[][..])) {
                assert!(matches!(
                    read_message(&mut server).unwrap(),
                    Some(Message::Stdin(data)) if data == chunk
                ));
            }

            server
                .set_read_timeout(Some(Duration::from_millis(50)))
                .unwrap();
            let error = server.read(&mut [0]).unwrap_err();
            assert!(matches!(
                error.kind(),
                ErrorKind::WouldBlock | ErrorKind::TimedOut
            ));

            for message in [
                Message::Stdout(b"first\0".to_vec()),
                Message::Stderr(vec![0xff, b'\n']),
                Message::Stdout(b"last".to_vec()),
                Message::Code(7),
            ] {
                write_message(&mut server, &message).unwrap();
            }
        });

        let result = run_client(client, io::Cursor::new(input), stdout, stderr).unwrap();
        server.join().unwrap();
        assert_eq!(result, ExitCode::from(7));
        assert_eq!(
            *log.lock().unwrap(),
            [
                (OutputStream::Stdout, b"first\0".to_vec()),
                (OutputStream::Stderr, vec![0xff, b'\n']),
                (OutputStream::Stdout, b"last".to_vec()),
            ]
        );
    }

    #[test]
    fn command_status_does_not_wait_for_stdin_to_finish() {
        let (client, mut server) = socket_pair();
        let (stdin, _input_writer) = UnixStream::pair().unwrap();
        write_message(&mut server, &Message::Code(0)).unwrap();
        let result = run_client(client, stdin, io::sink(), io::sink()).unwrap();
        assert_eq!(result, ExitCode::SUCCESS);
    }

    #[test]
    fn server_errors_are_reported_when_stdin_is_healthy() {
        let (client, mut server) = socket_pair();
        let server = thread::spawn(move || {
            assert!(matches!(
                read_message(&mut server).unwrap(),
                Some(Message::Start(_))
            ));
            assert!(matches!(
                read_message(&mut server).unwrap(),
                Some(Message::Stdin(data)) if data.is_empty()
            ));
            let denial = Message::Failed("authentication failed".into());
            write_message(&mut server, &denial).unwrap();
        });

        let error = run_client(client, io::empty(), io::sink(), io::sink()).unwrap_err();
        server.join().unwrap();
        assert_eq!(error.to_string(), "command failed: authentication failed");
    }

    #[test]
    fn closed_connection_reports_failure_to_send_start() {
        let (client, server) = socket_pair();
        drop(server);
        let error = run_client(client, io::empty(), io::sink(), io::sink()).unwrap_err();
        assert_eq!(error.to_string(), "failed to send start message");
    }

    struct Unclonable(UnixStream);

    impl Read for Unclonable {
        fn read(&mut self, data: &mut [u8]) -> io::Result<usize> {
            self.0.read(data)
        }
    }

    impl Write for Unclonable {
        fn write(&mut self, data: &[u8]) -> io::Result<usize> {
            self.0.write(data)
        }

        fn flush(&mut self) -> io::Result<()> {
            self.0.flush()
        }
    }

    impl SessionSocket for Unclonable {
        fn try_clone(&self) -> io::Result<Self> {
            Err(io::Error::other("clone failed"))
        }

        fn shutdown(&self, how: Shutdown) -> io::Result<()> {
            self.0.shutdown(how)
        }
    }

    #[test]
    fn socket_clone_failure_sends_no_start_frame() {
        let (socket, mut server) = socket_pair();
        let error =
            run_client(Unclonable(socket), io::empty(), io::sink(), io::sink()).unwrap_err();
        assert_eq!(error.to_string(), "failed to clone socket");
        assert!(read_message(&mut server).unwrap().is_none());
    }

    struct FailedReader;

    impl Read for FailedReader {
        fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
            Err(io::Error::other("read failed"))
        }
    }

    /// The server never answers, so only the stdin failure can end the session.
    fn stdin_read_error_ends_a_silent_session(client: impl SessionSocket, mut server: impl Read) {
        let error = run_client(client, FailedReader, io::sink(), io::sink()).unwrap_err();
        assert_eq!(error.to_string(), "failed to read stdin");

        // The client hangs up, which is what makes the daemon stop the command.
        assert!(matches!(
            read_message(&mut server).unwrap(),
            Some(Message::Start(_))
        ));
        assert!(read_message(&mut server).unwrap().is_none());
    }

    #[test]
    fn stdin_read_errors_end_a_silent_unix_session() {
        let (client, server) = socket_pair();
        stdin_read_error_ends_a_silent_session(client, server);
    }

    #[test]
    fn stdin_read_errors_end_a_silent_tcp_session() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
        let (server, _) = listener.accept().unwrap();
        server.set_read_timeout(Some(TIMEOUT)).unwrap();
        stdin_read_error_ends_a_silent_session(client, server);
    }
}