second-brain-sync 0.13.3

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
use std::fmt;
use std::io::{ErrorKind, Read, Write};
use std::net::TcpStream;
use std::time::{Duration, Instant};

use anyhow::{Context, Result, anyhow, bail};
use chacha20poly1305::aead::Aead;
use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce};
use hkdf::Hkdf;
use serde::Serialize;
use serde::de::DeserializeOwned;
use sha2::Sha256;
use spake2::{Ed25519Group, Identity, Password, Spake2};
use zeroize::Zeroizing;

use super::code::{CodeKind, HostSecrets, JoinCode};

const MAGIC: &[u8] = b"second-brain-pair/1";
const JOINER_ID: &[u8] = b"second-brain pairing joiner";
const HOST_ID: &[u8] = b"second-brain pairing host";
const JOINER_TO_HOST: &[u8] = b"second-brain pairing joiner to host";
const HOST_TO_JOINER: &[u8] = b"second-brain pairing host to joiner";
/// Frames before the code is proven are small, so an unauthenticated peer
/// cannot make the listener buffer much.
const OPENING_FRAME_MAX: usize = 256;
/// The host's reply carries every device row and every epoch wrapped for the
/// joiner.
const SEALED_FRAME_MAX: usize = 8 << 20;
/// The joiner's request, the only sealed frame read before the code is
/// proven.
const FIRST_SEALED_MAX: usize = 64 << 10;
pub const IO_TIMEOUT: Duration = Duration::from_secs(30);

/// The other side closed the channel before replying; for a joiner this is
/// how a wrong, retired or expired code shows.
#[derive(Debug)]
pub struct ChannelClosed;

impl fmt::Display for ChannelClosed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(
            "the pairing device closed the connection: the code was wrong, was retired after \
             failed tries, or its `sb pair` has stopped",
        )
    }
}

impl std::error::Error for ChannelClosed {}

/// A connection both sides keyed from the same code through SPAKE2; every
/// frame after the opening is sealed with ChaCha20-Poly1305.
pub struct Channel {
    stream: TcpStream,
    seal: ChaCha20Poly1305,
    open: ChaCha20Poly1305,
    sent: u64,
    received: u64,
}

impl fmt::Debug for Channel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Channel")
            .field("peer", &self.stream.peer_addr().ok())
            .finish_non_exhaustive()
    }
}

pub enum Accepted {
    /// The joiner proved the code; `first` is its first sealed frame.
    Opened {
        channel: Channel,
        first: Zeroizing<Vec<u8>>,
    },
    /// The joiner's first sealed frame did not open, so it ran SPAKE2 over
    /// another code. This counts as a failed try.
    WrongCode,
    /// The connection broke or did not speak the protocol before proving
    /// anything; this is not a try at the code.
    Broken(anyhow::Error),
}

impl Channel {
    /// The listener's side: the joiner speaks first, naming which secret it
    /// runs SPAKE2 over.
    /// Everything before the code is proven must arrive by `deadline`.
    pub fn accept(mut stream: TcpStream, secrets: &HostSecrets, deadline: Instant) -> Accepted {
        let opened = (|| -> Result<(Spake2<Ed25519Group>, Vec<u8>)> {
            set_timeouts(&stream)?;
            let opening = read_frame_by(&mut stream, OPENING_FRAME_MAX, Some(deadline))?;
            let rest = opening
                .strip_prefix(MAGIC)
                .context("the peer does not speak second-brain pairing")?;
            let (&kind, joiner_msg) = rest.split_first().context("the opening frame is empty")?;
            let kind = CodeKind::from_byte(kind).context("the opening frame names no code kind")?;
            let password = secrets.password(kind);
            let (state, host_msg) = Spake2::<Ed25519Group>::start_b(
                &Password::new(password.as_slice()),
                &Identity::new(JOINER_ID),
                &Identity::new(HOST_ID),
            );
            write_frame(&mut stream, &host_msg)?;
            Ok((state, joiner_msg.to_vec()))
        })();
        let (state, joiner_msg) = match opened {
            Ok(opened) => opened,
            Err(e) => return Accepted::Broken(e),
        };
        let key = match state.finish(&joiner_msg) {
            Ok(key) => Zeroizing::new(key),
            Err(e) => {
                return Accepted::Broken(anyhow!("the joiner's SPAKE2 message is bad: {e:?}"));
            }
        };
        let mut channel = match Self::keyed(stream, &key, HOST_TO_JOINER, JOINER_TO_HOST) {
            Ok(channel) => channel,
            Err(e) => return Accepted::Broken(e),
        };
        let sealed = match read_frame_by(&mut channel.stream, FIRST_SEALED_MAX, Some(deadline)) {
            Ok(sealed) => sealed,
            Err(e) => return Accepted::Broken(e),
        };
        if let Err(e) = set_timeouts(&channel.stream) {
            return Accepted::Broken(e);
        }
        match channel.open_frame(&sealed) {
            Ok(first) => Accepted::Opened { channel, first },
            Err(_) => Accepted::WrongCode,
        }
    }

