teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
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
//! `teter link`, `status` and `kill` against a relay on a local port.
// An allow, not an expect: clippy exempts a #[test] function already, so an expect would go
// unfulfilled where only those use these. `allow_attributes` skips inner attributes.
#![allow(
    clippy::expect_used,
    clippy::panic,
    clippy::unwrap_used,
    clippy::unused_result_ok,
    reason = "a test reports by panicking; its helpers and stand-in servers live as long as the test"
)]

#[cfg(target_os = "linux")]
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::time::Duration;

#[path = "../../test-support/processes.rs"]
mod processes;

#[path = "../../test-support/machine.rs"]
mod machine;

/// A socket directory of this test's own; the session processes the binary
/// starts there outlive it, and are ended when it drops.
struct Sockets(std::path::PathBuf);

impl Sockets {
    fn new(tag: &str) -> Self {
        Self(std::env::temp_dir().join(format!("tc{}-{tag}", std::process::id())))
    }

    fn arg(&self) -> &std::ffi::OsStr {
        self.0.as_os_str()
    }

    /// The state directory of this test's own (`XDG_STATE_HOME`), so the
    /// binary's session registry is never the user's.
    fn state(&self) -> std::path::PathBuf {
        self.0.with_extension("state")
    }
}

impl Drop for Sockets {
    /// Ends every process whose command line names this directory: the
    /// session processes started for the test (they outlive the link, as
    /// they should).
    fn drop(&mut self) {
        processes::kill_naming(&self.0.to_string_lossy());
        std::fs::remove_dir_all(&self.0).ok();
        std::fs::remove_dir_all(self.state()).ok();
    }
}

/// A relay on a local port, in this test's runtime.
async fn local_relay() -> std::net::SocketAddr {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    machine::serve(listener, teter_relay::Config::new());
    addr
}

/// Runs `teter status` on `sockets`; returns what it printed.
async fn status_of(sockets: &Sockets) -> String {
    let status = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .arg("status")
        .arg("--sockets")
        .arg(sockets.arg())
        .env("XDG_STATE_HOME", sockets.state())
        .output()
        .await
        .unwrap();
    assert!(status.status.success(), "{status:?}");
    String::from_utf8(status.stdout).unwrap()
}

type Lines = tokio::io::Lines<tokio::io::BufReader<tokio::process::ChildStdout>>;

/// The link on `sockets` against the relay at `addr`, logging everything
/// (its session processes too) to `stderr_path`; its output's lines.
fn link_logging_all(
    addr: std::net::SocketAddr,
    sockets: &Sockets,
    stderr_path: &std::path::Path,
) -> (tokio::process::Child, Lines) {
    use tokio::io::AsyncBufReadExt;

    let mut child = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .arg("link")
        .args([
            "--relay",
            &format!("ws://{addr}/backend"),
            "--shell",
            "/bin/sh",
        ])
        .arg("--sockets")
        .arg(sockets.arg())
        .env("XDG_STATE_HOME", sockets.state())
        .env(
            "XDG_CONFIG_HOME",
            machine::fixed_host_config(&sockets.state(), &format!("ws://{addr}")),
        )
        // All of teter's; tungstenite's trace dumps every frame by design.
        .env("RUST_LOG", "trace,tungstenite=debug")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(std::fs::File::create(stderr_path).unwrap())
        .kill_on_drop(true)
        .spawn()
        .unwrap();
    let stdout = tokio::io::BufReader::new(child.stdout.take().unwrap()).lines();
    (child, stdout)
}

