Skip to main content

second_brain_sync/keyring/
own_row.rs

1use std::sync::Mutex;
2
3use anyhow::{Context, Result};
4use second_brain_core::keys::{DeviceRecord, valid_host_key, valid_login};
5
6use super::Keyring;
7use crate::pairing::SshServer;
8
9/// Held from reading this device's row to storing its next version, so two
10/// writers never sign the same version and one of them fails.
11static OWN_ROW_WRITE: Mutex<()> = Mutex::new(());
12
13impl Keyring<'_> {
14    /// Signs the next version of this device's row when `edit` changes it.
15    /// False when `edit` changed nothing.
16    pub(super) fn update_own_row(&self, edit: impl FnOnce(&mut DeviceRecord)) -> Result<bool> {
17        let _writing = OWN_ROW_WRITE
18            .lock()
19            .unwrap_or_else(|poisoned| poisoned.into_inner());
20        let own = self.own();
21        let current = self
22            .store
23            .device_record(own)?
24            .context("this device has no signed row")?
25            .current
26            .record;
27        let mut record = current.clone();
28        edit(&mut record);
29        if record == current {
30            return Ok(false);
31        }
32        record.version = current.version + 1;
33        self.store
34            .update_device_record(&record.sign(own, self.device.signing_key()))
35    }
36
37    /// Puts this device's sshd into its signed row, so every device of its
38    /// identity can pin its host key and dial it, whichever device paired
39    /// it. A field `ssh` lacks, or holds in a form unsafe for ssh, keeps its
40    /// signed value. False when nothing changed or this device has no row.
41    pub fn sign_own_ssh(&self, ssh: &SshServer) -> Result<bool> {
42        if self.store.device_record(self.own())?.is_none() {
43            return Ok(false);
44        }
45        self.update_own_row(|record| {
46            if let Some(login) = ssh.login.as_ref().filter(|login| valid_login(login)) {
47                record.ssh_login = Some(login.clone());
48            }
49            if ssh.port != 0 {
50                record.ssh_port = Some(ssh.port);
51            }
52            if let Some(host_key) = ssh.row_host_key().filter(|key| valid_host_key(key)) {
53                record.ssh_host_key = Some(host_key.to_string());
54            }
55        })
56    }
57}