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