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
//! `teter signup`, `login` and `logout` against a relay with a store, with
//! the default key derivation, each "device" a config directory of its own.
// 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::unwrap_used,
    reason = "a test reports by panicking; its helpers live as long as the test"
)]

use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

/// A directory of this test's own (the store and the devices), removed when
/// it drops.
struct Scratch(PathBuf);

impl Scratch {
    fn new(tag: &str) -> Self {
        let dir = std::env::temp_dir().join(format!("tacc{}-{tag}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        Self(dir)
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        drop(std::fs::remove_dir_all(&self.0));
    }
}

/// A relay with a store in `scratch`, on a local port.
async fn relay(scratch: &Scratch) -> String {
    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(scratch.0.join("store.db")),
        open_signup: true,
        ..teter_relay::Config::new()
    })
    .unwrap();
    tokio::spawn(server.run(listener));
    format!("ws://{addr}")
}

/// `teter <args>` on the device whose config is `device`, with `password`.
async fn teter(device: &Path, password: &str, args: &[&str]) -> std::process::Output {
    tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .args(args)
        .env("XDG_CONFIG_HOME", device)
        .env("TETER_PASSWORD", password)
        .stdin(std::process::Stdio::null())
        .output()
        .await
        .unwrap()
}

fn saved(device: &Path) -> serde_json::Value {
    serde_json::from_slice(&std::fs::read(device.join("teter/account.json")).unwrap()).unwrap()
}

#[tokio::test]
async fn signup_then_login_on_another_device_gets_the_same_keys() {
    let scratch = Scratch::new("devices");
    let relay = relay(&scratch).await;
    let laptop = scratch.0.join("laptop");
    let phone = scratch.0.join("phone");

    let made = teter(
        &laptop,
        "correct horse",
        &["signup", &relay, "--name", "ana"],
    )
    .await;
    assert!(made.status.success(), "{made:?}");
    let on_laptop = saved(&laptop);
    let mode = std::fs::metadata(laptop.join("teter/account.json"))
        .unwrap()
        .permissions()
        .mode();
    assert_eq!(mode & 0o777, 0o600);

    let logged = teter(&phone, "correct horse", &["login", &relay, "--name", "ana"]).await;
    assert!(logged.status.success(), "{logged:?}");
    let on_phone = saved(&phone);
    assert_eq!(on_phone["private_keys"], on_laptop["private_keys"]);
    assert_eq!(on_phone["public_keys"], on_laptop["public_keys"]);
    // Each device its own login.
    assert_ne!(on_phone["token"], on_laptop["token"]);

    let out = teter(&phone, "", &["logout"]).await;
    assert!(out.status.success(), "{out:?}");
    assert!(!phone.join("teter/account.json").exists());
}

#[tokio::test]
async fn logout_removes_what_killed_commands_left_and_keeps_a_live_one_s() {
    let scratch = Scratch::new("leftovers");
    let relay = relay(&scratch).await;
    let laptop = scratch.0.join("laptop");
    let made = teter(
        &laptop,
        "correct horse",
        &["signup", &relay, "--name", "ana"],
    )
    .await;
    assert!(made.status.success(), "{made:?}");
    // A process that ran and is gone, and one that runs (this test).
    let mut gone = std::process::Command::new("true").spawn().unwrap();
    let dead = gone.id();
    gone.wait().unwrap();
    let live = std::process::id();
    let dir = laptop.join("teter");
    let files = [
        format!("account.new.{dead}"),
        format!("pending-tokens.new{dead}"),
        format!("account.new.{live}"),
        format!("pending-tokens.new{live}"),
        "account.new.notapid".to_owned(),
    ];
    for file in &files {
        std::fs::write(dir.join(file), b"secrets").unwrap();
    }

    let out = teter(&laptop, "", &["logout"]).await;
    assert!(out.status.success(), "{out:?}");
    let left: Vec<bool> = files.iter().map(|file| dir.join(file).exists()).collect();
    assert_eq!(left, [false, false, true, true, true]);

    // Logged out (or a first login killed, which leaves no account file):
    // a leftover still goes, and a signed PID is no PID.
    let more = [format!("account.new.{dead}"), "account.new.-1".to_owned()];
    for file in &more {
        std::fs::write(dir.join(file), b"secrets").unwrap();
    }
    let out = teter(&laptop, "", &["logout"]).await;
    assert!(!out.status.success(), "{out:?}");
    let left: Vec<bool> = more.iter().map(|file| dir.join(file).exists()).collect();
    assert_eq!(left, [false, true]);
}

