1use zeroize::Zeroize;
10use crate::state::set_encryption_enabled;
11use crate::stored_event::event_kind;
12
13pub const NIP55_PIN_CANARY: &str = "vector-nip55-pin-ok";
18
19fn encrypt_with_key(input: &str, key: &[u8; 32]) -> String {
20 crate::crypto::encrypt_with_key(input, key).expect("Encryption should not fail")
21}
22
23fn decrypt_with_key(ciphertext: &str, key: &[u8; 32]) -> Result<String, ()> {
24 crate::crypto::decrypt_with_key(ciphertext, key).map_err(|_| ())
25}
26
27#[derive(serde::Serialize, Clone)]
29pub struct MigrationProgress {
30 pub total: usize,
31 pub completed: usize,
32 pub phase: String,
33}
34
35pub fn disable(
48 key: &[u8; 32],
49 progress: &dyn Fn(MigrationProgress),
50) -> Result<(), String> {
51 let _change = crate::crypto::gate::key_change()?;
54 if !crate::db::writes_to_live_account() {
55 return Err("The account changed before encryption could be turned off".to_string());
56 }
57 let mut conn = crate::db::get_write_connection_guard_static()?;
58 let tx = conn.transaction()
59 .map_err(|e| format!("Failed to begin transaction: {}", e))?;
60
61 tx.execute(
63 "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', 'decrypting')",
64 [],
65 ).map_err(|e| format!("Failed to set migration_state: {}", e))?;
66
67 prove_key_in_tx(&tx, key, false)?;
68
69 let all_ids: Vec<String> = {
71 let mut stmt = tx.prepare(
72 r#"SELECT id FROM events
73 WHERE kind IN (?1, ?2, ?3, ?4)
74 AND length(content) >= 56
75 AND content NOT GLOB '*[^0-9a-f]*'"#,
76 ).map_err(|e| format!("Failed to prepare ID query: {}", e))?;
77
78 let rows = stmt.query_map(
79 rusqlite::params![
80 event_kind::CHAT_MESSAGE as i32,
81 event_kind::PRIVATE_DIRECT_MESSAGE as i32,
82 event_kind::MESSAGE_EDIT as i32,
83 event_kind::FILE_ATTACHMENT as i32,
84 ],
85 |row| row.get::<_, String>(0),
86 ).map_err(|e| format!("Failed to query IDs: {}", e))?;
87
88 rows.filter_map(|r| r.ok()).collect()
89 };
90
91 let total = all_ids.len();
92 let mut completed = 0;
93 let mut last_emitted_percent: i32 = -1;
94 let mut skipped = 0;
95
96 for id in &all_ids {
98 let content: Option<String> = tx.query_row(
99 "SELECT content FROM events WHERE id = ?1",
100 rusqlite::params![id],
101 |row| row.get(0),
102 ).ok();
103
104 if let Some(content) = content {
105 match decrypt_with_key(&content, key) {
106 Ok(plaintext) => {
107 tx.execute(
108 "UPDATE events SET content = ?1 WHERE id = ?2",
109 rusqlite::params![plaintext, id],
110 ).map_err(|e| format!("Failed to update event: {}", e))?;
111 }
112 Err(_) => {
113 crate::log_info!("[Encryption] Skipping event {} - looks encrypted but isn't", id);
115 skipped += 1;
116 }
117 }
118 }
119
120 completed += 1;
121 let current_percent = if total > 0 {
122 ((completed as f64 / total as f64) * 100.0) as i32
123 } else {
124 100
125 };
126
127 if current_percent >= last_emitted_percent + 5 {
128 last_emitted_percent = current_percent;
129 progress(MigrationProgress {
130 total,
131 completed,
132 phase: "decrypting".to_string(),
133 });
134 }
135 }
136
137 progress(MigrationProgress {
139 total,
140 completed,
141 phase: "finalizing".to_string(),
142 });
143
144 decrypt_setting_in_tx(&tx, "seed", key, |v| v.contains(' '))?;
145 decrypt_setting_in_tx(&tx, "pkey", key, |v| v.starts_with("nsec"))?;
146 decrypt_setting_in_tx(&tx, "bunker_url", key, |v| v.starts_with("bunker://"))?;
147 decrypt_pivx_in_tx(&tx, key)?;
148 decrypt_columns_in_tx(&tx, key)?;
149 sweep_residue_in_tx(&tx, key, None)?;
150
151 verify_plaintext_state_in_tx(&tx)?;
153
154 tx.execute(
156 "INSERT OR REPLACE INTO settings (key, value) VALUES ('encryption_enabled', 'false')",
157 [],
158 ).map_err(|e| format!("Failed to update encryption_enabled: {}", e))?;
159 super::settings::write_kdf_in_tx(&tx, None)?;
160
161 tx.execute(
164 "DELETE FROM settings WHERE key = 'nip55_pin_check'",
165 [],
166 ).map_err(|e| format!("Failed to clear pin canary: {}", e))?;
167 tx.execute(
168 "DELETE FROM settings WHERE key = 'security_type'",
169 [],
170 ).map_err(|e| format!("Failed to clear security_type: {}", e))?;
171
172 tx.execute(
175 "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
176 [],
177 ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
178
179 tx.execute(
180 "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', '')",
181 [],
182 ).map_err(|e| format!("Failed to clear migration_state: {}", e))?;
183
184 tx.commit().map_err(|e| format!("Failed to commit disable transaction: {}", e))?;
186
187 set_encryption_enabled(false);
188 crate::state::ENCRYPTION_KEY.clear(&[&crate::state::MY_SECRET_KEY]);
189 crate::crypto::forget_previous_key();
190
191 if skipped > 0 {
192 crate::log_info!("[Encryption] Skipped {} false-positive hex events", skipped);
193 }
194 crate::log_info!("[Encryption] Disable complete: decrypted {} events", total - skipped);
195
196 Ok(())
197}
198
199pub fn enable(
208 key: &[u8; 32],
209 kdf: &crate::crypto::Kdf,
210 security_type: &str,
211 biometric_wrap: Option<&str>,
212 nip55_canary: Option<&str>,
213 progress: &dyn Fn(MigrationProgress),
214) -> Result<(), String> {
215 if kdf.is_legacy() {
216 return Err("A new key needs its own salt".to_string());
217 }
218 let _change = crate::crypto::gate::key_change()?;
221 if !crate::db::writes_to_live_account() {
222 return Err("The account changed before encryption could be turned on".to_string());
223 }
224 let mut conn = crate::db::get_write_connection_guard_static()?;
225 let tx = conn.transaction()
226 .map_err(|e| format!("Failed to begin transaction: {}", e))?;
227
228 tx.execute(
230 "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', 'encrypting')",
231 [],
232 ).map_err(|e| format!("Failed to set migration_state: {}", e))?;
233
234 let all_ids: Vec<String> = {
236 let mut stmt = tx.prepare(
237 r#"SELECT id FROM events
238 WHERE kind IN (?1, ?2, ?3, ?4) AND content <> ''
239 AND (length(content) < 56 OR content GLOB '*[^0-9a-f]*')"#,
240 ).map_err(|e| format!("Failed to prepare ID query: {}", e))?;
241
242 let rows = stmt.query_map(
243 rusqlite::params![
244 event_kind::CHAT_MESSAGE as i32,
245 event_kind::PRIVATE_DIRECT_MESSAGE as i32,
246 event_kind::MESSAGE_EDIT as i32,
247 event_kind::FILE_ATTACHMENT as i32,
248 ],
249 |row| row.get::<_, String>(0),
250 ).map_err(|e| format!("Failed to query IDs: {}", e))?;
251
252 rows.filter_map(|r| r.ok()).collect()
253 };
254
255 let total = all_ids.len();
256 let mut completed = 0;
257 let mut last_emitted_percent: i32 = -1;
258
259 for id in &all_ids {
261 let content: Option<String> = tx.query_row(
262 "SELECT content FROM events WHERE id = ?1",
263 rusqlite::params![id],
264 |row| row.get(0),
265 ).ok();
266
267 if let Some(content) = content {
268 let encrypted = encrypt_with_key(&content, key);
269 tx.execute(
270 "UPDATE events SET content = ?1 WHERE id = ?2",
271 rusqlite::params![encrypted, id],
272 ).map_err(|e| format!("Failed to update event: {}", e))?;
273 }
274
275 completed += 1;
276 let current_percent = if total > 0 {
277 ((completed as f64 / total as f64) * 100.0) as i32
278 } else {
279 100
280 };
281
282 if current_percent >= last_emitted_percent + 5 {
283 last_emitted_percent = current_percent;
284 progress(MigrationProgress {
285 total,
286 completed,
287 phase: "encrypting".to_string(),
288 });
289 }
290 }
291
292 progress(MigrationProgress {
294 total,
295 completed,
296 phase: "finalizing".to_string(),
297 });
298
299 seal_plain_messages_in_tx(&tx, key)?;
301 encrypt_setting_in_tx(&tx, "seed", key, |v| v.contains(' '))?;
302 encrypt_setting_in_tx(&tx, "pkey", key, |v| v.starts_with("nsec"))?;
303 encrypt_setting_in_tx(&tx, "bunker_url", key, |v| v.starts_with("bunker://"))?;
304 encrypt_pivx_in_tx(&tx, key)?;
305 encrypt_columns_in_tx(&tx, key)?;
306
307 verify_encrypted_state_in_tx(&tx, key)?;
309
310 tx.execute(
312 "INSERT OR REPLACE INTO settings (key, value) VALUES ('encryption_enabled', 'true')",
313 [],
314 ).map_err(|e| format!("Failed to update encryption_enabled: {}", e))?;
315 super::settings::write_kdf_in_tx(&tx, kdf.descriptor().as_deref())?;
316
317 tx.execute(
318 "INSERT OR REPLACE INTO settings (key, value) VALUES ('security_type', ?1)",
319 rusqlite::params![security_type],
320 ).map_err(|e| format!("Failed to update security_type: {}", e))?;
321
322 if let Some(c) = nip55_canary {
325 tx.execute(
326 "INSERT OR REPLACE INTO settings (key, value) VALUES ('nip55_pin_check', ?1)",
327 rusqlite::params![c],
328 ).map_err(|e| format!("Failed to set pin canary: {}", e))?;
329 }
330
331 match biometric_wrap {
336 Some(w) => {
337 tx.execute(
338 "INSERT OR REPLACE INTO settings (key, value) VALUES ('biometric_wrapped_key', ?1)",
339 rusqlite::params![w],
340 ).map_err(|e| format!("Failed to set biometric wrap: {}", e))?;
341 }
342 None => {
343 tx.execute(
344 "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
345 [],
346 ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
347 }
348 }
349
350 tx.execute(
351 "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', '')",
352 [],
353 ).map_err(|e| format!("Failed to clear migration_state: {}", e))?;
354
355 tx.commit().map_err(|e| format!("Failed to commit enable transaction: {}", e))?;
357
358 crate::state::ENCRYPTION_KEY.set(*key, &[&crate::state::MY_SECRET_KEY]);
359 set_encryption_enabled(true);
360
361 crate::log_info!("[Encryption] Enable complete: encrypted {} events", total);
362
363 Ok(())
364}
365
366fn decrypt_setting_in_tx(
372 tx: &rusqlite::Transaction,
373 key_name: &str,
374 key: &[u8; 32],
375 is_plaintext: fn(&str) -> bool,
376) -> Result<(), String> {
377 let val: Option<String> = tx.query_row(
378 "SELECT value FROM settings WHERE key = ?1",
379 rusqlite::params![key_name],
380 |row| row.get(0),
381 ).ok();
382
383 if let Some(current) = val {
384 if is_plaintext(¤t) {
385 return Ok(()); }
387
388 let decrypted = decrypt_with_key(¤t, key)
389 .map_err(|_| format!("Failed to decrypt setting '{}'", key_name))?;
390
391 tx.execute(
392 "UPDATE settings SET value = ?1 WHERE key = ?2",
393 rusqlite::params![decrypted, key_name],
394 ).map_err(|e| format!("Failed to update setting '{}': {}", key_name, e))?;
395 }
396
397 Ok(())
398}
399
400fn encrypt_setting_in_tx(
403 tx: &rusqlite::Transaction,
404 key_name: &str,
405 key: &[u8; 32],
406 is_plaintext: fn(&str) -> bool,
407) -> Result<(), String> {
408 let val: Option<String> = tx.query_row(
409 "SELECT value FROM settings WHERE key = ?1",
410 rusqlite::params![key_name],
411 |row| row.get(0),
412 ).ok();
413
414 if let Some(current) = val {
415 if is_plaintext(¤t) {
416 let encrypted = encrypt_with_key(¤t, key);
417 tx.execute(
418 "UPDATE settings SET value = ?1 WHERE key = ?2",
419 rusqlite::params![encrypted, key_name],
420 ).map_err(|e| format!("Failed to update setting '{}': {}", key_name, e))?;
421 }
422 }
423
424 Ok(())
425}
426
427fn decrypt_pivx_in_tx(
429 tx: &rusqlite::Transaction,
430 key: &[u8; 32],
431) -> Result<(), String> {
432 let keys: Vec<(i64, String)> = {
433 let mut stmt = tx.prepare("SELECT id, privkey_encrypted FROM pivx_promos")
434 .map_err(|e| format!("Failed to prepare PIVX query: {}", e))?;
435 let rows = stmt.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)))
436 .map_err(|e| format!("Failed to query PIVX promos: {}", e))?;
437 rows.filter_map(|r| r.ok()).collect()
438 };
439
440 for (id, key_val) in keys {
441 if key_val.len() > 64 {
443 let decrypted = decrypt_with_key(&key_val, key)
444 .map_err(|_| format!("Failed to decrypt PIVX key {}", id))?;
445 tx.execute(
446 "UPDATE pivx_promos SET privkey_encrypted = ?1 WHERE id = ?2",
447 rusqlite::params![decrypted, id],
448 ).map_err(|e| format!("Failed to update PIVX key: {}", e))?;
449 }
450 }
451
452 Ok(())
453}
454
455fn encrypt_pivx_in_tx(
457 tx: &rusqlite::Transaction,
458 key: &[u8; 32],
459) -> Result<(), String> {
460 let keys: Vec<(i64, String)> = {
461 let mut stmt = tx.prepare("SELECT id, privkey_encrypted FROM pivx_promos")
462 .map_err(|e| format!("Failed to prepare PIVX query: {}", e))?;
463 let rows = stmt.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)))
464 .map_err(|e| format!("Failed to query PIVX promos: {}", e))?;
465 rows.filter_map(|r| r.ok()).collect()
466 };
467
468 for (id, key_val) in keys {
469 if key_val.len() <= 64 {
471 let encrypted = encrypt_with_key(&key_val, key);
472 tx.execute(
473 "UPDATE pivx_promos SET privkey_encrypted = ?1 WHERE id = ?2",
474 rusqlite::params![encrypted, id],
475 ).map_err(|e| format!("Failed to update PIVX key: {}", e))?;
476 }
477 }
478
479 Ok(())
480}
481
482fn xform_text(v: &str, enc: Option<&[u8; 32]>, dec: Option<&[u8; 32]>) -> Result<String, String> {
496 if v.is_empty() {
498 return Ok(String::new());
499 }
500 let mut s = zeroize::Zeroizing::new(v.to_string());
501 if let Some(k) = dec {
502 if let Ok(p) = decrypt_with_key(&s, k) {
503 s = zeroize::Zeroizing::new(p);
504 }
505 }
506 if let Some(k) = enc {
507 if decrypt_with_key(&s, k).map(zeroize::Zeroizing::new).is_err() {
508 return Ok(encrypt_with_key(&s, k));
509 }
510 }
511 Ok(s.to_string())
512}
513
514fn xform_blob(v: &[u8], enc: Option<&[u8; 32]>, dec: Option<&[u8; 32]>) -> Result<Vec<u8>, String> {
515 let mut b = zeroize::Zeroizing::new(v.to_vec());
516 if let Some(k) = dec {
517 if let Ok(p) = crate::crypto::decrypt_blob_with_key(&b, k) {
518 b = zeroize::Zeroizing::new(p);
519 }
520 }
521 if let Some(k) = enc {
522 if crate::crypto::decrypt_blob_with_key(&b, k).map(zeroize::Zeroizing::new).is_err() {
523 return crate::crypto::encrypt_blob_with_key(&b, k);
524 }
525 }
526 Ok(b.to_vec())
527}
528
529#[cfg(test)]
530mod xform_tests {
531 use super::*;
532 const K: [u8; 32] = [7u8; 32];
533 const K2: [u8; 32] = [9u8; 32];
534
535 #[test]
536 fn bare_hex_plaintext_is_encrypted_not_skipped() {
537 let token = "de".repeat(32); let wrapped = xform_text(&token, Some(&K), None).unwrap();
541 assert_ne!(wrapped, token, "bare-hex plaintext must be encrypted");
542 assert_eq!(decrypt_with_key(&wrapped, &K).unwrap(), token);
543 }
544
545 #[test]
546 fn encrypt_is_idempotent() {
547 let token = "de".repeat(32);
548 let once = xform_text(&token, Some(&K), None).unwrap();
549 let twice = xform_text(&once, Some(&K), None).unwrap();
550 assert_eq!(once, twice, "re-running encrypt must not double-wrap");
551 assert_eq!(decrypt_with_key(&twice, &K).unwrap(), token);
552 }
553
554 #[test]
555 fn disable_then_reenable_roundtrips_bare_hex() {
556 let token = "ab".repeat(32);
557 let enc = xform_text(&token, Some(&K), None).unwrap();
558 let dec = xform_text(&enc, None, Some(&K)).unwrap();
559 assert_eq!(dec, token, "disable decrypts back to plaintext");
560 let re = xform_text(&dec, Some(&K), None).unwrap();
561 assert_eq!(decrypt_with_key(&re, &K).unwrap(), token, "re-enable wraps the bare-hex again");
562 }
563
564 #[test]
565 fn rekey_rewraps_bare_hex_under_new_key() {
566 let token = "cd".repeat(32);
567 let old = xform_text(&token, Some(&K), None).unwrap();
568 let new = xform_text(&old, Some(&K2), Some(&K)).unwrap(); assert!(decrypt_with_key(&new, &K).is_err(), "no longer under old key");
570 assert_eq!(decrypt_with_key(&new, &K2).unwrap(), token, "now under new key");
571 }
572
573 #[test]
574 fn nonhex_plaintext_roundtrips() {
575 assert_eq!(xform_text("", Some(&K), None).unwrap(), "", "empty stays empty");
576 for v in ["general", "{\"roles\":[]}", "wss://relay.example"] {
577 let enc = xform_text(v, Some(&K), None).unwrap();
578 assert_eq!(decrypt_with_key(&enc, &K).unwrap(), v);
579 assert_eq!(xform_text(&enc, None, Some(&K)).unwrap(), v);
580 }
581 }
582
583 fn migrate_test_schema(conn: &rusqlite::Connection) {
586 conn.execute_batch(
587 "CREATE TABLE communities (community_id TEXT, server_root_key BLOB, name TEXT, relays TEXT, description TEXT, icon TEXT, banner TEXT, banlist TEXT, banlist_marks TEXT, roles TEXT, invite_registry TEXT, owner_pubkey TEXT, owner_salt TEXT, meta_extra TEXT, control_pk TEXT, control_root BLOB);
588 CREATE TABLE community_channels (channel_id TEXT, channel_key BLOB, name TEXT, meta_extra TEXT);
589 CREATE TABLE community_epoch_keys (key BLOB);
590 CREATE TABLE community_message_keys (outer_event_id TEXT, ephemeral_secret BLOB, relays TEXT);
591 CREATE TABLE community_wrap_owners (outer_event_id TEXT, owner_secret BLOB, relays TEXT);
592 CREATE TABLE pending_channel_keys (id INTEGER PRIMARY KEY AUTOINCREMENT, channel_key BLOB, sender TEXT);
593 CREATE TABLE pending_community_invites (community_id TEXT, bundle_json TEXT, inviter_npub TEXT);
594 CREATE TABLE community_public_invites (token TEXT, url TEXT, label TEXT);
595 CREATE TABLE community_invite_link_sets (creator TEXT, locators TEXT);
596 CREATE TABLE community_guestbook (community_id TEXT, events TEXT, cursor_secs INTEGER);
597 CREATE TABLE community_guestbook_events (seq INTEGER PRIMARY KEY, book INTEGER, rumor_id BLOB, body BLOB);
598 CREATE TABLE community_departures_seen (seq INTEGER PRIMARY KEY, book INTEGER, body BLOB);
599 CREATE TABLE community_owed_authors (seq INTEGER PRIMARY KEY, book INTEGER, channel_id TEXT, body BLOB);
600 CREATE TABLE community_policies (community_id TEXT, policy_id TEXT, bytes TEXT, hash TEXT, enabled INTEGER, updated_at INTEGER);
601 CREATE TABLE community_pins (community_id TEXT, channel_id TEXT, content TEXT, PRIMARY KEY (community_id, channel_id));
602 CREATE TABLE community_writers (community_id TEXT, channel_id TEXT, content TEXT, PRIMARY KEY (community_id, channel_id));
603 CREATE TABLE attachments (key TEXT, nonce TEXT, name TEXT, url TEXT, fallback_urls TEXT, img_meta TEXT);
604 CREATE TABLE media_store (hash TEXT PRIMARY KEY, key TEXT, nonce TEXT);
605 CREATE TABLE events (preview_metadata TEXT);
606 CREATE TABLE nip17_wrap_keys (rumor_json TEXT);
607 CREATE TABLE community_bans (community_id TEXT, npub TEXT);
608 CREATE TABLE community_held_wraps (wrap_id TEXT PRIMARY KEY, wrap TEXT);
609 CREATE TABLE community_control_wraps (wrap_id BLOB PRIMARY KEY, wrap BLOB);
610 CREATE TABLE community_audit_local (id TEXT PRIMARY KEY, entry TEXT);
611 CREATE TABLE dm_held_wallpapers (chat_id TEXT, payload TEXT);",
612 ).unwrap();
613 }
614
615 #[test]
620 fn guestbook_and_policies_survive_enable_rekey_disable() {
621 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
622 migrate_test_schema(&conn);
623 conn.execute(
624 "INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, ?2, 7)",
625 rusqlite::params!["aa".repeat(32), r#"[{"rumor_id":"x"}]"#],
626 )
627 .unwrap();
628 conn.execute(
629 "INSERT INTO community_policies (community_id, policy_id, bytes, hash, enabled, updated_at)
630 VALUES (?1, 'p1', ?2, 'hh', 1, 0)",
631 rusqlite::params!["aa".repeat(32), r#"{"format":1,"name":"x"}"#],
632 )
633 .unwrap();
634 let read = |c: &rusqlite::Connection| -> (String, String) {
635 (
636 c.query_row("SELECT events FROM community_guestbook", [], |r| r.get(0)).unwrap(),
637 c.query_row("SELECT bytes FROM community_policies", [], |r| r.get(0)).unwrap(),
638 )
639 };
640 let before = read(&conn);
641 let k1 = [0x21u8; 32];
642 let k2 = [0x22u8; 32];
643 let step = |c: &mut rusqlite::Connection, enc: Option<&[u8; 32]>, dec: Option<&[u8; 32]>| {
644 let tx = c.transaction().unwrap();
645 sweep_columns_in_tx(&tx, enc, dec).unwrap();
646 tx.commit().unwrap();
647 };
648 step(&mut conn, Some(&k1), None);
649 let enabled = read(&conn);
653 assert_ne!(enabled.0, before.0, "the guestbook must actually be encrypted by the sweep");
654 assert_ne!(enabled.1, before.1, "the policy bytes must actually be encrypted by the sweep");
655
656 step(&mut conn, Some(&k2), Some(&k1));
657 step(&mut conn, None, Some(&k2));
658 assert_eq!(read(&conn), before, "a rekey round-trip must return the plaintext it started with");
659 }
660
661 #[test]
666 fn v2_control_pair_survives_enable_rekey_disable() {
667 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
668 migrate_test_schema(&conn);
669 let control_root: Vec<u8> = vec![0x5Au8; 32];
670 conn.execute(
671 "INSERT INTO communities (community_id, server_root_key, name, relays, banlist, roles, invite_registry, owner_pubkey, owner_salt, meta_extra, control_pk, control_root)
672 VALUES (?1, ?2, 'n', '[]', '[]', '{}', '[]', ?3, ?4, '{\"custom\":null,\"extra\":{}}', ?5, ?6)",
673 rusqlite::params!["cc".repeat(32), vec![0x11u8; 32], "ab".repeat(32), "cd".repeat(32), "ef".repeat(32), control_root],
674 ).unwrap();
675 let read = |c: &rusqlite::Connection| -> (String, String, Vec<u8>) {
676 c.query_row("SELECT owner_pubkey, control_pk, control_root FROM communities", [], |r| {
677 Ok((r.get(0)?, r.get(1)?, r.get(2)?))
678 }).unwrap()
679 };
680
681 let tx = conn.transaction().unwrap();
682 encrypt_columns_in_tx(&tx, &K).unwrap();
683 tx.commit().unwrap();
684 let (owner_pk, control_pk, root) = read(&conn);
685 assert_ne!(owner_pk, "ab".repeat(32), "owner commitment must be wrapped after enable");
686 assert_ne!(control_pk, "ef".repeat(32), "control_pk must be wrapped after enable");
687 assert_ne!(root, vec![0x5Au8; 32], "control_root must be wrapped after enable");
688
689 let tx = conn.transaction().unwrap();
690 rekey_columns_in_tx(&tx, &K, &K2).unwrap();
691 tx.commit().unwrap();
692
693 let tx = conn.transaction().unwrap();
694 decrypt_columns_in_tx(&tx, &K2).unwrap();
695 tx.commit().unwrap();
696 let (owner_pk, control_pk, root) = read(&conn);
697 assert_eq!(owner_pk, "ab".repeat(32), "owner commitment survives enable → rekey → disable");
698 assert_eq!(control_pk, "ef".repeat(32), "control_pk survives enable → rekey → disable");
699 assert_eq!(root, vec![0x5Au8; 32], "control_root survives enable → rekey → disable");
700 }
701
702 #[test]
705 fn public_invite_label_survives_enable_rekey_disable() {
706 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
707 migrate_test_schema(&conn);
708 conn.execute(
709 "INSERT INTO community_public_invites (token, url, label) VALUES (?1, ?2, ?3)",
710 rusqlite::params!["ab".repeat(32), "https://vectorapp.io/invite#x", "Reddit"],
711 ).unwrap();
712 let read_label = |c: &rusqlite::Connection| -> String {
713 c.query_row("SELECT label FROM community_public_invites", [], |r| r.get(0)).unwrap()
714 };
715
716 let tx = conn.transaction().unwrap();
717 encrypt_columns_in_tx(&tx, &K).unwrap();
718 tx.commit().unwrap();
719 assert_ne!(read_label(&conn), "Reddit", "label must be wrapped after enable");
720
721 let tx = conn.transaction().unwrap();
722 rekey_columns_in_tx(&tx, &K, &K2).unwrap();
723 tx.commit().unwrap();
724
725 let tx = conn.transaction().unwrap();
726 decrypt_columns_in_tx(&tx, &K2).unwrap();
727 tx.commit().unwrap();
728 assert_eq!(read_label(&conn), "Reddit", "label must survive enable → rekey → disable");
729 }
730
731 #[test]
734 fn sweep_list_matches_the_real_schema() {
735 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
736 conn.execute_batch(crate::db::schema::SQL_SCHEMA).unwrap();
737 crate::db::schema::run_migrations(&mut conn).unwrap();
738 for (table, cols) in SWEEP {
739 conn.prepare(&format!("SELECT {} FROM {table}", cols.join(", ")))
740 .unwrap_or_else(|e| panic!("{table}: {e}"));
741 }
742 }
743
744 #[test]
747 fn every_swept_column_survives_enable_rekey_disable() {
748 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
749 migrate_test_schema(&conn);
750 let mut n = 0u8;
751 for (table, cols) in SWEEP {
752 for with_nulls in [false, true] {
753 let vals: Vec<rusqlite::types::Value> = cols.iter().map(|c| {
754 n += 1;
755 let blob = conn
756 .query_row("SELECT type FROM pragma_table_info(?1) WHERE name = ?2", [table, c], |r| r.get::<_, String>(0))
757 .unwrap() == "BLOB";
758 if with_nulls && *c != cols[0] {
759 rusqlite::types::Value::Null
760 } else if blob {
761 rusqlite::types::Value::Blob(vec![n; 32])
762 } else {
763 rusqlite::types::Value::Text(format!("{c}-{n}"))
764 }
765 }).collect();
766 let marks = vec!["?"; cols.len()].join(", ");
767 let sql = format!("INSERT OR REPLACE INTO {table} ({}) VALUES ({marks})", cols.join(", "));
768 conn.execute(&sql, rusqlite::params_from_iter(vals.iter())).unwrap();
769 }
770 }
771 let snapshot = |c: &rusqlite::Connection| -> Vec<Vec<rusqlite::types::Value>> {
772 SWEEP.iter().flat_map(|(table, cols)| {
773 let mut stmt = c.prepare(&format!("SELECT {} FROM {table} ORDER BY rowid", cols.join(", "))).unwrap();
774 let rows = stmt
775 .query_map([], |r| (0..cols.len()).map(|i| r.get::<_, rusqlite::types::Value>(i)).collect())
776 .unwrap()
777 .map(|r| r.unwrap())
778 .collect::<Vec<Vec<rusqlite::types::Value>>>();
779 rows
780 }).collect()
781 };
782 let before = snapshot(&conn);
783 let step = |c: &mut rusqlite::Connection, enc: Option<&[u8; 32]>, dec: Option<&[u8; 32]>| {
784 let tx = c.transaction().unwrap();
785 sweep_columns_in_tx(&tx, enc, dec).unwrap();
786 tx.commit().unwrap();
787 };
788
789 step(&mut conn, Some(&K), None);
790 let enabled = snapshot(&conn);
791 for (row_before, row_enabled) in before.iter().zip(&enabled) {
792 for (b, e) in row_before.iter().zip(row_enabled) {
793 match b {
794 rusqlite::types::Value::Null => assert_eq!(e, b, "NULL stays NULL"),
795 _ => assert_ne!(e, b, "every listed value must actually be wrapped by enable"),
796 }
797 }
798 }
799 step(&mut conn, Some(&K2), Some(&K));
800 {
801 let tx = conn.transaction().unwrap();
802 assert_eq!(sweep_residue_in_tx(&tx, &K, Some(&K2)).unwrap(), 0, "the list alone leaves nothing on the old key");
803 }
804 step(&mut conn, None, Some(&K2));
805 assert_eq!(snapshot(&conn), before, "enable, rekey and disable return every value it started with");
806 }
807
808 #[test]
811 fn residue_sweep_moves_unlisted_ciphertext_and_nothing_else() {
812 const K3: [u8; 32] = [11u8; 32];
813 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
814 conn.execute_batch("CREATE TABLE future (t TEXT, b BLOB, n INTEGER);").unwrap();
815 let text_ct = encrypt_with_key("hello", &K);
816 let blob_ct = crate::crypto::encrypt_blob_with_key(&[0x42u8; 32], &K).unwrap();
817 let foreign = encrypt_with_key("someone else's", &K3);
818 let bare_hex = "ab".repeat(32);
819 conn.execute("INSERT INTO future VALUES (?1, ?2, 1)", rusqlite::params![text_ct, blob_ct]).unwrap();
820 conn.execute("INSERT INTO future VALUES (?1, NULL, 2)", rusqlite::params![foreign]).unwrap();
821 conn.execute("INSERT INTO future VALUES (?1, x'00ff', 3)", rusqlite::params![bare_hex]).unwrap();
822
823 let tx = conn.transaction().unwrap();
824 assert_eq!(sweep_residue_in_tx(&tx, &K, Some(&K2)).unwrap(), 2);
825 tx.commit().unwrap();
826 let (t, b): (String, Vec<u8>) = conn.query_row("SELECT t, b FROM future WHERE n = 1", [], |r| Ok((r.get(0)?, r.get(1)?))).unwrap();
827 assert_eq!(decrypt_with_key(&t, &K2).unwrap(), "hello");
828 assert_eq!(crate::crypto::decrypt_blob_with_key(&b, &K2).unwrap(), vec![0x42u8; 32]);
829 let untouched: (String, String) = conn.query_row(
830 "SELECT (SELECT t FROM future WHERE n = 2), (SELECT t FROM future WHERE n = 3)", [], |r| Ok((r.get(0)?, r.get(1)?)),
831 ).unwrap();
832 assert_eq!(untouched, (foreign, bare_hex), "values not under the old key are left alone");
833
834 let tx = conn.transaction().unwrap();
835 assert_eq!(sweep_residue_in_tx(&tx, &K2, None).unwrap(), 2);
836 tx.commit().unwrap();
837 let (t, b): (String, Vec<u8>) = conn.query_row("SELECT t, b FROM future WHERE n = 1", [], |r| Ok((r.get(0)?, r.get(1)?))).unwrap();
838 assert_eq!((t.as_str(), b), ("hello", vec![0x42u8; 32]), "disable opens text to text and blob to blob");
839 }
840
841 #[test]
844 fn residue_sweep_refuses_what_it_cannot_move() {
845 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
846 conn.execute_batch("CREATE TABLE keyed (k TEXT PRIMARY KEY, v TEXT) WITHOUT ROWID;").unwrap();
847 conn.execute("INSERT INTO keyed VALUES ('a', ?1)", [encrypt_with_key("x", &K)]).unwrap();
848 let tx = conn.transaction().unwrap();
849 assert!(sweep_residue_in_tx(&tx, &K, Some(&K2)).is_err());
850 drop(tx);
851
852 let mut conn = rusqlite::Connection::open_in_memory().unwrap();
853 conn.execute_batch("CREATE TABLE odd (v TEXT);").unwrap();
854 let sealed = crate::crypto::encrypt_blob_with_key(&[0xff, 0xfe, 0x00], &K).unwrap();
855 conn.execute("INSERT INTO odd VALUES (?1)", [crate::simd::hex::bytes_to_hex_string(&sealed)]).unwrap();
856 let tx = conn.transaction().unwrap();
857 assert!(sweep_residue_in_tx(&tx, &K, None).is_err(), "bytes that are not text never land in a text column");
858 }
859
860 #[test]
863 fn a_key_is_proven_by_whatever_the_store_holds() {
864 let fresh = || {
865 let mut c = rusqlite::Connection::open_in_memory().unwrap();
866 c.execute_batch(crate::db::schema::SQL_SCHEMA).unwrap();
867 crate::db::schema::run_migrations(&mut c).unwrap();
868 c
869 };
870 let proves = |c: &mut rusqlite::Connection, k: &[u8; 32], require: bool| {
871 let tx = c.transaction().unwrap();
872 prove_key_in_tx(&tx, k, require).is_ok()
873 };
874
875 let mut empty = fresh();
876 assert!(proves(&mut empty, &K, false), "nothing encrypted, nothing to lose");
877 assert!(!proves(&mut empty, &K, true), "an enable-direction pass needs an anchor");
878
879 let mut local = fresh();
880 local.execute("INSERT INTO settings (key, value) VALUES ('pkey', ?1)", [encrypt_with_key("nsec1abc", &K)]).unwrap();
881 assert!(proves(&mut local, &K, true));
882 assert!(!proves(&mut local, &K2, false));
883
884 let mut keyless = fresh();
885 keyless.execute("INSERT INTO settings (key, value) VALUES ('nip55_pin_check', ?1)", [encrypt_with_key(NIP55_PIN_CANARY, &K)]).unwrap();
886 assert!(proves(&mut keyless, &K, true));
887 assert!(!proves(&mut keyless, &K2, false));
888
889 let mut no_canary = fresh();
890 let blob = crate::crypto::encrypt_blob_with_key(&[7u8; 32], &K).unwrap();
891 no_canary.execute(
892 "INSERT INTO community_epoch_keys (community_id, scope_id, epoch, key, created_at) VALUES ('c', 's', 0, ?1, 0)",
893 [blob],
894 ).unwrap();
895 assert!(proves(&mut no_canary, &K, true), "a sealed community key is proof enough");
896 assert!(!proves(&mut no_canary, &K2, false), "a key that opens none of the samples is refused");
897 }
898
899 #[test]
900 fn blob_roundtrip_and_idempotent() {
901 let raw = [0x42u8; 32];
902 let enc = xform_blob(&raw, Some(&K), None).unwrap();
903 assert_eq!(enc.len(), 60);
904 assert_eq!(xform_blob(&enc, Some(&K), None).unwrap(), enc, "blob encrypt idempotent");
905 assert_eq!(xform_blob(&enc, None, Some(&K)).unwrap(), raw.to_vec());
906 let re = xform_blob(&enc, Some(&K2), Some(&K)).unwrap();
908 assert_eq!(crate::crypto::decrypt_blob_with_key(&re, &K2).unwrap(), raw.to_vec());
909 }
910}
911
912const SWEEP: &[(&str, &[&str])] = &[
916 ("attachments", &["key", "nonce", "name", "url", "fallback_urls", "img_meta"]),
917 ("media_store", &["key", "nonce"]),
918 ("events", &["preview_metadata"]),
919 ("nip17_wrap_keys", &["rumor_json"]),
920 ("communities", &[
921 "server_root_key", "name", "relays", "description", "icon", "banner", "banlist",
922 "banlist_marks", "roles", "invite_registry", "owner_pubkey", "owner_salt", "meta_extra",
923 "control_pk", "control_root",
924 ]),
925 ("community_channels", &["channel_key", "name", "meta_extra"]),
926 ("community_epoch_keys", &["key"]),
927 ("community_message_keys", &["ephemeral_secret", "relays"]),
928 ("community_wrap_owners", &["owner_secret", "relays"]),
929 ("pending_channel_keys", &["channel_key", "sender"]),
930 ("pending_community_invites", &["bundle_json", "inviter_npub"]),
931 ("community_guestbook", &["events"]),
932 ("community_guestbook_events", &["body"]),
933 ("community_departures_seen", &["body"]),
934 ("community_owed_authors", &["body"]),
935 ("community_policies", &["bytes"]),
936 ("community_public_invites", &["token", "url", "label"]),
937 ("community_invite_link_sets", &["creator", "locators"]),
938 ("community_pins", &["content"]),
939 ("community_writers", &["content"]),
940 ("community_bans", &["npub"]),
941 ("community_held_wraps", &["wrap"]),
942 ("community_control_wraps", &["wrap"]),
943 ("community_audit_local", &["entry"]),
944 ("dm_held_wallpapers", &["payload"]),
945];
946
947fn sweep_columns_in_tx(
948 tx: &rusqlite::Transaction,
949 enc: Option<&[u8; 32]>,
950 dec: Option<&[u8; 32]>,
951) -> Result<(), String> {
952 for (table, cols) in SWEEP {
953 xform_columns_in_tx(tx, table, cols, enc, dec)?;
954 }
955 Ok(())
956}
957
958fn xform_columns_in_tx(
962 tx: &rusqlite::Transaction,
963 table: &str,
964 cols: &[&str],
965 enc: Option<&[u8; 32]>,
966 dec: Option<&[u8; 32]>,
967) -> Result<(), String> {
968 use rusqlite::types::Value;
969 let present: Vec<String> = {
970 let mut stmt = tx
971 .prepare("SELECT name FROM pragma_table_info(?1)")
972 .map_err(|e| format!("columns of {table}: {e}"))?;
973 let mapped = stmt.query_map([table], |r| r.get::<_, String>(0)).map_err(|e| format!("columns of {table}: {e}"))?;
974 mapped.collect::<Result<_, _>>().map_err(|e| format!("columns of {table}: {e}"))?
975 };
976 let cols: Vec<&str> = cols.iter().copied().filter(|c| present.iter().any(|p| p == c)).collect();
977 if cols.is_empty() {
978 crate::log_warn!("[Encryption] {table} is missing from this database; nothing to sweep there");
979 return Ok(());
980 }
981 let rows: Vec<(i64, Vec<Value>)> = {
982 let mut stmt = tx
983 .prepare(&format!("SELECT rowid, {} FROM {table}", cols.join(", ")))
984 .map_err(|e| format!("prepare {table}: {e}"))?;
985 let mapped = stmt
986 .query_map([], |r| {
987 let vals = (1..=cols.len()).map(|i| r.get::<_, Value>(i)).collect::<Result<Vec<_>, _>>()?;
988 Ok((r.get::<_, i64>(0)?, vals))
989 })
990 .map_err(|e| format!("query {table}: {e}"))?;
991 mapped.collect::<Result<_, _>>().map_err(|e| format!("read {table}: {e}"))?
992 };
993 let set = cols.iter().enumerate().map(|(i, c)| format!("{c} = ?{}", i + 1)).collect::<Vec<_>>().join(", ");
994 let mut update = tx
995 .prepare(&format!("UPDATE {table} SET {set} WHERE rowid = ?{}", cols.len() + 1))
996 .map_err(|e| format!("prepare update {table}: {e}"))?;
997 for (rowid, vals) in rows {
998 let mut out = Vec::with_capacity(vals.len() + 1);
999 for v in &vals {
1000 out.push(match v {
1001 Value::Text(s) => Value::Text(xform_text(s, enc, dec)?),
1002 Value::Blob(b) => Value::Blob(xform_blob(b, enc, dec)?),
1003 other => other.clone(),
1004 });
1005 }
1006 if out == vals {
1007 continue;
1008 }
1009 out.push(Value::Integer(rowid));
1010 update
1011 .execute(rusqlite::params_from_iter(out.iter()))
1012 .map_err(|e| format!("update {table}: {e}"))?;
1013 }
1014 Ok(())
1015}
1016
1017pub(crate) fn sweep_residue_in_tx(
1021 tx: &rusqlite::Transaction,
1022 from: &[u8; 32],
1023 to: Option<&[u8; 32]>,
1024) -> Result<usize, String> {
1025 let tables: Vec<(String, bool)> = {
1026 let mut stmt = tx
1027 .prepare("SELECT name, wr FROM pragma_table_list WHERE schema = 'main' AND type = 'table' AND name NOT LIKE 'sqlite_%'")
1028 .map_err(|e| format!("residue: list tables: {e}"))?;
1029 let mapped = stmt
1030 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)))
1031 .map_err(|e| format!("residue: list tables: {e}"))?;
1032 mapped.collect::<Result<_, _>>().map_err(|e| format!("residue: list tables: {e}"))?
1033 };
1034
1035 let quote = |name: &str| format!("\"{}\"", name.replace('"', "\"\""));
1036 let cipher = crate::crypto::chachapoly::ChaCha20Poly1305::new(from);
1037 let mut scratch = Vec::new();
1038 let mut total = 0;
1039 for (table, without_rowid) in tables {
1040 let cols: Vec<String> = {
1041 let mut stmt = tx
1042 .prepare("SELECT name FROM pragma_table_info(?1)")
1043 .map_err(|e| format!("residue: columns of {table}: {e}"))?;
1044 let mapped = stmt
1045 .query_map([&table], |r| r.get::<_, String>(0))
1046 .map_err(|e| format!("residue: columns of {table}: {e}"))?;
1047 mapped.collect::<Result<_, _>>().map_err(|e| format!("residue: columns of {table}: {e}"))?
1048 };
1049 if cols.is_empty() {
1050 continue;
1051 }
1052 let quoted: Vec<String> = cols.iter().map(|c| quote(c)).collect();
1053 let rowid = if without_rowid { "NULL" } else { "rowid" };
1054 let mut found: Vec<(i64, usize)> = Vec::new();
1057 {
1058 let mut stmt = tx
1059 .prepare(&format!("SELECT {rowid}, {} FROM {}", quoted.join(", "), quote(&table)))
1060 .map_err(|e| format!("residue: scan {table}: {e}"))?;
1061 let mut rows = stmt.query([]).map_err(|e| format!("residue: scan {table}: {e}"))?;
1062 while let Some(row) = rows.next().map_err(|e| format!("residue: scan {table}: {e}"))? {
1063 for (i, col) in cols.iter().enumerate() {
1064 let cell = row.get_ref(i + 1).map_err(|e| format!("residue: read {table}.{col}: {e}"))?;
1065 if !opens_under(cell, &cipher, &mut scratch) {
1066 continue;
1067 }
1068 if without_rowid {
1069 return Err(format!("residue: {table}.{col} holds ciphertext but the table has no rowid to address it"));
1070 }
1071 found.push((row.get(0).map_err(|e| format!("residue: rowid of {table}: {e}"))?, i));
1072 }
1073 }
1074 }
1075 for &(id, i) in &found {
1076 let col = "ed[i];
1077 let moved = tx
1078 .query_row(&format!("SELECT {col} FROM {} WHERE rowid = ?1", quote(&table)), [id], |r| {
1079 Ok(move_cell(r.get_ref(0)?, from, to))
1080 })
1081 .map_err(|e| format!("residue: reread {table}.{}: {e}", cols[i]))?
1082 .map_err(|e| format!("residue: {table}.{}: {e}", cols[i]))?;
1083 let Some(moved) = moved else { continue };
1084 tx.execute(&format!("UPDATE {} SET {col} = ?1 WHERE rowid = ?2", quote(&table)), rusqlite::params![moved, id])
1085 .map_err(|e| format!("residue: update {table}.{}: {e}", cols[i]))?;
1086 }
1087 let mut by_col = std::collections::BTreeMap::<&str, usize>::new();
1088 for &(_, i) in &found {
1089 *by_col.entry(cols[i].as_str()).or_default() += 1;
1090 }
1091 for (col, n) in by_col {
1092 crate::log_warn!("[Encryption] {n} value(s) in {table}.{col} were outside the sweep lists; moved with the key");
1093 }
1094 total += found.len();
1095 }
1096 Ok(total)
1097}
1098
1099fn seal_plain_messages_in_tx(tx: &rusqlite::Transaction, key: &[u8; 32]) -> Result<usize, String> {
1103 let cipher = crate::crypto::chachapoly::ChaCha20Poly1305::new(key);
1104 let mut scratch = Vec::new();
1105 let sealed: Vec<(i64, String)> = {
1106 let mut stmt = tx
1107 .prepare("SELECT rowid, content FROM events WHERE kind IN (?1, ?2, ?3, ?4) AND content <> ''")
1108 .map_err(|e| format!("plain messages: {e}"))?;
1109 let mut rows = stmt
1110 .query(rusqlite::params![
1111 event_kind::CHAT_MESSAGE as i32,
1112 event_kind::PRIVATE_DIRECT_MESSAGE as i32,
1113 event_kind::MESSAGE_EDIT as i32,
1114 event_kind::FILE_ATTACHMENT as i32,
1115 ])
1116 .map_err(|e| format!("plain messages: {e}"))?;
1117 let mut out = Vec::new();
1118 while let Some(row) = rows.next().map_err(|e| format!("plain messages: {e}"))? {
1119 let cell = row.get_ref(1).map_err(|e| format!("plain messages: {e}"))?;
1120 if opens_under(cell, &cipher, &mut scratch) {
1121 continue;
1122 }
1123 let rusqlite::types::ValueRef::Text(text) = cell else { continue };
1124 let Ok(text) = std::str::from_utf8(text) else { continue };
1125 out.push((row.get(0).map_err(|e| format!("plain messages: {e}"))?, encrypt_with_key(text, key)));
1126 }
1127 out
1128 };
1129 for (rowid, content) in &sealed {
1130 tx.execute("UPDATE events SET content = ?1 WHERE rowid = ?2", rusqlite::params![content, rowid])
1131 .map_err(|e| format!("seal message: {e}"))?;
1132 }
1133 Ok(sealed.len())
1134}
1135
1136fn opens_under(
1139 cell: rusqlite::types::ValueRef<'_>,
1140 cipher: &crate::crypto::chachapoly::ChaCha20Poly1305,
1141 scratch: &mut Vec<u8>,
1142) -> bool {
1143 use rusqlite::types::ValueRef;
1144 scratch.clear();
1145 match cell {
1146 ValueRef::Text(bytes) => match std::str::from_utf8(bytes) {
1147 Ok(s) if crate::crypto::looks_encrypted(s) => match crate::simd::hex::hex_string_to_bytes_checked(s) {
1148 Some(framed) => *scratch = framed,
1149 None => return false,
1150 },
1151 _ => return false,
1152 },
1153 ValueRef::Blob(bytes) => scratch.extend_from_slice(bytes),
1154 _ => return false,
1155 }
1156 let opened = cipher.open_framed_in_place(scratch).is_ok();
1157 crate::crypto::wipe(scratch);
1158 opened
1159}
1160
1161fn move_cell(
1164 cell: rusqlite::types::ValueRef<'_>,
1165 from: &[u8; 32],
1166 to: Option<&[u8; 32]>,
1167) -> Result<Option<rusqlite::types::Value>, String> {
1168 use rusqlite::types::{Value, ValueRef};
1169 match cell {
1170 ValueRef::Text(bytes) => {
1171 let Ok(s) = std::str::from_utf8(bytes) else { return Ok(None) };
1172 if !crate::crypto::looks_encrypted(s) {
1173 return Ok(None);
1174 }
1175 let Some(framed) = crate::simd::hex::hex_string_to_bytes_checked(s) else { return Ok(None) };
1176 let Ok(mut plain) = crate::crypto::decrypt_blob_with_key(&framed, from) else { return Ok(None) };
1177 let moved = match to {
1178 Some(k) => crate::crypto::encrypt_blob_with_key(&plain, k)
1179 .map(|sealed| Value::Text(crate::simd::hex::bytes_to_hex_string(&sealed))),
1180 None => String::from_utf8(plain.clone())
1181 .map(Value::Text)
1182 .map_err(|_| "opens to bytes that are not text".to_string()),
1183 };
1184 plain.zeroize();
1185 moved.map(Some)
1186 }
1187 ValueRef::Blob(bytes) => {
1188 let Ok(mut plain) = crate::crypto::decrypt_blob_with_key(bytes, from) else { return Ok(None) };
1189 let moved = match to {
1190 Some(k) => crate::crypto::encrypt_blob_with_key(&plain, k).map(Value::Blob),
1191 None => Ok(Value::Blob(plain.clone())),
1192 };
1193 plain.zeroize();
1194 moved.map(Some)
1195 }
1196 _ => Ok(None),
1197 }
1198}
1199
1200fn encrypt_columns_in_tx(tx: &rusqlite::Transaction, key: &[u8; 32]) -> Result<(), String> {
1202 sweep_columns_in_tx(tx, Some(key), None)
1203}
1204fn decrypt_columns_in_tx(tx: &rusqlite::Transaction, key: &[u8; 32]) -> Result<(), String> {
1206 sweep_columns_in_tx(tx, None, Some(key))
1207}
1208pub(crate) fn rekey_columns_in_tx(tx: &rusqlite::Transaction, old_key: &[u8; 32], new_key: &[u8; 32]) -> Result<(), String> {
1210 sweep_columns_in_tx(tx, Some(new_key), Some(old_key))
1211}
1212
1213const BACKFILL_VERSION: &str = "8";
1218
1219pub fn backfill_at_rest() -> Result<(), String> {
1225 if !crate::state::is_encryption_enabled_fast() {
1226 return Ok(());
1227 }
1228 if crate::db::get_sql_setting("community_at_rest_encrypted".to_string())
1229 .ok()
1230 .flatten()
1231 .as_deref()
1232 == Some(BACKFILL_VERSION)
1233 {
1234 return Ok(());
1235 }
1236 let _change = crate::crypto::gate::key_change()?;
1237 let sealed = crate::state::ENCRYPTION_KEY.with_key(|key| -> Result<(), String> {
1238 let conn = crate::db::get_write_connection_guard_static()?;
1239 let tx = conn.unchecked_transaction().map_err(|e| format!("backfill tx: {e}"))?;
1240 prove_key_in_tx(&tx, key, true)?;
1243 encrypt_setting_in_tx(&tx, "seed", key, |v| v.contains(' '))?;
1244 encrypt_setting_in_tx(&tx, "bunker_url", key, |v| v.starts_with("bunker://"))?;
1245 encrypt_columns_in_tx(&tx, key)?;
1246 seal_plain_messages_in_tx(&tx, key)?;
1247 tx.execute(
1248 "INSERT OR REPLACE INTO settings (key, value) VALUES ('community_at_rest_encrypted', ?1)",
1249 [BACKFILL_VERSION],
1250 )
1251 .map_err(|e| format!("backfill flag: {e}"))?;
1252 tx.commit().map_err(|e| format!("backfill commit: {e}"))
1253 });
1254 let Some(sealed) = sealed else { return Ok(()) };
1256 sealed?;
1257 crate::log_info!("[Encryption] Community at-rest backfill complete");
1258 Ok(())
1259}
1260
1261fn verify_plaintext_state_in_tx(tx: &rusqlite::Transaction) -> Result<(), String> {
1268 if let Ok(pkey) = tx.query_row::<String, _, _>(
1270 "SELECT value FROM settings WHERE key = 'pkey'", [], |row| row.get(0),
1271 ) {
1272 if !pkey.starts_with("nsec") {
1273 return Err(format!(
1274 "VERIFICATION FAILED: pkey is not plaintext after decryption (len={}, prefix={}). \
1275 Aborting to protect your data — encryption status was NOT changed.",
1276 pkey.len(), &pkey[..pkey.len().min(8)]
1277 ));
1278 }
1279 }
1280
1281 if let Ok(seed) = tx.query_row::<String, _, _>(
1283 "SELECT value FROM settings WHERE key = 'seed'", [], |row| row.get(0),
1284 ) {
1285 if !seed.contains(' ') {
1286 return Err(
1287 "VERIFICATION FAILED: seed is not plaintext after decryption. \
1288 Aborting to protect your data — encryption status was NOT changed."
1289 .to_string(),
1290 );
1291 }
1292 }
1293
1294 let mut stmt = tx.prepare("SELECT id, length(privkey_encrypted) FROM pivx_promos")
1296 .map_err(|e| format!("Verification query failed: {}", e))?;
1297 let bad_keys: Vec<i64> = stmt
1298 .query_map([], |row| {
1299 let id: i64 = row.get(0)?;
1300 let len: i64 = row.get(1)?;
1301 Ok((id, len))
1302 })
1303 .map_err(|e| format!("Verification query failed: {}", e))?
1304 .filter_map(|r| r.ok())
1305 .filter(|(_, len)| *len > 64)
1306 .map(|(id, _)| id)
1307 .collect();
1308
1309 if !bad_keys.is_empty() {
1310 return Err(format!(
1311 "VERIFICATION FAILED: {} PIVX key(s) still encrypted (IDs: {:?}). \
1312 Aborting to protect your data — encryption status was NOT changed.",
1313 bad_keys.len(), bad_keys
1314 ));
1315 }
1316
1317 crate::log_info!("[Encryption] Verification passed: all data confirmed plaintext");
1318 Ok(())
1319}
1320
1321fn verify_encrypted_state_in_tx(
1324 tx: &rusqlite::Transaction,
1325 key: &[u8; 32],
1326) -> Result<(), String> {
1327 if let Ok(pkey) = tx.query_row::<String, _, _>(
1329 "SELECT value FROM settings WHERE key = 'pkey'", [], |row| row.get(0),
1330 ) {
1331 if pkey.starts_with("nsec") {
1332 return Err(
1333 "VERIFICATION FAILED: pkey is still plaintext after encryption. \
1334 Aborting to protect your data — encryption status was NOT changed."
1335 .to_string(),
1336 );
1337 }
1338 match decrypt_with_key(&pkey, key) {
1339 Ok(decrypted) if decrypted.starts_with("nsec") => {}
1340 Ok(decrypted) => {
1341 return Err(format!(
1342 "VERIFICATION FAILED: pkey decrypts but not to nsec (len={}, prefix={}). \
1343 Possible double-encryption. Aborting.",
1344 decrypted.len(), &decrypted[..decrypted.len().min(6)]
1345 ));
1346 }
1347 Err(_) => {
1348 return Err(
1349 "VERIFICATION FAILED: pkey cannot be decrypted with current key. Aborting."
1350 .to_string(),
1351 );
1352 }
1353 }
1354 }
1355
1356 if let Ok(seed) = tx.query_row::<String, _, _>(
1358 "SELECT value FROM settings WHERE key = 'seed'", [], |row| row.get(0),
1359 ) {
1360 if seed.contains(' ') {
1361 return Err(
1362 "VERIFICATION FAILED: seed is still plaintext after encryption. Aborting."
1363 .to_string(),
1364 );
1365 }
1366 match decrypt_with_key(&seed, key) {
1367 Ok(decrypted) if decrypted.contains(' ') => {}
1368 Ok(_) => {
1369 return Err(
1370 "VERIFICATION FAILED: seed decrypts but not to BIP39 mnemonic. \
1371 Possible double-encryption. Aborting."
1372 .to_string(),
1373 );
1374 }
1375 Err(_) => {
1376 return Err(
1377 "VERIFICATION FAILED: seed cannot be decrypted with current key. Aborting."
1378 .to_string(),
1379 );
1380 }
1381 }
1382 }
1383
1384 crate::log_info!("[Encryption] Verification passed: all data confirmed encrypted and round-trips correctly");
1385 Ok(())
1386}
1387
1388pub fn key_matches_account(key: &[u8; 32]) -> bool {
1393 let Ok(conn) = crate::db::get_db_connection_guard_static() else {
1394 return false;
1395 };
1396 let pkey: Option<String> = conn
1397 .query_row("SELECT value FROM settings WHERE key = 'pkey'", [], |r| r.get(0))
1398 .ok();
1399 if let Some(p) = pkey {
1400 if !p.starts_with("nsec") {
1401 return matches!(decrypt_with_key(&p, key), Ok(d) if d.starts_with("nsec"));
1402 }
1403 }
1404 let canary: Option<String> = conn
1405 .query_row("SELECT value FROM settings WHERE key = 'nip55_pin_check'", [], |r| r.get(0))
1406 .ok();
1407 if let Some(c) = canary {
1408 return matches!(
1409 decrypt_with_key(&c, key),
1410 Ok(d) if d == NIP55_PIN_CANARY
1411 );
1412 }
1413 true
1414}
1415
1416pub fn rekey(
1426 old_key: &[u8; 32],
1427 new_key: &[u8; 32],
1428 new_kdf: &crate::crypto::Kdf,
1429 security_type: &str,
1430 biometric_wrap: Option<&str>,
1431 progress: &dyn Fn(MigrationProgress),
1432) -> Result<(), String> {
1433 let wrap = match biometric_wrap {
1434 Some(w) => Wrap::Set(w),
1435 None => Wrap::Drop,
1436 };
1437 rekey_with(old_key, new_key, new_kdf, Some(security_type), wrap, Upgrade::No, progress).map(|_| ())
1438}
1439
1440pub fn upgrade_legacy_derivation(
1446 legacy_key: &[u8; 32],
1447 new_key: &[u8; 32],
1448 new_kdf: &crate::crypto::Kdf,
1449 progress: &dyn Fn(MigrationProgress),
1450) -> Result<bool, String> {
1451 if new_kdf.is_legacy() {
1452 return Err("an upgrade needs a salted derivation".to_string());
1453 }
1454 rekey_with(legacy_key, new_key, new_kdf, None, Wrap::Drop, Upgrade::Legacy, progress)
1457}
1458
1459enum Wrap<'a> {
1461 Set(&'a str),
1463 Drop,
1465}
1466
1467#[derive(Clone, Copy, PartialEq)]
1470enum Upgrade {
1471 No,
1472 Legacy,
1473}
1474
1475fn rekey_with(
1476 old_key: &[u8; 32],
1477 new_key: &[u8; 32],
1478 new_kdf: &crate::crypto::Kdf,
1479 security_type: Option<&str>,
1480 wrap: Wrap<'_>,
1481 upgrade: Upgrade,
1482 progress: &dyn Fn(MigrationProgress),
1483) -> Result<bool, String> {
1484 if !same_key(old_key, new_key) && new_kdf.is_legacy() {
1485 return Err("A new key needs its own salt".to_string());
1486 }
1487 let _change = crate::crypto::gate::key_change()?;
1490 if !crate::db::writes_to_live_account() {
1491 return Err("The account changed before its key could".to_string());
1492 }
1493 if upgrade == Upgrade::Legacy {
1494 let vault_holds_legacy = crate::state::ENCRYPTION_KEY.with_key(|k| same_key(k, old_key)).unwrap_or(false);
1496 if !crate::crypto::Kdf::of_account()?.is_legacy() || !vault_holds_legacy {
1497 return Ok(false);
1498 }
1499 }
1500 let mut conn = crate::db::get_write_connection_guard_static()?;
1501 let wipe = upgrade == Upgrade::Legacy;
1502 let secure_delete_before: i64 = if wipe {
1503 let before = conn.query_row("PRAGMA secure_delete", [], |r| r.get(0)).map_err(|e| format!("secure_delete: {e}"))?;
1504 conn.execute_batch("PRAGMA secure_delete = ON;").map_err(|e| format!("secure_delete: {e}"))?;
1505 before
1506 } else {
1507 0
1508 };
1509 let result = rekey_tx(&mut conn, old_key, new_key, new_kdf, security_type, wrap, upgrade, progress);
1510 if wipe {
1511 let _ = conn.execute_batch(&format!("PRAGMA secure_delete = {secure_delete_before};"));
1513 let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1514 }
1515 result.map(|_| true)
1516}
1517
1518#[allow(clippy::too_many_arguments)]
1519fn rekey_tx(
1520 conn: &mut rusqlite::Connection,
1521 old_key: &[u8; 32],
1522 new_key: &[u8; 32],
1523 new_kdf: &crate::crypto::Kdf,
1524 security_type: Option<&str>,
1525 wrap: Wrap<'_>,
1526 upgrade: Upgrade,
1527 progress: &dyn Fn(MigrationProgress),
1528) -> Result<(), String> {
1529 let (require_anchor, wipe) = (upgrade == Upgrade::Legacy, upgrade == Upgrade::Legacy);
1530 let tx = conn.transaction()
1532 .map_err(|e| format!("Failed to begin transaction: {}", e))?;
1533
1534 tx.execute(
1536 "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', 'rekeying')",
1537 [],
1538 ).map_err(|e| format!("Failed to set migration_state: {}", e))?;
1539
1540 prove_key_in_tx(&tx, old_key, require_anchor)?;
1541 if !same_key(old_key, new_key) {
1544 rekey_listed_in_tx(&tx, old_key, new_key, progress)?;
1545 sweep_residue_in_tx(&tx, old_key, Some(new_key))?;
1546 verify_encrypted_state_in_tx(&tx, new_key)?;
1547 }
1548
1549 super::settings::write_kdf_in_tx(&tx, new_kdf.descriptor().as_deref())?;
1552 if let Some(security_type) = security_type {
1553 tx.execute(
1554 "INSERT OR REPLACE INTO settings (key, value) VALUES ('security_type', ?1)",
1555 rusqlite::params![security_type],
1556 ).map_err(|e| format!("Failed to update security_type: {}", e))?;
1557 }
1558
1559 match wrap {
1562 Wrap::Set(w) => {
1563 tx.execute(
1564 "INSERT OR REPLACE INTO settings (key, value) VALUES ('biometric_wrapped_key', ?1)",
1565 rusqlite::params![w],
1566 ).map_err(|e| format!("Failed to set biometric wrap: {}", e))?;
1567 }
1568 Wrap::Drop => {
1569 tx.execute(
1570 "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
1571 [],
1572 ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
1573 }
1574 }
1575 if wipe {
1576 tx.execute("DELETE FROM settings WHERE key = 'last_vacuum'", [])
1579 .map_err(|e| format!("Failed to schedule vacuum: {}", e))?;
1580 }
1581
1582 tx.execute(
1583 "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', '')",
1584 [],
1585 ).map_err(|e| format!("Failed to clear migration_state: {}", e))?;
1586
1587 let moving = !same_key(old_key, new_key);
1591 if moving {
1592 crate::crypto::hold_previous_key(old_key);
1593 crate::state::ENCRYPTION_KEY.set(*new_key, &[]);
1594 }
1595
1596 if let Err(e) = tx.commit() {
1598 let landed = crate::crypto::Kdf::of_account().is_ok_and(|k| k == *new_kdf) && !new_kdf.is_legacy();
1601 if moving && !landed {
1602 crate::state::ENCRYPTION_KEY.set(*old_key, &[]);
1603 crate::crypto::forget_previous_key();
1604 } else if moving {
1605 crate::crypto::forget_previous_key_later();
1606 }
1607 return Err(format!("Failed to commit re-key transaction: {}", e));
1608 }
1609 if moving {
1610 crate::crypto::forget_previous_key_later();
1611 }
1612 Ok(())
1613}
1614
1615pub async fn upgrade_after_unlock(password: &str, legacy_key: &[u8; 32]) -> Result<bool, String> {
1621 const RETRY_AFTER_SECS: u64 = 24 * 60 * 60;
1622 if !crate::crypto::Kdf::of_account()?.is_legacy() || !crate::state::is_encryption_enabled_fast() {
1623 return Ok(false);
1624 }
1625 if crate::db::get_sql_setting("security_type".to_string())?.as_deref() == Some("biometric") {
1626 return Ok(false);
1627 }
1628 let now = crate::clock::now_secs();
1629 let last_try: u64 = crate::db::get_sql_setting("kdf_upgrade_attempt".to_string())?.and_then(|v| v.parse().ok()).unwrap_or(0);
1630 if now.saturating_sub(last_try) < RETRY_AFTER_SECS {
1631 return Ok(false);
1632 }
1633 if !key_proves_positively(legacy_key)? {
1635 return Ok(false);
1636 }
1637
1638 crate::emit_event("encryption_upgrading", &MigrationProgress { total: 0, completed: 0, phase: "deriving".to_string() });
1640 let new_kdf = crate::crypto::Kdf::fresh();
1641 let new_key = zeroize::Zeroizing::new(crate::crypto::derive_key(password, &new_kdf).await);
1642 let progress = |p: MigrationProgress| crate::emit_event("encryption_upgrading", &p);
1643 match upgrade_legacy_derivation(legacy_key, &new_key, &new_kdf, &progress) {
1644 Ok(moved) => {
1645 if moved {
1646 crate::log_info!("[Encryption] Moved this account onto its own key derivation salt");
1647 }
1648 Ok(moved)
1649 }
1650 Err(e) => {
1651 let _ = crate::db::set_sql_setting("kdf_upgrade_attempt".to_string(), now.to_string());
1652 Err(e)
1653 }
1654 }
1655}
1656
1657fn key_proves_positively(key: &[u8; 32]) -> Result<bool, String> {
1660 let mut conn = crate::db::get_db_connection_guard_static()?;
1661 let tx = conn.transaction().map_err(|e| format!("key proof: {e}"))?;
1662 Ok(prove_key_in_tx(&tx, key, true).is_ok())
1663}
1664
1665pub const CREDENTIAL_REQUIRED: &str = "CREDENTIAL_REQUIRED";
1667pub const CREDENTIAL_INCORRECT: &str = "CREDENTIAL_INCORRECT";
1669
1670pub const CREDENTIAL_LOCKED: &str = "CREDENTIAL_LOCKED";
1672const FREE_TRIES: u32 = 5;
1674const MAX_WAIT_SECS: u64 = 15 * 60;
1676static PROVING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
1678
1679pub async fn prove_credential(credential: &str) -> Result<zeroize::Zeroizing<[u8; 32]>, String> {
1684 let _one_at_a_time = PROVING.lock().await;
1685 let now = crate::clock::now_secs();
1686 let read = |key: &str| crate::db::get_sql_setting(key.to_string()).ok().flatten().and_then(|v| v.parse::<u64>().ok());
1687 if let Some(retry_at) = read("credential_retry_at").filter(|&t| t > now) {
1688 let wait = if retry_at - now > MAX_WAIT_SECS {
1690 let _ = crate::db::set_sql_setting("credential_retry_at".to_string(), (now + MAX_WAIT_SECS).to_string());
1691 MAX_WAIT_SECS
1692 } else {
1693 retry_at - now
1694 };
1695 return Err(format!("{CREDENTIAL_LOCKED}:{wait}"));
1696 }
1697 let kdf = crate::crypto::Kdf::of_account()?;
1698 let key = zeroize::Zeroizing::new(crate::crypto::derive_key(credential, &kdf).await);
1699 if let Err(e) = prove_key(&key) {
1700 if e == CREDENTIAL_INCORRECT {
1701 let failures = record_miss()?;
1702 if failures >= FREE_TRIES {
1703 let wait = (30u64 << (failures - FREE_TRIES).min(5)).min(MAX_WAIT_SECS);
1704 let _ = crate::db::set_sql_setting("credential_retry_at".to_string(), (now + wait).to_string());
1705 }
1706 }
1707 return Err(e);
1708 }
1709 if read("credential_failures").is_some() {
1710 let _ = crate::db::remove_setting("credential_failures");
1711 let _ = crate::db::remove_setting("credential_retry_at");
1712 }
1713 Ok(key)
1714}
1715
1716fn record_miss() -> Result<u32, String> {
1718 let conn = crate::db::get_write_connection_guard_static()?;
1719 conn.query_row(
1720 "INSERT INTO settings (key, value) VALUES ('credential_failures', '1')
1721 ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)
1722 RETURNING CAST(value AS INTEGER)",
1723 [],
1724 |r| r.get::<_, i64>(0),
1725 )
1726 .map(|n| n.clamp(0, u32::MAX as i64) as u32)
1727 .map_err(|e| format!("count credential miss: {e}"))
1728}
1729
1730pub fn prove_key(key: &[u8; 32]) -> Result<(), String> {
1732 if key_proves_positively(key)? { Ok(()) } else { Err(CREDENTIAL_INCORRECT.to_string()) }
1733}
1734
1735pub fn open_identity_secrets(
1738 key: Option<&[u8; 32]>,
1739) -> Result<(zeroize::Zeroizing<String>, Option<zeroize::Zeroizing<String>>), String> {
1740 use rusqlite::OptionalExtension;
1741 let conn = crate::db::get_db_connection_guard_static()?;
1742 let read = |name: &str| -> Result<Option<String>, String> {
1743 conn.query_row("SELECT value FROM settings WHERE key = ?1", [name], |r| r.get::<_, String>(0))
1744 .optional()
1745 .map_err(|e| format!("read {name}: {e}"))
1746 };
1747 let open = |stored: String| -> Result<zeroize::Zeroizing<String>, String> {
1748 let stored = zeroize::Zeroizing::new(stored);
1749 match key {
1750 Some(k) => decrypt_with_key(&stored, k).map(zeroize::Zeroizing::new).map_err(|_| CREDENTIAL_INCORRECT.to_string()),
1751 None => Ok(stored),
1752 }
1753 };
1754 let nsec = open(read("pkey")?.ok_or("No private key is stored for this account")?)?;
1755 if !nsec.starts_with("nsec1") {
1756 return Err("The stored private key is unreadable".to_string());
1757 }
1758 let seed = match (read("seed")?, key) {
1759 (None, _) => None,
1760 (Some(stored), None) => Some(zeroize::Zeroizing::new(stored)),
1761 (Some(stored), Some(k)) => match decrypt_with_key(&stored, k) {
1762 Ok(plain) => Some(zeroize::Zeroizing::new(plain)),
1763 Err(_) if stored.contains(' ') => Some(zeroize::Zeroizing::new(stored)),
1766 Err(_) => {
1767 crate::log_warn!("[Encryption] The stored seed phrase doesn't open; leaving it out");
1768 None
1769 }
1770 },
1771 };
1772 Ok((nsec, seed))
1773}
1774
1775pub fn vacuum_now() -> Result<(), String> {
1778 let conn = crate::db::get_write_connection_guard_static()?;
1779 conn.execute_batch("VACUUM; PRAGMA wal_checkpoint(TRUNCATE);").map_err(|e| format!("vacuum: {e}"))
1780}
1781
1782pub(crate) fn rekey_listed_in_tx(
1785 tx: &rusqlite::Transaction,
1786 old_key: &[u8; 32],
1787 new_key: &[u8; 32],
1788 progress: &dyn Fn(MigrationProgress),
1789) -> Result<(), String> {
1790 let all_ids: Vec<String> = {
1792 let mut stmt = tx.prepare(
1793 r#"SELECT id FROM events
1794 WHERE kind IN (?1, ?2, ?3, ?4)
1795 AND length(content) >= 56
1796 AND content NOT GLOB '*[^0-9a-f]*'"#,
1797 ).map_err(|e| format!("Failed to prepare ID query: {}", e))?;
1798
1799 let rows = stmt.query_map(
1800 rusqlite::params![
1801 event_kind::CHAT_MESSAGE as i32,
1802 event_kind::PRIVATE_DIRECT_MESSAGE as i32,
1803 event_kind::MESSAGE_EDIT as i32,
1804 event_kind::FILE_ATTACHMENT as i32,
1805 ],
1806 |row| row.get::<_, String>(0),
1807 ).map_err(|e| format!("Failed to query IDs: {}", e))?;
1808
1809 rows.filter_map(|r| r.ok()).collect()
1810 };
1811
1812 let total = all_ids.len();
1813 let mut completed = 0;
1814 let mut last_emitted_percent: i32 = -1;
1815
1816 for id in &all_ids {
1818 let content: Option<String> = tx.query_row(
1819 "SELECT content FROM events WHERE id = ?1",
1820 rusqlite::params![id],
1821 |row| row.get(0),
1822 ).ok();
1823
1824 if let Some(content) = content {
1825 match decrypt_with_key(&content, old_key) {
1826 Ok(plaintext) => {
1827 let re_encrypted = encrypt_with_key(&plaintext, new_key);
1828 tx.execute(
1829 "UPDATE events SET content = ?1 WHERE id = ?2",
1830 rusqlite::params![re_encrypted, id],
1831 ).map_err(|e| format!("Failed to update event: {}", e))?;
1832 }
1833 Err(_) => {
1834 crate::log_warn!("[Rekey] Skipping event {} - decrypt failed", id);
1836 }
1837 }
1838 }
1839
1840 completed += 1;
1841 let current_percent = if total > 0 {
1842 ((completed as f64 / total as f64) * 100.0) as i32
1843 } else {
1844 100
1845 };
1846
1847 if current_percent >= last_emitted_percent + 5 {
1848 last_emitted_percent = current_percent;
1849 progress(MigrationProgress {
1850 total,
1851 completed,
1852 phase: "rekeying".to_string(),
1853 });
1854 }
1855 }
1856
1857 progress(MigrationProgress {
1859 total,
1860 completed,
1861 phase: "finalizing".to_string(),
1862 });
1863
1864 rekey_setting_in_tx(tx, "pkey", old_key, new_key)?;
1865 rekey_setting_in_tx(tx, "seed", old_key, new_key)?;
1866 rekey_setting_in_tx(tx, "nip55_pin_check", old_key, new_key)?;
1871 rekey_setting_in_tx(tx, "bunker_url", old_key, new_key)?;
1872 rekey_pivx_in_tx(tx, old_key, new_key)?;
1873 rekey_columns_in_tx(tx, old_key, new_key)?;
1874
1875 Ok(())
1876}
1877
1878fn same_key(a: &[u8; 32], b: &[u8; 32]) -> bool {
1879 a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
1880}
1881
1882fn prove_key_in_tx(tx: &rusqlite::Transaction, key: &[u8; 32], require_anchor: bool) -> Result<(), String> {
1887 use rusqlite::OptionalExtension;
1888 const WRONG: &str = "This key does not open the account's encrypted data; nothing was changed";
1889 let setting = |name: &str| -> Result<Option<String>, String> {
1890 tx.query_row("SELECT value FROM settings WHERE key = ?1", [name], |r| r.get::<_, String>(0))
1891 .optional()
1892 .map_err(|e| format!("read {name}: {e}"))
1893 };
1894 if let Some(pkey) = setting("pkey")? {
1895 if !pkey.starts_with("nsec") {
1896 let opened = decrypt_with_key(&pkey, key).map(zeroize::Zeroizing::new);
1897 return match opened {
1898 Ok(nsec) if nsec.starts_with("nsec") => Ok(()),
1899 _ => Err(WRONG.to_string()),
1900 };
1901 }
1902 }
1903 if let Some(canary) = setting("nip55_pin_check")? {
1904 return match decrypt_with_key(&canary, key) {
1905 Ok(plain) if plain == NIP55_PIN_CANARY => Ok(()),
1906 _ => Err(WRONG.to_string()),
1907 };
1908 }
1909 let samples = [
1910 "SELECT content FROM events WHERE kind IN (?1, ?2, ?3, ?4) AND length(content) >= 56
1911 AND content NOT GLOB '*[^0-9a-f]*' ORDER BY created_at DESC LIMIT 256",
1912 "SELECT server_root_key FROM communities WHERE length(server_root_key) > 32 LIMIT 256",
1913 "SELECT channel_key FROM community_channels WHERE length(channel_key) > 32 LIMIT 256",
1914 "SELECT key FROM community_epoch_keys WHERE length(key) > 32 LIMIT 256",
1915 ];
1916 let kinds = [
1917 event_kind::CHAT_MESSAGE as i64,
1918 event_kind::PRIVATE_DIRECT_MESSAGE as i64,
1919 event_kind::MESSAGE_EDIT as i64,
1920 event_kind::FILE_ATTACHMENT as i64,
1921 ];
1922 let cipher = crate::crypto::chachapoly::ChaCha20Poly1305::new(key);
1923 let mut scratch = Vec::new();
1924 let mut seen = false;
1925 for sql in samples {
1926 let mut stmt = tx.prepare(sql).map_err(|e| format!("key proof: {e}"))?;
1927 let params: &[i64] = if sql.contains("?1") { &kinds } else { &[] };
1928 let mut rows = stmt.query(rusqlite::params_from_iter(params)).map_err(|e| format!("key proof: {e}"))?;
1929 while let Some(row) = rows.next().map_err(|e| format!("key proof: {e}"))? {
1930 seen = true;
1931 if opens_under(row.get_ref(0).map_err(|e| format!("key proof: {e}"))?, &cipher, &mut scratch) {
1932 return Ok(());
1933 }
1934 }
1935 }
1936 match (seen, require_anchor) {
1937 (true, _) => Err(WRONG.to_string()),
1938 (false, true) => Err("Nothing here can confirm the key, so the store was left as it is".to_string()),
1939 (false, false) => Ok(()),
1940 }
1941}
1942
1943fn rekey_setting_in_tx(
1945 tx: &rusqlite::Transaction,
1946 key: &str,
1947 old_key: &[u8; 32],
1948 new_key: &[u8; 32],
1949) -> Result<(), String> {
1950
1951 let val: Option<String> = tx.query_row(
1952 "SELECT value FROM settings WHERE key = ?1",
1953 rusqlite::params![key],
1954 |row| row.get(0),
1955 ).ok();
1956
1957 if let Some(encrypted_val) = val {
1958 let looks_encrypted = encrypted_val.len() >= 56
1962 && encrypted_val.bytes().all(|b| b.is_ascii_hexdigit());
1963 let plaintext = match decrypt_with_key(&encrypted_val, old_key) {
1964 Ok(p) => p,
1965 Err(_) if !looks_encrypted => encrypted_val.clone(),
1966 Err(_) => return Err(format!("Failed to decrypt setting '{}'", key)),
1967 };
1968
1969 let re_encrypted = encrypt_with_key(&plaintext, new_key);
1970
1971 tx.execute(
1972 "UPDATE settings SET value = ?1 WHERE key = ?2",
1973 rusqlite::params![re_encrypted, key],
1974 ).map_err(|e| format!("Failed to update setting '{}': {}", key, e))?;
1975 }
1976
1977 Ok(())
1978}
1979
1980fn rekey_pivx_in_tx(
1982 tx: &rusqlite::Transaction,
1983 old_key: &[u8; 32],
1984 new_key: &[u8; 32],
1985) -> Result<(), String> {
1986
1987 let keys: Vec<(i64, String)> = {
1988 let mut stmt = tx.prepare("SELECT id, privkey_encrypted FROM pivx_promos")
1989 .map_err(|e| format!("Failed to prepare PIVX query: {}", e))?;
1990 let rows = stmt.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)))
1991 .map_err(|e| format!("Failed to query PIVX promos: {}", e))?;
1992 rows.filter_map(|r| r.ok()).collect()
1993 };
1994
1995 for (id, key_val) in keys {
1996 if key_val.len() > 64 {
1998 let decrypted = decrypt_with_key(&key_val, old_key)
1999 .map_err(|_| format!("Failed to decrypt PIVX key {}", id))?;
2000 let re_encrypted = encrypt_with_key(&decrypted, new_key);
2001
2002 tx.execute(
2003 "UPDATE pivx_promos SET privkey_encrypted = ?1 WHERE id = ?2",
2004 rusqlite::params![re_encrypted, id],
2005 ).map_err(|e| format!("Failed to update PIVX key: {}", e))?;
2006 }
2007 }
2008
2009 Ok(())
2010}
2011
2012#[cfg(test)]
2013mod rekey_setting_tests {
2014 use super::*;
2015 const OLD: [u8; 32] = [3u8; 32];
2016 const NEW: [u8; 32] = [5u8; 32];
2017
2018 fn conn() -> rusqlite::Connection {
2019 let c = rusqlite::Connection::open_in_memory().unwrap();
2020 c.execute_batch("CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT);").unwrap();
2021 c
2022 }
2023 fn put(c: &rusqlite::Connection, k: &str, v: &str) {
2024 c.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
2025 rusqlite::params![k, v]).unwrap();
2026 }
2027 fn get(c: &rusqlite::Connection, k: &str) -> String {
2028 c.query_row("SELECT value FROM settings WHERE key = ?1", rusqlite::params![k], |r| r.get(0)).unwrap()
2029 }
2030
2031 #[test]
2034 fn canary_survives_rekey() {
2035 let mut c = conn();
2036 put(&c, "nip55_pin_check", &encrypt_with_key(NIP55_PIN_CANARY, &OLD));
2037 let tx = c.transaction().unwrap();
2038 rekey_setting_in_tx(&tx, "nip55_pin_check", &OLD, &NEW).unwrap();
2039 tx.commit().unwrap();
2040 assert_eq!(
2041 decrypt_with_key(&get(&c, "nip55_pin_check"), &NEW).unwrap(),
2042 NIP55_PIN_CANARY
2043 );
2044 }
2045
2046 #[test]
2048 fn bunker_url_survives_rekey() {
2049 let mut c = conn();
2050 let url = "bunker://abc?relay=wss://relay.example";
2051 put(&c, "bunker_url", &encrypt_with_key(url, &OLD));
2052 let tx = c.transaction().unwrap();
2053 rekey_setting_in_tx(&tx, "bunker_url", &OLD, &NEW).unwrap();
2054 tx.commit().unwrap();
2055 assert_eq!(decrypt_with_key(&get(&c, "bunker_url"), &NEW).unwrap(), url);
2056 }
2057
2058 #[test]
2061 fn plaintext_row_is_adopted_not_fatal() {
2062 let mut c = conn();
2063 let url = "bunker://plain?relay=wss://r.example";
2064 put(&c, "bunker_url", url);
2065 let tx = c.transaction().unwrap();
2066 rekey_setting_in_tx(&tx, "bunker_url", &OLD, &NEW).unwrap();
2067 tx.commit().unwrap();
2068 assert_eq!(decrypt_with_key(&get(&c, "bunker_url"), &NEW).unwrap(), url);
2069 }
2070
2071 #[test]
2074 fn wrong_old_key_aborts() {
2075 let mut c = conn();
2076 put(&c, "pkey", &encrypt_with_key("nsec1example", &[9u8; 32]));
2077 let tx = c.transaction().unwrap();
2078 assert!(rekey_setting_in_tx(&tx, "pkey", &OLD, &NEW).is_err());
2079 }
2080
2081 #[test]
2083 fn missing_row_is_noop() {
2084 let mut c = conn();
2085 let tx = c.transaction().unwrap();
2086 rekey_setting_in_tx(&tx, "nip55_pin_check", &OLD, &NEW).unwrap();
2087 tx.commit().unwrap();
2088 assert_eq!(
2089 c.query_row("SELECT count(*) FROM settings", [], |r| r.get::<_, i64>(0)).unwrap(), 0
2090 );
2091 }
2092}