diff --git a/.agents/CLIPHOARD_HARDENING_CHECKLIST.md b/.agents/CLIPHOARD_HARDENING_CHECKLIST.md index 42ff0ff..d0b0da0 100644 --- a/.agents/CLIPHOARD_HARDENING_CHECKLIST.md +++ b/.agents/CLIPHOARD_HARDENING_CHECKLIST.md @@ -7,8 +7,7 @@ code and an appropriate test or desktop/package observation support it. - [x] SQLCipher storage with manually entered, non-persisted passphrase. - [x] Wrong-passphrase rejection and encrypted round-trip coverage. -- [x] Explicit migration from legacy plaintext history. -- [x] Optional removal of retained plaintext migration backups. +- [x] Explicit rejection of legacy plaintext history; no plaintext migration or bypass path. - [x] User-only permissions for data, config, logs, lock, and socket. - [x] Bounded clipboard reads and no clipboard contents in normal logs. - [ ] Review and test crash, swap, and snapshot exposure of plaintext in memory. @@ -21,7 +20,7 @@ code and an appropriate test or desktop/package observation support it. - [x] Tray popup, pause state, and graceful Quit action. - [x] Single-instance lock and show/toggle command. - [ ] Complete real Cinnamon/X11 acceptance of shortcut, focus/paste, tray, - opacity, pause, migration, and quit behavior. + opacity, pause, passphrase, and quit behavior. ## Delivery @@ -36,12 +35,12 @@ code and an appropriate test or desktop/package observation support it. ## Test policy - [x] Audited the inline tests against current behavior; removed one path-shape - smoke test and stale documentation-coupled naming. The remaining 31 tests - cover data-loss, ordering, privacy, bounds, migration, lifecycle, or parsing + smoke test and stale documentation-coupled naming. The remaining 32 tests + cover data-loss, ordering, privacy, bounds, encryption, lifecycle, or parsing behavior; GUI/X11 acceptance remains manual where headless tests cannot prove it. - Unit tests must protect data-loss, ordering, privacy, bounds, migration, lifecycle, or parsing behavior. - GUI/X11 behavior that cannot be exercised headlessly remains explicitly marked as manual acceptance, not represented by a green unit-test count. -- Passphrase rotation is intentionally out of scope for this goal. +- Passphrase rotation is covered by an encrypted round-trip test. diff --git a/Cargo.lock b/Cargo.lock index aae0547..5d5f5d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -148,7 +148,7 @@ dependencies = [ [[package]] name = "cliphoard" -version = "1.0.0" +version = "1.1.0" dependencies = [ "anyhow", "dirs", diff --git a/Cargo.toml b/Cargo.toml index 3ec73cc..4e9b7ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cliphoard" -version = "1.0.0" +version = "1.1.0" edition = "2021" description = "A tiny, keyboard-first clipboard history utility" license = "MIT" diff --git a/README.md b/README.md index 9d5e600..3aa8413 100644 --- a/README.md +++ b/README.md @@ -8,15 +8,16 @@ with SQLCipher and unlocked with a passphrase that Cliphoard does not store. Install the package on Debian, Ubuntu, or Mint: ```bash -sudo apt install ./cliphoard_1.0.0_amd64.deb +sudo apt install ./cliphoard_1.1.0_amd64.deb ``` The package installs the `cliphoard` command, desktop launcher, tray icon, autostart entry, and a copy of this README at `/usr/share/doc/cliphoard/README.md`. Start it from the desktop menu, tray, or with `cliphoard`. -On first start, enter a passphrase. An older plaintext database is migrated -only after confirmation; Cliphoard then offers to remove its retained backup. +On first start, create a passphrase and remember it; Cliphoard cannot recover +it. Existing history must already be encrypted. Plaintext databases are not +opened or migrated. ## Build from source @@ -28,7 +29,7 @@ sudo apt install cargo rustc dpkg-dev libgtk-4-dev libdbus-1-dev libx11-dev libx cargo test --locked --all-features cargo build --release --locked --features gui packaging/build-deb.sh -sudo apt install ./target/cliphoard_1.0.0_amd64.deb +sudo apt install ./target/cliphoard_1.1.0_amd64.deb ``` An isolated Docker build produces the same package: @@ -78,3 +79,19 @@ Cliphoard’s control. Runtime paths are `~/.local/share/cliphoard/cliphoard.db`, `~/.config/cliphoard/config.toml`, and `~/.local/state/cliphoard/`. + +## Upgrade from a plaintext database + +Version 1.1.0 no longer opens or migrates plaintext databases. If Cliphoard +reports that the database is plaintext, stop Cliphoard and remove the old +database before starting the new version. This permanently removes its +history: + +```bash +pkill -x cliphoard || true +rm -f ~/.local/share/cliphoard/cliphoard.db \ + ~/.local/share/cliphoard/cliphoard.db.plaintext-backup* +``` + +If the old history is needed, keep a copy elsewhere and use the previous +release to export or otherwise preserve it before deleting the local files. diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..2104815 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,79 @@ +# Cliphoard release procedure + +Run releases from the repository root. The current Git remote stores source +and tags, but no binary-upload destination is configured. + +## Prepare + +```bash +git switch main +git pull --ff-only +git status --short +``` + +Choose the next semantic version, for example `1.1.0`, and tag it `v1.1.0`. +Update the version in `Cargo.toml`, the root `cliphoard` package in +`Cargo.lock`, `packaging/debian/control`, `packaging/build-deb.sh`, and the +versioned `.deb` names in `README.md`. + +## Verify and build + +```bash +cargo fmt --all -- --check +cargo test --locked --all-features +cargo clippy --locked --all-features -- -D warnings +cargo build --release --locked --features gui +CLIPHOARD_VERSION=1.1.0 packaging/build-deb.sh +dpkg-deb --info target/cliphoard_1.1.0_amd64.deb +dpkg-deb --contents target/cliphoard_1.1.0_amd64.deb +sha256sum target/cliphoard_1.1.0_amd64.deb target/release/cliphoard +``` + +The Docker workflow from the README provides an isolated test, release-build, +and package-build path: + +```bash +docker build -t cliphoard-builder . +docker run --rm -v "$PWD/target:/out" cliphoard-builder +``` + +## Commit and tag + +Only commit after the gates pass: + +```bash +git diff --check +git status --short +git add Cargo.toml Cargo.lock README.md packaging/debian/control packaging/build-deb.sh src .agents RELEASING.md +git commit -m "Release Cliphoard 1.1.0" +git tag -a v1.1.0 -m "Release Cliphoard 1.1.0" +``` + +Replace `1.1.0` and `v1.1.0` with the actual version. + +## Sync + +```bash +git show --stat --oneline HEAD +git show --no-patch --decorate HEAD +git push origin main +git push origin v1.1.0 +``` + +If another commit landed remotely after the initial pull, stop and resolve it +before pushing. Never force-push release history. + +## Publish the Gitea release and binary + +Pushing Git does not upload `target/*.deb`: `target/` is ignored and the +binary is not committed. Create a Gitea release for the pushed tag, include a +summary of commits and changes, explicitly call out breaking changes, and +attach the `.deb`, release binary, and checksum file. The release must include +the plaintext-database deletion note and commands from `README.md`. + +## Final smoke check + +On a clean machine or disposable environment, install the exact `.deb`, start +Cliphoard, create/unlock the encrypted database, and confirm the tray, popup, +autostart, and passphrase flows. Keep the release commit, tag, artifact name, +checksum, and test results together. diff --git a/packaging/build-deb.sh b/packaging/build-deb.sh index 5b6b9ad..0da99b7 100755 --- a/packaging/build-deb.sh +++ b/packaging/build-deb.sh @@ -1,7 +1,7 @@ #!/bin/sh set -eu -version="${CLIPHOARD_VERSION:-1.0.0}" +version="${CLIPHOARD_VERSION:-1.1.0}" package_root="${PWD}/target/cliphoard-deb" rm -rf "$package_root" mkdir -p "$package_root/DEBIAN" \ diff --git a/packaging/debian/control b/packaging/debian/control index bdca5ee..29397ec 100644 --- a/packaging/debian/control +++ b/packaging/debian/control @@ -1,5 +1,5 @@ Package: cliphoard -Version: 1.0.0 +Version: 1.1.0 Section: utils Priority: optional Architecture: amd64 diff --git a/src/config.rs b/src/config.rs index 07438f2..c0f3f08 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,8 @@ use anyhow::{Context, Result}; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf}; -#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(default)] pub struct Config { pub history_limit: usize, @@ -11,6 +11,7 @@ pub struct Config { pub history_retention_days: u64, pub global_shortcut: String, pub autostart: bool, + pub show_window_after_unlock: bool, pub log_level: String, } @@ -23,6 +24,7 @@ impl Default for Config { history_retention_days: 30, global_shortcut: "Ctrl+Alt+V".into(), autostart: true, + show_window_after_unlock: true, log_level: "info".into(), } } @@ -103,6 +105,24 @@ impl Config { } validate_shortcut(&self.global_shortcut) } + + pub fn save(&self) -> Result<()> { + let path = Self::path(); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).with_context(|| { + format!( + "failed to create configuration directory {}", + parent.display() + ) + })?; + fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?; + } + let text = toml::to_string_pretty(self).context("failed to serialize configuration")?; + fs::write(&path, text) + .with_context(|| format!("failed to write configuration {}", path.display()))?; + fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?; + Ok(()) + } } fn validate_shortcut(shortcut: &str) -> Result<()> { @@ -134,6 +154,7 @@ mod tests { assert_eq!(c.max_entry_bytes, 1_048_576); assert_eq!(c.history_retention_days, 30); assert_eq!(c.global_shortcut, "Ctrl+Alt+V"); + assert!(c.show_window_after_unlock); assert!(c.validate().is_ok()); } diff --git a/src/gui.rs b/src/gui.rs index a313feb..5c4fc70 100644 --- a/src/gui.rs +++ b/src/gui.rs @@ -1,5 +1,6 @@ use std::{ cell::RefCell, + path::Path, rc::Rc, sync::{ atomic::{AtomicBool, Ordering}, @@ -11,8 +12,8 @@ use std::{ use anyhow::{Context, Result}; use gtk4::prelude::*; use gtk4::{ - Application, ApplicationWindow, Box as GtkBox, Button, Entry, Label, ListBox, ListBoxRow, - Orientation, ResponseType, ScrolledWindow, TextView, + Application, ApplicationWindow, Box as GtkBox, Button, CheckButton, Entry, Label, ListBox, + ListBoxRow, Orientation, ResponseType, ScrolledWindow, TextView, }; use zeroize::Zeroizing; @@ -71,24 +72,9 @@ const PLAY_ICON: &str = "▶"; const HELP_ICON: &str = "❓"; pub fn run(config: Config, instance: InstanceGuard, show_on_start: bool) -> Result<()> { - let passphrase = prompt_for_passphrase()?; let database_path = Database::default_path(); - let migrated = Database::is_plaintext(&database_path)?; - let database = if migrated { - if !confirm_plaintext_migration()? { - anyhow::bail!("plaintext history migration was declined") - } - Database::migrate_plaintext(&database_path, &passphrase) - .context("could not encrypt existing Cliphoard history")? - } else { - Database::open_encrypted(&database_path, &passphrase) - .context("could not unlock Cliphoard history; check the passphrase")? - }; - if migrated && confirm_plaintext_cleanup()? { - if let Err(error) = Database::remove_plaintext_backups(&database_path) { - tracing::error!(%error, "failed to remove plaintext migration backup"); - } - } + let first_start = !database_path.exists(); + let (passphrase, database) = prompt_for_database(&database_path, first_start)?; drop(passphrase); let now = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -97,6 +83,7 @@ pub fn run(config: Config, instance: InstanceGuard, show_on_start: bool) -> Resu database.prune_expired(now, config.history_retention_days)?; database.trim_unpinned(config.history_limit)?; let application = Application::new(Some("io.cliphoard.Cliphoard"), Default::default()); + let show_window = show_on_start || config.show_window_after_unlock; let clipboard_watcher = match X11ClipboardWatcher::start() { Ok(watcher) => Some(watcher), Err(error) => { @@ -148,7 +135,7 @@ pub fn run(config: Config, instance: InstanceGuard, show_on_start: bool) -> Resu application, &startup_config, Rc::clone(&startup_state), - show_on_start, + show_window, startup_tray.clone(), ) { tracing::error!(%error, "failed to build popup window"); @@ -160,116 +147,144 @@ pub fn run(config: Config, instance: InstanceGuard, show_on_start: bool) -> Resu Ok(()) } -fn prompt_for_passphrase() -> Result> { +fn prompt_for_database(path: &Path, first_start: bool) -> Result<(Zeroizing, Database)> { let application = Application::new(Some("io.cliphoard.Cliphoard.Unlock"), Default::default()); - let passphrase = Rc::new(RefCell::new(None)); - let result = Rc::clone(&passphrase); + let result = Rc::new(RefCell::new(None)); + let result_for_activate = Rc::clone(&result); + let path = path.to_path_buf(); application.connect_activate(move |application| { let window = ApplicationWindow::builder() .application(application) - .title("Unlock Cliphoard") + .title(if first_start { + "Create Cliphoard passphrase" + } else { + "Unlock Cliphoard" + }) .default_width(420) - .default_height(140) + .default_height(220) + .modal(true) .build(); let content = GtkBox::new(Orientation::Vertical, 10); content.set_margin_top(18); content.set_margin_bottom(18); content.set_margin_start(18); content.set_margin_end(18); - content.append(&Label::new(Some("Enter your Cliphoard passphrase:"))); + let instructions = if first_start { + "Create a passphrase for your encrypted clipboard history. You will need to remember it every time Cliphoard starts. Cliphoard cannot recover it." + } else { + "Enter the passphrase you created for Cliphoard to unlock your encrypted clipboard history." + }; + let instruction_label = Label::new(Some(instructions)); + instruction_label.set_wrap(true); + content.append(&instruction_label); let input = Entry::new(); input.set_visibility(false); + input.set_placeholder_text(Some("Passphrase")); input.set_activates_default(true); content.append(&input); - let unlock = Button::with_label("Unlock"); + let confirmation = if first_start { + let confirmation = Entry::new(); + confirmation.set_visibility(false); + confirmation.set_placeholder_text(Some("Confirm passphrase")); + confirmation.set_activates_default(true); + content.append(&confirmation); + Some(confirmation) + } else { + None + }; + let error_label = Label::new(None); + error_label.set_wrap(true); + error_label.set_selectable(true); + content.append(&error_label); + let unlock = Button::with_label(if first_start { + "Create passphrase" + } else { + "Unlock" + }); unlock.set_receives_default(true); content.append(&unlock); + let cancel = Button::with_label("Cancel"); + content.append(&cancel); window.set_child(Some(&content)); window.set_default_widget(Some(&unlock)); let application_for_unlock = application.clone(); - let result_for_unlock = Rc::clone(&result); + let result_for_unlock = Rc::clone(&result_for_activate); let input_for_unlock = input.clone(); + let confirmation_for_unlock = confirmation.clone(); + let error_for_unlock = error_label.clone(); + let path_for_unlock = path.clone(); + let window_for_unlock = window.clone(); unlock.connect_clicked(move |_| { let value = input_for_unlock.text().to_string(); - if !value.is_empty() { - *result_for_unlock.borrow_mut() = Some(value); - application_for_unlock.quit(); + if value.is_empty() { + error_for_unlock.set_text("Enter a passphrase to continue, or choose Cancel to close."); + } else if confirmation_for_unlock + .as_ref() + .is_some_and(|confirmation| confirmation.text().as_str() != value) + { + error_for_unlock + .set_text("The passphrases do not match. Check both fields and try again."); + } else { + match Database::open_encrypted(&path_for_unlock, &value) { + Ok(database) => { + *result_for_unlock.borrow_mut() = + Some((Zeroizing::new(value), database)); + window_for_unlock.set_visible(false); + application_for_unlock.quit(); + } + Err(open_error) => { + let detail = open_error.to_string(); + if detail.contains("plaintext databases are no longer supported") { + error_for_unlock.set_text("This database is plaintext and cannot be opened by Cliphoard. Delete or replace it with an encrypted Cliphoard database, then try again."); + } else { + error_for_unlock.set_text(&format!( + "Could not unlock Cliphoard: {detail}\n\nCheck your passphrase and try again." + )); + } + input_for_unlock.set_text(""); + if let Some(confirmation) = confirmation_for_unlock.as_ref() { + confirmation.set_text(""); + } + input_for_unlock.grab_focus(); + } + } } }); + let application_for_cancel = application.clone(); + let window_for_cancel = window.clone(); + cancel.connect_clicked(move |_| { + window_for_cancel.set_visible(false); + application_for_cancel.quit(); + }); let application_for_close = application.clone(); + let window_for_close = window.clone(); window.connect_close_request(move |_| { + window_for_close.set_visible(false); application_for_close.quit(); glib::Propagation::Stop }); + let application_for_escape = application.clone(); + let window_for_escape = window.clone(); + let keys = gtk4::EventControllerKey::new(); + keys.connect_key_pressed(move |_, key, _, _| { + if key == gtk4::gdk::Key::Escape { + window_for_escape.set_visible(false); + application_for_escape.quit(); + glib::Propagation::Stop + } else { + glib::Propagation::Proceed + } + }); + window.add_controller(keys); window.present(); input.grab_focus(); }); application.run_with_args(&["cliphoard-unlock"]); - let result = passphrase + let result = result .borrow_mut() .take() .context("Cliphoard unlock was cancelled"); - result.map(Zeroizing::new) -} - -fn confirm_plaintext_migration() -> Result { - let application = Application::new(Some("io.cliphoard.Cliphoard.Migrate"), Default::default()); - let migrate = Rc::new(RefCell::new(false)); - let result = Rc::clone(&migrate); - application.connect_activate(move |application| { - let dialog = gtk4::Dialog::builder() - .application(application) - .title("Encrypt existing Cliphoard history?") - .modal(true) - .default_width(520) - .build(); - dialog.content_area().append(&Label::new(Some( - "An unencrypted Cliphoard history was found. Migrate it to an encrypted database? The original will be retained as a backup until you remove it.", - ))); - dialog.add_button("Cancel", ResponseType::Cancel); - dialog.add_button("Migrate and encrypt", ResponseType::Accept); - let result_for_response = Rc::clone(&result); - let application_for_response = application.clone(); - dialog.connect_response(move |dialog, response| { - *result_for_response.borrow_mut() = response == ResponseType::Accept; - dialog.close(); - application_for_response.quit(); - }); - dialog.present(); - }); - application.run_with_args(&["cliphoard-migrate"]); - let result = *migrate.borrow(); - Ok(result) -} - -fn confirm_plaintext_cleanup() -> Result { - let application = Application::new(Some("io.cliphoard.Cliphoard.Cleanup"), Default::default()); - let remove = Rc::new(RefCell::new(false)); - let result = Rc::clone(&remove); - application.connect_activate(move |application| { - let dialog = gtk4::Dialog::builder() - .application(application) - .title("Remove plaintext backup?") - .modal(true) - .default_width(520) - .build(); - dialog.content_area().append(&Label::new(Some( - "The encrypted history is ready. Remove the retained plaintext migration backup now? This removes the file from disk but cannot erase copies in backups or snapshots.", - ))); - dialog.add_button("Keep backup", ResponseType::Cancel); - dialog.add_button("Remove plaintext backup", ResponseType::Accept); - let result_for_response = Rc::clone(&result); - let application_for_response = application.clone(); - dialog.connect_response(move |dialog, response| { - *result_for_response.borrow_mut() = response == ResponseType::Accept; - dialog.close(); - application_for_response.quit(); - }); - dialog.present(); - }); - application.run_with_args(&["cliphoard-cleanup"]); - let result = *remove.borrow(); - Ok(result) + result } fn build_window( @@ -307,6 +322,8 @@ fn build_window( let clear_button = Button::with_label(&format!("{CLEAR_ICON} Clear History")); let pause_button = Button::with_label(&format!("{PAUSE_ICON} Pause Recording")); let help_button = Button::with_label(&format!("{HELP_ICON} Help")); + let change_passphrase_button = Button::with_label("Change passphrase"); + let settings_button = Button::with_label("Settings"); let row_actions = RowActions { copy: copy_button.clone(), paste: paste_button.clone(), @@ -330,6 +347,8 @@ fn build_window( actions.append(&clear_button); actions.append(&pause_button); actions.append(&help_button); + actions.append(&change_passphrase_button); + actions.append(&settings_button); root.append(&actions); root.append(&status); let window = ApplicationWindow::builder() @@ -670,6 +689,28 @@ fn build_window( let shortcut_for_help = config.global_shortcut.clone(); help_button.connect_clicked(move |_| show_help(&window_for_help, &shortcut_for_help)); + let window_for_passphrase = window.clone(); + let state_for_passphrase = Rc::clone(&state); + let status_for_passphrase = status.clone(); + change_passphrase_button.connect_clicked(move |_| { + change_passphrase( + &window_for_passphrase, + Rc::clone(&state_for_passphrase), + &status_for_passphrase, + ); + }); + + let window_for_settings = window.clone(); + let config_for_settings = config.clone(); + let status_for_settings = status.clone(); + settings_button.connect_clicked(move |_| { + show_settings( + &window_for_settings, + &config_for_settings, + &status_for_settings, + ); + }); + let state_for_clear = Rc::clone(&state); let cleared_list = list.clone(); let status_for_clear = status.clone(); @@ -1055,6 +1096,115 @@ fn show_text_dialog(window: &ApplicationWindow, title: &str, content: &str) { dialog.present(); } +fn show_settings(window: &ApplicationWindow, config: &Config, status: &Label) { + let dialog = gtk4::Dialog::builder() + .transient_for(window) + .modal(true) + .title("Cliphoard settings") + .default_width(460) + .build(); + let content = GtkBox::new(Orientation::Vertical, 10); + content.set_margin_top(18); + content.set_margin_bottom(18); + content.set_margin_start(18); + content.set_margin_end(18); + let show_window = CheckButton::with_label("Show the Cliphoard window after unlock"); + show_window.set_active(config.show_window_after_unlock); + content.append(&show_window); + let explanation = Label::new(Some( + "When disabled, Cliphoard starts in the tray after you enter the passphrase. You can still open the window with the global shortcut.", + )); + explanation.set_wrap(true); + content.append(&explanation); + dialog.content_area().append(&content); + dialog.add_button("Cancel", ResponseType::Cancel); + dialog.add_button("Save", ResponseType::Accept); + let config_for_response = config.clone(); + let status_for_response = status.clone(); + dialog.connect_response(move |dialog, response| { + if response == ResponseType::Accept { + let mut updated_config = config_for_response.clone(); + updated_config.show_window_after_unlock = show_window.is_active(); + match updated_config.save() { + Ok(()) => set_status(&status_for_response, "Settings saved"), + Err(error) => set_status( + &status_for_response, + &format!("Could not save settings: {error}"), + ), + } + } + dialog.close(); + }); + dialog.present(); +} + +fn change_passphrase(window: &ApplicationWindow, state: Rc>, status: &Label) { + let dialog = gtk4::Dialog::builder() + .transient_for(window) + .modal(true) + .title("Change Cliphoard passphrase") + .default_width(460) + .build(); + let content = GtkBox::new(Orientation::Vertical, 10); + content.set_margin_top(18); + content.set_margin_bottom(18); + content.set_margin_start(18); + content.set_margin_end(18); + let explanation = Label::new(Some( + "Choose a new passphrase and remember it. You will need it the next time Cliphoard starts.", + )); + explanation.set_wrap(true); + content.append(&explanation); + let new_passphrase = Entry::new(); + new_passphrase.set_visibility(false); + new_passphrase.set_placeholder_text(Some("New passphrase")); + content.append(&new_passphrase); + let confirmation = Entry::new(); + confirmation.set_visibility(false); + confirmation.set_placeholder_text(Some("Confirm new passphrase")); + content.append(&confirmation); + let error = Label::new(None); + error.set_wrap(true); + content.append(&error); + dialog.content_area().append(&content); + dialog.add_button("Cancel", ResponseType::Cancel); + dialog.add_button("Change passphrase", ResponseType::Accept); + let new_passphrase_for_response = new_passphrase.clone(); + let confirmation_for_response = confirmation.clone(); + let state_for_response = state; + let status_for_response = status.clone(); + dialog.connect_response(move |dialog, response| { + if response != ResponseType::Accept { + dialog.close(); + return; + } + let value = new_passphrase_for_response.text().to_string(); + if value.is_empty() { + error.set_text("Enter a new passphrase, or choose Cancel to close."); + return; + } + if confirmation_for_response.text().as_str() != value { + error.set_text("The passphrases do not match. Check both fields and try again."); + return; + } + match state_for_response + .borrow() + .database + .change_passphrase(&value) + { + Ok(()) => { + set_status(&status_for_response, "Passphrase changed successfully"); + dialog.close(); + } + Err(error_value) => { + error.set_text(&format!("Could not change passphrase: {error_value}")); + } + } + }); + dialog.present(); + new_passphrase.grab_focus(); +} + fn show_help(window: &ApplicationWindow, shortcut: &str) { let help = format!( "Cliphoard help\n\n\ @@ -1072,8 +1222,9 @@ Search\n\ Search is case-insensitive and ranks exact, prefix, substring, then fuzzy matches.\n\ Pinned entries stay above unpinned results; matching text is highlighted.\n\n\ Security\n\ -Enter the passphrase at startup. It is never stored. Legacy plaintext history is\n\ -migrated only after confirmation, then its backup can be removed.\n\n\ +On first start, create a passphrase and remember it. Enter it at every startup;\n\ +it is never stored and Cliphoard cannot recover it. Plaintext databases are not\n\ +opened or migrated.\n\n\ Installation and removal\n\ See README.md for the exact source-build, .deb, uninstall, autostart, and data\n\ removal commands. The tray menu includes Quit Cliphoard.\n", diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 57e7250..9212f67 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -33,9 +33,24 @@ impl Database { !passphrase.is_empty(), "database passphrase must not be empty" ); + let path = path.as_ref(); + anyhow::ensure!( + !Self::is_plaintext(path)?, + "a plaintext database was found; plaintext databases are no longer supported" + ); Self::open_internal(path, Some(passphrase)) } + pub fn change_passphrase(&self, new_passphrase: &str) -> Result<()> { + anyhow::ensure!( + !new_passphrase.is_empty(), + "database passphrase must not be empty" + ); + self.connection + .pragma_update(None, "rekey", new_passphrase) + .context("failed to change database passphrase") + } + pub fn is_plaintext(path: impl AsRef) -> Result { let path = path.as_ref(); if !path.exists() { @@ -55,100 +70,6 @@ impl Database { Ok(bytes == header.len() && &header == Self::SQLITE_HEADER) } - pub fn migrate_plaintext(path: impl AsRef, passphrase: &str) -> Result { - let path = path.as_ref().to_path_buf(); - anyhow::ensure!( - Self::is_plaintext(&path)?, - "database is not plaintext SQLite" - ); - let metadata = std::fs::symlink_metadata(&path)?; - anyhow::ensure!( - !metadata.file_type().is_symlink(), - "refusing to migrate symlinked database {}", - path.display() - ); - let source = Connection::open(&path) - .with_context(|| format!("failed to open plaintext history {}", path.display()))?; - let mut statement = source.prepare( - "SELECT id, content, created_at, last_used_at, pinned FROM entries ORDER BY id", - )?; - let entries = statement - .query_map([], |row| { - Ok(Entry { - id: row.get(0)?, - content: row.get(1)?, - content_hash: content_hash(&row.get::<_, String>(1)?), - created_at: row.get(2)?, - last_used_at: row.get(3)?, - pinned: row.get::<_, i64>(4)? != 0, - }) - })? - .collect::>>()?; - drop(statement); - drop(source); - - let temporary = path.with_extension(format!("db.migrating-{}", std::process::id())); - anyhow::ensure!( - !temporary.exists(), - "database migration is already in progress" - ); - let encrypted = Self::open_encrypted(&temporary, passphrase)?; - for entry in entries { - encrypted.connection.execute( - "INSERT OR IGNORE INTO entries(id, content, content_hash, created_at, last_used_at, pinned) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - params![entry.id, entry.content, entry.content_hash, entry.created_at, entry.last_used_at, entry.pinned as i64], - )?; - } - drop(encrypted); - - let mut backup = path.with_extension("db.plaintext-backup"); - let mut suffix = 1; - while backup.exists() { - backup = path.with_extension(format!("db.plaintext-backup.{suffix}")); - suffix += 1; - } - std::fs::rename(&path, &backup).with_context(|| { - format!( - "failed to preserve plaintext database as {}", - backup.display() - ) - })?; - if let Err(error) = std::fs::rename(&temporary, &path) { - let _ = std::fs::rename(&backup, &path); - let _ = std::fs::remove_file(&temporary); - return Err(error).with_context(|| { - format!("failed to install encrypted database {}", path.display()) - }); - } - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; - Self::open_encrypted(path, passphrase) - } - - pub fn remove_plaintext_backups(path: impl AsRef) -> Result { - let path = path.as_ref(); - let parent = path - .parent() - .context("database path has no parent directory")?; - let filename = path - .file_name() - .context("database path has no filename")? - .to_string_lossy(); - let prefix = format!("{filename}.plaintext-backup"); - let mut removed = 0; - for entry in std::fs::read_dir(parent)? { - let entry = entry?; - let name = entry.file_name(); - let name = name.to_string_lossy(); - if (name == prefix || name.starts_with(&format!("{prefix}."))) - && entry.file_type()?.is_file() - { - std::fs::remove_file(entry.path())?; - removed += 1; - } - } - Ok(removed) - } - fn open_internal(path: impl AsRef, passphrase: Option<&str>) -> Result { let path = path.as_ref().to_path_buf(); if let Ok(metadata) = std::fs::symlink_metadata(&path) { @@ -451,9 +372,28 @@ mod tests { } #[test] - fn plaintext_migration_preserves_history_and_keeps_a_backup() { + fn encrypted_database_can_change_passphrase() { let path = std::env::temp_dir().join(format!( - "cliphoard-migration-{}-{}.db", + "cliphoard-rekey-{}-{}.db", + std::process::id(), + std::thread::current().name().unwrap_or("test") + )); + let _ = std::fs::remove_file(&path); + let db = Database::open_encrypted(&path, "old passphrase").unwrap(); + db.upsert_content("rekey test payload", 1).unwrap(); + db.change_passphrase("new passphrase").unwrap(); + drop(db); + + assert!(Database::open_encrypted(&path, "old passphrase").is_err()); + let db = Database::open_encrypted(&path, "new passphrase").unwrap(); + assert_eq!(db.load_entries().unwrap()[0].content, "rekey test payload"); + let _ = std::fs::remove_file(path); + } + + #[test] + fn encrypted_open_rejects_plaintext_databases() { + let path = std::env::temp_dir().join(format!( + "cliphoard-plaintext-{}-{}.db", std::process::id(), std::thread::current().name().unwrap_or("test") )); @@ -462,26 +402,15 @@ mod tests { source .execute_batch(include_str!("../../migrations/001_initial.sql")) .unwrap(); - source - .execute( - "INSERT INTO entries(content, content_hash, created_at, last_used_at, pinned) VALUES (?1, ?2, ?3, ?4, ?5)", - params!["migrate me", content_hash("migrate me"), 10_i64, 20_i64, 1_i64], - ) - .unwrap(); drop(source); - let db = Database::migrate_plaintext(&path, "migration passphrase").unwrap(); - let entries = db.load_entries().unwrap(); - assert_eq!(entries.len(), 1); - assert_eq!(entries[0].content, "migrate me"); - assert_eq!(entries[0].created_at, 10); - assert!(entries[0].pinned); - drop(db); - assert!(!Database::is_plaintext(&path).unwrap()); - let backup = path.with_extension("db.plaintext-backup"); - assert!(backup.exists()); - assert_eq!(Database::remove_plaintext_backups(&path).unwrap(), 1); - assert!(!backup.exists()); + let error = match Database::open_encrypted(&path, "some passphrase") { + Ok(_) => panic!("plaintext database was opened as encrypted storage"), + Err(error) => error, + }; + assert!(error + .to_string() + .contains("plaintext databases are no longer supported")); let _ = std::fs::remove_file(&path); }