second-brain-api 0.13.5

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
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
mod common;

use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};
use std::sync::Arc;
use std::time::{Duration, Instant};

use axum::http::StatusCode;
use second_brain_api::AppState;
use second_brain_api::clock_gate::ClockGate;
use second_brain_api::discovery;
use second_brain_api::pairing::{Pairing, PairingConfig};
use second_brain_api::routes;
use second_brain_core::keys::{
    DeviceKeys, KeyStorage, ensure_device_keys, move_aside_for_pairing, open_device_store,
    open_handed,
};
use second_brain_core::machine::MachineIdentity;
use second_brain_core::schema::{Memory, MemoryType};
use second_brain_core::sqlite_store::BootstrapState;
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::store::Store;
use second_brain_sync::keyring::Keyring;
use second_brain_sync::mdns::{self, Net, Responder};
use second_brain_sync::pairing::{
    HostSecrets, JOIN_PENDING_FILE, JoinCode, KeyPurpose, KeyRequest, fetch_keys,
};
use serde_json::{Value, json};
use tempfile::TempDir;
use tower::ServiceExt;

use common::{get, json_body, post_json, state_in};

const HOST_KEY: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPairingTestHostKey";
const WAIT: Duration = Duration::from_secs(30);

struct Daemon {
    app: axum::Router,
    store: Arc<SqliteStore>,
    pairing: Arc<Pairing>,
    dir: TempDir,
    _sshd: Option<TcpListener>,
}

impl Daemon {
    /// With `sshd`, the device has a host key and something answers on its
    /// ssh port, as a machine running sshd does.
    fn new(id: &str, sshd: bool) -> Self {
        Self::looking_up(id, sshd, None)
    }

    /// Looks a pairing device up at `discovery` when joined without a host.
    fn looking_up(id: &str, sshd: bool, discovery: Option<Net>) -> Self {
        let dir = tempfile::tempdir().unwrap();
        let store = SqliteStore::in_memory(id.to_string()).unwrap();
        ensure_device_keys(&store, dir.path()).unwrap();
        Self::serving(id, sshd, store, dir, discovery)
    }

    fn serving(
        id: &str,
        sshd: bool,
        store: SqliteStore,
        dir: TempDir,
        discovery: Option<Net>,
    ) -> Self {
        let key_dir = dir.path().join("etc-ssh");
        std::fs::create_dir_all(&key_dir).unwrap();
        let listener = sshd.then(|| {
            std::fs::write(
                key_dir.join("ssh_host_ed25519_key.pub"),
                format!("{HOST_KEY} root@{id}\n"),
            )
            .unwrap();
            TcpListener::bind("127.0.0.1:0").unwrap()
        });
        let config = PairingConfig {
            listen_ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
            port: 0,
            ssh_host_key_dir: key_dir,
            ssh_port: listener
                .as_ref()
                .map_or(1, |l| l.local_addr().unwrap().port()),
            discovery,
        };
        let base = Arc::into_inner(state_in(store, dir.path(), ClockGate::open_for_tests()))
            .expect("a new state has one owner");
        let state = Arc::new(AppState {
            pairing: Arc::new(Pairing::new(config)),
            ..base
        });
        let store = state.sqlite.clone();
        Self {
            app: routes::router().with_state(state.clone()),
            store,
            pairing: state.pairing.clone(),
            dir,
            _sshd: listener,
        }
    }

    async fn call(&self, request: axum::http::Request<axum::body::Body>) -> (StatusCode, Value) {
        let response = self.app.clone().oneshot(request).await.unwrap();
        let status = response.status();
        (status, json_body(response).await)
    }

    fn keyring(&self) -> Keyring<'_> {
        Keyring::load(&self.store, self.dir.path()).unwrap()
    }

    fn known_hosts(&self) -> String {
        std::fs::read_to_string(self.dir.path().join("known_hosts")).unwrap_or_default()
    }

    async fn status_until(&self, done: impl Fn(&Value) -> bool) -> Value {
        let start = Instant::now();
        loop {
            let (_, status) = self.call(get("/v1/pair/status")).await;
            if done(&status) {
                return status;
            }
            assert!(
                start.elapsed() < WAIT,
                "pairing never reached the state: {status}"
            );
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
    }
}

fn sshd_port(daemon: &Daemon) -> u16 {
    daemon._sshd.as_ref().unwrap().local_addr().unwrap().port()
}

async fn join(joiner: &Daemon, code: &str, port: u64) -> (StatusCode, Value) {
    joiner
        .call(post_json(
            "/v1/pair/join",
            json!({"code": code, "host": format!("127.0.0.1:{port}")}),
        ))
        .await
}