    /// The joiner's side. The code is proven only when the host answers the
    /// first sealed frame.
    pub fn connect(mut stream: TcpStream, code: &JoinCode) -> Result<Self> {
        set_timeouts(&stream)?;
        let (state, joiner_msg) = Spake2::<Ed25519Group>::start_a(
            &Password::new(code.password()),
            &Identity::new(JOINER_ID),
            &Identity::new(HOST_ID),
        );
        let mut opening = MAGIC.to_vec();
        opening.push(code.kind().byte());
        opening.extend_from_slice(&joiner_msg);
        write_frame(&mut stream, &opening)?;
        let host_msg = read_frame(&mut stream, OPENING_FRAME_MAX)?;
        let key = Zeroizing::new(
            state
                .finish(&host_msg)
                .map_err(|e| anyhow!("the pairing device's SPAKE2 message is bad: {e:?}"))?,
        );
        Self::keyed(stream, &key, JOINER_TO_HOST, HOST_TO_JOINER)
    }

    fn keyed(stream: TcpStream, key: &[u8], seal_info: &[u8], open_info: &[u8]) -> Result<Self> {
        let hkdf = Hkdf::<Sha256>::new(None, key);
        let mut seal = Zeroizing::new([0u8; 32]);
        let mut open = Zeroizing::new([0u8; 32]);
        hkdf.expand(seal_info, seal.as_mut())
            .map_err(|e| anyhow!("deriving the pairing keys: {e}"))?;
        hkdf.expand(open_info, open.as_mut())
            .map_err(|e| anyhow!("deriving the pairing keys: {e}"))?;
        Ok(Self {
            stream,
            seal: ChaCha20Poly1305::new((&*seal).into()),
            open: ChaCha20Poly1305::new((&*open).into()),
            sent: 0,
            received: 0,
        })
    }

    pub fn set_read_timeout(&self, timeout: Duration) -> Result<()> {
        self.stream.set_read_timeout(Some(timeout))?;
        Ok(())
    }

    pub fn send(&mut self, plaintext: &[u8]) -> Result<()> {
        let nonce = nonce(self.sent);
        let sealed = self
            .seal
            .encrypt(&nonce, plaintext)
            .map_err(|_| anyhow!("sealing a pairing frame failed"))?;
        self.sent += 1;
        write_frame(&mut self.stream, &sealed)
    }

    pub fn recv(&mut self) -> Result<Zeroizing<Vec<u8>>> {
        let sealed = read_frame(&mut self.stream, SEALED_FRAME_MAX)?;
        self.open_frame(&sealed)
    }

    fn open_frame(&mut self, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
        let nonce = nonce(self.received);
        let plaintext = self
            .open
            .decrypt(&nonce, sealed)
            .map_err(|_| anyhow!("a pairing frame did not open"))?;
        self.received += 1;
        Ok(Zeroizing::new(plaintext))
    }

    pub fn send_json<T: Serialize>(&mut self, value: &T) -> Result<()> {
        let body = Zeroizing::new(serde_json::to_vec(value).context("encoding a pairing frame")?);
        self.send(&body)
    }

    pub fn recv_json<T: DeserializeOwned>(&mut self) -> Result<T> {
        let body = self.recv()?;
        serde_json::from_slice(&body).context("decoding a pairing frame")
    }
}

fn nonce(counter: u64) -> Nonce {
    let mut bytes = [0u8; 12];
    bytes[4..].copy_from_slice(&counter.to_be_bytes());
    bytes.into()
}

fn set_timeouts(stream: &TcpStream) -> Result<()> {
    stream.set_read_timeout(Some(IO_TIMEOUT))?;
    stream.set_write_timeout(Some(IO_TIMEOUT))?;
    Ok(())
}

fn write_frame(stream: &mut TcpStream, body: &[u8]) -> Result<()> {
    let len = u32::try_from(body.len()).context("a pairing frame is too large")?;
    stream.write_all(&len.to_be_bytes())?;
    stream.write_all(body)?;
    stream.flush()?;
    Ok(())
}

fn read_frame(stream: &mut TcpStream, max: usize) -> Result<Vec<u8>> {
    read_frame_by(stream, max, None)
}

/// With a deadline, every read waits only for the time left, so a peer
/// trickling bytes cannot hold the connection past it.
fn read_frame_by(stream: &mut TcpStream, max: usize, deadline: Option<Instant>) -> Result<Vec<u8>> {
    let mut len = [0u8; 4];
    read_full(stream, &mut len, deadline)?;
    let len = usize::try_from(u32::from_be_bytes(len)).unwrap_or(usize::MAX);
    if len > max {
        bail!("a pairing frame of {len} bytes is over the {max} byte limit");
    }
    let mut body = vec![0u8; len];
    read_full(stream, &mut body, deadline)?;
    Ok(body)
}

