second-brain-core 0.13.4

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
use std::collections::{BTreeMap, BTreeSet};

use age::x25519::Recipient;
use anyhow::{Context, Result, anyhow, bail, ensure};
use ed25519_dalek::VerifyingKey;

use super::{DeviceKeys, DeviceRecord, Epoch, IdentityTag, SignedRecord};
use crate::sqlite_store::SqliteStore;

/// Which identity a joining device held before it took its paired row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PriorIdentity {
    None,
    Same,
    Other(IdentityTag),
}

/// On the pairing device: signs `record` as the joining device's first row
/// in this device's identity and stores it. Pairing a device again with the
/// same keys returns its stored first row, countersigned by this device,
/// whatever else in the row changed since. A device this identity's stored
/// revocations reach is refused before anything is written, even when only
/// its revocation is stored; one that kept its machine id but not its keys
/// needs a fresh machine id. A row the joiner held under another identity
/// is replaced.
pub fn admit_device(
    store: &SqliteStore,
    pairer: &DeviceKeys,
    record: DeviceRecord,
) -> Result<SignedRecord> {
    let own = store.machine_id().to_string();
    let joiner = record.machine_id.clone();
    check_fields(&record)?;
    ensure!(
        joiner != own,
        "the joining device has this device's machine id {own}; one of them is a copy and needs a \
         fresh machine id"
    );
    ensure!(record.version == 1, "a first row has version 1");
    let own_row = store
        .device_record(&own)?
        .context("this device has no signed row, so it has no identity to pair into")?;
    ensure!(
        own_row.current.record.identity_tag == record.identity_tag,
        "the row names identity {}, not this device's identity",
        record.identity_tag
    );
    let tag = IdentityTag::from(record.identity_tag.clone());
    ensure!(
        !store.revoked_by_rule(&tag, None)?.contains(&joiner),
        "{}",
        removed_joiner(&joiner)
    );

    match store.device_record(&joiner)? {
        Some(stored) if stored.current.record.identity_tag == record.identity_tag => {
            ensure!(!stored.revoked, "{}", removed_joiner(&joiner));
            ensure!(
                same_keys(&stored.first.record, &record),
                "device {joiner} is already paired with other keys; a device that lost its keys \
                 needs a fresh machine id"
            );
            if !stored.first.signatures.iter().any(|s| s.signer == own) {
                let mut countersigned = stored.first.clone();
                countersigned.countersign(&own, pairer.signing_key());
                store.insert_first_device_record(&countersigned, &own, &pairer.verifying_key())?;
            }
        }
        Some(_) => {
            let signed = record.sign(&own, pairer.signing_key());
            store.replace_device_record_for_new_identity(&signed, &own, &pairer.verifying_key())?;
            store.apply_revocations(&tag)?;
        }
        None => {
            let signed = record.sign(&own, pairer.signing_key());
            store.insert_first_device_record(&signed, &own, &pairer.verifying_key())?;
        }
    }
    Ok(store
        .device_record(&joiner)?
        .context("the admitted row is not in the store after the write")?
        .first)
}

fn removed_joiner(joiner: &str) -> String {
    format!(
        "device {joiner} was removed from this identity, so it cannot rejoin it under this \
         machine id; nothing was changed"
    )
}

fn same_keys(a: &DeviceRecord, b: &DeviceRecord) -> bool {
    a.age_recipient == b.age_recipient
        && a.ssh_public_key == b.ssh_public_key
        && a.signing_public_key == b.signing_public_key
}

