second-brain-sync 0.13.2

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::sync::{Mutex, PoisonError};

use anyhow::{Context, Result, bail};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use second_brain_core::keys::valid_machine_id;

use crate::ssh::write_atomic;

pub const TAG_PREFIX: &str = "second-brain:";

const KEY_TYPE: &str = "ssh-ed25519";

static WRITE_LOCK: Mutex<()> = Mutex::new(());

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grant {
    pub machine_id: String,
    pub ssh_public_key: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Change {
    pub added: Vec<String>,
    pub removed: Vec<String>,
    /// Grants left out because no safe line could be built for them, with
    /// the reason; the rest are still applied.
    pub skipped: Vec<(String, String)>,
}

impl Change {
    pub fn is_empty(&self) -> bool {
        self.added.is_empty() && self.removed.is_empty()
    }
}

fn shell_word(path: &str) -> String {
    let plain = path
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'+' | b'-'));
    if plain {
        path.to_string()
    } else {
        format!("'{}'", path.replace('\'', "'\\''"))
    }
}

pub fn forced_line(sb: &Path, grant: &Grant) -> Result<String> {
    let id = &grant.machine_id;
    if !valid_machine_id(id) {
        bail!("machine id {id:?} is not 1 to 128 of A-Z a-z 0-9 . _ -");
    }
    let mut fields = grant.ssh_public_key.split_whitespace();
    let (Some(key_type), Some(key)) = (fields.next(), fields.next()) else {
        bail!("ssh public key must be `{KEY_TYPE} <base64>`");
    };
    if key_type != KEY_TYPE {
        bail!("ssh public key type {key_type:?} is not {KEY_TYPE}");
    }
    let blob = STANDARD
        .decode(key)
        .context("ssh public key is not valid base64")?;
    if blob.is_empty() {
        bail!("ssh public key is empty");
    }
    let sb = sb.to_str().context("sb path is not valid UTF-8")?;
    if sb.is_empty()
        || sb
            .chars()
            .any(|c| matches!(c, '"' | '\\' | '\n' | '\r' | '\0'))
    {
        bail!("sb path {sb:?} holds a character that cannot go in an authorized_keys command");
    }
    Ok(format!(
        "command=\"{} sync-serve --machine {id}\",restrict {KEY_TYPE} {key} {TAG_PREFIX}{id}",
        shell_word(sb)
    ))
}

fn tagged_id(segment: &[u8]) -> Option<String> {
    let text = String::from_utf8_lossy(segment);
    let last = text.split_whitespace().next_back()?;
    let id = last.strip_prefix(TAG_PREFIX)?;
    (!id.is_empty()).then(|| id.to_string())
}