#[tokio::test]
async fn the_link_prints_the_session_and_status_alone_the_token_and_secret() {
    let addr = local_relay().await;
    let sockets = Sockets::new("prints");
    let stderr_path = sockets.0.with_extension("stderr");
    let (mut child, mut stdout) = link_logging_all(addr, &sockets, &stderr_path);
    let mut lines = Vec::new();
    while lines.len() < 2 {
        let line = tokio::time::timeout(Duration::from_secs(10), stdout.next_line())
            .await
            .expect("the backend printed nothing")
            .unwrap()
            .expect("the backend ended");
        lines.push(line);
    }
    let line = |prefix: &str| {
        lines
            .iter()
            .find_map(|line| line.strip_prefix(prefix))
            .unwrap_or_else(|| panic!("no {prefix:?} in {lines:?}"))
            .to_owned()
    };
    let id = line("session: ");
    assert!(uuid_like(&id), "{id}");

    // `status` asks the session process: the same session, its token and the
    // secret.
    let shown = status_of(&sockets).await;
    assert!(shown.starts_with("main\n"), "{shown}");
    assert!(shown.contains(&format!("  session: {id}\n")), "{shown}");
    let token = status_value(&shown, "token");
    assert_eq!(token.len(), 64, "{token}");
    let secret = status_value(&shown, "secret");
    assert!(
        teter_client::e2e::Secret::parse(&secret).is_ok(),
        "{secret}"
    );

    // Neither the link's output (not a terminal: a service's, #152) and logs
    // nor the session process's log hold the secret, nor the token.
    tokio::time::sleep(Duration::from_millis(300)).await;
    assert!(child.try_wait().unwrap().is_none(), "the link ended");
    child.kill().await.ok();
    while let Ok(Some(line)) = stdout.next_line().await {
        lines.push(line);
    }
    let logs = std::fs::read_to_string(&stderr_path).unwrap();
    std::fs::remove_file(&stderr_path).ok();
    assert!(
        logs.contains("serving the session"),
        "the link logged nothing"
    );
    let session_log = std::fs::read_to_string(sockets.0.join("main.log")).unwrap();
    for (what, text) in [
        ("output", lines.join("\n")),
        ("logs", logs),
        ("session log", session_log),
    ] {
        assert!(!text.contains(&secret), "the link's {what} hold the secret");
        assert!(!text.contains(&token), "the link's {what} hold the token");
    }
}

/// A value of `teter status`'s output: `  <key>: <value>`.
fn status_value(shown: &str, key: &str) -> String {
    shown
        .lines()
        .find_map(|line| line.strip_prefix(&format!("  {key}: ")))
        .unwrap_or_else(|| panic!("no {key} in {shown}"))
        .to_owned()
}

#[test]
fn status_without_sessions_says_so() {
    let sockets = Sockets::new("none");
    let out = Command::new(env!("CARGO_BIN_EXE_teter"))
        .arg("status")
        .arg("--sockets")
        .arg(sockets.arg())
        .env("XDG_STATE_HOME", sockets.state())
        .output()
        .unwrap();
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("no session runs"), "{stderr}");
}

/// A link on a machine that is not registered cannot serve at all: it exits
/// with the status a service does not restart on (#165).
#[test]
fn an_unregistered_machine_s_link_exits_with_the_in_use_status() {
    let sockets = Sockets::new("unregistered");
    for (args, status) in [(&[][..], 3), (&["--in-use-status", "0"][..], 0)] {
        let out = Command::new(env!("CARGO_BIN_EXE_teter"))
            .arg("link")
            .args(args)
            .arg("--sockets")
            .arg(sockets.arg())
            .env("XDG_STATE_HOME", sockets.state())
            .env("XDG_CONFIG_HOME", sockets.state().join("config"))
            .env_remove("TETER_RELAY")
            .stdin(Stdio::null())
            .output()
            .unwrap();
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert_eq!(out.status.code(), Some(status), "{args:?}: {stderr}");
        assert!(stderr.contains("not registered"), "{stderr}");
    }
}

fn status_in(sockets: &Sockets) -> std::process::Output {
    Command::new(env!("CARGO_BIN_EXE_teter"))
        .arg("status")
        .arg("--sockets")
        .arg(sockets.arg())
        .env("XDG_STATE_HOME", sockets.state())
        .output()
        .unwrap()
}

#[test]
fn status_fails_when_no_session_process_answers() {
    use std::os::unix::fs::DirBuilderExt;
    let sockets = Sockets::new("silent");
    std::fs::DirBuilder::new()
        .mode(0o700)
        .create(&sockets.0)
        .unwrap();
    // A socket nobody listens on: a session process that died.
    drop(std::os::unix::net::UnixListener::bind(sockets.0.join("gone.sock")).unwrap());
    let out = status_in(&sockets);
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("gone:"), "{stderr}");
    assert!(stderr.contains("answered"), "{stderr}");
}

#[test]
fn status_refuses_a_directory_open_to_others() {
    use std::os::unix::fs::DirBuilderExt;
    let sockets = Sockets::new("open");
    std::fs::DirBuilder::new()
        .mode(0o755)
        .create(&sockets.0)
        .unwrap();
    std::fs::set_permissions(
        &sockets.0,
        std::os::unix::fs::PermissionsExt::from_mode(0o777),
    )
    .unwrap();
    let out = status_in(&sockets);
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("closed to others"), "{stderr}");
}