#[tokio::test(flavor = "multi_thread")]
async fn a_device_never_synced_founds_an_identity_and_pairs_a_new_one() {
    let desk = Daemon::new("desk", true);
    let laptop = Daemon::new("laptop", false);
    assert!(desk.keyring().identity().is_none());

    let (status, started) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    assert_eq!(status, StatusCode::OK, "{started}");
    assert_eq!(started["state"], "waiting");
    let founded = &started["founded"];
    let phrase = founded["phrase"].as_str().expect("founding shows a phrase");
    assert_eq!(phrase.split('-').count(), 8, "{phrase}");
    let tag = desk.keyring().identity().unwrap().clone();
    assert_eq!(founded["identity"], tag.as_str());
    let code = started["code"].as_str().unwrap().to_string();
    assert_eq!(code.split('-').count(), 4);
    let port = started["port"].as_u64().unwrap();

    let (status, joined) = join(&laptop, &code, port).await;
    assert_eq!(status, StatusCode::OK, "{joined}");
    assert_eq!(joined["identity"], tag.as_str());
    assert_eq!(joined["host"]["machine_id"], "desk");

    let paired = desk.status_until(|s| s["state"] != "waiting").await;
    assert_eq!(paired["state"], "paired", "{paired}");
    assert_eq!(paired["device"]["machine_id"], "laptop");
    assert!(paired["code"].is_null(), "a used code is no longer shown");

    assert_eq!(laptop.keyring().identity(), Some(&tag));
    assert_eq!(
        laptop.keyring().held_epochs(),
        desk.keyring().held_epochs(),
        "the new device opens its envelopes"
    );
    let pinned = format!("[127.0.0.1]:{} {HOST_KEY}", sshd_port(&desk));
    assert!(
        laptop.known_hosts().lines().any(|l| l == pinned),
        "{}",
        laptop.known_hosts()
    );
    assert_eq!(
        laptop.store.recovery_recipients(&tag).unwrap(),
        desk.store.recovery_recipients(&tag).unwrap()
    );

    let (_, second) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    assert!(
        second["founded"].is_null(),
        "an identity is founded only once: {second}"
    );
    desk.call(post_json("/v1/pair/close", json!({}))).await;
}