fn read_bytes(path: &Path) -> Result<Option<Vec<u8>>> {
    match fs::read(path) {
        Ok(bytes) => Ok(Some(bytes)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
    }
}

pub fn reconcile(path: &Path, sb: &Path, grants: &[Grant], cut: &[String]) -> Result<Change> {
    let cut: HashSet<&str> = cut.iter().map(String::as_str).collect();
    let mut wanted: Vec<(&str, String)> = Vec::new();
    let mut skipped = Vec::new();
    for grant in grants
        .iter()
        .filter(|g| !cut.contains(g.machine_id.as_str()))
    {
        if wanted.iter().any(|(id, _)| *id == grant.machine_id) {
            continue;
        }
        match forced_line(sb, grant) {
            Ok(line) => wanted.push((grant.machine_id.as_str(), line)),
            Err(e) => skipped.push((grant.machine_id.clone(), format!("{e:#}"))),
        }
    }

    let _guard = WRITE_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
    let original = read_bytes(path)?;
    let data = original.as_deref().unwrap_or_default();

    let mut out: Vec<u8> = Vec::with_capacity(data.len());
    let mut emitted: HashSet<String> = HashSet::new();
    let mut change = Change {
        skipped,
        ..Change::default()
    };
    for segment in data.split_inclusive(|b| *b == b'\n') {
        let Some(id) = tagged_id(segment) else {
            out.extend_from_slice(segment);
            continue;
        };
        let Some((_, line)) = wanted.iter().find(|(want, _)| *want == id) else {
            if !change.removed.contains(&id) {
                change.removed.push(id);
            }
            continue;
        };
        if !emitted.insert(id.clone()) {
            continue;
        }
        let current = String::from_utf8_lossy(segment);
        if current.trim_end_matches(['\n', '\r']) == line {
            out.extend_from_slice(segment);
        } else {
            out.extend_from_slice(line.as_bytes());
            out.push(b'\n');
            change.added.push(id);
        }
    }
    for (id, line) in &wanted {
        if emitted.contains(*id) {
            continue;
        }
        if out.last().is_some_and(|b| *b != b'\n') {
            out.push(b'\n');
        }
        out.extend_from_slice(line.as_bytes());
        out.push(b'\n');
        change.added.push((*id).to_string());
    }

    if out == data {
        return Ok(change);
    }
    write_atomic(path, &out, None)?;
    Ok(change)
}

pub fn granted(path: &Path) -> Result<Vec<String>> {
    let data = read_bytes(path)?.unwrap_or_default();
    Ok(data.split(|b| *b == b'\n').filter_map(tagged_id).collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::os::unix::fs::PermissionsExt;
    use std::path::PathBuf;

    const KEY_A: &str =
        "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl";
    const KEY_B: &str =
        "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJm";
    const FOREIGN: &str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC0 alice@laptop";

    fn grant(id: &str, key: &str) -> Grant {
        Grant {
            machine_id: id.to_string(),
            ssh_public_key: key.to_string(),
        }
    }

    fn sb() -> PathBuf {
        PathBuf::from("/usr/local/bin/sb")
    }

    fn line(id: &str, key: &str) -> String {
        forced_line(&sb(), &grant(id, key)).unwrap()
    }

    #[test]
    fn forced_line_has_exact_shape() {
        assert_eq!(
            line("m-1", KEY_A),
            format!(
                "command=\"/usr/local/bin/sb sync-serve --machine m-1\",restrict {KEY_A} second-brain:m-1"
            )
        );
    }

    #[test]
    fn forced_line_drops_key_comment() {
        let with_comment = format!("{KEY_A} laptop comment");
        assert_eq!(line("m-1", &with_comment), line("m-1", KEY_A));
    }

    #[test]
    fn forced_line_single_quotes_path_with_space() {
        let l = forced_line(Path::new("/opt/my sb/sb"), &grant("m", KEY_A)).unwrap();
        assert!(l.starts_with("command=\"'/opt/my sb/sb' sync-serve --machine m\",restrict "));
    }

    #[test]
    fn forced_line_refuses_bad_input() {
        for id in ["", "a b", "a\nb", "a\"b", "a/b", &"x".repeat(129)] {
            assert!(forced_line(&sb(), &grant(id, KEY_A)).is_err(), "id {id:?}");
        }
        for key in [
            "",
            "ssh-rsa AAAAB3NzaC1yc2E=",
            "ssh-ed25519",
            "ssh-ed25519 !!!notbase64",
            "ecdsa-sha2-nistp256 AAAA",
        ] {
            assert!(forced_line(&sb(), &grant("m", key)).is_err(), "key {key:?}");
        }
        for path in ["/a\"b/sb", "/a\\b/sb", "/a\nb/sb", "/a\0b/sb"] {
            assert!(
                forced_line(Path::new(path), &grant("m", KEY_A)).is_err(),
                "path {path:?}"
            );
        }
    }

    #[test]
    fn one_grant_adds_one_tagged_line_and_keeps_foreign() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        let original = format!("# mine\n\n{FOREIGN}\n");
        fs::write(&path, &original).unwrap();
        let change = reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
        assert_eq!(change.added, vec!["m-1".to_string()]);
        assert!(change.removed.is_empty());
        let now = fs::read_to_string(&path).unwrap();
        assert_eq!(now, format!("{original}{}\n", line("m-1", KEY_A)));
        assert_eq!(granted(&path).unwrap(), vec!["m-1".to_string()]);
    }

    #[test]
    fn missing_final_newline_is_handled() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        fs::write(&path, FOREIGN).unwrap();
        reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            format!("{FOREIGN}\n{}\n", line("m-1", KEY_A))
        );
    }

    #[test]
    fn second_reconcile_changes_nothing_and_keeps_mtime() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        fs::write(&path, format!("{FOREIGN}\n")).unwrap();
        let grants = [grant("m-1", KEY_A)];
        reconcile(&path, &sb(), &grants, &[]).unwrap();
        let before = fs::metadata(&path).unwrap().modified().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(20));
        let change = reconcile(&path, &sb(), &grants, &[]).unwrap();
        assert!(change.is_empty());
        assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), before);
    }

    #[test]
    fn cut_removes_only_that_id() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        fs::write(&path, format!("{FOREIGN}\n")).unwrap();
        let grants = [grant("m-1", KEY_A), grant("m-2", KEY_B)];
        reconcile(&path, &sb(), &grants, &[]).unwrap();
        let change = reconcile(&path, &sb(), &grants[1..], &["m-1".to_string()]).unwrap();
        assert_eq!(change.removed, vec!["m-1".to_string()]);
        assert!(change.added.is_empty());
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            format!("{FOREIGN}\n{}\n", line("m-2", KEY_B))
        );
    }

    #[test]
    fn changed_key_or_sb_path_replaces_line() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
        reconcile(&path, &sb(), &[grant("m-1", KEY_B)], &[]).unwrap();
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            format!("{}\n", line("m-1", KEY_B))
        );
        let other = Path::new("/home/u/.cargo/bin/sb");
        reconcile(&path, other, &[grant("m-1", KEY_B)], &[]).unwrap();
        let expected = forced_line(other, &grant("m-1", KEY_B)).unwrap();
        assert_eq!(fs::read_to_string(&path).unwrap(), format!("{expected}\n"));
    }

    #[test]
    fn duplicate_tagged_lines_collapse() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        let l = line("m-1", KEY_A);
        fs::write(&path, format!("{l}\n{FOREIGN}\n{l}\n")).unwrap();
        reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            format!("{l}\n{FOREIGN}\n")
        );
    }

    #[test]
    fn symlinked_file_is_written_through() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real_keys");
        fs::write(&target, format!("{FOREIGN}\n")).unwrap();
        let link = dir.path().join("authorized_keys");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        reconcile(&link, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
        assert!(
            fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert!(
            fs::read_to_string(&target)
                .unwrap()
                .contains("second-brain:m-1")
        );
    }

    #[test]
    fn modes_new_and_existing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".ssh").join("authorized_keys");
        reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
        let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode(&path), 0o600);
        assert_eq!(mode(path.parent().unwrap()), 0o700);
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
        reconcile(&path, &sb(), &[grant("m-2", KEY_B)], &[]).unwrap();
        assert_eq!(mode(&path), 0o644);
    }

    #[test]
    fn missing_file_with_only_cuts_is_not_created() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".ssh").join("authorized_keys");
        let change = reconcile(&path, &sb(), &[], &["m-1".to_string()]).unwrap();
        assert!(change.is_empty());
        assert!(!path.exists());
        assert!(!path.parent().unwrap().exists());
        assert!(granted(&path).unwrap().is_empty());
    }

    #[test]
    fn a_bad_grant_is_skipped_and_the_rest_still_apply() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        fs::write(&path, format!("{}\n", line("gone", KEY_B))).unwrap();
        let change = reconcile(
            &path,
            &sb(),
            &[grant("bad id", KEY_A), grant("good", KEY_A)],
            &["gone".to_string()],
        )
        .unwrap();
        assert_eq!(granted(&path).unwrap(), vec!["good".to_string()]);
        assert_eq!(change.removed, vec!["gone".to_string()]);
        assert_eq!(
            change
                .skipped
                .iter()
                .map(|(id, _)| id.as_str())
                .collect::<Vec<_>>(),
            vec!["bad id"]
        );
    }

    #[test]
    fn a_tagged_line_with_no_grant_is_dropped() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        fs::write(
            &path,
            format!(
                "{}\n{FOREIGN}\n{}\n",
                line("gone", KEY_A),
                line("kept", KEY_B)
            ),
        )
        .unwrap();
        let change = reconcile(&path, &sb(), &[grant("kept", KEY_B)], &[]).unwrap();
        assert_eq!(change.removed, vec!["gone".to_string()]);
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            format!("{FOREIGN}\n{}\n", line("kept", KEY_B))
        );
    }

    #[test]
    fn granted_lists_ids_in_file_order() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("authorized_keys");
        fs::write(
            &path,
            format!(
                "{}\n{FOREIGN}\n{}\n",
                line("zed", KEY_A),
                line("abe", KEY_B)
            ),
        )
        .unwrap();
        assert_eq!(
            granted(&path).unwrap(),
            vec!["zed".to_string(), "abe".to_string()]
        );
    }
}