/// The row is signed and spreads to every peer, and later items write its
/// ssh fields into authorized_keys and known_hosts.
fn check_fields(record: &DeviceRecord) -> Result<()> {
    let token = |field: &str, value: &str| {
        ensure!(
            is_token(value),
            "the joining device sent a {field} that is empty or holds spaces or control characters"
        );
        Ok(())
    };
    let line = |field: &str, value: &str| {
        ensure!(
            !value.chars().any(char::is_control),
            "the joining device sent a {field} holding control characters"
        );
        Ok(())
    };
    ensure!(
        super::valid_machine_id(&record.machine_id),
        "the joining device sent a machine id that is not 1 to 128 of A-Z a-z 0-9 . _ -"
    );
    line("name", &record.name)?;
    if let Some(login) = &record.ssh_login {
        token("ssh login", login)?;
    }
    let ssh_key: Vec<&str> = record.ssh_public_key.split(' ').collect();
    ensure!(
        matches!(ssh_key.as_slice(), ["ssh-ed25519", body] if is_base64(body)),
        "the joining device sent an ssh key that is not one `ssh-ed25519 <base64>` line"
    );
    if let Some(host_key) = &record.ssh_host_key {
        ensure!(
            valid_host_key(host_key),
            "the joining device sent a host key that is not one `<type> <base64>` line"
        );
    }
    record
        .age_recipient
        .parse::<Recipient>()
        .map_err(|e| anyhow!("the joining device sent an invalid age recipient: {e}"))?;
    record.signing_public_key()?;
    Ok(())
}

/// One `<type> <base64>` public key line, as a signed row carries a host
/// key into every peer's known_hosts.
pub fn valid_host_key(host_key: &str) -> bool {
    let parts: Vec<&str> = host_key.split(' ').collect();
    matches!(parts.as_slice(), [kind, body] if is_token(kind) && is_base64(body))
}

fn is_token(text: &str) -> bool {
    !text.is_empty() && !text.chars().any(|c| c.is_whitespace() || c.is_control())
}

fn is_base64(text: &str) -> bool {
    !text.is_empty()
        && text
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='))
}

/// On the joining device, before anything is written: the row `host` sent
/// for this device carries this device's three keys and verifies under the
/// host's key.
pub fn check_own_paired_row(
    own: &str,
    device: &DeviceKeys,
    row: &SignedRecord,
    host: &str,
    host_key: &VerifyingKey,
) -> Result<()> {
    let record = &row.record;
    ensure!(
        record.machine_id == own,
        "the pairing device sent a row for machine {}, not this device ({own})",
        record.machine_id
    );
    ensure!(
        record.age_recipient == device.age_recipient().to_string()
            && record.ssh_public_key == device.ssh_public_key()
            && record.signing_public_key == device.verifying_key().to_bytes(),
        "the pairing device sent a row for other keys than this device's"
    );
    row.verify_by(host, host_key)
}

/// On the joining device: takes the first row `host` signed for it as this
/// device's own, after `check_own_paired_row`. Floor bookkeeping is the
/// caller's, once the identity's other rows are stored.
pub fn take_own_paired_row(
    store: &SqliteStore,
    device: &DeviceKeys,
    row: &SignedRecord,
    host: &str,
    host_key: &VerifyingKey,
) -> Result<PriorIdentity> {
    let own = store.machine_id();
    check_own_paired_row(own, device, row, host, host_key)?;
    let prior = match store.device_record(own)? {
        Some(stored) if stored.current.record.identity_tag == row.record.identity_tag => {
            store.insert_first_device_record(row, host, host_key)?;
            PriorIdentity::Same
        }
        Some(stored) => {
            store.replace_device_record_for_new_identity(row, host, host_key)?;
            PriorIdentity::Other(IdentityTag::from(stored.current.record.identity_tag))
        }
        None => {
            store.insert_first_device_record(row, host, host_key)?;
            PriorIdentity::None
        }
    };
    Ok(prior)
}

