1use std::collections::HashSet;
2use std::fs;
3use std::path::Path;
4use std::sync::{Mutex, PoisonError};
5
6use anyhow::{Context, Result, bail};
7use base64::Engine;
8use base64::engine::general_purpose::STANDARD;
9use second_brain_core::keys::valid_machine_id;
10
11use crate::ssh::write_atomic;
12
13pub const TAG_PREFIX: &str = "second-brain:";
14
15const KEY_TYPE: &str = "ssh-ed25519";
16
17static WRITE_LOCK: Mutex<()> = Mutex::new(());
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Grant {
21 pub machine_id: String,
22 pub ssh_public_key: String,
23}
24
25#[derive(Debug, Clone, Default, PartialEq, Eq)]
26pub struct Change {
27 pub added: Vec<String>,
28 pub removed: Vec<String>,
29 pub skipped: Vec<(String, String)>,
32}
33
34impl Change {
35 pub fn is_empty(&self) -> bool {
36 self.added.is_empty() && self.removed.is_empty()
37 }
38}
39
40fn shell_word(path: &str) -> String {
41 let plain = path
42 .bytes()
43 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'+' | b'-'));
44 if plain {
45 path.to_string()
46 } else {
47 format!("'{}'", path.replace('\'', "'\\''"))
48 }
49}
50
51pub fn forced_line(sb: &Path, grant: &Grant) -> Result<String> {
52 let id = &grant.machine_id;
53 if !valid_machine_id(id) {
54 bail!("machine id {id:?} is not 1 to 128 of A-Z a-z 0-9 . _ -");
55 }
56 let mut fields = grant.ssh_public_key.split_whitespace();
57 let (Some(key_type), Some(key)) = (fields.next(), fields.next()) else {
58 bail!("ssh public key must be `{KEY_TYPE} <base64>`");
59 };
60 if key_type != KEY_TYPE {
61 bail!("ssh public key type {key_type:?} is not {KEY_TYPE}");
62 }
63 let blob = STANDARD
64 .decode(key)
65 .context("ssh public key is not valid base64")?;
66 if blob.is_empty() {
67 bail!("ssh public key is empty");
68 }
69 let sb = sb.to_str().context("sb path is not valid UTF-8")?;
70 if sb.is_empty()
71 || sb
72 .chars()
73 .any(|c| matches!(c, '"' | '\\' | '\n' | '\r' | '\0'))
74 {
75 bail!("sb path {sb:?} holds a character that cannot go in an authorized_keys command");
76 }
77 Ok(format!(
78 "command=\"{} sync-serve --machine {id}\",restrict {KEY_TYPE} {key} {TAG_PREFIX}{id}",
79 shell_word(sb)
80 ))
81}
82
83fn tagged_id(segment: &[u8]) -> Option<String> {
84 let text = String::from_utf8_lossy(segment);
85 let last = text.split_whitespace().next_back()?;
86 let id = last.strip_prefix(TAG_PREFIX)?;
87 (!id.is_empty()).then(|| id.to_string())
88}
89
90fn read_bytes(path: &Path) -> Result<Option<Vec<u8>>> {
91 match fs::read(path) {
92 Ok(bytes) => Ok(Some(bytes)),
93 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
94 Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
95 }
96}
97
98pub fn reconcile(path: &Path, sb: &Path, grants: &[Grant], cut: &[String]) -> Result<Change> {
99 let cut: HashSet<&str> = cut.iter().map(String::as_str).collect();
100 let mut wanted: Vec<(&str, String)> = Vec::new();
101 let mut skipped = Vec::new();
102 for grant in grants
103 .iter()
104 .filter(|g| !cut.contains(g.machine_id.as_str()))
105 {
106 if wanted.iter().any(|(id, _)| *id == grant.machine_id) {
107 continue;
108 }
109 match forced_line(sb, grant) {
110 Ok(line) => wanted.push((grant.machine_id.as_str(), line)),
111 Err(e) => skipped.push((grant.machine_id.clone(), format!("{e:#}"))),
112 }
113 }
114
115 let _guard = WRITE_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
116 let original = read_bytes(path)?;
117 let data = original.as_deref().unwrap_or_default();
118
119 let mut out: Vec<u8> = Vec::with_capacity(data.len());
120 let mut emitted: HashSet<String> = HashSet::new();
121 let mut change = Change {
122 skipped,
123 ..Change::default()
124 };
125 for segment in data.split_inclusive(|b| *b == b'\n') {
126 let Some(id) = tagged_id(segment) else {
127 out.extend_from_slice(segment);
128 continue;
129 };
130 let Some((_, line)) = wanted.iter().find(|(want, _)| *want == id) else {
131 if !change.removed.contains(&id) {
132 change.removed.push(id);
133 }
134 continue;
135 };
136 if !emitted.insert(id.clone()) {
137 continue;
138 }
139 let current = String::from_utf8_lossy(segment);
140 if current.trim_end_matches(['\n', '\r']) == line {
141 out.extend_from_slice(segment);
142 } else {
143 out.extend_from_slice(line.as_bytes());
144 out.push(b'\n');
145 change.added.push(id);
146 }
147 }
148 for (id, line) in &wanted {
149 if emitted.contains(*id) {
150 continue;
151 }
152 if out.last().is_some_and(|b| *b != b'\n') {
153 out.push(b'\n');
154 }
155 out.extend_from_slice(line.as_bytes());
156 out.push(b'\n');
157 change.added.push((*id).to_string());
158 }
159
160 if out == data {
161 return Ok(change);
162 }
163 write_atomic(path, &out, None)?;
164 Ok(change)
165}
166
167pub fn granted(path: &Path) -> Result<Vec<String>> {
168 let data = read_bytes(path)?.unwrap_or_default();
169 Ok(data.split(|b| *b == b'\n').filter_map(tagged_id).collect())
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175 use std::fs;
176 use std::os::unix::fs::PermissionsExt;
177 use std::path::PathBuf;
178
179 const KEY_A: &str =
180 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl";
181 const KEY_B: &str =
182 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJm";
183 const FOREIGN: &str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC0 alice@laptop";
184
185 fn grant(id: &str, key: &str) -> Grant {
186 Grant {
187 machine_id: id.to_string(),
188 ssh_public_key: key.to_string(),
189 }
190 }
191
192 fn sb() -> PathBuf {
193 PathBuf::from("/usr/local/bin/sb")
194 }
195
196 fn line(id: &str, key: &str) -> String {
197 forced_line(&sb(), &grant(id, key)).unwrap()
198 }
199
200 #[test]
201 fn forced_line_has_exact_shape() {
202 assert_eq!(
203 line("m-1", KEY_A),
204 format!(
205 "command=\"/usr/local/bin/sb sync-serve --machine m-1\",restrict {KEY_A} second-brain:m-1"
206 )
207 );
208 }
209
210 #[test]
211 fn forced_line_drops_key_comment() {
212 let with_comment = format!("{KEY_A} laptop comment");
213 assert_eq!(line("m-1", &with_comment), line("m-1", KEY_A));
214 }
215
216 #[test]
217 fn forced_line_single_quotes_path_with_space() {
218 let l = forced_line(Path::new("/opt/my sb/sb"), &grant("m", KEY_A)).unwrap();
219 assert!(l.starts_with("command=\"'/opt/my sb/sb' sync-serve --machine m\",restrict "));
220 }
221
222 #[test]
223 fn forced_line_refuses_bad_input() {
224 for id in ["", "a b", "a\nb", "a\"b", "a/b", &"x".repeat(129)] {
225 assert!(forced_line(&sb(), &grant(id, KEY_A)).is_err(), "id {id:?}");
226 }
227 for key in [
228 "",
229 "ssh-rsa AAAAB3NzaC1yc2E=",
230 "ssh-ed25519",
231 "ssh-ed25519 !!!notbase64",
232 "ecdsa-sha2-nistp256 AAAA",
233 ] {
234 assert!(forced_line(&sb(), &grant("m", key)).is_err(), "key {key:?}");
235 }
236 for path in ["/a\"b/sb", "/a\\b/sb", "/a\nb/sb", "/a\0b/sb"] {
237 assert!(
238 forced_line(Path::new(path), &grant("m", KEY_A)).is_err(),
239 "path {path:?}"
240 );
241 }
242 }
243
244 #[test]
245 fn one_grant_adds_one_tagged_line_and_keeps_foreign() {
246 let dir = tempfile::tempdir().unwrap();
247 let path = dir.path().join("authorized_keys");
248 let original = format!("# mine\n\n{FOREIGN}\n");
249 fs::write(&path, &original).unwrap();
250 let change = reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
251 assert_eq!(change.added, vec!["m-1".to_string()]);
252 assert!(change.removed.is_empty());
253 let now = fs::read_to_string(&path).unwrap();
254 assert_eq!(now, format!("{original}{}\n", line("m-1", KEY_A)));
255 assert_eq!(granted(&path).unwrap(), vec!["m-1".to_string()]);
256 }
257
258 #[test]
259 fn missing_final_newline_is_handled() {
260 let dir = tempfile::tempdir().unwrap();
261 let path = dir.path().join("authorized_keys");
262 fs::write(&path, FOREIGN).unwrap();
263 reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
264 assert_eq!(
265 fs::read_to_string(&path).unwrap(),
266 format!("{FOREIGN}\n{}\n", line("m-1", KEY_A))
267 );
268 }
269
270 #[test]
271 fn second_reconcile_changes_nothing_and_keeps_mtime() {
272 let dir = tempfile::tempdir().unwrap();
273 let path = dir.path().join("authorized_keys");
274 fs::write(&path, format!("{FOREIGN}\n")).unwrap();
275 let grants = [grant("m-1", KEY_A)];
276 reconcile(&path, &sb(), &grants, &[]).unwrap();
277 let before = fs::metadata(&path).unwrap().modified().unwrap();
278 std::thread::sleep(std::time::Duration::from_millis(20));
279 let change = reconcile(&path, &sb(), &grants, &[]).unwrap();
280 assert!(change.is_empty());
281 assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), before);
282 }
283
284 #[test]
285 fn cut_removes_only_that_id() {
286 let dir = tempfile::tempdir().unwrap();
287 let path = dir.path().join("authorized_keys");
288 fs::write(&path, format!("{FOREIGN}\n")).unwrap();
289 let grants = [grant("m-1", KEY_A), grant("m-2", KEY_B)];
290 reconcile(&path, &sb(), &grants, &[]).unwrap();
291 let change = reconcile(&path, &sb(), &grants[1..], &["m-1".to_string()]).unwrap();
292 assert_eq!(change.removed, vec!["m-1".to_string()]);
293 assert!(change.added.is_empty());
294 assert_eq!(
295 fs::read_to_string(&path).unwrap(),
296 format!("{FOREIGN}\n{}\n", line("m-2", KEY_B))
297 );
298 }
299
300 #[test]
301 fn changed_key_or_sb_path_replaces_line() {
302 let dir = tempfile::tempdir().unwrap();
303 let path = dir.path().join("authorized_keys");
304 reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
305 reconcile(&path, &sb(), &[grant("m-1", KEY_B)], &[]).unwrap();
306 assert_eq!(
307 fs::read_to_string(&path).unwrap(),
308 format!("{}\n", line("m-1", KEY_B))
309 );
310 let other = Path::new("/home/u/.cargo/bin/sb");
311 reconcile(&path, other, &[grant("m-1", KEY_B)], &[]).unwrap();
312 let expected = forced_line(other, &grant("m-1", KEY_B)).unwrap();
313 assert_eq!(fs::read_to_string(&path).unwrap(), format!("{expected}\n"));
314 }
315
316 #[test]
317 fn duplicate_tagged_lines_collapse() {
318 let dir = tempfile::tempdir().unwrap();
319 let path = dir.path().join("authorized_keys");
320 let l = line("m-1", KEY_A);
321 fs::write(&path, format!("{l}\n{FOREIGN}\n{l}\n")).unwrap();
322 reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
323 assert_eq!(
324 fs::read_to_string(&path).unwrap(),
325 format!("{l}\n{FOREIGN}\n")
326 );
327 }
328
329 #[test]
330 fn symlinked_file_is_written_through() {
331 let dir = tempfile::tempdir().unwrap();
332 let target = dir.path().join("real_keys");
333 fs::write(&target, format!("{FOREIGN}\n")).unwrap();
334 let link = dir.path().join("authorized_keys");
335 std::os::unix::fs::symlink(&target, &link).unwrap();
336 reconcile(&link, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
337 assert!(
338 fs::symlink_metadata(&link)
339 .unwrap()
340 .file_type()
341 .is_symlink()
342 );
343 assert!(
344 fs::read_to_string(&target)
345 .unwrap()
346 .contains("second-brain:m-1")
347 );
348 }
349
350 #[test]
351 fn modes_new_and_existing() {
352 let dir = tempfile::tempdir().unwrap();
353 let path = dir.path().join(".ssh").join("authorized_keys");
354 reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
355 let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
356 assert_eq!(mode(&path), 0o600);
357 assert_eq!(mode(path.parent().unwrap()), 0o700);
358 fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
359 reconcile(&path, &sb(), &[grant("m-2", KEY_B)], &[]).unwrap();
360 assert_eq!(mode(&path), 0o644);
361 }
362
363 #[test]
364 fn missing_file_with_only_cuts_is_not_created() {
365 let dir = tempfile::tempdir().unwrap();
366 let path = dir.path().join(".ssh").join("authorized_keys");
367 let change = reconcile(&path, &sb(), &[], &["m-1".to_string()]).unwrap();
368 assert!(change.is_empty());
369 assert!(!path.exists());
370 assert!(!path.parent().unwrap().exists());
371 assert!(granted(&path).unwrap().is_empty());
372 }
373
374 #[test]
375 fn a_bad_grant_is_skipped_and_the_rest_still_apply() {
376 let dir = tempfile::tempdir().unwrap();
377 let path = dir.path().join("authorized_keys");
378 fs::write(&path, format!("{}\n", line("gone", KEY_B))).unwrap();
379 let change = reconcile(
380 &path,
381 &sb(),
382 &[grant("bad id", KEY_A), grant("good", KEY_A)],
383 &["gone".to_string()],
384 )
385 .unwrap();
386 assert_eq!(granted(&path).unwrap(), vec!["good".to_string()]);
387 assert_eq!(change.removed, vec!["gone".to_string()]);
388 assert_eq!(
389 change
390 .skipped
391 .iter()
392 .map(|(id, _)| id.as_str())
393 .collect::<Vec<_>>(),
394 vec!["bad id"]
395 );
396 }
397
398 #[test]
399 fn a_tagged_line_with_no_grant_is_dropped() {
400 let dir = tempfile::tempdir().unwrap();
401 let path = dir.path().join("authorized_keys");
402 fs::write(
403 &path,
404 format!(
405 "{}\n{FOREIGN}\n{}\n",
406 line("gone", KEY_A),
407 line("kept", KEY_B)
408 ),
409 )
410 .unwrap();
411 let change = reconcile(&path, &sb(), &[grant("kept", KEY_B)], &[]).unwrap();
412 assert_eq!(change.removed, vec!["gone".to_string()]);
413 assert_eq!(
414 fs::read_to_string(&path).unwrap(),
415 format!("{FOREIGN}\n{}\n", line("kept", KEY_B))
416 );
417 }
418
419 #[test]
420 fn granted_lists_ids_in_file_order() {
421 let dir = tempfile::tempdir().unwrap();
422 let path = dir.path().join("authorized_keys");
423 fs::write(
424 &path,
425 format!(
426 "{}\n{FOREIGN}\n{}\n",
427 line("zed", KEY_A),
428 line("abe", KEY_B)
429 ),
430 )
431 .unwrap();
432 assert_eq!(
433 granted(&path).unwrap(),
434 vec!["zed".to_string(), "abe".to_string()]
435 );
436 }
437}