Skip to main content

vector_core/crypto/
gate.rs

1//! Keeps every at-rest write on the key the store uses. A writer holds a [`Sealing`] ticket from
2//! before it reads the vault (or the enabled flag) until its row is written; a migration holds
3//! [`KeyChange`] from before its transaction until the vault and the flag show the result. A value
4//! sealed under one key can then never land after the store has moved to another.
5//!
6//! Tickets are not `Send`, so on native neither can be held across an `.await` in a spawned task:
7//! the encrypt and the write it protects stay one synchronous step. The web's tasks need not be
8//! `Send`, so there that is a rule, enforced by a panic if it is ever broken.
9
10use std::cell::Cell;
11use std::marker::PhantomData;
12use std::sync::{Condvar, Mutex};
13
14struct State {
15    writers: usize,
16    changing: bool,
17    waiting: usize,
18}
19
20static STATE: Mutex<State> = Mutex::new(State { writers: 0, changing: false, waiting: 0 });
21static TURN: Condvar = Condvar::new();
22
23thread_local! {
24    /// Sealing tickets this thread holds; nested writers on one thread never wait on themselves.
25    static DEPTH: Cell<usize> = const { Cell::new(0) };
26    /// Set while this thread runs a migration, so anything it calls passes straight through.
27    static CHANGING_HERE: Cell<bool> = const { Cell::new(false) };
28}
29
30fn lock() -> std::sync::MutexGuard<'static, State> {
31    STATE.lock().unwrap_or_else(|e| e.into_inner())
32}
33
34#[cfg(not(target_arch = "wasm32"))]
35fn wait(s: std::sync::MutexGuard<'static, State>) -> std::sync::MutexGuard<'static, State> {
36    TURN.wait(s).unwrap_or_else(|e| e.into_inner())
37}
38
39/// One thread on the web: a ticket held across an `.await` is the only way to get here, and
40/// waiting would never end.
41#[cfg(target_arch = "wasm32")]
42fn wait(_s: std::sync::MutexGuard<'static, State>) -> std::sync::MutexGuard<'static, State> {
43    panic!("at-rest gate contended on a single thread: a ticket was held across an await");
44}
45
46/// Held by a writer across its encrypt and its write.
47#[must_use]
48pub struct Sealing {
49    /// Only a thread's outermost ticket outside a migration counts as a writer.
50    counted: bool,
51    _not_send: PhantomData<*const ()>,
52}
53
54/// Wait out any key change, then hold one off until this ticket drops.
55pub fn sealing() -> Sealing {
56    let counted = !CHANGING_HERE.with(Cell::get) && DEPTH.with(Cell::get) == 0;
57    if counted {
58        let mut s = lock();
59        // A queued key change goes first, so a steady stream of writes can't starve it.
60        while s.changing || s.waiting > 0 {
61            s = wait(s);
62        }
63        s.writers += 1;
64    }
65    DEPTH.with(|d| d.set(d.get() + 1));
66    Sealing { counted, _not_send: PhantomData }
67}
68
69impl Drop for Sealing {
70    fn drop(&mut self) {
71        DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
72        if self.counted {
73            let mut s = lock();
74            s.writers -= 1;
75            if s.writers == 0 {
76                TURN.notify_all();
77            }
78        }
79    }
80}
81
82/// Whether this thread may seal a value right now: inside a writer's ticket or a migration.
83pub fn held() -> bool {
84    DEPTH.with(Cell::get) > 0 || CHANGING_HERE.with(Cell::get)
85}
86
87/// Held by a migration from before its transaction until the vault and the flag are updated.
88#[must_use]
89pub struct KeyChange {
90    _not_send: PhantomData<*const ()>,
91}
92
93/// Wait for in-flight writers to land, then hold new ones off until this ticket drops.
94pub fn key_change() -> Result<KeyChange, String> {
95    if DEPTH.with(Cell::get) > 0 || CHANGING_HERE.with(Cell::get) {
96        return Err("A key change can't start inside an at-rest write".to_string());
97    }
98    let mut s = lock();
99    s.waiting += 1;
100    while s.changing || s.writers > 0 {
101        s = wait(s);
102    }
103    s.waiting -= 1;
104    s.changing = true;
105    drop(s);
106    CHANGING_HERE.with(|c| c.set(true));
107    Ok(KeyChange { _not_send: PhantomData })
108}
109
110/// [`key_change`] for an account switch: waits out writers in flight. Nested inside a write or a
111/// migration on this thread it holds nothing, since waiting there would wait on itself.
112pub fn switching() -> Option<KeyChange> {
113    key_change().ok()
114}
115
116impl Drop for KeyChange {
117    fn drop(&mut self) {
118        CHANGING_HERE.with(|c| c.set(false));
119        lock().changing = false;
120        TURN.notify_all();
121    }
122}
123
124/// Seal outside a ticket: an error in tests, where every writer runs; a warning elsewhere.
125pub(crate) fn require_held(what: &str) {
126    if held() {
127        return;
128    }
129    if cfg!(test) {
130        panic!("{what} sealed outside the at-rest gate");
131    }
132    crate::log_warn!("[Encryption] {what} sealed outside the at-rest gate");
133}
134
135/// The key a seal uses for the account this work writes to: `None` for a plaintext store. The
136/// vault and the flag describe the account on screen; a late task of a swapped-out account asks
137/// its own store, and an encrypted one is refused, since its key left with it.
138pub(crate) fn with_sealing_key<R>(f: impl FnOnce(Option<&[u8; 32]>) -> R) -> Result<R, String> {
139    if crate::db::writes_to_live_account() {
140        if !crate::state::is_encryption_enabled_fast() {
141            return Ok(f(None));
142        }
143        return crate::state::ENCRYPTION_KEY
144            .with_key(|key| f(Some(key)))
145            .ok_or_else(|| "encryption enabled but key vault is empty".to_string());
146    }
147    let enabled = crate::db::get_sql_setting("encryption_enabled".to_string())?;
148    let security = crate::db::get_sql_setting("security_type".to_string())?;
149    if crate::state::resolve_encryption_enabled(enabled.as_deref(), security.as_deref()) {
150        Err("The account changed before this write; its key is no longer unlocked".to_string())
151    } else {
152        Ok(f(None))
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use std::sync::atomic::{AtomicBool, Ordering};
160    use std::sync::Arc;
161    use std::time::Duration;
162
163    #[test]
164    fn nested_sealing_on_one_thread_does_not_wait() {
165        let _a = sealing();
166        let _b = sealing();
167        assert!(held());
168        assert!(key_change().is_err(), "a key change inside a write would wait on itself");
169    }
170
171    #[test]
172    fn a_key_change_waits_for_writers_and_holds_new_ones_off() {
173        let writing = sealing();
174        let changed = Arc::new(AtomicBool::new(false));
175        let flag = changed.clone();
176        let migration = std::thread::spawn(move || {
177            let _k = key_change().unwrap();
178            flag.store(true, Ordering::SeqCst);
179            std::thread::sleep(Duration::from_millis(50));
180            flag.store(false, Ordering::SeqCst);
181        });
182        std::thread::sleep(Duration::from_millis(50));
183        assert!(!changed.load(Ordering::SeqCst), "the key change waits for the write in flight");
184        drop(writing);
185        while !changed.load(Ordering::SeqCst) {
186            std::thread::yield_now();
187        }
188        let _after = sealing();
189        assert!(!changed.load(Ordering::SeqCst), "a new write waits until the key change is done");
190        migration.join().unwrap();
191    }
192}