#[tokio::test]
async fn logging_in_again_ends_the_device_s_login_before() {
    let scratch = Scratch::new("again");
    let relay = relay(&scratch).await;
    let laptop = scratch.0.join("laptop");
    let made = teter(
        &laptop,
        "correct horse",
        &["signup", &relay, "--name", "ana"],
    )
    .await;
    assert!(made.status.success(), "{made:?}");
    // The first login's files, kept aside as another device would hold
    // them: its device key too.
    let copy = scratch.0.join("copy");
    std::fs::create_dir_all(copy.join("teter")).unwrap();
    for file in ["account.json", "device.key"] {
        std::fs::copy(
            laptop.join("teter").join(file),
            copy.join("teter").join(file),
        )
        .unwrap();
    }
    let works = teter(&copy, "", &["token", "ls"]).await;
    assert!(works.status.success(), "{works:?}");

    let again = teter(
        &laptop,
        "correct horse",
        &["login", &relay, "--name", "ana"],
    )
    .await;
    assert!(again.status.success(), "{again:?}");
    let ended = teter(&copy, "", &["token", "ls"]).await;
    assert!(
        !ended.status.success(),
        "the first login still works: {ended:?}"
    );
    let now = teter(&laptop, "", &["token", "ls"]).await;
    assert!(now.status.success(), "{now:?}");
}

#[tokio::test]
async fn a_copy_of_the_account_file_alone_logs_nothing_in() {
    let scratch = Scratch::new("copied");
    let relay = relay(&scratch).await;
    let laptop = scratch.0.join("laptop");
    let made = teter(
        &laptop,
        "correct horse",
        &["signup", &relay, "--name", "ana"],
    )
    .await;
    assert!(made.status.success(), "{made:?}");
    // With no keyring (the tests'), the device key is in a file of its own,
    // closed to others, never in account.json, and the login says so.
    let stderr = String::from_utf8_lossy(&made.stderr);
    assert!(stderr.contains("device.key"), "{stderr}");
    let key = laptop.join("teter/device.key");
    let mode = std::fs::metadata(&key).unwrap().permissions().mode();
    assert_eq!(mode & 0o777, 0o600);
    let seed = std::fs::read_to_string(&key).unwrap();
    let file = std::fs::read_to_string(laptop.join("teter/account.json")).unwrap();
    assert!(
        !file.contains(seed.trim()),
        "the device key in account.json"
    );
    assert!(saved(&laptop).get("device_key").is_none());

    // account.json alone, on another machine: nothing works.
    let copy = scratch.0.join("copy");
    std::fs::create_dir_all(copy.join("teter")).unwrap();
    std::fs::copy(
        laptop.join("teter/account.json"),
        copy.join("teter/account.json"),
    )
    .unwrap();
    for args in [&["token", "ls"][..], &["machine", "ls"], &["ls", "box"]] {
        let out = teter(&copy, "", args).await;
        assert!(!out.status.success(), "{args:?} worked: {out:?}");
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(stderr.contains("no device key"), "{args:?}: {stderr}");
    }
    // Another device's key with it does no better: the relay refuses.
    let phone = scratch.0.join("phone");
    let logged = teter(&phone, "correct horse", &["login", &relay, "--name", "ana"]).await;
    assert!(logged.status.success(), "{logged:?}");
    std::fs::copy(
        phone.join("teter/device.key"),
        copy.join("teter/device.key"),
    )
    .unwrap();
    let out = teter(&copy, "", &["token", "ls"]).await;
    assert!(!out.status.success(), "a stranger's key worked: {out:?}");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains(teter_common::account::NOT_PROVEN),
        "{stderr}"
    );
    // A damaged key file counts as lost: logging out still works.
    std::fs::write(phone.join("teter/device.key"), [0xff, 0xfe]).unwrap();
    let out = teter(&phone, "", &["logout"]).await;
    assert!(out.status.success(), "{out:?}");
    assert!(!phone.join("teter/account.json").exists());
    // The laptop itself goes on.
    let works = teter(&laptop, "", &["token", "ls"]).await;
    assert!(works.status.success(), "{works:?}");
    // Logging out takes the key file too.
    let out = teter(&laptop, "", &["logout"]).await;
    assert!(out.status.success(), "{out:?}");
    assert!(!key.exists());
}