fn read_full(stream: &mut TcpStream, buf: &mut [u8], deadline: Option<Instant>) -> Result<()> {
    let mut filled = 0;
    while filled < buf.len() {
        if let Some(deadline) = deadline {
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                bail!("the peer did not finish the pairing opening in time");
            }
            stream.set_read_timeout(Some(left))?;
        }
        match stream.read(&mut buf[filled..]) {
            Ok(0) => return Err(ChannelClosed.into()),
            Ok(n) => filled += n,
            Err(e) if e.kind() == ErrorKind::Interrupted => {}
            Err(e) => return Err(e).context("reading a pairing frame"),
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::net::TcpListener;
    use std::sync::mpsc;
    use std::thread;

    use super::*;

    const WAIT: Duration = Duration::from_secs(20);

    fn pair_of(secrets: HostSecrets, code: JoinCode) -> (Result<Channel>, Accepted) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let (tx, rx) = mpsc::channel();
        let host = thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let accepted = Channel::accept(stream, &secrets, Instant::now() + WAIT);
            tx.send(()).unwrap();
            accepted
        });
        let joined =
            Channel::connect(TcpStream::connect(addr).unwrap(), &code).and_then(|mut channel| {
                channel.send(b"hello")?;
                Ok(channel)
            });
        rx.recv_timeout(WAIT).expect("the host side must finish");
        (joined, host.join().unwrap())
    }

    #[test]
    fn the_same_code_opens_a_channel_both_ways() {
        let secrets = HostSecrets::generate();
        let code = JoinCode::parse(&secrets.code()).unwrap();
        let (joined, accepted) = pair_of(secrets, code);
        let mut joiner = joined.unwrap();
        let Accepted::Opened { mut channel, first } = accepted else {
            panic!("the right code must open the channel");
        };
        assert_eq!(&first[..], b"hello");
        channel.send_json(&vec!["reply".to_string()]).unwrap();
        let reply: Vec<String> = joiner.recv_json().unwrap();
        assert_eq!(reply, vec!["reply".to_string()]);
        joiner.send(b"second").unwrap();
        assert_eq!(&channel.recv().unwrap()[..], b"second");
    }

    #[test]
    fn the_invite_secret_opens_a_channel_too() {
        let secrets = HostSecrets::generate();
        let code = JoinCode::parse(&secrets.invite(&["127.0.0.1".into()], 1)).unwrap();
        let (joined, accepted) = pair_of(secrets, code);
        joined.unwrap();
        assert!(matches!(accepted, Accepted::Opened { .. }));
    }

    #[test]
    fn a_wrong_code_is_a_failed_try_and_the_joiner_sees_the_channel_close() {
        let secrets = HostSecrets::generate();
        let other = HostSecrets::generate();
        let code = JoinCode::parse(&other.code()).unwrap();
        let (joined, accepted) = pair_of(secrets, code);
        assert!(matches!(accepted, Accepted::WrongCode));
        let mut joiner = joined.unwrap();
        let err = joiner.recv().unwrap_err();
        assert!(err.downcast_ref::<ChannelClosed>().is_some(), "{err:#}");
    }

    #[test]
    fn a_peer_that_does_not_speak_the_protocol_is_not_a_try() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let host = thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            Channel::accept(stream, &HostSecrets::generate(), Instant::now() + WAIT)
        });
        let mut stream = TcpStream::connect(addr).unwrap();
        write_frame(&mut stream, b"GET / HTTP/1.1").unwrap();
        assert!(matches!(host.join().unwrap(), Accepted::Broken(_)));

        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let host = thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            Channel::accept(stream, &HostSecrets::generate(), Instant::now() + WAIT)
        });
        let mut stream = TcpStream::connect(addr).unwrap();
        stream.write_all(&u32::MAX.to_be_bytes()).unwrap();
        assert!(matches!(host.join().unwrap(), Accepted::Broken(_)));
    }

    #[test]
    fn a_replayed_or_reordered_frame_does_not_open() {
        let secrets = HostSecrets::generate();
        let code = JoinCode::parse(&secrets.code()).unwrap();
        let (joined, accepted) = pair_of(secrets, code);
        let mut joiner = joined.unwrap();
        let Accepted::Opened { mut channel, .. } = accepted else {
            panic!("the right code must open the channel");
        };
        let nonce0 = nonce(0);
        let replay = joiner.seal.encrypt(&nonce0, &b"again"[..]).unwrap();
        write_frame(&mut joiner.stream, &replay).unwrap();
        assert!(channel.recv().is_err());
    }

    #[test]
    fn a_peer_trickling_its_opening_is_dropped_at_the_deadline() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let host = thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let started = Instant::now();
            let accepted = Channel::accept(
                stream,
                &HostSecrets::generate(),
                Instant::now() + Duration::from_millis(500),
            );
            (accepted, started.elapsed())
        });
        let mut stream = TcpStream::connect(addr).unwrap();
        stream.write_all(&64u32.to_be_bytes()).unwrap();
        let trickle = thread::spawn(move || {
            for _ in 0..40 {
                if stream.write_all(b"s").is_err() {
                    return;
                }
                thread::sleep(Duration::from_millis(100));
            }
        });
        let (accepted, took) = host.join().unwrap();
        assert!(matches!(accepted, Accepted::Broken(_)));
        assert!(took < Duration::from_secs(3), "held for {took:?}");
        trickle.join().unwrap();
    }
}