1use crate::{derive_key, open_db, platform, restrict_to_owner, VaultKey, SALT_LEN};
29use rusqlite::Connection;
30use std::fs;
31use std::path::{Path, PathBuf};
32
33pub const MIN_PASSWORD_CHARS: usize = 12;
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum Stage {
39 CopiedOld,
40 WroteNewSalt,
41 Exported,
42 Verified,
43 SwappedDatabase,
44}
45
46#[derive(Debug, PartialEq, Eq)]
47pub struct Report {
48 pub rows: u64,
50 pub kept_database: PathBuf,
52 pub kept_salt: PathBuf,
53}
54
55fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
56 let mut s = path.as_os_str().to_owned();
57 s.push(suffix);
58 PathBuf::from(s)
59}
60
61fn sql_literal(path: &Path) -> String {
62 path.to_string_lossy().replace('\'', "''")
63}
64
65fn table_counts(conn: &Connection) -> Result<Vec<(String, i64)>, String> {
67 let names: Vec<String> = {
68 let mut st = conn
69 .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
70 .map_err(|e| e.to_string())?;
71 let rows = st.query_map([], |r| r.get(0)).map_err(|e| e.to_string())?;
72 rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
73 };
74 names
75 .into_iter()
76 .map(|n| {
77 let c: i64 = conn
78 .query_row(&format!("SELECT count(*) FROM \"{n}\""), [], |r| r.get(0))
79 .map_err(|e| e.to_string())?;
80 Ok((n, c))
81 })
82 .collect()
83}
84
85fn intact(conn: &Connection) -> Result<(), String> {
86 let ok: String = conn
87 .query_row("PRAGMA integrity_check", [], |r| r.get(0))
88 .map_err(|e| e.to_string())?;
89 if ok != "ok" {
90 return Err(format!("integrity check failed: {ok}"));
91 }
92 let mut st = conn
93 .prepare("PRAGMA cipher_integrity_check")
94 .map_err(|e| e.to_string())?;
95 if st
96 .query_map([], |r| r.get::<_, String>(0))
97 .map_err(|e| e.to_string())?
98 .next()
99 .is_some()
100 {
101 return Err("SQLCipher integrity check failed".into());
102 }
103 Ok(())
104}
105
106pub fn rekey_with(
109 db_path: &Path,
110 salt_path: &Path,
111 old_password: &str,
112 new_password: &str,
113 stop_after: Option<Stage>,
114) -> Result<Report, String> {
115 if new_password.chars().count() < MIN_PASSWORD_CHARS {
116 return Err(format!(
117 "The new master password must be at least {MIN_PASSWORD_CHARS} characters"
118 ));
119 }
120 if new_password == old_password {
121 return Err("The new master password is the same as the old one".into());
122 }
123 recover_interrupted(db_path, salt_path, old_password)?;
124 crate::check_salt_pairing(db_path, salt_path)?;
125 let old_salt: [u8; SALT_LEN] = fs::read(salt_path)
126 .map_err(|e| e.to_string())?
127 .try_into()
128 .map_err(|_| "vault.salt is corrupt (wrong length)".to_string())?;
129 let old_key = derive_key(old_password, &old_salt)?;
130 let conn = open_db(db_path, &old_key)?;
131 let before = table_counts(&conn)?;
132 intact(&conn)?;
133
134 let kept_db = with_suffix(db_path, ".pre-rekey");
135 let kept_salt = with_suffix(salt_path, ".pre-rekey");
136 let new_salt_path = with_suffix(salt_path, ".new");
137 let new_db_path = with_suffix(db_path, ".rekey-new");
138 let _ = fs::remove_file(&new_db_path);
139 let _ = fs::remove_file(&new_salt_path);
140
141 let stop = |stage: Stage| -> Result<(), String> {
142 if stop_after == Some(stage) {
143 Err(format!("interrupted after {stage:?}"))
144 } else {
145 Ok(())
146 }
147 };
148 let cleanup = || {
149 let _ = fs::remove_file(&new_db_path);
150 let _ = fs::remove_file(&new_salt_path);
151 };
152
153 let guard = open_db(db_path, &old_key)?;
156 let result = (|| -> Result<u64, String> {
157 guard
159 .execute_batch("BEGIN IMMEDIATE;")
160 .map_err(|e| format!("the vault is in use by another program: {e}"))?;
161 conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
162 .map_err(|e| e.to_string())?;
163 fs::copy(db_path, &kept_db).map_err(|e| format!("cannot keep the old database: {e}"))?;
164 fs::copy(salt_path, &kept_salt).map_err(|e| format!("cannot keep the old salt: {e}"))?;
165 restrict_to_owner(&kept_db)?;
166 restrict_to_owner(&kept_salt)?;
167 stop(Stage::CopiedOld)?;
168
169 let new_salt: [u8; SALT_LEN] = rand::random();
171 {
172 use std::io::Write;
173 let mut f = fs::File::create(&new_salt_path).map_err(|e| e.to_string())?;
174 f.write_all(&new_salt).map_err(|e| e.to_string())?;
175 f.sync_all().map_err(|e| e.to_string())?;
176 }
177 restrict_to_owner(&new_salt_path)?;
178 let new_key: VaultKey = derive_key(new_password, &new_salt)?;
179 stop(Stage::WroteNewSalt)?;
180
181 let version: i64 = conn
183 .query_row("PRAGMA user_version", [], |r| r.get(0))
184 .map_err(|e| e.to_string())?;
185 conn.execute_batch(&format!(
186 "ATTACH DATABASE '{}' AS rekeyed KEY \"x'{}'\"; SELECT sqlcipher_export('rekeyed'); PRAGMA rekeyed.user_version = {version}; DETACH DATABASE rekeyed;",
187 sql_literal(&new_db_path),
188 hex::encode(new_key)
189 ))
190 .map_err(|e| format!("export failed: {e}"))?;
191 restrict_to_owner(&new_db_path)?;
192 stop(Stage::Exported)?;
193
194 let check = open_db(&new_db_path, &new_key).map_err(|e| {
196 format!("the re-encrypted copy does not open with the new password: {e}")
197 })?;
198 intact(&check)?;
199 let after = table_counts(&check)?;
200 if after != before {
201 return Err("the re-encrypted copy does not hold the same rows".into());
202 }
203 let rows = after.iter().map(|(_, c)| *c as u64).sum();
204 check
205 .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
206 .map_err(|e| e.to_string())?;
207 drop(check);
208 stop(Stage::Verified)?;
209 Ok(rows)
210 })();
211
212 let rows = match result {
213 Ok(rows) => rows,
214 Err(e) => {
215 let _ = guard.execute_batch("ROLLBACK;");
216 drop(guard);
217 drop(conn);
218 if stop_after.is_none() {
221 cleanup();
222 }
223 return Err(e);
224 }
225 };
226
227 let _ = guard.execute_batch("ROLLBACK;");
229 drop(guard);
230 drop(conn);
231 for suffix in ["-wal", "-shm"] {
232 let _ = fs::remove_file(with_suffix(db_path, suffix));
233 }
234 platform::replace_file(&new_db_path, db_path)
235 .map_err(|e| format!("cannot install the new database: {e}"))?;
236 stop(Stage::SwappedDatabase)?;
237 platform::replace_file(&new_salt_path, salt_path)
238 .map_err(|e| format!("cannot install the new salt: {e}"))?;
239 Ok(Report {
240 rows,
241 kept_database: kept_db,
242 kept_salt,
243 })
244}
245
246pub fn rekey(
248 db_path: &Path,
249 salt_path: &Path,
250 old_password: &str,
251 new_password: &str,
252) -> Result<Report, String> {
253 rekey_with(db_path, salt_path, old_password, new_password, None)
254}
255
256pub fn recover_interrupted(
263 db_path: &Path,
264 salt_path: &Path,
265 password: &str,
266) -> Result<bool, String> {
267 let new_salt_path = with_suffix(salt_path, ".new");
268 let new_db_path = with_suffix(db_path, ".rekey-new");
269 if !new_salt_path.exists() {
270 if new_db_path.exists() {
272 let _ = fs::remove_file(&new_db_path);
273 return Ok(true);
274 }
275 return Ok(false);
276 }
277 let new_salt = fs::read(&new_salt_path).map_err(|e| e.to_string())?;
278 let swapped = derive_key(password, &new_salt)
279 .ok()
280 .is_some_and(|key| db_path.exists() && open_db_quietly(db_path, &key));
281 if swapped {
282 platform::replace_file(&new_salt_path, salt_path)
283 .map_err(|e| format!("cannot finish the interrupted password change: {e}"))?;
284 } else {
285 let _ = fs::remove_file(&new_salt_path);
286 }
287 let _ = fs::remove_file(&new_db_path);
288 Ok(true)
289}
290
291fn open_db_quietly(db_path: &Path, key: &VaultKey) -> bool {
293 let Ok(conn) = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
294 else {
295 return false;
296 };
297 conn.execute_batch(&format!("PRAGMA key = \"x'{}'\";", hex::encode(key)))
298 .is_ok()
299 && conn
300 .execute_batch("SELECT count(*) FROM sqlite_master;")
301 .is_ok()
302}
303
304pub fn cleanup_after_unlock(db_path: &Path, salt_path: &Path) -> bool {
307 let a = fs::remove_file(with_suffix(db_path, ".pre-rekey")).is_ok();
308 let b = fs::remove_file(with_suffix(salt_path, ".pre-rekey")).is_ok();
309 a || b
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 struct Vault {
317 dir: PathBuf,
318 db: PathBuf,
319 salt: PathBuf,
320 }
321
322 fn vault(old: &str) -> Vault {
323 let dir = std::env::temp_dir().join(format!("vc-rekey-{}", crate::new_uuid()));
324 fs::create_dir_all(&dir).unwrap();
325 let (db, salt) = (dir.join("vault.db"), dir.join("vault.salt"));
326 let s = crate::read_or_create_salt(&salt).unwrap();
327 let key = derive_key(old, &s).unwrap();
328 let conn = open_db(&db, &key).unwrap();
329 crate::init_schema(&conn).unwrap();
330 conn.execute_batch(
331 "CREATE TABLE IF NOT EXISTS probe (k TEXT PRIMARY KEY, v TEXT); INSERT INTO probe VALUES ('a', 'one'), ('b', 'two');",
332 )
333 .unwrap();
334 Vault { dir, db, salt }
335 }
336
337 fn unlock(v: &Vault, password: &str) -> Result<Connection, String> {
339 recover_interrupted(&v.db, &v.salt, password)?;
340 let salt = fs::read(&v.salt).map_err(|e| e.to_string())?;
341 open_db(&v.db, &derive_key(password, &salt)?)
342 }
343
344 fn rows(conn: &Connection) -> i64 {
345 conn.query_row("SELECT count(*) FROM probe", [], |r| r.get(0))
346 .unwrap()
347 }
348
349 static OLD: std::sync::LazyLock<String> =
351 std::sync::LazyLock::new(|| format!("the old master password {}", 1));
352 static NEW: std::sync::LazyLock<String> =
353 std::sync::LazyLock::new(|| format!("the new master password {}", 2));
354
355 #[test]
356 fn the_new_password_opens_the_same_data_and_the_old_one_no_longer_does() {
357 let v = vault(&OLD);
358 let report = rekey(&v.db, &v.salt, &OLD, &NEW).unwrap();
359 assert!(report.rows >= 2);
360 assert_eq!(rows(&unlock(&v, &NEW).unwrap()), 2);
361 assert_eq!(unlock(&v, &OLD).err().unwrap(), "Wrong master password");
362 assert!(
363 report.kept_database.exists() && report.kept_salt.exists(),
364 "the way back is kept"
365 );
366 assert!(cleanup_after_unlock(&v.db, &v.salt));
368 assert!(!report.kept_database.exists() && !report.kept_salt.exists());
369 assert!(
370 !cleanup_after_unlock(&v.db, &v.salt),
371 "nothing left to remove"
372 );
373 let _ = fs::remove_dir_all(&v.dir);
374 }
375
376 #[test]
377 fn the_kept_copy_still_opens_with_the_old_password() {
378 let v = vault(&OLD);
379 let report = rekey(&v.db, &v.salt, &OLD, &NEW).unwrap();
380 let salt = fs::read(&report.kept_salt).unwrap();
381 let conn = open_db(&report.kept_database, &derive_key(&OLD, &salt).unwrap()).unwrap();
382 assert_eq!(rows(&conn), 2);
383 drop(conn);
384 let _ = fs::remove_dir_all(&v.dir);
385 }
386
387 #[test]
388 fn a_stop_at_any_step_leaves_a_vault_that_opens_with_the_old_or_the_new_password() {
389 for (stage, new_wins) in [
390 (Stage::CopiedOld, false),
391 (Stage::WroteNewSalt, false),
392 (Stage::Exported, false),
393 (Stage::Verified, false),
394 (Stage::SwappedDatabase, true),
395 ] {
396 let v = vault(&OLD);
397 let err = rekey_with(&v.db, &v.salt, &OLD, &NEW, Some(stage)).unwrap_err();
398 assert!(err.contains("interrupted"), "{stage:?}: {err}");
399 let (winner, loser) = if new_wins {
400 (&**NEW, &**OLD)
401 } else {
402 (&**OLD, &**NEW)
403 };
404 let conn = unlock(&v, winner)
405 .unwrap_or_else(|e| panic!("{stage:?}: the expected password should open: {e}"));
406 assert_eq!(rows(&conn), 2, "{stage:?}");
407 drop(conn);
408 assert!(
409 unlock(&v, loser).is_err(),
410 "{stage:?}: the other password should not open"
411 );
412 assert!(
413 !with_suffix(&v.salt, ".new").exists(),
414 "{stage:?}: no half-finished salt is left"
415 );
416 assert!(
417 !with_suffix(&v.db, ".rekey-new").exists(),
418 "{stage:?}: no half-written copy is left"
419 );
420 let _ = fs::remove_dir_all(&v.dir);
421 }
422 }
423
424 #[test]
425 fn recovery_is_a_no_op_when_nothing_was_interrupted() {
426 let v = vault(&OLD);
427 assert!(!recover_interrupted(&v.db, &v.salt, &OLD).unwrap());
428 fs::write(with_suffix(&v.db, ".rekey-new"), b"junk").unwrap();
430 assert!(recover_interrupted(&v.db, &v.salt, &OLD).unwrap());
431 assert!(!with_suffix(&v.db, ".rekey-new").exists());
432 let _ = fs::remove_dir_all(&v.dir);
433 }
434
435 #[test]
436 fn a_wrong_old_password_a_weak_new_one_and_an_unchanged_one_are_refused_before_any_file_changes(
437 ) {
438 let v = vault(&OLD);
439 let before = (fs::read(&v.db).unwrap().len(), fs::read(&v.salt).unwrap());
440 assert_eq!(
441 rekey(&v.db, &v.salt, &format!("{}x", *OLD), &NEW).unwrap_err(),
442 "Wrong master password"
443 );
444 let weak = rekey(&v.db, &v.salt, &OLD, &"x".repeat(5)).unwrap_err();
445 assert!(weak.contains("at least 12"), "{weak}");
446 let same = rekey(&v.db, &v.salt, &OLD, &OLD).unwrap_err();
447 assert!(same.contains("same"), "{same}");
448 assert_eq!(fs::read(&v.salt).unwrap(), before.1);
449 assert!(!with_suffix(&v.db, ".pre-rekey").exists());
450 assert_eq!(rows(&unlock(&v, &OLD).unwrap()), 2);
451 let _ = fs::remove_dir_all(&v.dir);
452 }
453
454 #[test]
455 fn a_missing_salt_is_reported_as_such_and_not_papered_over() {
456 let v = vault(&OLD);
457 fs::remove_file(&v.salt).unwrap();
458 let err = rekey(&v.db, &v.salt, &OLD, &NEW).unwrap_err();
459 assert!(
460 err.contains("vault.salt") && err.contains("missing"),
461 "{err}"
462 );
463 let _ = fs::remove_dir_all(&v.dir);
464 }
465
466 #[test]
467 fn a_vault_another_program_holds_open_for_writing_is_refused_not_corrupted() {
468 let v = vault(&OLD);
469 let salt = fs::read(&v.salt).unwrap();
470 let other = open_db(&v.db, &derive_key(&OLD, &salt).unwrap()).unwrap();
471 other.execute_batch("BEGIN IMMEDIATE;").unwrap();
472 let err = rekey(&v.db, &v.salt, &OLD, &NEW).unwrap_err();
473 assert!(err.contains("in use"), "{err}");
474 other.execute_batch("ROLLBACK;").unwrap();
475 drop(other);
476 assert_eq!(rows(&unlock(&v, &OLD).unwrap()), 2, "still the old vault");
477 assert!(
478 !with_suffix(&v.salt, ".new").exists() && !with_suffix(&v.db, ".rekey-new").exists()
479 );
480 let _ = fs::remove_dir_all(&v.dir);
481 }
482}