teter 26.11.6

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
//! Signed, replay-safe commands from a device to a machine (#88): a valid
//! command runs; one replayed, altered, or signed by another account is
//! refused and runs nothing.
// 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::indexing_slicing,
    clippy::too_many_lines,
    clippy::unused_result_ok,
    clippy::unwrap_used,
    reason = "a test reports by panicking; its helpers live as long as the test"
)]

use std::path::{Path, PathBuf};
use std::time::Duration;

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

use teter_backend::registry::Registry;
use teter_client::account::AccountKeys;
use teter_client::command::{Channel, seal_command};
use teter_common::account::{AccountReply, AccountRequest, unhex};
use teter_common::command::{Command, Outcome};
use tokio::time::timeout;

const WAIT: Duration = Duration::from_secs(15);

/// The test's folder, removed (and the session processes ended) when it
/// drops.
struct World {
    dir: PathBuf,
}

impl World {
    fn sockets(&self) -> PathBuf {
        self.dir.join("sockets")
    }

    async fn teter(&self, device: &Path, args: &[&str]) -> std::process::Output {
        tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
            .args(args)
            .env("XDG_CONFIG_HOME", device)
            .env("XDG_STATE_HOME", device.join("state"))
            .env("TETER_PASSWORD", "correct horse")
            .env_remove("TETER_RELAY")
            .stdin(std::process::Stdio::null())
            .output()
            .await
            .unwrap()
    }
}

impl Drop for World {
    fn drop(&mut self) {
        processes::kill_naming(&self.sockets().to_string_lossy());
        std::fs::remove_dir_all(&self.dir).ok();
    }
}

/// A relay with a store, an account, its machine registered and linked
/// with a session "victim" besides main, and a command channel to it.
struct Served {
    world: World,
    channel: Channel,
    account: AccountKeys,
    machine: String,
    registry: Registry,
    relay: String,
    login: String,
    _link: tokio::process::Child,
}