#[tokio::test]
async fn a_wrong_password_fails_without_saying_which_part_was_wrong() {
    let scratch = Scratch::new("wrong");
    let relay = relay(&scratch).await;
    let laptop = scratch.0.join("laptop");
    let made = teter(
        &laptop,
        "correct horse",
        &["signup", &relay, "--name", "ana"],
    )
    .await;
    assert!(made.status.success(), "{made:?}");

    let phone = scratch.0.join("phone");
    for (name, password) in [("ana", "wrong horse"), ("nobody", "correct horse")] {
        let out = teter(&phone, password, &["login", &relay, "--name", name]).await;
        assert!(!out.status.success());
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            stderr.contains(teter_common::account::WRONG_LOGIN),
            "{stderr}"
        );
        assert!(!phone.join("teter/account.json").exists());
    }
}

#[tokio::test]
async fn the_store_holds_no_password_or_unwrapped_private_key() {
    let scratch = Scratch::new("store");
    let relay = relay(&scratch).await;
    let laptop = scratch.0.join("laptop");
    let password = "correct horse battery staple";
    let made = teter(&laptop, password, &["signup", &relay, "--name", "ana"]).await;
    assert!(made.status.success(), "{made:?}");
    let private = saved(&laptop)["private_keys"].as_str().unwrap().to_owned();
    let private: Vec<u8> = private
        .as_bytes()
        .chunks(2)
        .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap())
        .collect();

    let mut written = Vec::new();
    for name in ["store.db", "store.db-wal"] {
        written.extend(std::fs::read(scratch.0.join(name)).unwrap_or_default());
    }
    let contains = |needle: &[u8]| written.windows(needle.len()).any(|window| window == needle);
    assert!(!contains(password.as_bytes()), "the password");
    let (x25519, ed25519) = private.split_at(32);
    assert!(!contains(x25519), "the X25519 private key");
    assert!(!contains(ed25519), "the Ed25519 private key");
}

#[tokio::test]
async fn signup_on_a_closed_relay_takes_the_invite_its_admin_made() {
    let scratch = Scratch::new("invite");
    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(scratch.0.join("store.db")),
        ..teter_relay::Config::new()
    })
    .unwrap();
    tokio::spawn(server.run(listener));
    let relay = format!("ws://{addr}");
    let device = scratch.0.join("laptop");

    let out = teter(&device, "pw", &["signup", &relay, "--name", "ana"]).await;
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8(out.stderr).unwrap();
    assert!(err.contains("needs an invite"), "{err:?}");

    let store = teter_relay::storage::Store::open(&scratch.0.join("store.db")).unwrap();
    let now = i64::try_from(
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
    )
    .unwrap();
    let (_, code) = teter_relay::admin::create_invite(&store, now, 3600).unwrap();
    let out = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .args(["signup", &relay, "--name", "ana"])
        .env("XDG_CONFIG_HOME", &device)
        .env("TETER_PASSWORD", "pw")
        .env("TETER_INVITE", &code)
        .stdin(std::process::Stdio::null())
        .output()
        .await
        .unwrap();
    assert!(out.status.success(), "{out:?}");
}

/// `teter <args>` on `device` with `password`, its secrets in the keyring
/// stand-in at `keyring` (#126).
async fn teter_with_keyring(
    device: &Path,
    keyring: &Path,
    password: &str,
    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", password)
        .env("TETER_KEYRING", format!("test:{}", keyring.display()))
        .stdin(std::process::Stdio::null())
        .output()
        .await
        .unwrap()
}

