use std::io::Write;
use std::path::Path;
use std::process::{Command, Output, Stdio};
use second_brain_core::keys::{
KeyStorage, RecoveryPhrase, create_device_keys, found_identity, load_device_keys, store_key_for,
};
use second_brain_core::machine::MachineIdentity;
use second_brain_core::schema::{Memory, MemoryType};
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::sqlite_store::encrypt_migration::{FileState, db_file_state};
use second_brain_core::store::{Store, StoreAdmin};
const NOW: i64 = 1_793_600_000_000_000;
fn backup(dir: &Path) -> (RecoveryPhrase, String, Memory) {
let machine = MachineIdentity::load_or_create(dir).unwrap();
let device = create_device_keys(dir, &KeyStorage::File).unwrap();
let store = SqliteStore::open(&dir.join("brain.db"), machine.id.clone()).unwrap();
store.register_machine(&machine).unwrap();
let phrase = RecoveryPhrase::generate().unwrap();
found_identity(&store, &device, "lost", &[phrase.recipient().unwrap()], NOW).unwrap();
let memory = Memory::new(
"kept across the restore".to_string(),
MemoryType::Semantic,
"test".to_string(),
String::new(),
);
store.store_memory(&memory).unwrap();
(phrase, machine.id, memory)
}
fn restore(home: &Path, backup: &Path, typed: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_sb"))
.arg("restore")
.arg(backup)
.env("HOME", home)
.env("SECOND_BRAIN_API", "http://127.0.0.1:9")
.env("SECOND_BRAIN_BIND", "127.0.0.1:9")
.env("SECOND_BRAIN_DEVICE_KEY_STORE", "file")
.env_remove("RUST_LOG")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(format!("{typed}\n").as_bytes())
.unwrap();
child.wait_with_output().unwrap()
}
#[test]
fn sb_restore_brings_a_backup_back_under_a_new_device_and_prints_a_new_phrase() {
let old = tempfile::tempdir().unwrap();
let (phrase, old_id, memory) = backup(old.path());
let home = tempfile::tempdir().unwrap();
let out = restore(
home.path(),
old.path(),
&phrase.expose_text().to_lowercase(),
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert_eq!(out.status.code(), Some(0), "{out:?}");
let shown = stdout
.lines()
.find_map(|line| line.strip_prefix(" "))
.expect("the new phrase is printed");
let new_phrase = RecoveryPhrase::parse(shown).unwrap();
assert_ne!(
new_phrase.fingerprint().unwrap(),
phrase.fingerprint().unwrap()
);
assert!(
stdout.contains(&new_phrase.fingerprint().unwrap()),
"{stdout}"
);
let data_dir = home.path().join(".second-brain");
let machine = MachineIdentity::load_or_create(&data_dir).unwrap();
assert_ne!(machine.id, old_id);
assert!(stdout.contains(&machine.id), "{stdout}");
let db = data_dir.join("brain.db");
assert_eq!(db_file_state(&db).unwrap(), FileState::Encrypted);
let device = load_device_keys(&data_dir).unwrap().unwrap();
let key = store_key_for(&db, &device).unwrap();
let store = SqliteStore::open_with_key(&db, machine.id.clone(), &key).unwrap();
assert_eq!(
store.get_memory(memory.id).unwrap().unwrap().content,
memory.content
);
assert_eq!(
store
.recovery_envelopes(&new_phrase.recipient().unwrap())
.unwrap()
.len(),
2,
"the new identity's epoch and the backup's"
);
}
#[test]
fn sb_restore_with_another_phrase_leaves_home_alone() {
let old = tempfile::tempdir().unwrap();
backup(old.path());
let home = tempfile::tempdir().unwrap();
let other = RecoveryPhrase::generate().unwrap();
let out = restore(home.path(), old.path(), &other.expose_text());
assert_eq!(out.status.code(), Some(1), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("opens no key"), "{stderr}");
assert!(std::fs::read_dir(home.path()).unwrap().next().is_none());
let out = restore(home.path(), old.path(), "not a phrase");
assert_eq!(out.status.code(), Some(1), "{out:?}");
assert!(String::from_utf8_lossy(&out.stderr).contains("recovery phrase"));
}