async fn served(tag: &str) -> Served {
    let world = World {
        dir: std::env::temp_dir().join(format!("tcmd{tag}{}", std::process::id())),
    };
    std::fs::create_dir_all(&world.dir).unwrap();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let server = teter_relay::Server::new(teter_relay::Config {
        store: Some(world.dir.join("store.db")),
        open_signup: true,
        ..teter_relay::Config::new()
    })
    .unwrap();
    tokio::spawn(server.run(listener));
    let relay = format!("ws://{addr}");
    let (laptop, machine_dir) = (world.dir.join("laptop"), world.dir.join("machine"));

    let out = world
        .teter(&laptop, &["signup", &relay, "--name", "ana"])
        .await;
    assert!(out.status.success(), "{out:?}");
    let out = world.teter(&laptop, &["token", "create"]).await;
    let token = String::from_utf8(out.stdout).unwrap().trim().to_owned();
    let out = world
        .teter(
            &machine_dir,
            &["register", "--token", &token, "--name", "jupiter"],
        )
        .await;
    assert!(out.status.success(), "{out:?}");
    let registry = Registry::at(machine_dir.join("state/teter/sessions"));
    registry.add("victim").unwrap();

    let _link = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .args(["link", "--shell", "/bin/sh", "--sockets"])
        .arg(world.sockets())
        .env("XDG_CONFIG_HOME", &machine_dir)
        .env("XDG_STATE_HOME", machine_dir.join("state"))
        .env_remove("TETER_RELAY")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true)
        .spawn()
        .unwrap();

    // The account's keys and its machine, as a logged-in device has them.
    let saved: serde_json::Value =
        serde_json::from_slice(&std::fs::read(laptop.join("teter/account.json")).unwrap()).unwrap();
    let account =
        AccountKeys::from_private_bytes(&unhex(saved["private_keys"].as_str().unwrap()).unwrap())
            .unwrap();
    let login = saved["token"].as_str().unwrap().to_owned();
    let machine = timeout(WAIT, async {
        loop {
            let reply = teter_client::account::request(
                &relay,
                None,
                &AccountRequest::Sessions {
                    login: login.clone(),
                },
            )
            .await
            .unwrap();
            if let AccountReply::Sessions { machines, .. } = reply
                && let Some(machine) = machines
                    .into_iter()
                    .find(|machine| machine.relay.is_some() && machine.sessions.len() == 2)
            {
                return machine;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("the machine was not served");
    let (session, join) = machine.relay.clone().unwrap();
    let channel = Channel::open(
        &format!("{relay}/frontend"),
        None,
        session,
        join,
        machine.id.clone(),
        machine.public_key.clone(),
    )
    .await
    .unwrap();
    Served {
        world,
        channel,
        account,
        machine: machine.id,
        registry,
        relay,
        login,
        _link,
    }
}

#[tokio::test]
async fn a_signed_command_runs_and_a_replayed_altered_or_foreign_one_does_not() {
    let mut held = served("replay").await;
    let (account, machine, registry) = (
        AccountKeys::from_private_bytes(&*held.account.private_bytes()).unwrap(),
        held.machine.clone(),
        &held.registry,
    );
    let channel = &mut held.channel;
    let kill = || Command::Kill {
        name: "victim".to_owned(),
    };
    let refused = |result: std::io::Result<Outcome>| {
        let e = result.expect_err("the machine ran it");
        assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "{e}");
    };

    // Signed by another account.
    let challenge = channel.challenge().await.unwrap();
    let stranger = AccountKeys::generate().unwrap();
    let sealed = seal_command(&stranger, &machine, &challenge, kill()).unwrap();
    refused(
        channel
            .send_sealed(&account, &challenge.nonce, sealed)
            .await,
    );

    // Altered on the way.
    let challenge = channel.challenge().await.unwrap();
    let mut sealed = seal_command(&account, &machine, &challenge, kill()).unwrap();
    *sealed.last_mut().unwrap() ^= 1;
    refused(
        channel
            .send_sealed(&account, &challenge.nonce, sealed)
            .await,
    );
    assert!(
        registry.contains("victim").unwrap(),
        "a refused command ran"
    );

    // A valid one runs.
    let challenge = channel.challenge().await.unwrap();
    let sealed = seal_command(&account, &machine, &challenge, kill()).unwrap();
    let outcome = channel
        .send_sealed(&account, &challenge.nonce, sealed.clone())
        .await
        .unwrap();
    assert_eq!(outcome, Outcome::Done);
    assert!(
        !registry.contains("victim").unwrap(),
        "the session is still registered"
    );

    // Replayed: on its used challenge, and on a fresh one.
    registry.add("victim").unwrap();
    refused(
        channel
            .send_sealed(&account, &challenge.nonce, sealed.clone())
            .await,
    );
    let fresh = channel.challenge().await.unwrap();
    refused(channel.send_sealed(&account, &fresh.nonce, sealed).await);
    assert!(
        registry.contains("victim").unwrap(),
        "a replayed command ran"
    );
}

#[tokio::test]
async fn sessions_are_listed_created_and_killed_through_the_relay() {
    let mut held = served("ls").await;
    let (account, machine, registry) = (
        AccountKeys::from_private_bytes(&*held.account.private_bytes()).unwrap(),
        held.machine.clone(),
        held.registry.clone(),
    );
    let world_dir = held.world.dir.clone();
    let channel = &mut held.channel;
    let names = |outcome: Outcome| match outcome {
        Outcome::Sessions { sessions } => sessions
            .into_iter()
            .map(|session| (session.name, session.running))
            .collect::<Vec<_>>(),
        other @ (Outcome::Done | Outcome::Failed { .. }) => panic!("not a list: {other:?}"),
    };
    let listed = names(channel.run(&account, Command::List).await.unwrap());
    assert!(listed.contains(&("victim".to_owned(), true)), "{listed:?}");

    // A new session runs, and the link serves it: its record reaches the
    // relay, sealed.
    let new = || Command::New {
        name: "zanzibar".to_owned(),
    };
    assert_eq!(channel.run(&account, new()).await.unwrap(), Outcome::Done);
    assert!(registry.contains("zanzibar").unwrap());
    let listed = names(channel.run(&account, Command::List).await.unwrap());
    assert!(
        listed.contains(&("zanzibar".to_owned(), true)),
        "{listed:?}"
    );
    let store = teter_relay::storage::Store::open(&world_dir.join("store.db")).unwrap();
    let served = timeout(WAIT, async {
        while store.session_records(&machine).unwrap().len() < 3 {
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await;
    assert!(served.is_ok(), "the link did not serve the new session");

    // A name taken, and one that is no name.
    let taken = channel.run(&account, new()).await.unwrap();
    assert!(
        matches!(&taken, Outcome::Failed { reason } if reason.contains("already exists")),
        "{taken:?}"
    );
    let bad = Command::New {
        name: "../x".to_owned(),
    };
    let bad = channel.run(&account, bad).await.unwrap();
    assert!(matches!(bad, Outcome::Failed { .. }), "{bad:?}");

    let kill = Command::Kill {
        name: "zanzibar".to_owned(),
    };
    assert_eq!(channel.run(&account, kill).await.unwrap(), Outcome::Done);
    let listed = names(channel.run(&account, Command::List).await.unwrap());
    assert!(
        !listed.iter().any(|(name, _)| name == "zanzibar"),
        "{listed:?}"
    );

    // The relay's store never held a session name.
    let mut written = Vec::new();
    for name in ["store.db", "store.db-wal"] {
        written.extend(std::fs::read(world_dir.join(name)).unwrap_or_default());
    }
    assert!(
        !written.windows(8).any(|window| window == b"zanzibar"),
        "a session name in the store"
    );
}

/// The machine's session records as the relay lists them to the account.
async fn records(held: &Served) -> Vec<teter_common::account::SessionRecordInfo> {
    let reply = teter_client::account::request(
        &held.relay,
        None,
        &AccountRequest::Sessions {
            login: held.login.clone(),
        },
    )
    .await
    .unwrap();
    // Any other answer lists nothing, and the caller's wait fails.
    let AccountReply::Sessions { machines, .. } = reply else {
        return Vec::new();
    };
    machines
        .into_iter()
        .find(|machine| machine.id == held.machine)
        .map(|machine| machine.sessions)
        .unwrap_or_default()
}

#[tokio::test]
async fn the_relay_counts_the_frontends_attached_to_each_session() {
    // #135: what `teter ls` shows as a session's clients.
    let held = served("clients").await;
    let record = timeout(WAIT, async {
        loop {
            if let Some(record) = records(&held)
                .await
                .into_iter()
                .find(|record| record.relay.is_some())
            {
                return record;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("no session served");
    assert_eq!(record.clients, Some(0));
    let (session, token) = record.relay.clone().unwrap();
    let frontend = teter_frontend::join(&teter_frontend::Config {
        relay: format!("{}/frontend", held.relay),
        session,
        token,
        secret: teter_client::e2e::Secret::generate().unwrap(),
        ca_cert: None,
        channel: Some(record.channel.clone()),
        history: 0,
        rows: 0,
        sealed_history: false,
    })
    .await
    .unwrap();
    let count = |want: u32| {
        let held = &held;
        let channel = record.channel.clone();
        async move {
            let reached = timeout(WAIT, async {
                loop {
                    let listed = records(held).await;
                    let now = listed
                        .iter()
                        .find(|record| record.channel == channel)
                        .and_then(|record| record.clients);
                    if now == Some(want) {
                        return;
                    }
                    tokio::time::sleep(Duration::from_millis(50)).await;
                }
            })
            .await;
            assert!(reached.is_ok(), "never {want} clients");
        }
    };
    count(1).await;
    // Another session's records stay at none.
    assert!(
        records(&held)
            .await
            .iter()
            .filter(|other| other.channel != record.channel)
            .all(|other| other.clients == Some(0))
    );
    drop(frontend);
    count(0).await;
}