vector_core/crypto/
gate.rs1use 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 static DEPTH: Cell<usize> = const { Cell::new(0) };
26 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#[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#[must_use]
48pub struct Sealing {
49 counted: bool,
51 _not_send: PhantomData<*const ()>,
52}
53
54pub 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 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
82pub fn held() -> bool {
84 DEPTH.with(Cell::get) > 0 || CHANGING_HERE.with(Cell::get)
85}
86
87#[must_use]
89pub struct KeyChange {
90 _not_send: PhantomData<*const ()>,
91}
92
93pub 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
110pub 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
124pub(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
135pub(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}