//! Password-protected sections (issue #523). //! //! A protected section keeps everything in it (its pages, their pictures, ink, attachments and //! saved versions, and any subpages) in one sealed file, `_protected.ncsafe`, beside its //! `_node.toml`, which says `protected = true`. While the section is locked nothing else is in //! its folder, so nothing that reads the folder (the tree, search, export, backups, another //! program) finds anything readable in it. //! //! Unlocking takes the section's content out of the sealed file into the folder, where it is //! edited as any other section's. Locking seals the folder's content again, checks that the //! sealed file opens, and deletes the plain files. The sealed file is kept while the section is //! unlocked, so a section unlocked and never locked again (the program stopped) still has it. //! //! The password is turned into a key with Argon2id and the content sealed with //! XChaCha20-Poly1305. The key is held only in memory, by whoever unlocked the section, and //! cleared from memory when it is dropped. Files deleted from a disk may still be recovered from //! it by tools made for that, as with any deleted file: locking is not a secure erase. //! //! A mark file, `_protected.open`, says the section is not locked. It reads `opening` while the //! content is being taken out, `open` once it is all out, and `sealed` once the content has been //! sealed again and the plain files are being deleted. A section found `opening` or `sealed` (the //! program stopped part way) is tidied without its password: the sealed file holds all of it. A //! section found `open` needs its password to be sealed again, since what was written into it //! since it was unlocked is only in the plain files. use crate::error::{Result, StoreError}; use crate::tree::{self, read_node}; use notecraft_model::{NodeKind, kv}; use std::fs; use std::path::{Path, PathBuf}; /// The sealed file a protected section keeps its content in. pub const SEALED: &str = "_protected.ncsafe"; /// The mark that says a protected section is not locked. pub const OPEN_MARK: &str = "_protected.open"; /// The key in `_node.toml` that says a section is protected. const KEY: &str = "protected"; /// What a locked section's folder holds. Anything else in it is content. const KEPT: [&str; 3] = ["_node.toml", SEALED, OPEN_MARK]; /// What `StoreError::Invalid` says when the password does not open the section. const WRONG_PASSWORD: &str = "that password does not open this section"; /// What `StoreError::Invalid` says when a change is asked of a locked section. const LOCKED: &str = "this section is locked with a password; unlock it first"; /// Whether a protected section is open to read and change. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum State { Locked, Unlocked, } /// Whether this error says the password was wrong. pub fn is_wrong_password(e: &StoreError) -> bool { matches!(e, StoreError::Invalid(m) if m == WRONG_PASSWORD) } /// Whether this error says the section is locked. pub fn is_locked_error(e: &StoreError) -> bool { matches!(e, StoreError::Invalid(m) if m == LOCKED) } /// Whether `section`'s `_node.toml` says it is protected. pub fn is_protected(section: &Path) -> bool { fs::read_to_string(section.join("_node.toml")).is_ok_and(|t| kv::parse(&t).get(KEY).is_some_and(|v| v.trim() == "true")) } fn mark(section: &Path) -> Option { fs::read_to_string(section.join(OPEN_MARK)).ok().map(|m| m.trim().to_string()) } /// Whether a protected section is locked or unlocked; `None` for one that is not protected. pub fn state(section: &Path) -> Option { is_protected(section).then(|| open_or_locked(section)) } /// The same, for a folder whose `_node.toml` has been read already. pub(crate) fn state_in(section: &Path, node: &std::collections::HashMap) -> Option { node.get(KEY).is_some_and(|v| v.trim() == "true").then(|| open_or_locked(section)) } fn open_or_locked(section: &Path) -> State { if mark(section).as_deref() == Some("open") { State::Unlocked } else { State::Locked } } /// The protected section `path` is in, or is: the nearest folder at or above it that is one. pub fn section_of(path: &Path) -> Option { path.ancestors().find(|dir| is_protected(dir)).map(Path::to_path_buf) } /// Whether `path` is, or is inside, a locked section. pub fn is_locked_inside(path: &Path) -> bool { section_of(path).is_some_and(|s| state(&s) == Some(State::Locked)) } /// Refuses a change at `path` while it is in a locked section: nothing may be written there but /// the sealed file. pub fn refuse_if_locked(path: &Path) -> Result<()> { if is_locked_inside(path) { Err(StoreError::invalid(LOCKED)) } else { Ok(()) } } /// Every protected section under `root` (a notebook or a folder of them), at any depth. pub fn protected_sections(root: &Path) -> Vec { fn walk(node: &tree::Node, out: &mut Vec) { if node.info.kind == NodeKind::Section && is_protected(&node.path) { out.push(node.path.clone()); } for child in &node.children { walk(child, out); } } let mut out = Vec::new(); if let Some(node) = tree::load_tree(root) { walk(&node, &mut out); } out } /// After the program stopped with sections unlocked (issue #523): every protected section under /// `root` that was part way through unlocking or locking is locked again, since its sealed file /// holds all of it. Returns the sections left unlocked, whose password is needed to seal what /// was written into them. pub fn recover(root: &Path) -> Vec { let mut open = Vec::new(); for section in protected_sections(root) { match mark(§ion).as_deref() { Some("open") => open.push(section), Some(_) => { if let Err(e) = tidy(§ion) { log::warn!("could not finish locking {}: {e}", section.display()); } } None => {} } } open } /// A section's content: every file and folder in it but the ones a locked section keeps. fn content(section: &Path) -> Result> { let entries = fs::read_dir(section).map_err(|e| StoreError::io("read", section, e))?; let mut out = Vec::new(); for entry in entries { let entry = entry.map_err(|e| StoreError::io("read", section, e))?; if !KEPT.iter().any(|kept| entry.file_name() == *kept) && !entry.file_name().to_string_lossy().starts_with(SEALED) { out.push(entry.path()); } } Ok(out) } /// Deletes the section's plain content and its mark, leaving it locked. Only safe once the /// sealed file holds all of it. fn tidy(section: &Path) -> Result<()> { for path in content(section)? { let gone = if path.is_dir() { crate::ops::remove_tree(&path) } else { fs::remove_file(&path) }; gone.map_err(|e| StoreError::io("delete", &path, e))?; } remove_mark(section) } fn set_mark(section: &Path, value: &str) -> Result<()> { let file = section.join(OPEN_MARK); fs::write(&file, value).map_err(|e| StoreError::io("write", &file, e)) } fn remove_mark(section: &Path) -> Result<()> { let file = section.join(OPEN_MARK); match fs::remove_file(&file) { Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(StoreError::io("delete", &file, e)), _ => Ok(()), } } /// Sets or clears `protected` in the section's `_node.toml`, keeping every other line. fn set_protected(section: &Path, on: bool) -> Result<()> { let file = section.join("_node.toml"); let text = fs::read_to_string(&file).map_err(|e| StoreError::io("read", &file, e))?; let kept: String = text.lines().filter(|l| l.split_once('=').is_none_or(|(key, _)| key.trim() != KEY)).map(|l| format!("{l}\n")).collect(); let out = if on { format!("{kept}{KEY} = true\n") } else { kept }; crate::page::write_atomic(&file, &out) } fn section_only(section: &Path) -> Result<()> { if read_node(section).is_some_and(|n| n.kind == NodeKind::Section) { Ok(()) } else { Err(StoreError::invalid("only a section can be protected with a password")) } } fn check_password(password: &str) -> Result<()> { if password.is_empty() { Err(StoreError::invalid("a password cannot be empty")) } else { Ok(()) } } /// Packs the section's content into one archive: for each folder and file, a kind byte (`d` or /// `f`), its path in the section (with `/`) as a length and UTF-8, and for a file its length and /// bytes. Links are not followed. fn pack(section: &Path) -> Result>> { fn put(out: &mut Vec, kind: u8, name: &str, bytes: Option<&[u8]>) { out.push(kind); out.extend_from_slice(&(name.len() as u32).to_le_bytes()); out.extend_from_slice(name.as_bytes()); if let Some(bytes) = bytes { out.extend_from_slice(&(bytes.len() as u64).to_le_bytes()); out.extend_from_slice(bytes); } } fn walk(dir: &Path, prefix: &str, out: &mut Vec) -> Result<()> { let mut entries: Vec = fs::read_dir(dir) .map_err(|e| StoreError::io("read", dir, e))? .collect::>() .map_err(|e| StoreError::io("read", dir, e))?; entries.sort_by_key(fs::DirEntry::file_name); for entry in entries { let name = entry.file_name(); let Some(name) = name.to_str() else { return Err(StoreError::invalid(format!("{} has a name that cannot be sealed", entry.path().display()))); }; let kind = entry.file_type().map_err(|e| StoreError::io("read", &entry.path(), e))?; let path = if prefix.is_empty() { name.to_string() } else { format!("{prefix}/{name}") }; if kind.is_dir() { put(out, b'd', &path, None); walk(&entry.path(), &path, out)?; } else if kind.is_file() { let bytes = zeroize::Zeroizing::new(fs::read(entry.path()).map_err(|e| StoreError::io("read", &entry.path(), e))?); put(out, b'f', &path, Some(&bytes)); } } Ok(()) } let mut out = zeroize::Zeroizing::new(b"NCPACK1\0".to_vec()); for path in content(section)? { let name = tree::folder_name(&path); if path.is_dir() { put(&mut out, b'd', &name, None); walk(&path, &name, &mut out)?; } else if path.is_file() { let bytes = zeroize::Zeroizing::new(fs::read(&path).map_err(|e| StoreError::io("read", &path, e))?); put(&mut out, b'f', &name, Some(&bytes)); } } Ok(out) } /// Writes an archive's folders and files into the section. A path that would leave the section, /// or name one of the files a locked section keeps, is refused before anything is written. fn unpack(section: &Path, archive: &[u8]) -> Result<()> { let bad = || StoreError::invalid("the sealed section is damaged"); let mut entries: Vec<(u8, &str, Option<&[u8]>)> = Vec::new(); let mut rest = archive.strip_prefix(b"NCPACK1\0").ok_or_else(bad)?; while let Some((&kind, after)) = rest.split_first() { let (len, after) = after.split_first_chunk::<4>().ok_or_else(bad)?; let len = u32::from_le_bytes(*len) as usize; let (name, after) = after.split_at_checked(len).ok_or_else(bad)?; let name = std::str::from_utf8(name).map_err(|_| bad())?; let safe = !name.is_empty() && name.split('/').all(|part| !part.is_empty() && part != "." && part != ".." && !part.contains(['\\', ':'])) && !KEPT.contains(&name) && !name.starts_with(SEALED); if !safe { return Err(bad()); } match kind { b'd' => { entries.push((kind, name, None)); rest = after; } b'f' => { let (size, after) = after.split_first_chunk::<8>().ok_or_else(bad)?; let size = usize::try_from(u64::from_le_bytes(*size)).map_err(|_| bad())?; let (bytes, after) = after.split_at_checked(size).ok_or_else(bad)?; entries.push((kind, name, Some(bytes))); rest = after; } _ => return Err(bad()), } } for (kind, name, bytes) in entries { let path = section.join(name); match bytes { None if kind == b'd' => fs::create_dir_all(&path).map_err(|e| StoreError::io("create", &path, e))?, Some(bytes) => { if let Some(parent) = path.parent() { fs::create_dir_all(parent).map_err(|e| StoreError::io("create", parent, e))?; } fs::write(&path, bytes).map_err(|e| StoreError::io("write", &path, e))?; } None => {} } } Ok(()) } /// The key a section was unlocked with, held in memory to lock it again. Cleared when dropped. pub struct Key(crypto::Key); impl std::fmt::Debug for Key { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Key(..)") } } fn read_sealed(section: &Path) -> Result> { let file = section.join(SEALED); fs::read(&file).map_err(|e| StoreError::io("read", &file, e)) } /// Seals the archive into the section's sealed file: written beside it first, read back and /// opened, and only then put in its place. fn write_sealed(section: &Path, key: &crypto::Key, archive: &[u8]) -> Result<()> { let sealed = crypto::seal(key, archive)?; let file = section.join(SEALED); let tmp = section.join(format!("{SEALED}.tmp-write")); let written = (|| { fs::write(&tmp, &sealed).map_err(|e| StoreError::io("write", &tmp, e))?; let back = fs::read(&tmp).map_err(|e| StoreError::io("read", &tmp, e))?; if crypto::open(key, &back).ok().is_none_or(|opened| opened.as_slice() != archive) { return Err(StoreError::invalid("the sealed section did not read back whole; it was not locked")); } fs::rename(&tmp, &file).map_err(|e| StoreError::io("replace", &file, e)) })(); if written.is_err() { let _ = fs::remove_file(&tmp); } written } /// Protects a section with a password and locks it (issue #523). Everything in it is sealed and /// the plain files deleted. pub fn protect(section: &Path, password: &str) -> Result<()> { section_only(section)?; check_password(password)?; if is_protected(section) { return Err(StoreError::invalid("this section already has a password")); } let key = crypto::Key::new(password)?; // Marked unlocked first, so a stop part way leaves a section that asks to be locked rather // than one that says it is locked with its plain files still there. set_mark(section, "open")?; write_sealed(section, &key, &pack(section)?)?; set_protected(section, true)?; set_mark(section, "sealed")?; tidy(section) } /// Unlocks a locked section with its password: its content is taken out of the sealed file into /// its folder. Returns the key to lock it with again. pub fn unlock(section: &Path, password: &str) -> Result { match state(section) { None => return Err(StoreError::invalid("this section has no password")), Some(State::Unlocked) => return Err(StoreError::invalid("this section is already unlocked")), Some(State::Locked) => {} } let sealed = read_sealed(section)?; let key = crypto::Key::derive(password, &sealed)?; let archive = crypto::open(&key, &sealed)?; // Whatever a stop part way through left is the sealed file's content again. tidy(section)?; set_mark(section, "opening")?; if let Err(e) = unpack(section, &archive) { let _ = tidy(section); return Err(e); } set_mark(section, "open")?; Ok(Key(key)) } /// Locks an unlocked section with the key it was unlocked with: its content is sealed again and /// the plain files deleted. pub fn lock(section: &Path, key: &Key) -> Result<()> { if state(section) != Some(State::Unlocked) { return Err(StoreError::invalid("this section is not unlocked")); } // The key must still open the sealed file: a section whose password was changed elsewhere is // not sealed with the old one. crypto::open(&key.0, &read_sealed(section)?)?; write_sealed(section, &key.0, &pack(section)?)?; set_mark(section, "sealed")?; tidy(section) } /// Locks an unlocked section with its password, for one left unlocked when the program stopped. pub fn lock_with_password(section: &Path, password: &str) -> Result<()> { if state(section) != Some(State::Unlocked) { return Err(StoreError::invalid("this section is not unlocked")); } let key = crypto::Key::derive(password, &read_sealed(section)?)?; lock(section, &Key(key)) } /// Changes a section's password. The old one must open it. A locked section stays locked; an /// unlocked one is sealed with the new password as it is now and stays unlocked, and the key to /// lock it with is returned. pub fn change_password(section: &Path, old: &str, new: &str) -> Result> { check_password(new)?; let was = state(section).ok_or_else(|| StoreError::invalid("this section has no password"))?; let sealed = read_sealed(section)?; let old_key = crypto::Key::derive(old, &sealed)?; let archive = crypto::open(&old_key, &sealed)?; let key = crypto::Key::new(new)?; match was { State::Locked => { write_sealed(section, &key, &archive)?; Ok(None) } State::Unlocked => { write_sealed(section, &key, &pack(section)?)?; Ok(Some(Key(key))) } } } /// Takes a section's password away: it is unlocked if it is locked, and then kept as an /// ordinary section, with its sealed file deleted. pub fn unprotect(section: &Path, password: &str) -> Result<()> { if state(section) == Some(State::Locked) { unlock(section, password)?; } else { let sealed = read_sealed(section)?; crypto::open(&crypto::Key::derive(password, &sealed)?, &sealed)?; } set_protected(section, false)?; let file = section.join(SEALED); fs::remove_file(&file).map_err(|e| StoreError::io("delete", &file, e))?; remove_mark(section) } #[cfg(not(target_arch = "wasm32"))] mod crypto { //! The sealed file: `NCSAFE1\0`, a version byte, Argon2id's memory (KiB), passes and lanes as //! little-endian u32s, a 16-byte salt and a 24-byte nonce, then the XChaCha20-Poly1305 //! ciphertext. The header is the cipher's associated data, so it cannot be changed unseen. use super::{StoreError, WRONG_PASSWORD}; use crate::error::Result; use chacha20poly1305::aead::rand_core::RngCore; use chacha20poly1305::aead::{Aead, KeyInit, OsRng, Payload}; use chacha20poly1305::{XChaCha20Poly1305, XNonce}; use zeroize::Zeroizing; const MAGIC: &[u8; 8] = b"NCSAFE1\0"; const VERSION: u8 = 1; const HEADER: usize = 8 + 1 + 12 + 16 + 24; /// Argon2id's cost: 64 MiB of memory and three passes, one lane. Tests use a small cost, so /// they run quickly; a sealed file says its own cost, so either opens. #[cfg(not(test))] const COST: (u32, u32, u32) = (64 * 1024, 3, 1); #[cfg(test)] const COST: (u32, u32, u32) = (64, 1, 1); /// The most a sealed file may ask for, so a damaged or made-up file cannot ask for more /// memory or time than the program has. const MOST: (u32, u32, u32) = (1024 * 1024, 64, 16); pub struct Key { key: Zeroizing<[u8; 32]>, salt: [u8; 16], cost: (u32, u32, u32), } fn derive(password: &str, salt: &[u8; 16], cost: (u32, u32, u32)) -> Result> { let params = argon2::Params::new(cost.0, cost.1, cost.2, Some(32)) .map_err(|e| StoreError::invalid(format!("the password settings are not valid: {e}")))?; let argon = argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params); let mut key = Zeroizing::new([0u8; 32]); argon .hash_password_into(password.as_bytes(), salt, key.as_mut()) .map_err(|e| StoreError::invalid(format!("the key could not be made: {e}")))?; Ok(key) } fn damaged() -> StoreError { StoreError::invalid("the sealed section is damaged or was not made by NoteCraft") } impl Key { /// A new key for `password`, with a salt of its own. pub fn new(password: &str) -> Result { let mut salt = [0u8; 16]; OsRng.fill_bytes(&mut salt); Ok(Key { key: derive(password, &salt, COST)?, salt, cost: COST }) } /// The key `password` gives for a sealed file, with its salt and cost. pub fn derive(password: &str, sealed: &[u8]) -> Result { let header = sealed.get(..HEADER).ok_or_else(damaged)?; if &header[..8] != MAGIC || header[8] != VERSION { return Err(damaged()); } let word = |at: usize| header.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes).ok_or_else(damaged); let cost = (word(9)?, word(13)?, word(17)?); if cost.0 > MOST.0 || cost.1 > MOST.1 || cost.2 > MOST.2 { return Err(damaged()); } let salt: [u8; 16] = header[21..37].try_into().map_err(|_| damaged())?; Ok(Key { key: derive(password, &salt, cost)?, salt, cost }) } } /// Seals `plain` with a fresh nonce. pub fn seal(key: &Key, plain: &[u8]) -> Result> { let cipher = XChaCha20Poly1305::new(key.key.as_ref().into()); let mut nonce = [0u8; 24]; OsRng.fill_bytes(&mut nonce); let mut out = Vec::with_capacity(HEADER + plain.len() + 16); out.extend_from_slice(MAGIC); out.push(VERSION); for n in [key.cost.0, key.cost.1, key.cost.2] { out.extend_from_slice(&n.to_le_bytes()); } out.extend_from_slice(&key.salt); out.extend_from_slice(&nonce); let sealed = cipher .encrypt(XNonce::from_slice(&nonce), Payload { msg: plain, aad: &out }) .map_err(|_| StoreError::invalid("the section could not be sealed"))?; out.extend_from_slice(&sealed); Ok(out) } /// Opens a sealed file with `key`. A key that does not open it is a wrong password. pub fn open(key: &Key, sealed: &[u8]) -> Result>> { let (header, body) = sealed.split_at_checked(HEADER).ok_or_else(damaged)?; if header[21..37] != key.salt { return Err(StoreError::invalid(WRONG_PASSWORD)); } let cipher = XChaCha20Poly1305::new(key.key.as_ref().into()); cipher .decrypt(XNonce::from_slice(&header[37..]), Payload { msg: body, aad: header }) .map(Zeroizing::new) .map_err(|_| StoreError::invalid(WRONG_PASSWORD)) } } #[cfg(target_arch = "wasm32")] mod crypto { //! The web build keeps its notebooks in the browser and has no section passwords. use super::StoreError; use crate::error::Result; use zeroize::Zeroizing; pub struct Key; fn missing() -> StoreError { StoreError::invalid("section passwords are not available here") } impl Key { pub fn new(_password: &str) -> Result { Err(missing()) } pub fn derive(_password: &str, _sealed: &[u8]) -> Result { Err(missing()) } } pub fn seal(_key: &Key, _plain: &[u8]) -> Result> { Err(missing()) } pub fn open(_key: &Key, _sealed: &[u8]) -> Result>> { Err(missing()) } } #[cfg(test)] mod tests { use super::*; use crate::testing::TempDir; use crate::{PageFormat, Settings, ops, page}; const SECRET: &str = "Margarine-ostrich-quill"; /// A notebook with a section holding a page (with a picture and a subpage) whose text has /// `SECRET` in it, in `format`. fn notebook(t: &TempDir, format: PageFormat) -> (PathBuf, PathBuf, PathBuf) { let settings = Settings::at(t.path().join("settings.toml")); let book = ops::create_notebook(t.path(), "Book", Some(format), &settings).expect("notebook"); let section = ops::create_node(&book, "Private", NodeKind::Section, Some(format), &settings).expect("section"); let page = ops::create_node(§ion, "Diary", NodeKind::Page, Some(format), &settings).expect("page"); add(&page, format, &format!("Today: {SECRET}.")); fs::create_dir_all(page.join("assets")).expect("assets"); fs::write(page.join("assets").join("photo.png"), format!("picture of {SECRET}")).expect("picture"); ops::create_node(&page, "Inner", NodeKind::Page, Some(format), &settings).expect("subpage"); (book, section, page) } /// Adds a paragraph to a page, saved as the window saves it (an earlier version is kept). fn add(page: &Path, format: PageFormat, words: &str) { let body = page::load_page(page).expect("load").body; let more = match format { PageFormat::Html => format!("{}