#[tokio::test(flavor = "multi_thread")]
async fn three_wrong_codes_rotate_the_code_and_change_nothing() {
    let desk = Daemon::new("desk", false);
    let laptop = Daemon::new("laptop", false);
    let (_, started) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    let first = started["code"].as_str().unwrap().to_string();
    let port = started["port"].as_u64().unwrap();
    let wrong = HostSecrets::generate().code().to_string();

    for tried in 1..=3u64 {
        let (status, refused) = join(&laptop, &wrong, port).await;
        assert_eq!(status, StatusCode::CONFLICT, "{refused}");
        assert!(refused.to_string().contains("code was wrong"), "{refused}");
        if tried < 3 {
            desk.status_until(|s| s["wrong_tries"] == tried).await;
        }
    }
    let rotated = desk.status_until(|s| s["retired"] == 1).await;
    let second = rotated["code"].as_str().unwrap().to_string();
    assert_ne!(second, first);
    assert_eq!(rotated["state"], "waiting");

    let (status, _) = join(&laptop, &first, port).await;
    assert_eq!(status, StatusCode::CONFLICT, "the retired code must fail");
    assert!(laptop.keyring().identity().is_none());
    assert!(laptop.known_hosts().is_empty());

    let (status, joined) = join(&laptop, &second, port).await;
    assert_eq!(status, StatusCode::OK, "{joined}");
    assert!(
        joined["known_hosts"].as_array().unwrap().is_empty(),
        "a host without sshd pins nothing"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn joining_needs_a_well_formed_code_and_a_host() {
    let laptop = Daemon::new("laptop", false);
    let (status, body) = laptop
        .call(post_json(
            "/v1/pair/join",
            json!({"code": "not a code", "host": "127.0.0.1"}),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
    let code = HostSecrets::generate().code().to_string();
    let (status, body) = laptop
        .call(post_json("/v1/pair/join", json!({"code": code})))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
    assert!(body.to_string().contains("--host"), "{body}");
    let (_, none) = laptop.call(get("/v1/pair/status")).await;
    assert_eq!(none["state"], "none");
}

#[derive(Clone, Default)]
struct Captured(Arc<std::sync::Mutex<Vec<u8>>>);

impl std::io::Write for Captured {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0.lock().unwrap().extend_from_slice(buf);
        Ok(buf.len())
    }

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

impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Captured {
    type Writer = Captured;

    fn make_writer(&'a self) -> Self::Writer {
        self.clone()
    }
}

fn captured_logs() -> &'static Captured {
    static LOGS: std::sync::OnceLock<Captured> = std::sync::OnceLock::new();
    LOGS.get_or_init(|| {
        let logs = Captured::default();
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_writer(logs.clone())
            .with_ansi(false)
            .init();
        logs
    })
}

#[tokio::test(flavor = "multi_thread")]
async fn pairing_logs_no_code_invite_or_phrase() {
    let logs = captured_logs();
    let desk = Daemon::new("desk", true);
    let laptop = Daemon::new("laptop", false);
    let (_, started) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    let port = started["port"].as_u64().unwrap();
    let mut secrets = vec![
        started["code"].as_str().unwrap().to_string(),
        started["founded"]["phrase"].as_str().unwrap().to_string(),
    ];
    let invite = started["invite"].as_str().unwrap();
    let secret = invite
        .strip_prefix("sb-pair:")
        .and_then(|rest| rest.split('@').next())
        .unwrap()
        .to_string();
    secrets.push(secret);
    let wrong = HostSecrets::generate().code().to_string();
    secrets.push(wrong.clone());

    for _ in 0..3 {
        join(&laptop, &wrong, port).await;
    }
    let rotated = desk.status_until(|s| s["retired"] == 1).await;
    let code = rotated["code"].as_str().unwrap().to_string();
    secrets.push(code.clone());
    let (status, joined) = join(&laptop, &code, port).await;
    assert_eq!(status, StatusCode::OK, "{joined}");
    desk.status_until(|s| s["state"] == "paired").await;

    let text = String::from_utf8_lossy(&logs.0.lock().unwrap()).to_string();
    assert!(
        text.contains("pairing:"),
        "the flow must have logged: {text}"
    );
    for secret in &secrets {
        assert!(!text.contains(secret.as_str()), "{secret} was logged");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_taken_port_founds_nothing_so_no_phrase_is_lost() {
    let desk = Daemon::new("desk", false);
    let taken = TcpListener::bind("127.0.0.1:0").unwrap();
    let port = taken.local_addr().unwrap().port();
    let (status, body) = desk
        .call(post_json("/v1/pair/start", json!({"port": port})))
        .await;
    assert_ne!(status, StatusCode::OK, "{body}");
    assert!(desk.keyring().identity().is_none(), "{body}");
    drop(taken);
    let (status, started) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    assert_eq!(status, StatusCode::OK, "{started}");
    assert!(started["founded"]["phrase"].is_string(), "{started}");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_removed_device_is_refused_a_pairing_listener() {
    let desk = Daemon::new("desk", false);
    let phone = Daemon::new("phone", false);
    let (_, started) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    let code = started["code"].as_str().unwrap().to_string();
    let port = started["port"].as_u64().unwrap();
    let (status, joined) = join(&phone, &code, port).await;
    assert_eq!(status, StatusCode::OK, "{joined}");
    desk.status_until(|s| s["state"] == "paired").await;

    phone
        .keyring()
        .remove_device("desk", &Default::default(), 1_790_000_000_000_000)
        .unwrap();
    let from_phone = phone.keyring().handshake_for("desk", None).unwrap();
    assert!(
        desk.keyring()
            .accept("phone", &from_phone, 1_790_000_000_000_000)
            .is_err()
    );
    assert!(desk.keyring().is_removed().unwrap());

    let (status, refused) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    assert_eq!(status, StatusCode::CONFLICT, "{refused}");
    assert!(refused.to_string().contains("sb pair <code>"), "{refused}");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_pin_failure_after_the_join_reports_the_join_done_with_a_warning() {
    let desk = Daemon::new("desk", true);
    let laptop = Daemon::new("laptop", false);
    std::fs::create_dir(laptop.dir.path().join("known_hosts")).unwrap();
    let (_, started) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    let code = started["code"].as_str().unwrap().to_string();
    let port = started["port"].as_u64().unwrap();
    let tag = desk.keyring().identity().unwrap().clone();

    let (status, joined) = join(&laptop, &code, port).await;
    assert_eq!(status, StatusCode::OK, "{joined}");
    assert_eq!(joined["identity"], tag.as_str());
    let warning = joined["warning"].as_str().expect("a pin failure is warned");
    assert!(warning.contains("known_hosts"), "{warning}");
    assert!(warning.contains("host keys were not pinned"), "{warning}");
    assert!(warning.contains("ssh will ask you to trust"), "{warning}");
    assert!(joined["known_hosts"].as_array().unwrap().is_empty());

    let paired = desk.status_until(|s| s["state"] != "waiting").await;
    assert_eq!(paired["state"], "paired", "{paired}");
    assert_eq!(paired["device"]["machine_id"], "laptop");
    assert_eq!(laptop.keyring().identity(), Some(&tag));
    assert_eq!(laptop.keyring().held_epochs(), desk.keyring().held_epochs());
}

/// Answers lookups for `daemon` on loopback, as its daemon does on the LAN.
fn responder_for(daemon: &Daemon, name: &str) -> Responder {
    discovery::spawn_responder(
        &Net::Unicast(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))),
        daemon.store.clone(),
        daemon.pairing.clone(),
        name.to_string(),
    )
    .expect("a loopback responder starts")
}

#[tokio::test(flavor = "multi_thread")]
async fn a_new_device_finds_the_pairing_device_on_its_network_without_a_host() {
    let desk = Daemon::new("desk", true);
    let responder = responder_for(&desk, "desk");
    let at = Net::Unicast(responder.local_addr());
    assert!(
        mdns::browse(&at, mdns::PAIR_SERVICE, mdns::LOOKUP_WINDOW)
            .unwrap()
            .is_empty(),
        "nothing is advertised before `sb pair`"
    );

    let (status, started) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    assert_eq!(status, StatusCode::OK, "{started}");
    let code = started["code"].as_str().unwrap().to_string();
    let laptop = Daemon::looking_up("laptop", false, Some(at.clone()));
    let (status, joined) = laptop
        .call(post_json("/v1/pair/join", json!({"code": code})))
        .await;
    assert_eq!(status, StatusCode::OK, "{joined}");
    assert_eq!(joined["host"]["machine_id"], "desk");
    let paired = desk.status_until(|s| s["state"] != "waiting").await;
    assert_eq!(paired["state"], "paired", "{paired}");
    assert_eq!(
        laptop.keyring().identity(),
        desk.keyring().identity(),
        "the device found joined the pairing device's identity"
    );

    assert!(
        mdns::browse(&at, mdns::PAIR_SERVICE, mdns::LOOKUP_WINDOW)
            .unwrap()
            .is_empty(),
        "a used listener is no longer advertised"
    );
    let devices = mdns::browse(&at, mdns::SERVICE, mdns::LOOKUP_WINDOW).unwrap();
    assert_eq!(devices.len(), 1, "{devices:?}");
    assert_eq!(devices[0].get(mdns::TXT_ID), Some("desk"));
    assert_eq!(devices[0].port, sshd_port(&desk));
    assert!(devices[0].get(mdns::TXT_LOGIN).is_some());
}

#[tokio::test(flavor = "multi_thread")]
async fn a_device_never_paired_and_without_sshd_advertises_nothing() {
    let laptop = Daemon::new("laptop", false);
    let responder = responder_for(&laptop, "laptop");
    let at = Net::Unicast(responder.local_addr());
    assert!(
        mdns::browse(&at, mdns::SERVICE, mdns::LOOKUP_WINDOW)
            .unwrap()
            .is_empty()
    );
    let (status, started) = laptop.call(post_json("/v1/pair/start", json!({}))).await;
    assert_eq!(status, StatusCode::OK, "{started}");
    let listeners = mdns::browse(&at, mdns::PAIR_SERVICE, mdns::LOOKUP_WINDOW).unwrap();
    assert_eq!(listeners.len(), 1, "{listeners:?}");
    assert_eq!(listeners[0].port as u64, started["port"].as_u64().unwrap());
    assert!(
        mdns::browse(&at, mdns::SERVICE, mdns::LOOKUP_WINDOW)
            .unwrap()
            .is_empty(),
        "a device without sshd has nothing to dial"
    );
    laptop.call(post_json("/v1/pair/close", json!({}))).await;
    assert!(
        mdns::browse(&at, mdns::PAIR_SERVICE, mdns::LOOKUP_WINDOW)
            .unwrap()
            .is_empty()
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn restore_keys_hands_every_held_epoch_to_a_restore_and_adds_no_device() {
    let desk = Daemon::new("desk", true);
    let (status, refused) = desk
        .call(post_json("/v1/pair/start", json!({"restore_keys": true})))
        .await;
    assert_eq!(status, StatusCode::CONFLICT, "{refused}");
    assert!(desk.keyring().identity().is_none(), "nothing is founded");

    desk.call(post_json("/v1/pair/start", json!({}))).await;
    let tag = desk.keyring().identity().unwrap().clone();
    let rows = desk.store.device_records().unwrap().len();
    let responder = responder_for(&desk, "desk");
    let at = Net::Unicast(responder.local_addr());
    let (status, started) = desk
        .call(post_json("/v1/pair/start", json!({"restore_keys": true})))
        .await;
    assert_eq!(status, StatusCode::OK, "{started}");
    assert!(started["founded"].is_null());
    assert!(
        mdns::browse(&at, mdns::PAIR_SERVICE, mdns::LOOKUP_WINDOW)
            .unwrap()
            .is_empty(),
        "a listener handing over keys is not advertised for joins"
    );
    let code = started["code"].as_str().unwrap().to_string();
    let port = u16::try_from(started["port"].as_u64().unwrap()).unwrap();

    let transit = DeviceKeys::generate().unwrap();
    let request = KeyRequest {
        purpose: KeyPurpose::RestoreKeys,
        name: "new laptop".into(),
        age_recipient: transit.age_recipient().to_string(),
    };
    let held = tokio::task::spawn_blocking(move || {
        fetch_keys(
            &[("127.0.0.1".to_string(), port)],
            &JoinCode::parse(&code).unwrap(),
            &request,
            |handover| open_handed(&handover.envelopes, &transit),
        )
        .unwrap()
        .0
    })
    .await
    .unwrap();

    assert_eq!(held.len(), 1);
    assert_eq!(held[0].identity, tag);
    let done = desk.status_until(|s| s["state"] != "waiting").await;
    assert_eq!(done["state"], "handed_over", "{done}");
    assert_eq!(done["device"]["name"], "new laptop");
    assert_eq!(desk.store.device_records().unwrap().len(), rows);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_device_that_discards_its_store_bootstraps_and_keeps_the_old_one_readable() {
    let desk = Daemon::new("desk", true);
    desk.call(post_json("/v1/pair/start", json!({}))).await;
    desk.call(post_json("/v1/pair/close", json!({}))).await;
    let home = tempfile::tempdir().unwrap();
    let data = tempfile::Builder::new()
        .prefix("data")
        .tempdir_in(home.path())
        .unwrap();
    let kept = Memory::new(
        "written on the laptop since the backup".to_string(),
        MemoryType::Semantic,
        "test".to_string(),
        String::new(),
    );
    {
        let machine = MachineIdentity::load_or_create(data.path()).unwrap();
        let opened = open_device_store(
            &data.path().join("brain.db"),
            data.path(),
            machine.id,
            &KeyStorage::File,
        )
        .unwrap();
        opened.store.store_memory(&kept).unwrap();
    }

    let aside =
        move_aside_for_pairing(data.path(), 1_793_600_000_000_000, &[JOIN_PENDING_FILE]).unwrap();
    let machine = MachineIdentity::load_or_create(data.path()).unwrap();
    let opened = open_device_store(
        &data.path().join("brain.db"),
        data.path(),
        machine.id.clone(),
        &KeyStorage::File,
    )
    .unwrap();
    ensure_device_keys(&opened.store, data.path()).unwrap();
    let laptop = Daemon::serving(&machine.id, false, opened.store, data, None);

    let (_, started) = desk.call(post_json("/v1/pair/start", json!({}))).await;
    let code = started["code"].as_str().unwrap().to_string();
    let (status, joined) = join(&laptop, &code, started["port"].as_u64().unwrap()).await;
    assert_eq!(status, StatusCode::OK, "{joined}");
    assert_eq!(
        laptop.store.bootstrap_state().unwrap(),
        Some(BootstrapState::Pending),
        "the emptied store takes the pairing bootstrap"
    );
    assert!(laptop.store.get_memory(kept.id).unwrap().is_none());

    let name = aside.file_name().unwrap().to_string_lossy().into_owned();
    let (status, copy) = laptop
        .call(post_json(
            "/v1/maintenance/plaintext-copy",
            json!({ "aside": name }),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "{copy}");
    let copy = SqliteStore::open(
        std::path::Path::new(copy["path"].as_str().unwrap()),
        "reader".into(),
    )
    .unwrap();
    assert_eq!(
        copy.get_memory(kept.id).unwrap().unwrap().content,
        kept.content,
        "what the device wrote before discarding stays readable"
    );
    desk.call(post_json("/v1/pair/close", json!({}))).await;
}