#[test]
fn an_unreachable_relay_exits_with_an_error() {
    // A socket bound to the port, and not listening: connections to it are
    // refused, and nothing else can take the port meanwhile (one freed
    // could be taken by a test running alongside, and answer).
    let held = tokio::net::TcpSocket::new_v4().unwrap();
    held.bind("127.0.0.1:0".parse().unwrap()).unwrap();
    let port = held.local_addr().unwrap().port();
    let sockets = Sockets::new("unreachable");
    let out = Command::new(env!("CARGO_BIN_EXE_teter"))
        .arg("link")
        .args(["--relay", &format!("ws://127.0.0.1:{port}/backend")])
        .arg("--sockets")
        .arg(sockets.arg())
        .env("XDG_STATE_HOME", sockets.state())
        .env(
            "XDG_CONFIG_HOME",
            machine::fixed_host_config(&sockets.state(), &format!("ws://127.0.0.1:{port}")),
        )
        .stdin(Stdio::null())
        .output()
        .unwrap();
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.starts_with("teter: "), "{stderr}");
}

fn uuid_like(s: &str) -> bool {
    s.len() == 36 && s.chars().filter(|&c| c == '-').count() == 4
}

#[test]
fn a_missing_ca_file_is_refused_with_its_path() {
    // A listener so the TCP connection succeeds and the TLS setup is reached.
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    let sockets = Sockets::new("ca");
    let mut child = Command::new(env!("CARGO_BIN_EXE_teter"))
        .arg("link")
        .args(["--relay", &format!("wss://localhost:{port}/backend")])
        .arg("--sockets")
        .arg(sockets.arg())
        .env("XDG_STATE_HOME", sockets.state())
        .args(["--ca-cert", "/nonexistent/ca.crt"])
        .env(
            "XDG_CONFIG_HOME",
            machine::fixed_host_config(&sockets.state(), &format!("wss://localhost:{port}")),
        )
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    // The CA file is read before any TLS: the refusal comes at once.
    let start = std::time::Instant::now();
    let status = loop {
        if let Some(status) = child.try_wait().unwrap() {
            break status;
        }
        if start.elapsed() > Duration::from_secs(5) {
            child.kill().ok();
            child.wait().ok();
            panic!("the backend did not refuse the missing CA file at once");
        }
        std::thread::sleep(Duration::from_millis(50));
    };
    assert!(!status.success());
    let mut stderr = String::new();
    std::io::Read::read_to_string(&mut child.stderr.take().unwrap(), &mut stderr).unwrap();
    assert!(stderr.contains("/nonexistent/ca.crt"), "{stderr}");
}

// Linux only: it looks into the processes through `/proc`.
#[cfg(target_os = "linux")]
/// The processes whose command line names `dir` and runs a session.
fn session_processes(dir: &std::path::Path) -> Vec<i32> {
    let dir = dir.to_string_lossy().into_owned();
    std::fs::read_dir("/proc")
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|entry| {
            let pid = entry.file_name().to_string_lossy().parse::<i32>().ok()?;
            let cmdline = std::fs::read(entry.path().join("cmdline")).ok()?;
            let args: Vec<_> = cmdline
                .split(|&b| b == 0)
                .map(String::from_utf8_lossy)
                .collect();
            (args.iter().any(|a| a == "session") && args.iter().any(|a| *a == dir)).then_some(pid)
        })
        .collect()
}

// Linux only: it looks into the processes through `/proc`.
#[cfg(target_os = "linux")]
/// The children of `pid`, from each process's parent in `/proc/<pid>/stat`.
fn children(pid: i32) -> Vec<i32> {
    std::fs::read_dir("/proc")
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|entry| {
            let child = entry.file_name().to_string_lossy().parse::<i32>().ok()?;
            let stat = std::fs::read_to_string(entry.path().join("stat")).ok()?;
            // After the command's closing parenthesis: state, then parent.
            let parent = stat.rsplit_once(')')?.1.split_whitespace().nth(1)?;
            (parent.parse::<i32>().ok()? == pid).then_some(child)
        })
        .collect()
}