{words}

\n", body.trim_end()), PageFormat::Cmgfm => format!("{}\n\n{words}\n", body.trim_end()), }; page::save_body(page, &more).expect("save"); } /// Every file under `dir` whose bytes hold `SECRET`. fn readable(dir: &Path) -> Vec { let mut out = Vec::new(); let mut stack = vec![dir.to_path_buf()]; while let Some(d) = stack.pop() { for entry in fs::read_dir(&d).into_iter().flatten().flatten() { let p = entry.path(); if p.is_dir() { stack.push(p); } else if fs::read(&p).is_ok_and(|b| b.windows(SECRET.len()).any(|w| w == SECRET.as_bytes())) { out.push(p); } } } out } #[test] fn a_locked_section_holds_nothing_readable_and_opens_only_with_its_password() { for format in PageFormat::ALL { let t = TempDir::new("protect-lock"); let (book, section, page) = notebook(&t, format); protect(§ion, "hunter2").expect("protect"); assert_eq!(state(§ion), Some(State::Locked)); assert!(readable(&book).is_empty(), "{format:?}: {:?}", readable(&book)); let mut left: Vec = fs::read_dir(§ion).expect("dir").flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); left.sort(); assert_eq!(left, ["_node.toml", SEALED]); assert!(tree::load_tree(§ion).is_some_and(|n| n.children.is_empty())); assert!(crate::search::search(&book, SECRET, 10).is_empty()); let wrong = unlock(§ion, "hunter3").expect_err("wrong password"); assert!(is_wrong_password(&wrong), "{wrong}"); assert_eq!(state(§ion), Some(State::Locked)); // Reopened, as after the program starts again: only the password is needed. let key = unlock(§ion, "hunter2").expect("unlock"); assert_eq!(state(§ion), Some(State::Unlocked)); assert!(page::load_page(&page).expect("page").body.contains(SECRET)); assert!(page.join("assets").join("photo.png").is_file()); add(&page, format, "And later: tapioca."); lock(§ion, &key).expect("lock"); assert!(readable(&book).is_empty()); assert!(!page.exists()); let _key = unlock(§ion, "hunter2").expect("unlock again"); let body = page::load_page(&page).expect("page").body; assert!(body.contains(SECRET) && body.contains("tapioca"), "{format:?}: {body}"); assert_eq!(tree::load_tree(§ion).map(|n| n.count()), Some(3), "the section, its page and the subpage"); } } #[test] fn nothing_new_goes_into_a_locked_section() { for format in PageFormat::ALL { let t = TempDir::new("protect-guard"); let (book, section, _) = notebook(&t, format); let other = ops::create_node(&book, "Open", NodeKind::Section, Some(format), &Settings::at(t.path().join("settings.toml"))).expect("section"); let loose = ops::create_node(&other, "Loose", NodeKind::Page, Some(format), &Settings::at(t.path().join("settings.toml"))).expect("page"); protect(§ion, "pw").expect("protect"); let made = ops::create_node(§ion, "Sneaky", NodeKind::Page, Some(format), &Settings::at(t.path().join("settings.toml"))); assert!(made.as_ref().is_err_and(is_locked_error), "{made:?}"); assert!(ops::move_node(&loose, §ion).is_err_and(|e| is_locked_error(&e))); assert!(ops::copy_node(&loose, §ion).is_err_and(|e| is_locked_error(&e))); assert!(loose.is_dir()); } } #[test] fn a_section_left_unlocked_is_found_and_locked_again() { for format in PageFormat::ALL { let t = TempDir::new("protect-recover"); let (book, section, page) = notebook(&t, format); protect(§ion, "pw").expect("protect"); drop(unlock(§ion, "pw").expect("unlock")); // The program stopped: the key is gone, the section is open. assert_eq!(recover(&book), std::slice::from_ref(§ion)); assert!(lock_with_password(§ion, "nope").is_err_and(|e| is_wrong_password(&e))); lock_with_password(§ion, "pw").expect("lock"); assert!(readable(&book).is_empty()); assert!(recover(&book).is_empty()); // Stopped part way through unlocking: the sealed file is all of it, so it is // simply locked again. let _key = unlock(§ion, "pw").expect("unlock"); set_mark(§ion, "opening").expect("mark"); assert!(recover(&book).is_empty()); assert_eq!(state(§ion), Some(State::Locked)); assert!(!page.exists()); assert!(readable(&book).is_empty()); } } #[test] fn the_password_can_be_changed_and_taken_away() { for format in PageFormat::ALL { let t = TempDir::new("protect-change"); let (book, section, page) = notebook(&t, format); protect(§ion, "first").expect("protect"); assert!(change_password(§ion, "wrong", "second").is_err_and(|e| is_wrong_password(&e))); assert!(change_password(§ion, "first", "second").expect("change").is_none()); assert!(unlock(§ion, "first").is_err_and(|e| is_wrong_password(&e))); let key = unlock(§ion, "second").expect("unlock"); let key = change_password(§ion, "second", "third").expect("change").unwrap_or(key); lock(§ion, &key).expect("lock"); unprotect(§ion, "third").expect("unprotect"); assert_eq!(state(§ion), None); assert!(!section.join(SEALED).exists()); assert!(page::load_page(&page).expect("page").body.contains(SECRET)); assert!(!fs::read_to_string(section.join("_node.toml")).expect("node").contains("protected")); assert!(!readable(&book).is_empty()); } } #[test] fn backups_and_the_recycle_bin_never_hold_a_plain_copy() { for format in PageFormat::ALL { let t = TempDir::new("protect-copies"); let (book, section, page) = notebook(&t, format); protect(§ion, "pw").expect("protect"); let key = unlock(§ion, "pw").expect("unlock"); let backups = t.path().join("backups"); crate::backup::back_up(&book, &backups).expect("backup while unlocked"); assert!(readable(&backups).is_empty(), "{format:?}: {:?}", readable(&backups)); // A page deleted while the section is open is gone, not kept readable in the bin. let inner = tree::child_dirs(&page).into_iter().next().expect("subpage"); assert_eq!(crate::recycle::delete(&book, &inner).expect("delete"), 1); assert!(!inner.exists()); assert!(crate::recycle::delete(&book, §ion).is_err(), "an open section is locked before it is deleted"); lock(§ion, &key).expect("lock"); crate::recycle::delete(&book, §ion).expect("delete the locked section"); assert!(readable(&book).is_empty()); assert_eq!(crate::recycle::list(&book).expect("bin").len(), 1); } } #[test] fn a_damaged_archive_is_refused_before_anything_is_written() { let t = TempDir::new("protect-unpack"); let mut archive = b"NCPACK1\0".to_vec(); let name = "../escape.txt"; archive.push(b'f'); archive.extend_from_slice(&(name.len() as u32).to_le_bytes()); archive.extend_from_slice(name.as_bytes()); archive.extend_from_slice(&3u64.to_le_bytes()); archive.extend_from_slice(b"bad"); assert!(unpack(t.path(), &archive).is_err()); assert!(!t.path().parent().expect("parent").join("escape.txt").exists()); assert!(unpack(t.path(), b"NCPACK1\0f\xff\xff").is_err()); } }