second_brain_api/
device_access.rs1use std::path::{Path, PathBuf};
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use anyhow::{Result, bail};
5use second_brain_core::keys::valid_machine_id;
6use second_brain_core::sqlite_store::SqliteStore;
7use second_brain_sync::authorized_keys::{self, Grant};
8use second_brain_sync::ssh::{
9 DevicePin, device_alias, known_hosts_path_in, pin_alias, unpin_devices,
10};
11
12#[derive(Default)]
15pub struct DeviceAccess {
16 pub authorized_keys: Option<PathBuf>,
18 pub sb: PathBuf,
20 kick: AtomicBool,
21}
22
23#[derive(Default)]
26pub struct Access {
27 pub grants: Vec<Grant>,
28 pub host_keys: Vec<(String, String)>,
29 pub cut: Vec<String>,
30 pub cut_pins: Vec<DevicePin>,
31 pub kept_pins: Vec<DevicePin>,
32}
33
34impl DeviceAccess {
35 pub fn for_this_user() -> Self {
38 let authorized_keys = home().map(|home| home.join(".ssh/authorized_keys"));
39 Self {
40 authorized_keys,
41 sb: installed_sb(),
42 kick: AtomicBool::new(false),
43 }
44 }
45
46 pub fn with_authorized_keys(path: PathBuf, sb: PathBuf) -> Self {
47 Self {
48 authorized_keys: Some(path),
49 sb,
50 kick: AtomicBool::new(false),
51 }
52 }
53
54 pub fn kick(&self) {
55 self.kick.store(true, Ordering::SeqCst);
56 }
57
58 pub fn take_kick(&self) -> bool {
59 self.kick.swap(false, Ordering::SeqCst)
60 }
61
62 pub fn reconcile(&self, sqlite: &SqliteStore, data_dir: &Path) -> Result<()> {
69 let access = access_of(sqlite)?;
70 let mut failed: Vec<String> = Vec::new();
71 if let Some(path) = &self.authorized_keys {
72 match authorized_keys::reconcile(path, &self.sb, &access.grants, &access.cut) {
73 Ok(change) => {
74 if !change.is_empty() {
75 tracing::info!(
76 "ssh access for devices: added {:?}, removed {:?}",
77 change.added,
78 change.removed
79 );
80 }
81 for (machine_id, reason) in &change.skipped {
82 tracing::warn!("no ssh access for device {machine_id}: {reason}");
83 }
84 }
85 Err(e) => failed.push(format!("updating {}: {e:#}", path.display())),
86 }
87 }
88 let known_hosts = known_hosts_path_in(data_dir);
89 if let Err(e) = unpin_devices(&known_hosts, &access.cut_pins, &access.kept_pins) {
90 failed.push(format!("unpinning cut devices' host keys: {e:#}"));
91 }
92 for (machine_id, host_key) in &access.host_keys {
93 if let Err(e) = pin_alias(
94 &known_hosts,
95 &device_alias(machine_id),
96 std::slice::from_ref(host_key),
97 ) {
98 failed.push(format!("pinning {machine_id}'s host key: {e:#}"));
99 }
100 }
101 if failed.is_empty() {
102 Ok(())
103 } else {
104 bail!("{}", failed.join("; "))
105 }
106 }
107
108 pub fn sweep(&self, sqlite: &SqliteStore, data_dir: &Path) {
111 if let Err(e) = self.reconcile(sqlite, data_dir) {
112 tracing::warn!("cannot update device ssh access: {e:#}");
113 }
114 }
115}
116
117pub fn access_of(sqlite: &SqliteStore) -> Result<Access> {
118 let own = sqlite.machine_id().to_string();
119 let rows = sqlite.device_records()?;
120 let identity = rows
121 .iter()
122 .find(|row| row.current.record.machine_id == own)
123 .map(|row| row.current.record.identity_tag.clone());
124 let mut access = Access::default();
125 for row in rows {
126 let record = row.current.record;
127 if record.machine_id == own || !valid_machine_id(&record.machine_id) {
128 continue;
129 }
130 let pin = DevicePin {
131 alias: device_alias(&record.machine_id),
132 signed_host_key: record.ssh_host_key.clone(),
133 };
134 if row.revoked || Some(&record.identity_tag) != identity.as_ref() {
135 access.cut.push(record.machine_id);
136 access.cut_pins.push(pin);
137 continue;
138 }
139 access.kept_pins.push(pin);
140 if let Some(host_key) = record.ssh_host_key.clone() {
141 access.host_keys.push((record.machine_id.clone(), host_key));
142 }
143 if !record.ssh_public_key.is_empty() {
144 access.grants.push(Grant {
145 machine_id: record.machine_id,
146 ssh_public_key: record.ssh_public_key,
147 });
148 }
149 }
150 Ok(access)
151}
152
153fn installed_sb() -> PathBuf {
154 let beside = std::env::current_exe()
155 .ok()
156 .and_then(|exe| exe.parent().map(|dir| dir.join("sb")));
157 let cargo = home().map(|home| home.join(".cargo/bin/sb"));
158 beside
159 .iter()
160 .chain(cargo.iter())
161 .find(|path| path.exists())
162 .or(beside.as_ref())
163 .cloned()
164 .unwrap_or_else(|| PathBuf::from("sb"))
165}
166
167fn home() -> Option<PathBuf> {
168 std::env::var_os("HOME")
169 .filter(|home| !home.is_empty())
170 .map(PathBuf::from)
171}