Skip to main content

syncspin_client/
storage.rs

1//! Where pairing records live.
2//!
3//! A pairing record is the long-term key the client keeps for a server it has paired with, and the
4//! pairing PSK is the key that admits the client to the pairing activity in the first place. Both
5//! belong to the host: it owns the file, its permissions, its backups and its lifetime. [`Storage`]
6//! is the whole surface the client needs, and a host that has no store configures none - the client
7//! then does not pair at all, and a plain guest session is unchanged.
8//!
9//! # Order and eviction
10//!
11//! [`Storage::load_pairings`] returns records oldest first, and a store the client writes keeps at
12//! most [`MAX_PAIRINGS`]. [`persist_pairing`] drops the first record that does not back the live
13//! connection, so eviction follows the order the store returns. That order is insertion order, not
14//! use order: a record only moves to the end when it is stored again, and the client does that
15//! after a completed pairing, not when it selects a record. A record kept since long ago can
16//! therefore be evicted before one used recently.
17//!
18//! # Capacity
19//!
20//! A store the client writes keeps at most [`MAX_PAIRINGS`] records. The floor is five and it is a
21//! floor, not a ceiling on what a host may hand back: a store the crate reads but did not write may
22//! hold more, and the client uses it as it is. The client never evicts the record backing the live
23//! connection, because losing it would drop the peer it is talking to.
24//!
25//! The rules are enforced by [`persist_pairing`], not by a backend: a host implements the four
26//! primitive operations of [`Storage`] and the crate does the ordering, the capacity and the
27//! live-record pin on top of them. A pairing therefore never fails for lack of space, whichever
28//! store the host chose. Calling [`Storage::store_pairing`] directly skips the live-record pin;
29//! `FileStorage` trims to the floor as a safety net, a host backend may not trim at all, and neither
30//! can know which connection is live. A host that writes a record itself calls [`persist_pairing`]
31//! rather than reimplementing either rule.
32//!
33//! # File backend
34//!
35//! `FileStorage` implements the trait over one JSON file and is available with the
36//! `storage-file` feature. It writes a temporary file in the same directory and renames it over the
37//! store, so a crash leaves either the old store or the new one; it creates its file with mode
38//! `0600` on Unix; and it refuses a file whose shape it does not recognise instead of rewriting it.
39//! No key, encoded or raw, appears in its `Debug` output or in an error.
40
41use anyhow::{bail, Result};
42
43use crate::config::StoredPsk;
44
45/// Most pairing records the client keeps in a store.
46///
47/// The value is the protocol's floor, not a preference: a store that holds more is read as it is.
48pub const MAX_PAIRINGS: usize = 5;
49
50/// The place pairing records and the pairing PSK live.
51///
52/// The host implements this trait - over a file, a database, or the device's own configuration -
53/// and hands it to the client. Every method may be called from the session task, so an
54/// implementation must be `Send + Sync`.
55///
56/// The trait is a store, not a policy: [`store_pairing`](Storage::store_pairing) replaces a record
57/// for the same server and appends the new one, and [`persist_pairing`] is what the client calls to
58/// apply the ordering, the capacity of [`MAX_PAIRINGS`] and the live-record pin. A backend therefore
59/// never has to know which connection is live.
60pub trait Storage: Send + Sync + 'static {
61    /// The long-lived pairing PSK the host restored, or `None` on a device's first run.
62    ///
63    /// The client draws a key when this is `None`, hands it back through
64    /// [`store_pairing_psk`](Storage::store_pairing_psk), and uses it on every connection. The
65    /// operator-facing version-0 token is `client_key || pairing_psk`; the crate has no accessor
66    /// that builds it yet, so a host assembles it from the identity's public key and this value
67    /// with `syncspin_core::pairing::token::encode_v0`. A key the host restored is used as it is, so
68    /// pairing survives a restart.
69    fn pairing_psk(&self) -> Result<Option<[u8; 32]>>;
70
71    /// Persists the pairing PSK the client drew on this run.
72    ///
73    /// The client calls this once, when [`pairing_psk`](Storage::pairing_psk) returned `None`; a
74    /// key is never rotated on its own.
75    fn store_pairing_psk(&self, psk: &[u8; 32]) -> Result<()>;
76
77    /// The records of known servers, oldest first.
78    ///
79    /// A backend may return more than [`MAX_PAIRINGS`] records; the client reads them all and never
80    /// trims a store it did not write.
81    fn load_pairings(&self) -> Result<Vec<StoredPsk>>;
82
83    /// Stores `record` as the newest record for its server.
84    ///
85    /// This is the primitive [`persist_pairing`] is built on: a record the store already holds for
86    /// the same `server_id` is replaced and the new one is placed at the end, so storing it again
87    /// moves it to the end of the list. A backend need not evict here - capacity and the live-record
88    /// pin belong to [`persist_pairing`], which calls this only after it has made room. `FileStorage`
89    /// trims to the floor as a safety net for a direct caller, and cannot pin a live record it does
90    /// not know. An empty `server_id` is rejected, so the store cannot be left holding a record that
91    /// can never be selected.
92    fn store_pairing(&self, record: StoredPsk) -> Result<()>;
93
94    /// Removes the record for `server_id`.
95    ///
96    /// Removing a record the store does not hold is not an error: a server may unpair a client that
97    /// already forgot it.
98    fn remove_pairing(&self, server_id: &str) -> Result<()>;
99}
100
101/// Stores `record` under the record rules: newest at the end, at most [`MAX_PAIRINGS`], never the
102/// record backing the live connection.
103///
104/// This is the operation the client uses after a completed pairing, and it works for any
105/// [`Storage`]: the rule is the crate's, not a backend's. `record.server_id` is the server being
106/// paired with, which may or may not be `live`; the live server is the one the connection is
107/// currently talking to, and its record is never chosen as a victim.
108///
109/// The store is read first, so room is made before the new record is written: a pairing never fails
110/// for lack of space. The victim is dropped through [`Storage::remove_pairing`], because eviction
111/// writes only through the trait. If a backend call fails, the error is returned; records it
112/// already removed stay removed and `record` is not stored.
113pub fn persist_pairing(storage: &dyn Storage, record: StoredPsk, live: Option<&str>) -> Result<()> {
114    if record.server_id.is_empty() {
115        bail!("a pairing record must name a server");
116    }
117
118    let mut records = storage.load_pairings()?;
119    records.retain(|held| held.server_id != record.server_id);
120    // Make room for the record that is about to be the newest one, then write it. The record being
121    // stored is not in `records`, so it can never be chosen as the victim.
122    while records.len() >= MAX_PAIRINGS {
123        let Some(index) = evictable(&records, live) else {
124            // Every remaining record belongs to the live connection; the live pin wins over the
125            // capacity floor, so the store keeps one more than five rather than drop it.
126            break;
127        };
128        let victim = records.remove(index);
129        storage.remove_pairing(&victim.server_id)?;
130    }
131    storage.store_pairing(record)
132}
133
134/// Drops the oldest record that is not `live` when `records` holds more than [`MAX_PAIRINGS`].
135///
136/// Returns the index that was removed, or `None` when the list has room or every record belongs to
137/// the live server. The live record wins over the capacity floor: with only live records in the
138/// list nothing is removed.
139///
140/// This is the list form of the rule [`persist_pairing`] applies, for a caller that already holds
141/// the records. It operates on a list in insertion order (oldest first), which is the order
142/// [`Storage::load_pairings`] returns. The caller is responsible for a record it is about to store:
143/// [`persist_pairing`] keeps that record out of the list until after eviction.
144pub fn evict(records: &mut Vec<StoredPsk>, live: Option<&str>) -> Option<usize> {
145    if records.len() <= MAX_PAIRINGS {
146        return None;
147    }
148    let index = evictable(records, live)?;
149    records.remove(index);
150    Some(index)
151}
152
153/// The index of the first record that may be dropped: not the live one, in insertion order.
154fn evictable(records: &[StoredPsk], live: Option<&str>) -> Option<usize> {
155    records
156        .iter()
157        .position(|record| Some(record.server_id.as_str()) != live)
158}
159
160#[cfg(feature = "storage-file")]
161mod file {
162    use std::collections::HashSet;
163    use std::fmt;
164    use std::fs::{self, File, OpenOptions};
165    use std::io::{ErrorKind, Write};
166    use std::path::{Path, PathBuf};
167    use std::sync::{Mutex, MutexGuard};
168
169    use anyhow::{anyhow, bail, Result};
170    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
171    use base64::Engine as _;
172    use serde::{Deserialize, Serialize};
173
174    use crate::config::{PskCategory, StoredPsk};
175
176    use super::{evict, Storage};
177
178    /// Version this build writes and the only one it reads.
179    const FORMAT_VERSION: u32 = 1;
180
181    /// Counts the temporary names a writer tries, so a leftover file from a crashed run is skipped.
182    const TEMPORARY_ATTEMPTS: u32 = 64;
183
184    /// A pairing store in one JSON file, behind the `storage-file` feature.
185    ///
186    /// Creating it creates the file if it is absent and checks one that exists: a file that is not
187    /// this backend's format, including one with a version this build does not know, is refused
188    /// with an error and never rewritten. Every write goes to a temporary file in the same
189    /// directory and is renamed over the store, so an interrupted write leaves the previous store
190    /// intact. On Unix the file is created with mode `0600`.
191    ///
192    /// The backend holds no records in memory: every call reads the file, and writes hold a lock so
193    /// two callers in one process cannot lose each other's record. One process owns the file; a
194    /// second process writing the same path at the same time is not coordinated, which matches the
195    /// client's one-connection design.
196    pub struct FileStorage {
197        path: PathBuf,
198        lock: Mutex<()>,
199    }
200
201    impl fmt::Debug for FileStorage {
202        /// Names the file, never its contents.
203        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204            formatter
205                .debug_struct("FileStorage")
206                .field("path", &self.path)
207                .finish_non_exhaustive()
208        }
209    }
210
211    impl FileStorage {
212        /// Opens the store at `path`, creating it when it does not exist.
213        ///
214        /// The parent directory must exist; this backend creates a file, never a directory. An
215        /// existing file must be a store of the shape this build writes, or the call returns an
216        /// error and the file is left untouched.
217        pub fn new(path: impl Into<PathBuf>) -> Result<Self> {
218            let path = path.into();
219            if path.file_name().is_none() {
220                bail!(
221                    "{} is not a file path a pairing store can use",
222                    path.display()
223                );
224            }
225            let storage = Self {
226                path,
227                lock: Mutex::new(()),
228            };
229
230            {
231                let _guard = storage.guard()?;
232                if storage.read()?.is_none() {
233                    storage.write(&Shape::empty())?;
234                }
235            }
236            Ok(storage)
237        }
238
239        /// The file this backend owns.
240        pub fn path(&self) -> &Path {
241            &self.path
242        }
243
244        /// Serializes this process's writers, so a read-modify-write cannot lose a record.
245        fn guard(&self) -> Result<MutexGuard<'_, ()>> {
246            self.lock.lock().map_err(|_| {
247                anyhow!(
248                    "the pairing store {} was left poisoned by a panicking writer",
249                    self.path.display()
250                )
251            })
252        }
253
254        /// Reads and checks the store; `None` means the file does not exist yet.
255        fn read(&self) -> Result<Option<Shape>> {
256            let text = match fs::read_to_string(&self.path) {
257                Ok(text) => text,
258                Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
259                Err(error) => bail!(
260                    "cannot read the pairing store {}: {error}",
261                    self.path.display()
262                ),
263            };
264            let shape =
265                Shape::parse(&text).map_err(|error| anyhow!("{}: {error}", self.path.display()))?;
266            Ok(Some(shape))
267        }
268
269        /// Reads the store, treating an absent file as an empty one.
270        fn read_or_empty(&self) -> Result<Shape> {
271            Ok(self.read()?.unwrap_or_else(Shape::empty))
272        }
273
274        /// Replaces the store with `shape` atomically: a temporary file, then a rename.
275        fn write(&self, shape: &Shape) -> Result<()> {
276            let text = serde_json::to_vec_pretty(shape)
277                .map_err(|error| anyhow!("cannot encode the pairing store: {error}"))?;
278
279            let (temporary, mut file) = self.temporary_file()?;
280            let written = file.write_all(&text).and_then(|()| file.sync_all());
281            drop(file);
282            if let Err(error) = written {
283                let _ = fs::remove_file(&temporary);
284                bail!(
285                    "cannot write the pairing store {}: {error}",
286                    self.path.display()
287                );
288            }
289            if let Err(error) = fs::rename(&temporary, &self.path) {
290                let _ = fs::remove_file(&temporary);
291                bail!(
292                    "cannot replace the pairing store {}: {error}",
293                    self.path.display()
294                );
295            }
296            Ok(())
297        }
298
299        /// Creates the temporary file beside the store, private to its owner on Unix.
300        ///
301        /// The file sits in the same directory because a rename is only atomic within one
302        /// filesystem.
303        fn temporary_file(&self) -> Result<(PathBuf, File)> {
304            let directory = match self.path.parent() {
305                Some(parent) if !parent.as_os_str().is_empty() => parent,
306                _ => Path::new("."),
307            };
308            let name = self
309                .path
310                .file_name()
311                .ok_or_else(|| anyhow!("{} has no file name", self.path.display()))?;
312            let name = name.to_string_lossy();
313
314            for attempt in 0..TEMPORARY_ATTEMPTS {
315                let candidate =
316                    directory.join(format!(".{name}.{}.{attempt}.tmp", std::process::id()));
317                let mut options = OpenOptions::new();
318                options.write(true).create_new(true);
319                #[cfg(unix)]
320                {
321                    use std::os::unix::fs::OpenOptionsExt;
322                    options.mode(0o600);
323                }
324                match options.open(&candidate) {
325                    Ok(file) => return Ok((candidate, file)),
326                    Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
327                    Err(error) => bail!(
328                        "cannot create a temporary file beside {}: {error}",
329                        self.path.display()
330                    ),
331                }
332            }
333            bail!(
334                "cannot create a temporary file beside {} after {TEMPORARY_ATTEMPTS} attempts",
335                self.path.display()
336            )
337        }
338    }
339
340    impl Storage for FileStorage {
341        fn pairing_psk(&self) -> Result<Option<[u8; 32]>> {
342            let _guard = self.guard()?;
343            let shape = self.read_or_empty()?;
344            shape.pairing_psk.as_deref().map(decode_key).transpose()
345        }
346
347        fn store_pairing_psk(&self, psk: &[u8; 32]) -> Result<()> {
348            let _guard = self.guard()?;
349            let mut shape = self.read_or_empty()?;
350            shape.pairing_psk = Some(encode_key(psk));
351            self.write(&shape)
352        }
353
354        fn load_pairings(&self) -> Result<Vec<StoredPsk>> {
355            let _guard = self.guard()?;
356            let shape = self.read_or_empty()?;
357            shape.pairings.iter().map(decode_record).collect()
358        }
359
360        fn store_pairing(&self, record: StoredPsk) -> Result<()> {
361            if record.server_id.is_empty() {
362                bail!("a pairing record must name a server");
363            }
364            let _guard = self.guard()?;
365            let mut shape = self.read_or_empty()?;
366
367            let mut records: Vec<StoredPsk> = shape
368                .pairings
369                .iter()
370                .map(decode_record)
371                .collect::<Result<_>>()?;
372            let server_id = record.server_id.clone();
373            records.retain(|held| held.server_id != server_id);
374            records.push(record);
375            // A safety net for a caller that uses the primitive directly: this backend cannot know
376            // which connection is live, so it drops the oldest record rather than pretend to pin
377            // one. `persist_pairing` makes the room before calling this and is what protects the
378            // live record; here the drop only keeps a direct caller from growing the file without
379            // bound.
380            while evict(&mut records, None).is_some() {}
381
382            shape.pairings = records.iter().map(encode_record).collect();
383            self.write(&shape)
384        }
385
386        fn remove_pairing(&self, server_id: &str) -> Result<()> {
387            let _guard = self.guard()?;
388            let mut shape = self.read_or_empty()?;
389            let held = shape.pairings.len();
390            shape
391                .pairings
392                .retain(|record| record.server_id != server_id);
393            if shape.pairings.len() == held {
394                return Ok(());
395            }
396            self.write(&shape)
397        }
398    }
399
400    /// The file's shape, exactly as this backend writes it.
401    #[derive(Deserialize, Serialize)]
402    #[serde(deny_unknown_fields)]
403    struct Shape {
404        version: u32,
405        pairing_psk: Option<String>,
406        pairings: Vec<ShapeRecord>,
407    }
408
409    /// One record in the file. The key is base64url without padding.
410    #[derive(Deserialize, Serialize)]
411    #[serde(deny_unknown_fields)]
412    struct ShapeRecord {
413        category: String,
414        psk: String,
415        server_id: String,
416    }
417
418    impl Shape {
419        /// An empty store in the shape this build writes.
420        fn empty() -> Self {
421            Self {
422                version: FORMAT_VERSION,
423                pairing_psk: None,
424                pairings: Vec::new(),
425            }
426        }
427
428        /// Checks that `text` is a store this build knows, without echoing its contents.
429        ///
430        /// The error names the reason and, for malformed JSON, the line and column: never a value,
431        /// because a record's value is a key.
432        fn parse(text: &str) -> Result<Self> {
433            let shape: Shape = serde_json::from_str(text).map_err(|error| {
434                anyhow!(
435                    "it is not the JSON this backend writes (line {}, column {})",
436                    error.line(),
437                    error.column()
438                )
439            })?;
440            if shape.version != FORMAT_VERSION {
441                bail!(
442                    "it announces format version {}, this build writes version {FORMAT_VERSION}",
443                    shape.version
444                );
445            }
446            if let Some(encoded) = shape.pairing_psk.as_deref() {
447                decode_key(encoded)?;
448            }
449            let mut seen = HashSet::with_capacity(shape.pairings.len());
450            for record in &shape.pairings {
451                let decoded = decode_record(record)?;
452                if !seen.insert(decoded.server_id) {
453                    bail!("it holds more than one record for the same server");
454                }
455            }
456            Ok(shape)
457        }
458    }
459
460    /// Encodes a 32-byte key the way the file spells it.
461    fn encode_key(key: &[u8; 32]) -> String {
462        URL_SAFE_NO_PAD.encode(key)
463    }
464
465    /// Decodes a 32-byte key from the file. The error never repeats the encoded value.
466    fn decode_key(encoded: &str) -> Result<[u8; 32]> {
467        let bytes = URL_SAFE_NO_PAD
468            .decode(encoded)
469            .map_err(|_| anyhow!("a stored key is not base64url"))?;
470        <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| anyhow!("a stored key is not 32 bytes"))
471    }
472
473    /// Turns a record in the file into the record the client uses.
474    fn decode_record(record: &ShapeRecord) -> Result<StoredPsk> {
475        if record.server_id.is_empty() {
476            bail!("a record has an empty server id");
477        }
478        let category = PskCategory::from_wire(&record.category)
479            .ok_or_else(|| anyhow!("a record names an unknown key category"))?;
480        Ok(StoredPsk {
481            category,
482            psk: decode_key(&record.psk)?,
483            server_id: record.server_id.clone(),
484        })
485    }
486
487    /// Turns a record the client uses into the shape the file holds.
488    fn encode_record(record: &StoredPsk) -> ShapeRecord {
489        ShapeRecord {
490            category: record.category.as_wire().to_owned(),
491            psk: encode_key(&record.psk),
492            server_id: record.server_id.clone(),
493        }
494    }
495}
496
497#[cfg(feature = "storage-file")]
498pub use file::FileStorage;