Skip to main content

second_brain_sync/keyring/
pairing.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::path::Path;
3
4use age::x25519::Recipient;
5use anyhow::{Context, Result, anyhow, bail, ensure};
6use second_brain_core::keys::{
7    DeviceRecord, Epoch, IdentityTag, PriorIdentity, Revocation, admit_device,
8    check_own_paired_row, listed_signing_key, recovery_fingerprint, revoked_by,
9    take_own_paired_row, take_paired_rows, wrap_for_recovery,
10};
11use second_brain_core::sqlite_store::SqliteStore;
12
13use super::Keyring;
14use crate::pairing::{Admission, JoinRequest, SshServer};
15use crate::protocol::SYNC_PROTOCOL_VERSION;
16
17/// What a joining device took from its admission.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Joined {
20    pub identity: IdentityTag,
21    /// The epochs this device now opens.
22    pub epochs: Vec<Epoch>,
23    /// This device held no identity before.
24    pub first: bool,
25    /// This device held another identity before.
26    pub moved: bool,
27    /// Other devices of the identity now in this store.
28    pub devices: usize,
29}
30
31impl Keyring<'_> {
32    /// What this device sends a pairing device once the code is proven.
33    pub fn join_request(
34        &self,
35        name: &str,
36        ssh: Option<SshServer>,
37        addresses: Vec<String>,
38    ) -> Result<JoinRequest> {
39        Ok(JoinRequest {
40            machine_id: self.own().to_string(),
41            name: name.to_string(),
42            age_recipient: self.device.age_recipient().to_string(),
43            ssh_public_key: self.device.ssh_public_key(),
44            signing_public_key: hex(&self.device.verifying_key().to_bytes()),
45            ssh,
46            addresses,
47            sync_protocol: SYNC_PROTOCOL_VERSION,
48            schema_version: self.store.schema_version()?,
49        })
50    }
51
52    /// Signs the joining device's first row into this identity and answers
53    /// with every epoch wrapped for it, the device list, the revocations
54    /// behind the epochs and this device's recovery recipients.
55    pub fn admit(
56        &self,
57        request: &JoinRequest,
58        name: &str,
59        ssh: Option<SshServer>,
60        addresses: Vec<String>,
61    ) -> Result<Admission> {
62        let tag = self
63            .identity
64            .as_ref()
65            .context("this device has no sync identity to pair a device into")?;
66        ensure!(!self.is_removed()?, REMOVED);
67        let schema_version = self.store.schema_version()?;
68        if (request.sync_protocol, request.schema_version)
69            != (SYNC_PROTOCOL_VERSION, schema_version)
70        {
71            bail!(
72                "{} runs sync protocol {} on schema {} and this device runs protocol {} on schema \
73                 {}; upgrade the older one, then pair again",
74                request.name,
75                request.sync_protocol,
76                request.schema_version,
77                SYNC_PROTOCOL_VERSION,
78                schema_version
79            );
80        }
81        ensure!(
82            !self.held.is_empty(),
83            "this device opens no epoch of its identity, so it has nothing to hand over"
84        );
85        let recovery = self.store.recovery_recipients(tag)?;
86        let record = DeviceRecord {
87            machine_id: request.machine_id.clone(),
88            identity_tag: tag.as_str().to_string(),
89            version: 1,
90            name: request.name.clone(),
91            age_recipient: request.age_recipient.clone(),
92            ssh_public_key: request.ssh_public_key.clone(),
93            signing_public_key: unhex32(&request.signing_public_key)
94                .context("the joining device sent a signing key that is not 64 hex digits")?,
95            recovery_fingerprints: recovery
96                .iter()
97                .map(|r| recovery_fingerprint(&r.to_string()))
98                .collect(),
99            ssh_login: request.ssh.as_ref().and_then(|s| s.login.clone()),
100            ssh_port: request.ssh.as_ref().map(|s| s.port),
101            ssh_host_key: request
102                .ssh
103                .as_ref()
104                .and_then(|s| s.row_host_key().map(str::to_string)),
105        };
106        admit_device(self.store, &self.device, record)?;
107        ensure!(
108            self.active_row(&request.machine_id)?.is_some(),
109            "{} is not an active device of this identity after its row was stored, so no epoch \
110             can be wrapped for it",
111            request.name
112        );
113        let keys = self.handshake_for(&request.machine_id, Some(&[]))?;
114        let unwrapped: Vec<u32> = self
115            .held
116            .iter()
117            .map(|(epoch, _)| epoch)
118            .filter(|epoch| !keys.envelopes.iter().any(|e| e.epoch == **epoch))
119            .map(|epoch| epoch.number)
120            .collect();
121        ensure!(
122            unwrapped.is_empty(),
123            "epochs {unwrapped:?} were not wrapped for {}",
124            request.name
125        );
126        Ok(Admission {
127            machine_id: self.own().to_string(),
128            name: name.to_string(),
129            keys,
130            recovery_recipients: recovery.iter().map(ToString::to_string).collect(),
131            ssh,
132            addresses,
133            sync_protocol: SYNC_PROTOCOL_VERSION,
134            schema_version,
135        })
136    }
137}
138
139/// On the joining device: takes the row the pairing device signed for it,
140/// the device list it vouched for over the channel, the epochs wrapped for
141/// it and its recovery recipients, adding them to the recipients this
142/// device trusted under an identity it leaves. Everything is checked before
143/// the first write, so a refused admission leaves this device as it was.
144/// Safe to rerun with the same admission.
145pub fn take_admission(
146    store: &SqliteStore,
147    data_dir: &Path,
148    admission: &Admission,
149    now_micros: i64,
150) -> Result<Joined> {
151    let host = &admission.machine_id;
152    let keys = &admission.keys;
153    let tag = keys
154        .identity_tag
155        .clone()
156        .context("the pairing device sent no identity")?;
157    let rows = &keys.devices;
158    let own = store.machine_id();
159    let own_row = rows
160        .iter()
161        .filter(|row| row.record.machine_id == own && row.record.identity_tag == tag.as_str())
162        .min_by_key(|row| row.record.version)
163        .context("the pairing device sent no row for this device")?;
164    let host_key = listed_signing_key(rows, host)?;
165    let before = Keyring::load(store, data_dir)?;
166    check_own_paired_row(own, &before.device, own_row, host, &host_key)?;
167    let mut recovery = admission
168        .recovery_recipients
169        .iter()
170        .map(|text| {
171            text.parse::<Recipient>()
172                .map_err(|e| anyhow!("the pairing device sent an invalid recovery recipient: {e}"))
173        })
174        .collect::<Result<Vec<_>>>()?;
175    check_not_revoked(store, &tag, admission)?;
176    before.check_envelopes_open(&tag, admission)?;
177    if let Some(earlier) = before.identity.as_ref().filter(|earlier| **earlier != tag) {
178        for recipient in store.recovery_recipients(earlier)? {
179            if !recovery
180                .iter()
181                .any(|r| r.to_string() == recipient.to_string())
182            {
183                recovery.push(recipient);
184            }
185        }
186    }
187
188    let prior = take_own_paired_row(store, &before.device, own_row, host, &host_key)?;
189    let devices = take_paired_rows(store, &tag, &keys.epochs, host, rows)?;
190    if prior != PriorIdentity::Same {
191        store.reset_floor_for_new_identity(&tag)?;
192    }
193    store.apply_revocations(&tag)?;
194
195    Keyring::load(store, data_dir)?.accept(host, keys, now_micros)?;
196    let keyring = Keyring::load(store, data_dir)?;
197    ensure!(
198        !keyring.held.is_empty(),
199        "the pairing device's envelopes did not open on this device"
200    );
201    keyring.list_recovery_fingerprints(&recovery)?;
202    let held: Vec<_> = keyring
203        .held
204        .iter()
205        .map(|(epoch, key)| (*epoch, key))
206        .collect();
207    wrap_for_recovery(store, &tag, &held, &recovery)?;
208    keyring.fill_recovery_envelopes()?;
209    Ok(Joined {
210        identity: tag,
211        epochs: keyring.held_epochs(),
212        first: prior == PriorIdentity::None,
213        moved: matches!(prior, PriorIdentity::Other(_)),
214        devices,
215    })
216}
217
218pub const REMOVED: &str = "this device was removed from its sync identity, so it cannot add devices; \
219                       join another device's identity with `sb pair <code>` on this device";
220
221/// Refuses an admission when the revocations it carries or this store
222/// holds reach the pairing device or this one, counting the first-row
223/// signatures it carries, those stored, and the pairer's on this device's
224/// row: taking it would leave this device revoked. This device is named as
225/// the removed one only when it is reached without the pairer's signature.
226fn check_not_revoked(store: &SqliteStore, tag: &IdentityTag, admission: &Admission) -> Result<()> {
227    let keys = &admission.keys;
228    let own = store.machine_id();
229    let mut firsts: BTreeMap<String, (u64, BTreeSet<String>)> = BTreeMap::new();
230    for row in keys
231        .devices
232        .iter()
233        .filter(|r| r.record.identity_tag == tag.as_str())
234    {
235        let id = &row.record.machine_id;
236        let signers = row
237            .signatures
238            .iter()
239            .map(|s| s.signer.clone())
240            .filter(|signer| signer != id)
241            .collect();
242        let earlier = firsts
243            .get(id)
244            .is_some_and(|(version, _)| *version <= row.record.version);
245        if !earlier {
246            firsts.insert(id.clone(), (row.record.version, signers));
247        }
248    }
249    let mut first_signers: BTreeMap<String, BTreeSet<String>> = firsts
250        .into_iter()
251        .map(|(id, (_, signers))| (id, signers))
252        .collect();
253    for row in store.device_records()? {
254        if row.first.record.identity_tag != tag.as_str() {
255            continue;
256        }
257        let id = row.first.record.machine_id.clone();
258        first_signers.entry(id.clone()).or_default().extend(
259            row.first
260                .signatures
261                .into_iter()
262                .map(|s| s.signer)
263                .filter(|signer| *signer != id),
264        );
265    }
266    let stored = store.revocations(tag)?;
267    let rules: Vec<&Revocation> = keys
268        .revocations
269        .iter()
270        .chain(&stored)
271        .map(|signed| &signed.revocation)
272        .filter(|r| r.identity_tag == tag.as_str())
273        .collect();
274    let mut without_pairer = first_signers.clone();
275    if let Some(signers) = without_pairer.get_mut(own) {
276        signers.remove(&admission.machine_id);
277    }
278    ensure!(
279        !revoked_by(&without_pairer, &rules).contains(own),
280        "this device was removed from {}'s sync identity, so it cannot rejoin it under this \
281         machine id; nothing was changed",
282        admission.name
283    );
284    first_signers
285        .entry(own.to_string())
286        .or_default()
287        .insert(admission.machine_id.clone());
288    let reached = revoked_by(&first_signers, &rules);
289    ensure!(
290        !reached.contains(&admission.machine_id) && !reached.contains(own),
291        "{} was removed from its sync identity, so joining through it would leave this device \
292         removed too; nothing was changed. Pair from a device still in the identity",
293        admission.name
294    );
295    Ok(())
296}
297
298impl Keyring<'_> {
299    /// True once a revocation this device holds reaches it.
300    pub fn is_removed(&self) -> Result<bool> {
301        self.is_revoked(self.own())
302    }
303
304    /// At least one envelope in the admission is for this device, opens
305    /// under its key, and has every revocation its epoch's cause names in
306    /// the admission too, so taking it cannot strand this device keyless.
307    fn check_envelopes_open(&self, tag: &IdentityTag, admission: &Admission) -> Result<()> {
308        let keys = &admission.keys;
309        let sent: BTreeSet<String> = keys.revocations.iter().map(|r| r.id()).collect();
310        let recipient = self.device.age_recipient().to_string();
311        let usable = keys.envelopes.iter().any(|envelope| {
312            let cause_held = keys
313                .causes
314                .iter()
315                .find(|(epoch, _)| *epoch == envelope.epoch)
316                .is_none_or(|(_, cause)| cause.revocations.is_subset(&sent));
317            envelope.identity_tag == *tag
318                && envelope.recipient == recipient
319                && envelope.machine_id.as_deref() == Some(self.own())
320                && cause_held
321                && envelope.open(self.device.age_identity()).is_ok()
322        });
323        ensure!(
324            usable,
325            "none of the epochs {} sent opens on this device; nothing was changed",
326            admission.name
327        );
328        Ok(())
329    }
330
331    /// Lists in this device's own row the fingerprints of `recovery` it does
332    /// not list yet and that are not retired, under its own signature.
333    fn list_recovery_fingerprints(&self, recovery: &[Recipient]) -> Result<()> {
334        let retired = self.store.retired_fingerprints()?;
335        self.update_own_row(|record| {
336            for recipient in recovery {
337                let fingerprint = recovery_fingerprint(&recipient.to_string());
338                if !retired.contains(&fingerprint)
339                    && !record.recovery_fingerprints.contains(&fingerprint)
340                {
341                    record.recovery_fingerprints.push(fingerprint);
342                }
343            }
344        })?;
345        Ok(())
346    }
347}
348
349fn hex(bytes: &[u8]) -> String {
350    bytes.iter().map(|b| format!("{b:02x}")).collect()
351}
352
353fn unhex32(text: &str) -> Option<[u8; 32]> {
354    let digits = text.as_bytes();
355    if digits.len() != 64 {
356        return None;
357    }
358    let mut out = [0u8; 32];
359    for (byte, pair) in out.iter_mut().zip(digits.chunks_exact(2)) {
360        let high = char::from(pair[0]).to_digit(16)?;
361        let low = char::from(pair[1]).to_digit(16)?;
362        *byte = u8::try_from((high << 4) | low).ok()?;
363    }
364    Some(out)
365}