second_brain_sync/keyring/
own_row.rs1use 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
9static OWN_ROW_WRITE: Mutex<()> = Mutex::new(());
12
13impl Keyring<'_> {
14 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 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}