#[tokio::test]
#[expect(clippy::too_many_lines, reason = "a keyring, then none")]
async fn the_keys_go_to_the_keyring_when_there_is_one_and_to_the_file_when_not() {
    let scratch = Scratch::new("keyring");
    let relay = relay(&scratch).await;
    let laptop = scratch.0.join("laptop");
    let keyring = scratch.0.join("keyring.json");

    // A keyring: the file names the account, the keyring holds its secrets,
    // and the device works from both.
    let made = teter_with_keyring(
        &laptop,
        &keyring,
        "correct horse",
        &["signup", &relay, "--name", "ana"],
    )
    .await;
    assert!(made.status.success(), "{made:?}");
    let file = saved(&laptop);
    assert_eq!(file["keyring"], true, "{file}");
    assert_eq!(file["token"], "", "{file}");
    assert_eq!(file["private_keys"], "", "{file}");
    assert!(!file["public_keys"].as_str().unwrap().is_empty());
    let held: serde_json::Value =
        serde_json::from_slice(&std::fs::read(&keyring).unwrap()).unwrap();
    let entry = held
        .as_object()
        .unwrap()
        .values()
        .next()
        .unwrap()
        .as_str()
        .unwrap();
    let secrets: serde_json::Value =
        serde_json::from_slice(&teter_common::account::unhex(entry).unwrap()).unwrap();
    assert_eq!(secrets["token"].as_str().unwrap().len(), 64, "{secrets}");
    assert!(!secrets["private_keys"].as_str().unwrap().is_empty());
    // The device key with them (#158), and in no file.
    assert_eq!(
        secrets["device_key"].as_str().unwrap().len(),
        64,
        "{secrets}"
    );
    assert!(!laptop.join("teter/device.key").exists());
    let listed = teter_with_keyring(&laptop, &keyring, "", &["token", "ls"]).await;
    assert!(listed.status.success(), "{listed:?}");

    // A keyring that does not answer at logout keeps the file: the relay's
    // login is still live, and the device still has what ends it.
    let unreachable = scratch.0.join("unreachable");
    std::fs::create_dir_all(&unreachable).unwrap();
    let out = teter_with_keyring(&laptop, &unreachable, "", &["logout"]).await;
    assert!(!out.status.success(), "{out:?}");
    let said = String::from_utf8_lossy(&out.stderr);
    assert!(said.contains("the account file stays"), "{said}");
    assert!(laptop.join("teter/account.json").exists());

    // Logout removes the secrets from the keyring with the file.
    let out = teter_with_keyring(&laptop, &keyring, "", &["logout"]).await;
    assert!(out.status.success(), "{out:?}");
    assert!(!laptop.join("teter/account.json").exists());
    let held: serde_json::Value =
        serde_json::from_slice(&std::fs::read(&keyring).unwrap()).unwrap();
    assert!(held.as_object().unwrap().is_empty(), "{held}");

    // A keyring that does not answer (a directory where its file would be):
    // the secrets stay in the file, mode 0600, and the device says so.
    let broken = scratch.0.join("not-a-file");
    std::fs::create_dir_all(&broken).unwrap();
    let phone = scratch.0.join("phone");
    let out = teter_with_keyring(
        &phone,
        &broken,
        "correct horse",
        &["login", &relay, "--name", "ana"],
    )
    .await;
    assert!(out.status.success(), "{out:?}");
    let said = String::from_utf8_lossy(&out.stderr);
    assert!(
        said.contains("no keyring took the account's keys"),
        "{said}"
    );
    assert!(said.contains("this device's key is kept in"), "{said}");
    assert!(phone.join("teter/device.key").exists());
    let file = saved(&phone);
    assert!(file.get("keyring").is_none(), "{file}");
    assert_eq!(file["token"].as_str().unwrap().len(), 64, "{file}");
    let mode = std::fs::metadata(phone.join("teter/account.json"))
        .unwrap()
        .permissions()
        .mode();
    assert_eq!(mode & 0o777, 0o600);
    let listed = teter_with_keyring(&phone, &broken, "", &["token", "ls"]).await;
    assert!(listed.status.success(), "{listed:?}");
}