/// On the joining device: takes the device list `host` sent over the
/// pairing channel. The host's own rows are taken on the channel's word. Any
/// other row needs a signature by a device already taken, or is
/// self-signed by the identity's founder (its tag derives from an epoch's
/// key id and that device's key) or by a member of a migrated identity,
/// whose rows the host took under the migration rules. Rows that never get
/// there are skipped. Returns how many other devices are stored.
pub fn take_paired_rows(
    store: &SqliteStore,
    tag: &IdentityTag,
    epochs: &[Epoch],
    host: &str,
    rows: &[SignedRecord],
) -> Result<usize> {
    let own = store.machine_id();
    let mut by_machine: BTreeMap<&str, Vec<&SignedRecord>> = BTreeMap::new();
    for row in rows {
        if row.record.identity_tag == tag.as_str() {
            by_machine
                .entry(row.record.machine_id.as_str())
                .or_default()
                .push(row);
        }
    }
    let mut keys = BTreeMap::new();
    for (id, versions) in &mut by_machine {
        versions.sort_by_key(|row| row.record.version);
        match versions[0].record.signing_public_key() {
            Ok(key) => {
                keys.insert(*id, key);
            }
            Err(e) => tracing::debug!("skipping the paired row for {id}: {e:#}"),
        }
    }
    let self_signed_ok = |id: &str| {
        keys.get(id).is_some_and(|key| {
            epochs.iter().any(|epoch| {
                *tag == IdentityTag::migrated(&epoch.key_id)
                    || *tag == IdentityTag::founded(&epoch.key_id, key)
            })
        })
    };

    let mut taken: BTreeSet<&str> = BTreeSet::from([own]);
    let mut pending: Vec<&str> = by_machine.keys().copied().filter(|id| *id != own).collect();
    pending.sort_by_key(|id| *id != host);
    let mut stored = 0;
    loop {
        let before = pending.len();
        let mut left = Vec::new();
        for id in pending {
            let versions = &by_machine[id];
            let first = versions[0];
            let signers: Vec<(&str, &VerifyingKey)> = first
                .signatures
                .iter()
                .filter_map(|s| {
                    let signer = s.signer.as_str();
                    let vouched = if signer == id {
                        id == host || self_signed_ok(id)
                    } else {
                        taken.contains(signer) || id == host
                    };
                    let key = keys.get(signer)?;
                    (vouched && first.verify_by(signer, key).is_ok()).then_some((signer, key))
                })
                .collect();
            if signers.is_empty() {
                left.push(id);
                continue;
            }
            match take_first(store, first, &signers) {
                Ok(()) => {
                    taken.insert(id);
                    stored += 1;
                }
                Err(e) => {
                    tracing::debug!("not taking the paired row for {id}: {e:#}");
                    continue;
                }
            }
            for later in &versions[1..] {
                if let Err(e) = store.update_device_record(later) {
                    tracing::debug!(
                        "not taking version {} of the paired row for {id}: {e:#}",
                        later.record.version
                    );
                }
            }
        }
        pending = left;
        if pending.is_empty() || pending.len() == before {
            for id in pending {
                tracing::debug!(
                    "not taking the paired row for {id}: no trusted signer vouches for it"
                );
            }
            return Ok(stored);
        }
    }
}

fn take_first(
    store: &SqliteStore,
    first: &SignedRecord,
    signers: &[(&str, &VerifyingKey)],
) -> Result<()> {
    let Some(((signer, key), rest)) = signers.split_first() else {
        bail!("no signer vouches for the row");
    };
    let held_elsewhere = store
        .device_record(&first.record.machine_id)?
        .is_some_and(|row| row.current.record.identity_tag != first.record.identity_tag);
    if held_elsewhere {
        store.replace_device_record_for_new_identity(first, signer, key)?;
    } else {
        store.insert_first_device_record(first, signer, key)?;
    }
    for (signer, key) in rest {
        store.insert_first_device_record(first, signer, key)?;
    }
    Ok(())
}