// Linux only: it looks into the processes through `/proc`.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn killing_the_links_process_group_leaves_the_session_and_its_shell() {
    use std::os::unix::process::CommandExt;

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    machine::serve(listener, teter_relay::Config::new());

    let sockets = Sockets::new("group");
    let mut link = Command::new(env!("CARGO_BIN_EXE_teter"))
        .arg("link")
        .args([
            "--relay",
            &format!("ws://{addr}/backend"),
            "--shell",
            "/bin/sh",
        ])
        .arg("--sockets")
        .arg(sockets.arg())
        .env("XDG_STATE_HOME", sockets.state())
        .env(
            "XDG_CONFIG_HOME",
            machine::fixed_host_config(&sockets.state(), &format!("ws://{addr}")),
        )
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        // The link leads a group of its own, as a service or a shell's job
        // would: the kill below ends the whole group.
        .process_group(0)
        .spawn()
        .unwrap();
    let stdout = link.stdout.take().unwrap();
    // The two lines: the session process started and the relay session is
    // made.
    let lines = tokio::task::spawn_blocking(move || BufReader::new(stdout).lines().take(2).count());
    let count = tokio::time::timeout(Duration::from_secs(10), lines)
        .await
        .expect("the backend printed nothing")
        .unwrap();
    assert_eq!(count, 2);

    let sessions = session_processes(&sockets.0);
    let [session] = sessions[..] else {
        panic!("one session process expected: {sessions:?}");
    };
    let group = rustix::process::Pid::from_raw(i32::try_from(link.id()).unwrap()).unwrap();
    rustix::process::kill_process_group(group, rustix::process::Signal::KILL).unwrap();
    link.wait().unwrap();

    // Give a signal that reached the session process time to end it.
    tokio::time::sleep(Duration::from_millis(300)).await;
    assert!(
        std::path::Path::new(&format!("/proc/{session}")).exists(),
        "the session process died with the link's group"
    );
    assert!(
        !children(session).is_empty(),
        "its shell died with the link's group"
    );
    tokio::net::UnixStream::connect(sockets.0.join("main.sock"))
        .await
        .expect("the session process no longer listens");
}

// Linux only: it looks into the processes through `/proc`.
#[cfg(target_os = "linux")]
/// The names of the variables in process `pid`'s environment.
fn env_names(pid: i32) -> Vec<String> {
    std::fs::read(format!("/proc/{pid}/environ"))
        .unwrap()
        .split(|&b| b == 0)
        .filter_map(|var| var.split(|&b| b == b'=').next())
        .map(|name| String::from_utf8_lossy(name).into_owned())
        .collect()
}

// Linux only: it looks into the processes through `/proc`.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn the_relay_url_reaches_neither_session_processes_nor_shells_and_a_second_link_exits_3() {
    use tokio::io::AsyncBufReadExt;

    let addr = local_relay().await;
    let sockets = Sockets::new("creds");
    let link = |sockets: &Sockets| {
        let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"));
        command
            .arg("link")
            .arg("--sockets")
            .arg(sockets.arg())
            .env("XDG_STATE_HOME", sockets.state())
            .args(["--shell", "/bin/sh"])
            .env("TETER_RELAY", format!("ws://{addr}/backend"))
            .env(
                "XDG_CONFIG_HOME",
                machine::fixed_host_config(&sockets.state(), &format!("ws://{addr}")),
            )
            .stdin(Stdio::null())
            .stderr(Stdio::null())
            .kill_on_drop(true);
        command
    };
    let mut first = link(&sockets).stdout(Stdio::piped()).spawn().unwrap();
    let mut stdout = tokio::io::BufReader::new(first.stdout.take().unwrap()).lines();
    for _ in 0..2 {
        tokio::time::timeout(Duration::from_secs(10), stdout.next_line())
            .await
            .expect("the backend printed nothing")
            .unwrap();
    }
    let sessions = session_processes(&sockets.0);
    let [session] = sessions[..] else {
        panic!("one session process expected: {sessions:?}");
    };
    let shells = children(session);
    assert!(!shells.is_empty(), "no shell");
    for pid in std::iter::once(session).chain(shells) {
        let names = env_names(pid);
        assert!(
            !names.iter().any(|name| name == "TETER_RELAY"),
            "TETER_RELAY in the environment of {pid}"
        );
    }

    // A second link on the same sockets: refused, with the status a service
    // does not restart on.
    let second = link(&sockets).stdout(Stdio::null()).status().await.unwrap();
    assert_eq!(second.code(), Some(3), "{second:?}");
    first.kill().await.ok();
}