Skip to main content

vault_core/
identity.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Which vault this is, and which copy of it is allowed to act.
4//!
5//! A vault has one `vault_id` for its whole life. Each copy that was ever opened has an
6//! `instance_id`, an `instance_epoch` that only grows, and a role: `active` or `standby`. A restore
7//! from a recovery package, or a copy of the files made by a sync folder, would otherwise be a
8//! second vault that believes it is the only one, with the same hub identity, pushing to the same
9//! nodes. The rules:
10//!
11//! - A restored vault is `standby` with a new `instance_id` (the `vault.restored` marker beside the
12//!   database, written by `unv recover restore`, is read the next time the database is opened). A
13//!   standby copy reads, verifies and exports; the hub does not push and the operations executor
14//!   does not run.
15//! - [`activate`] makes a copy `active` and raises the epoch above anything this copy has seen. The
16//!   person doing it is saying the old instance is retired.
17//! - The hub tells nodes its `(vault_id, epoch)`; a node remembers the highest epoch and refuses a
18//!   lower one, so a forgotten second hub cannot push over the live one.
19//! - [`sync_folder`] names a cloud-sync folder a live vault sits in. Two machines opening one
20//!   synced file is the way a vault gets corrupted or forked without anybody deciding to.
21
22use rusqlite::{Connection, OptionalExtension};
23use serde::{Deserialize, Serialize};
24use std::path::Path;
25
26/// The file `unv recover restore` leaves beside a restored vault. Its presence means "the next open
27/// is a new instance in standby".
28pub const RESTORED_MARKER: &str = "vault.restored";
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case")]
32pub enum Role {
33    Active,
34    Standby,
35}
36
37impl Role {
38    fn as_str(self) -> &'static str {
39        match self {
40            Self::Active => "active",
41            Self::Standby => "standby",
42        }
43    }
44    fn parse(text: &str) -> Self {
45        // Anything unreadable is treated as standby: the safe side of the two.
46        if text == "active" {
47            Self::Active
48        } else {
49            Self::Standby
50        }
51    }
52}
53
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Identity {
56    pub vault_id: String,
57    pub instance_id: String,
58    pub epoch: u64,
59    pub role: Role,
60}
61
62fn get(conn: &Connection, key: &str) -> Result<Option<String>, String> {
63    conn.query_row("SELECT value FROM vault_meta WHERE key = ?1", [key], |r| {
64        r.get(0)
65    })
66    .optional()
67    .map_err(|e| e.to_string())
68}
69
70fn put(conn: &Connection, key: &str, value: &str) -> Result<(), String> {
71    conn.execute(
72        "INSERT OR REPLACE INTO vault_meta (key, value) VALUES (?1, ?2)",
73        [key, value],
74    )
75    .map(|_| ())
76    .map_err(|e| e.to_string())
77}
78
79/// Reads the identity, creating it the first time: a new `vault_id`, a new `instance_id`, epoch 1,
80/// active. An existing vault gets one the first time it is opened by a build that knows about this.
81pub fn ensure(conn: &Connection) -> Result<Identity, String> {
82    let vault_id = match get(conn, "vault_id")? {
83        Some(v) => v,
84        None => {
85            let v = crate::new_uuid();
86            put(conn, "vault_id", &v)?;
87            v
88        }
89    };
90    let instance_id = match get(conn, "instance_id")? {
91        Some(v) => v,
92        None => {
93            let v = crate::new_uuid();
94            put(conn, "instance_id", &v)?;
95            v
96        }
97    };
98    let epoch = match get(conn, "instance_epoch")?.and_then(|v| v.parse::<u64>().ok()) {
99        Some(e) => e,
100        None => {
101            put(conn, "instance_epoch", "1")?;
102            1
103        }
104    };
105    let role = match get(conn, "instance_role")? {
106        Some(r) => Role::parse(&r),
107        None => {
108            put(conn, "instance_role", Role::Active.as_str())?;
109            Role::Active
110        }
111    };
112    Ok(Identity {
113        vault_id,
114        instance_id,
115        epoch,
116        role,
117    })
118}
119
120/// Makes this copy the active one and raises its epoch by one.
121pub fn activate(conn: &Connection) -> Result<Identity, String> {
122    let current = ensure(conn)?;
123    let epoch = current.epoch + 1;
124    put(conn, "instance_epoch", &epoch.to_string())?;
125    put(conn, "instance_role", Role::Active.as_str())?;
126    Ok(Identity {
127        epoch,
128        role: Role::Active,
129        ..current
130    })
131}
132
133/// Makes this copy a new instance in standby: what a restore does. The `vault_id` is kept (it is
134/// still that vault); the instance and its epoch are new.
135pub fn become_standby(conn: &Connection) -> Result<Identity, String> {
136    let current = ensure(conn)?;
137    let instance_id = crate::new_uuid();
138    put(conn, "instance_id", &instance_id)?;
139    put(conn, "instance_role", Role::Standby.as_str())?;
140    Ok(Identity {
141        instance_id,
142        role: Role::Standby,
143        ..current
144    })
145}
146
147/// Called when a database is opened: a restore marker beside it turns this copy into a standby
148/// instance, once. The marker is removed only after the change is stored.
149pub fn on_open(conn: &Connection, db_path: &Path) -> Result<(), String> {
150    let marker = db_path.with_file_name(RESTORED_MARKER);
151    if marker.exists() {
152        become_standby(conn)?;
153        std::fs::remove_file(&marker).map_err(|e| e.to_string())?;
154    }
155    Ok(())
156}
157
158/// Refuses an action that only the active instance may take.
159pub fn require_active(conn: &Connection, what: &str) -> Result<(), String> {
160    let id = ensure(conn)?;
161    match id.role {
162        Role::Active => Ok(()),
163        Role::Standby => Err(format!(
164            "This vault is a standby copy, so it will not {what}. Once the other instance is retired, run: unv vault activate"
165        )),
166    }
167}
168
169/// Cloud-sync clients a vault should not live inside.
170const SYNC_NAMES: &[(&str, &str)] = &[
171    ("dropbox", "Dropbox"),
172    ("onedrive", "OneDrive"),
173    ("google drive", "Google Drive"),
174    ("googledrive", "Google Drive"),
175    ("my drive", "Google Drive"),
176    ("icloud drive", "iCloud Drive"),
177    ("iclouddrive", "iCloud Drive"),
178    ("com~apple~clouddocs", "iCloud Drive"),
179    ("nextcloud", "Nextcloud"),
180    ("owncloud", "ownCloud"),
181    ("syncthing", "Syncthing"),
182    ("pcloud", "pCloud"),
183    ("megasync", "MEGA"),
184    ("box sync", "Box"),
185    ("sync.com", "Sync.com"),
186];
187
188/// The sync client whose folder `path` is inside, or `None`. `marker_exists` answers whether a
189/// directory holds a marker file (`.stfolder` for Syncthing); it is a parameter so the check can be
190/// tested without touching the disk.
191pub fn sync_folder(
192    path: &Path,
193    marker_exists: impl Fn(&Path, &str) -> bool,
194) -> Option<&'static str> {
195    for ancestor in path.ancestors() {
196        if let Some(name) = ancestor
197            .file_name()
198            .map(|n| n.to_string_lossy().to_lowercase())
199        {
200            for (needle, label) in SYNC_NAMES {
201                // `OneDrive - Contoso` and `Dropbox (Personal)` are real folder names.
202                if name == *needle || name.starts_with(&format!("{needle} ")) {
203                    return Some(label);
204                }
205            }
206        }
207        if marker_exists(ancestor, ".stfolder") {
208            return Some("Syncthing");
209        }
210    }
211    None
212}
213
214/// [`sync_folder`] against the real file system.
215pub fn sync_folder_on_disk(path: &Path) -> Option<&'static str> {
216    sync_folder(path, |dir, marker| dir.join(marker).exists())
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    fn conn() -> Connection {
224        let c = Connection::open_in_memory().unwrap();
225        c.execute_batch("CREATE TABLE vault_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);")
226            .unwrap();
227        c
228    }
229
230    #[test]
231    fn a_vault_gets_one_identity_and_keeps_it() {
232        let c = conn();
233        let a = ensure(&c).unwrap();
234        assert_eq!((a.epoch, a.role), (1, Role::Active));
235        assert_eq!(ensure(&c).unwrap(), a, "reading never changes it");
236        assert!(require_active(&c, "push").is_ok());
237    }
238
239    #[test]
240    fn a_restore_makes_a_new_standby_instance_of_the_same_vault_and_it_refuses_to_act() {
241        let c = conn();
242        let before = ensure(&c).unwrap();
243        let after = become_standby(&c).unwrap();
244        assert_eq!(after.vault_id, before.vault_id);
245        assert_ne!(after.instance_id, before.instance_id);
246        assert_eq!(after.role, Role::Standby);
247        let err = require_active(&c, "push to nodes").unwrap_err();
248        assert!(
249            err.contains("standby")
250                && err.contains("push to nodes")
251                && err.contains("unv vault activate"),
252            "{err}"
253        );
254    }
255
256    #[test]
257    fn activating_raises_the_epoch_and_makes_the_copy_active_again() {
258        let c = conn();
259        ensure(&c).unwrap();
260        become_standby(&c).unwrap();
261        let a = activate(&c).unwrap();
262        assert_eq!((a.epoch, a.role), (2, Role::Active));
263        assert_eq!(
264            activate(&c).unwrap().epoch,
265            3,
266            "each activation outranks the last"
267        );
268        assert!(require_active(&c, "push").is_ok());
269    }
270
271    #[test]
272    fn a_damaged_role_or_epoch_is_read_on_the_safe_side() {
273        let c = conn();
274        ensure(&c).unwrap();
275        put(&c, "instance_role", "garbage").unwrap();
276        assert_eq!(ensure(&c).unwrap().role, Role::Standby);
277        put(&c, "instance_epoch", "not a number").unwrap();
278        assert_eq!(ensure(&c).unwrap().epoch, 1);
279    }
280
281    #[test]
282    fn the_restore_marker_turns_the_next_open_into_standby_once() {
283        let dir = std::env::temp_dir().join(format!("vc-id-{}", crate::new_uuid()));
284        std::fs::create_dir_all(&dir).unwrap();
285        let db = dir.join("vault.db");
286        let c = conn();
287        ensure(&c).unwrap();
288        on_open(&c, &db).unwrap();
289        assert_eq!(
290            ensure(&c).unwrap().role,
291            Role::Active,
292            "no marker, no change"
293        );
294        std::fs::write(dir.join(RESTORED_MARKER), "").unwrap();
295        on_open(&c, &db).unwrap();
296        assert_eq!(ensure(&c).unwrap().role, Role::Standby);
297        assert!(!dir.join(RESTORED_MARKER).exists(), "the marker is spent");
298        activate(&c).unwrap();
299        on_open(&c, &db).unwrap();
300        assert_eq!(
301            ensure(&c).unwrap().role,
302            Role::Active,
303            "a second open does not demote it again"
304        );
305        let _ = std::fs::remove_dir_all(&dir);
306    }
307
308    #[test]
309    fn sync_clients_are_recognised_by_folder_name_on_every_platform() {
310        let none = |_: &Path, _: &str| false;
311        let cases = [
312            ("/home/me/Dropbox/vault/vault.db", "Dropbox"),
313            ("C:\\Users\\me\\OneDrive - Contoso\\vault.db", "OneDrive"),
314            (
315                "/Users/me/Library/Mobile Documents/com~apple~CloudDocs/v/vault.db",
316                "iCloud Drive",
317            ),
318            ("/Users/me/Google Drive/My Drive/v.db", "Google Drive"),
319            ("/home/me/Nextcloud/v.db", "Nextcloud"),
320            ("/home/me/ownCloud/v.db", "ownCloud"),
321            ("/home/me/pCloudDrive/pcloud/v.db", "pCloud"),
322        ];
323        for (path, label) in cases {
324            // Windows-style paths use backslashes; split them the way the platform would.
325            let p: std::path::PathBuf = path.split(['/', '\\']).collect();
326            assert_eq!(sync_folder(&p, none), Some(label), "{path}");
327        }
328        assert_eq!(
329            sync_folder(
330                Path::new("/home/me/.local/share/io.unenverse/vault.db"),
331                none
332            ),
333            None
334        );
335        assert_eq!(
336            sync_folder(Path::new("/home/me/dropbox-notes-archive-old/v.db"), none),
337            None
338        );
339    }
340
341    #[test]
342    fn a_syncthing_marker_in_any_parent_counts() {
343        let has = |dir: &Path, m: &str| dir == Path::new("/data/shared") && m == ".stfolder";
344        assert_eq!(
345            sync_folder(Path::new("/data/shared/deep/vault.db"), has),
346            Some("Syncthing")
347        );
348        assert_eq!(sync_folder(Path::new("/data/private/vault.db"), has), None);
349    }
350
351    #[test]
352    fn the_disk_check_finds_a_real_marker() {
353        let dir = std::env::temp_dir().join(format!("vc-st-{}", crate::new_uuid()));
354        std::fs::create_dir_all(dir.join(".stfolder")).unwrap();
355        assert_eq!(
356            sync_folder_on_disk(&dir.join("vault.db")),
357            Some("Syncthing")
358        );
359        let _ = std::fs::remove_dir_all(&dir);
360        assert_eq!(
361            sync_folder_on_disk(&std::env::temp_dir().join("nothing-here")),
362            None
363        );
364    }
365}