/// The signing key of `machine_id` from a device list, from its first row.
pub fn listed_signing_key(rows: &[SignedRecord], machine_id: &str) -> Result<VerifyingKey> {
    let Some(first) = rows
        .iter()
        .filter(|row| row.record.machine_id == machine_id)
        .min_by_key(|row| row.record.version)
    else {
        bail!("the device list has no row for {machine_id}");
    };
    first.record.signing_public_key()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::keys::{Revocation, found_identity};

    const NOW: i64 = 1_793_600_000_000_000;

    struct Side {
        store: SqliteStore,
        device: DeviceKeys,
    }

    fn side(id: &str) -> Side {
        Side {
            store: SqliteStore::in_memory(id.to_string()).unwrap(),
            device: DeviceKeys::generate().unwrap(),
        }
    }

    fn founded(id: &str) -> (Side, IdentityTag) {
        let side = side(id);
        let tag = found_identity(&side.store, &side.device, id, &[], NOW)
            .unwrap()
            .tag;
        (side, tag)
    }

    fn joining_record(joiner: &Side, tag: &IdentityTag) -> DeviceRecord {
        DeviceRecord {
            machine_id: joiner.store.machine_id().to_string(),
            identity_tag: tag.as_str().to_string(),
            version: 1,
            name: "laptop".into(),
            age_recipient: joiner.device.age_recipient().to_string(),
            ssh_public_key: joiner.device.ssh_public_key(),
            signing_public_key: joiner.device.verifying_key().to_bytes(),
            recovery_fingerprints: Vec::new(),
            ssh_login: Some("user".into()),
            ssh_port: Some(22),
            ssh_host_key: None,
        }
    }

    fn rows_of(store: &SqliteStore, tag: &IdentityTag) -> Vec<SignedRecord> {
        let mut rows = Vec::new();
        for row in store.device_records().unwrap() {
            if row.current.record.identity_tag != tag.as_str() {
                continue;
            }
            if row.current != row.first {
                rows.push(row.first);
            }
            rows.push(row.current);
        }
        rows
    }

    fn epochs_of(store: &SqliteStore, tag: &IdentityTag) -> Vec<Epoch> {
        store
            .key_epochs(tag)
            .unwrap()
            .into_iter()
            .map(|e| e.epoch)
            .collect()
    }

    #[test]
    fn a_joining_device_takes_the_row_its_pairer_signed_and_the_device_list() {
        let (host, tag) = founded("desk");
        let joiner = side("laptop");
        let row = admit_device(&host.store, &host.device, joining_record(&joiner, &tag)).unwrap();
        row.verify_by("desk", &host.device.verifying_key()).unwrap();

        let list = rows_of(&host.store, &tag);
        let host_key = listed_signing_key(&list, "desk").unwrap();
        assert_eq!(
            take_own_paired_row(&joiner.store, &joiner.device, &row, "desk", &host_key).unwrap(),
            PriorIdentity::None
        );
        let epochs = epochs_of(&host.store, &tag);
        assert_eq!(
            take_paired_rows(&joiner.store, &tag, &epochs, "desk", &list).unwrap(),
            1
        );

        let own = joiner.store.device_record("laptop").unwrap().unwrap();
        assert_eq!(own.current.record.identity_tag, tag.as_str());
        let desk = joiner.store.device_record("desk").unwrap().unwrap();
        desk.first.verify_self().unwrap();
        assert_eq!(
            desk.current,
            host.store.device_record("desk").unwrap().unwrap().current
        );
    }

    #[test]
    fn pairing_the_same_device_again_returns_its_row_even_after_its_fields_changed() {
        let (host, tag) = founded("desk");
        let joiner = side("laptop");
        let first = admit_device(&host.store, &host.device, joining_record(&joiner, &tag)).unwrap();
        let again = admit_device(&host.store, &host.device, joining_record(&joiner, &tag)).unwrap();
        assert_eq!(first, again);
        let changed = DeviceRecord {
            name: "renamed".into(),
            recovery_fingerprints: vec!["fp".into()],
            ssh_port: Some(2222),
            ..joining_record(&joiner, &tag)
        };
        assert_eq!(
            admit_device(&host.store, &host.device, changed).unwrap(),
            first
        );
    }

    #[test]
    fn a_kept_machine_id_with_new_keys_or_a_revoked_one_is_refused() {
        let (host, tag) = founded("desk");
        let joiner = side("laptop");
        admit_device(&host.store, &host.device, joining_record(&joiner, &tag)).unwrap();
        let reinstalled = side("laptop");
        let err = admit_device(
            &host.store,
            &host.device,
            joining_record(&reinstalled, &tag),
        )
        .unwrap_err();
        assert!(format!("{err:#}").contains("fresh machine id"), "{err:#}");

        host.store
            .conn()
            .execute("UPDATE machines SET revoked = 1 WHERE id = 'laptop'", [])
            .unwrap();
        let err =
            admit_device(&host.store, &host.device, joining_record(&joiner, &tag)).unwrap_err();
        assert!(format!("{err:#}").contains("removed"), "{err:#}");
    }

    #[test]
    fn a_joiner_known_only_by_its_stored_revocation_is_refused_before_any_write() {
        let (host, tag) = founded("desk");
        let joiner = side("laptop");
        let revocation = Revocation {
            identity_tag: tag.as_str().to_string(),
            revoker: "desk".into(),
            target: "laptop".into(),
            keep: BTreeSet::new(),
            created_at_micros: NOW,
        }
        .sign(host.device.signing_key());
        host.store
            .put_revocation(&revocation, &host.device.verifying_key())
            .unwrap();
        host.store.apply_revocations(&tag).unwrap();
        assert!(host.store.device_record("laptop").unwrap().is_none());

        let err =
            admit_device(&host.store, &host.device, joining_record(&joiner, &tag)).unwrap_err();
        let text = format!("{err:#}");
        assert!(text.contains("was removed from this identity"), "{text}");
        assert!(
            text.contains("cannot rejoin it under this machine id"),
            "{text}"
        );
        assert!(host.store.device_record("laptop").unwrap().is_none());
    }

    #[test]
    fn fields_that_would_break_an_ssh_file_are_refused_before_signing() {
        let (host, tag) = founded("desk");
        let joiner = side("laptop");
        let key = joiner.device.ssh_public_key();
        let bad = [
            DeviceRecord {
                machine_id: "lap top".into(),
                ..joining_record(&joiner, &tag)
            },
            DeviceRecord {
                machine_id: "lap/top".into(),
                ..joining_record(&joiner, &tag)
            },
            DeviceRecord {
                ssh_public_key: format!("{key}\ncommand=\"sh\" {key}"),
                ..joining_record(&joiner, &tag)
            },
            DeviceRecord {
                ssh_public_key: format!("{key} comment"),
                ..joining_record(&joiner, &tag)
            },
            DeviceRecord {
                ssh_login: Some("user\nroot".into()),
                ..joining_record(&joiner, &tag)
            },
            DeviceRecord {
                ssh_host_key: Some("ssh-ed25519 AAAA\n@cert-authority * x".into()),
                ..joining_record(&joiner, &tag)
            },
            DeviceRecord {
                name: "laptop\u{1b}[2J".into(),
                ..joining_record(&joiner, &tag)
            },
        ];
        for record in bad {
            assert!(
                admit_device(&host.store, &host.device, record.clone()).is_err(),
                "{record:?}"
            );
        }
        assert!(host.store.device_record("laptop").unwrap().is_none());
        let good = DeviceRecord {
            ssh_host_key: Some("ssh-ed25519 AAAAC3Nza+/=".into()),
            ..joining_record(&joiner, &tag)
        };
        admit_device(&host.store, &host.device, good).unwrap();
    }

    #[test]
    fn a_row_for_other_keys_or_not_signed_by_the_host_is_refused() {
        let (host, tag) = founded("desk");
        let joiner = side("laptop");
        let row = admit_device(&host.store, &host.device, joining_record(&joiner, &tag)).unwrap();
        let impostor = side("laptop");
        let host_key = host.device.verifying_key();
        let err = take_own_paired_row(&impostor.store, &impostor.device, &row, "desk", &host_key)
            .unwrap_err();
        assert!(format!("{err:#}").contains("other keys"), "{err:#}");

        let stranger = DeviceKeys::generate().unwrap();
        assert!(
            take_own_paired_row(
                &joiner.store,
                &joiner.device,
                &row,
                "desk",
                &stranger.verifying_key()
            )
            .is_err()
        );
        assert!(joiner.store.device_record("laptop").unwrap().is_none());
    }

    #[test]
    fn a_device_with_its_own_identity_moves_into_the_pairers() {
        let (host, tag) = founded("desk");
        let (joiner, old_tag) = founded("laptop");
        let row = admit_device(&host.store, &host.device, joining_record(&joiner, &tag)).unwrap();
        let host_key = host.device.verifying_key();
        assert_eq!(
            take_own_paired_row(&joiner.store, &joiner.device, &row, "desk", &host_key).unwrap(),
            PriorIdentity::Other(old_tag)
        );
        let own = joiner.store.device_record("laptop").unwrap().unwrap();
        assert_eq!(own.first, row);
        assert_eq!(
            take_own_paired_row(&joiner.store, &joiner.device, &row, "desk", &host_key).unwrap(),
            PriorIdentity::Same,
            "taking the same row again changes nothing"
        );
    }

    #[test]
    fn only_the_founder_or_a_taken_device_vouches_for_a_listed_row() {
        let (host, tag) = founded("desk");
        let joiner = side("laptop");
        let phone = side("phone");
        let ghost = side("ghost");
        let ghost_child = side("child");
        let outsider = DeviceKeys::generate().unwrap();

        let phone_row = DeviceRecord {
            machine_id: "phone".into(),
            ..joining_record(&phone, &tag)
        }
        .sign("desk", host.device.signing_key());
        let mut chained = DeviceRecord {
            machine_id: "tablet".into(),
            ..joining_record(&side("tablet"), &tag)
        }
        .sign("phone", phone.device.signing_key());
        chained.countersign("nobody", outsider.signing_key());
        let ghost_row = DeviceRecord {
            machine_id: "ghost".into(),
            ..joining_record(&ghost, &tag)
        }
        .sign("ghost", ghost.device.signing_key());
        let child_row = DeviceRecord {
            machine_id: "child".into(),
            ..joining_record(&ghost_child, &tag)
        }
        .sign("ghost", ghost.device.signing_key());

        let mut list = rows_of(&host.store, &tag);
        list.extend([child_row, ghost_row, chained, phone_row]);
        let epochs = epochs_of(&host.store, &tag);
        assert_eq!(
            take_paired_rows(&joiner.store, &tag, &epochs, "desk", &list).unwrap(),
            3,
            "desk (the founder), phone (signed by desk) and tablet (signed by phone)"
        );
        assert!(joiner.store.device_record("desk").unwrap().is_some());
        assert!(joiner.store.device_record("phone").unwrap().is_some());
        let tablet = joiner.store.device_record("tablet").unwrap().unwrap();
        assert_eq!(
            tablet
                .first
                .signatures
                .iter()
                .map(|s| s.signer.as_str())
                .collect::<Vec<_>>(),
            vec!["phone"]
        );
        assert!(joiner.store.device_record("ghost").unwrap().is_none());
        assert!(joiner.store.device_record("child").unwrap().is_none());
    }

    #[test]
    fn a_self_signed_founder_row_needs_the_tag_its_key_derives() {
        let (host, tag) = founded("desk");
        let joiner = side("laptop");
        let list = rows_of(&host.store, &tag);
        let unrelated = [Epoch {
            number: 1,
            key_id: crate::keys::IdentityKey::generate().unwrap().key_id(),
        }];
        assert_eq!(
            take_paired_rows(&joiner.store, &tag, &unrelated, "laptop-host", &list).unwrap(),
            0
        );
        let epochs = epochs_of(&host.store, &tag);
        assert_eq!(
            take_paired_rows(&joiner.store, &tag, &epochs, "laptop-host", &list).unwrap(),
            1
        );
    }
}