Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7ebaa0db4d | |||
| acbf499bb7 | |||
| 8bc6d5d1c5 | |||
| 4b7bdc487f | |||
| f4e483dd36 |
@@ -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.
|
||||
|
||||
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -148,7 +148,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cliphoard"
|
||||
version = "1.0.0"
|
||||
version = "1.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dirs",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cliphoard"
|
||||
version = "1.0.0"
|
||||
version = "1.3.0"
|
||||
edition = "2021"
|
||||
description = "A tiny, keyboard-first clipboard history utility"
|
||||
license = "MIT"
|
||||
|
||||
25
README.md
25
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.3.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.3.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.
|
||||
|
||||
33
RELEASE_NOTES.md
Normal file
33
RELEASE_NOTES.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# Cliphoard 1.3.0
|
||||
|
||||
## Highlights
|
||||
|
||||
- Added light, dark, and system appearance settings.
|
||||
- Added optional timestamps for clipboard entries.
|
||||
- Improved the popup controls with symbolic icons, tooltips, grouped footer
|
||||
actions, and clearer selected and pinned-entry styling.
|
||||
- Added confirmation dialogs for destructive history and entry actions.
|
||||
- Improved status feedback and action sensitivity when no entry is selected.
|
||||
- Settings changes are persisted in the user configuration file.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
This release continues to use encrypted SQLCipher storage and the existing
|
||||
passphrase. No database migration is required; new configuration fields use
|
||||
backward-compatible defaults. Plaintext databases remain unsupported and are
|
||||
not opened or migrated. If Cliphoard reports that the database is plaintext,
|
||||
stop Cliphoard and remove the old database before starting this release:
|
||||
|
||||
```bash
|
||||
pkill -x cliphoard || true
|
||||
rm -f ~/.local/share/cliphoard/cliphoard.db \
|
||||
~/.local/share/cliphoard/cliphoard.db.plaintext-backup*
|
||||
```
|
||||
|
||||
This permanently removes that local history. If it is needed, preserve a copy
|
||||
and use the previous release to export or otherwise preserve it first.
|
||||
|
||||
## Build requirements
|
||||
|
||||
Linux/X11, GTK4, and the runtime libraries listed by the Debian package are
|
||||
required. See `README.md` for installation and plaintext-database handling.
|
||||
123
RELEASING.md
Normal file
123
RELEASING.md
Normal file
@@ -0,0 +1,123 @@
|
||||
# Cliphoard release procedure
|
||||
|
||||
Run releases from the repository root. The process produces a source tag,
|
||||
release binary, Debian package, checksums, and a Gitea release.
|
||||
|
||||
## Prepare
|
||||
|
||||
```bash
|
||||
git switch main
|
||||
git pull --ff-only
|
||||
git status --short
|
||||
```
|
||||
|
||||
Choose the next semantic version, such as `1.2.0`, and matching tag `v1.2.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`. Review changes since the previous tag
|
||||
and write notes covering features, fixes, breaking changes, migration needs,
|
||||
passphrase behavior, and platform requirements.
|
||||
|
||||
## 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.2.0 packaging/build-deb.sh
|
||||
dpkg-deb --info target/cliphoard_1.2.0_amd64.deb
|
||||
dpkg-deb --contents target/cliphoard_1.2.0_amd64.deb
|
||||
sha256sum target/cliphoard_1.2.0_amd64.deb target/release/cliphoard > target/cliphoard_1.2.0_SHA256SUMS
|
||||
```
|
||||
|
||||
The isolated package path is:
|
||||
|
||||
```bash
|
||||
docker build -t cliphoard-builder .
|
||||
docker run --rm -v "$PWD/target:/out" cliphoard-builder
|
||||
```
|
||||
|
||||
Do not commit `target/`; retain the exact package, binary, and checksum files
|
||||
for upload.
|
||||
|
||||
## 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.2.0"
|
||||
git tag -a v1.2.0 -m "Release Cliphoard 1.2.0"
|
||||
```
|
||||
|
||||
Replace `1.2.0` and `v1.2.0` with the actual version.
|
||||
|
||||
## Push Git
|
||||
|
||||
Confirm the remote has not moved since the preparation pull. Never force-push:
|
||||
|
||||
```bash
|
||||
git show --stat --oneline HEAD
|
||||
git show --no-patch --decorate HEAD
|
||||
git push origin main
|
||||
git push origin v1.2.0
|
||||
```
|
||||
|
||||
If the remote changed, stop and reconcile it before pushing.
|
||||
|
||||
## Publish on Gitea
|
||||
|
||||
Pushing Git does not upload ignored `target/` files. Create a release for the
|
||||
pushed tag and attach:
|
||||
|
||||
- `target/cliphoard_1.2.0_amd64.deb`
|
||||
- `target/release/cliphoard`
|
||||
- `target/cliphoard_1.2.0_SHA256SUMS`
|
||||
|
||||
Using the Gitea web UI: open **Releases**, choose **New Release**, select
|
||||
`v1.2.0`, enter `Cliphoard 1.2.0`, paste the release notes, upload all three
|
||||
files, and publish. Include breaking changes and the plaintext-database
|
||||
deletion warning and commands from `README.md`.
|
||||
|
||||
For API automation, create a repository release-write token and set the
|
||||
installation-specific values without committing them:
|
||||
|
||||
```bash
|
||||
GITEA_URL="https://gitea.example.com"
|
||||
GITEA_OWNER="owner"
|
||||
GITEA_REPO="cliphoard"
|
||||
GITEA_TOKEN="..."
|
||||
VERSION="1.2.0"
|
||||
TAG="v${VERSION}"
|
||||
```
|
||||
|
||||
Create the release, then upload each artifact:
|
||||
|
||||
```bash
|
||||
release_json=$(curl --fail-with-body -sS \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "$(jq -n --arg tag "$TAG" --arg name "Cliphoard $VERSION" --arg body "$(cat RELEASE_NOTES.md)" \
|
||||
'{tag_name:$tag,target_commitish:"main",name:$name,body:$body,draft:false,prerelease:false}')" \
|
||||
"${GITEA_URL}/api/v1/repos/${GITEA_OWNER}/${GITEA_REPO}/releases"
|
||||
release_id=$(jq -r '.id' <<<"$release_json")
|
||||
for artifact in "target/cliphoard_${VERSION}_amd64.deb" "target/release/cliphoard" "target/cliphoard_${VERSION}_SHA256SUMS"; do
|
||||
curl --fail-with-body -sS -H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-F "attachment=@${artifact}" \
|
||||
"${GITEA_URL}/api/v1/repos/${GITEA_OWNER}/${GITEA_REPO}/releases/${release_id}/assets?name=$(basename "$artifact")"
|
||||
done
|
||||
```
|
||||
|
||||
Never put a token in the repository, shell history, or release notes. If no
|
||||
authenticated Gitea web session or API token is available, stop after the Git
|
||||
push and resume at publication.
|
||||
|
||||
## Final smoke check
|
||||
|
||||
On a clean machine, install the exact `.deb`, start Cliphoard, create/unlock
|
||||
the encrypted database, and check tray, popup, autostart, settings, and
|
||||
passphrase flows. Verify artifacts against `cliphoard_1.2.0_SHA256SUMS` and
|
||||
record the release URL, tag, checksums, and test results.
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
version="${CLIPHOARD_VERSION:-1.0.0}"
|
||||
version="${CLIPHOARD_VERSION:-1.3.0}"
|
||||
package_root="${PWD}/target/cliphoard-deb"
|
||||
rm -rf "$package_root"
|
||||
mkdir -p "$package_root/DEBIAN" \
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Package: cliphoard
|
||||
Version: 1.0.0
|
||||
Version: 1.3.0
|
||||
Section: utils
|
||||
Priority: optional
|
||||
Architecture: amd64
|
||||
|
||||
@@ -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)]
|
||||
#[serde(default)]
|
||||
pub struct Config {
|
||||
pub history_limit: usize,
|
||||
@@ -11,9 +11,30 @@ pub struct Config {
|
||||
pub history_retention_days: u64,
|
||||
pub global_shortcut: String,
|
||||
pub autostart: bool,
|
||||
pub always_on_top: bool,
|
||||
pub show_window_after_unlock: bool,
|
||||
pub clear_search_on_reopen: bool,
|
||||
pub show_timestamps: bool,
|
||||
pub inactive_opacity: f64,
|
||||
pub theme: Theme,
|
||||
pub ignored_patterns: Vec<String>,
|
||||
pub log_level: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Theme {
|
||||
System,
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl Default for Theme {
|
||||
fn default() -> Self {
|
||||
Self::System
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -23,6 +44,13 @@ impl Default for Config {
|
||||
history_retention_days: 30,
|
||||
global_shortcut: "Ctrl+Alt+V".into(),
|
||||
autostart: true,
|
||||
always_on_top: true,
|
||||
show_window_after_unlock: true,
|
||||
clear_search_on_reopen: false,
|
||||
show_timestamps: false,
|
||||
inactive_opacity: 0.60,
|
||||
theme: Theme::System,
|
||||
ignored_patterns: Vec::new(),
|
||||
log_level: "info".into(),
|
||||
}
|
||||
}
|
||||
@@ -95,6 +123,9 @@ impl Config {
|
||||
if self.history_retention_days == 0 {
|
||||
anyhow::bail!("history_retention_days must be greater than zero")
|
||||
}
|
||||
if !self.inactive_opacity.is_finite() || !(0.0..=1.0).contains(&self.inactive_opacity) {
|
||||
anyhow::bail!("inactive_opacity must be between 0 and 1")
|
||||
}
|
||||
if !matches!(
|
||||
self.log_level.to_ascii_lowercase().as_str(),
|
||||
"trace" | "debug" | "info" | "warn" | "error"
|
||||
@@ -103,6 +134,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 +183,11 @@ 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.always_on_top);
|
||||
assert!(c.show_window_after_unlock);
|
||||
assert_eq!(c.inactive_opacity, 0.60);
|
||||
assert_eq!(c.theme, Theme::System);
|
||||
assert!(!c.show_timestamps);
|
||||
assert!(c.validate().is_ok());
|
||||
}
|
||||
|
||||
@@ -159,4 +213,15 @@ mod tests {
|
||||
assert!(config.validate().is_ok(), "{shortcut}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_inactive_opacity() {
|
||||
for inactive_opacity in [-0.01, 1.01, f64::NAN, f64::INFINITY] {
|
||||
let config = Config {
|
||||
inactive_opacity,
|
||||
..Config::default()
|
||||
};
|
||||
assert!(config.validate().is_err(), "{inactive_opacity}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
872
src/gui.rs
872
src/gui.rs
File diff suppressed because it is too large
Load Diff
@@ -9,10 +9,13 @@ use x11rb::{
|
||||
};
|
||||
|
||||
const ACTIVE_OPACITY: f64 = 1.0;
|
||||
const INACTIVE_OPACITY: f64 = 0.60;
|
||||
|
||||
pub fn configure(window: &ApplicationWindow) {
|
||||
set_active_opacity(window);
|
||||
pub fn configure(window: &ApplicationWindow, inactive_opacity: f64, always_on_top: bool) {
|
||||
set_active_opacity(window, inactive_opacity);
|
||||
set_always_on_top(window, always_on_top);
|
||||
}
|
||||
|
||||
pub fn set_always_on_top(window: &ApplicationWindow, always_on_top: bool) {
|
||||
let Some(surface) = window.surface() else {
|
||||
return;
|
||||
};
|
||||
@@ -37,15 +40,6 @@ pub fn configure(window: &ApplicationWindow) {
|
||||
let Ok(above) = above_cookie.reply() else {
|
||||
return;
|
||||
};
|
||||
if let Err(error) = connection.change_property32(
|
||||
x11rb::protocol::xproto::PropMode::REPLACE,
|
||||
xid,
|
||||
state.atom,
|
||||
x11rb::protocol::xproto::AtomEnum::ATOM,
|
||||
&[above.atom],
|
||||
) {
|
||||
tracing::warn!(%error, "could not mark popup as always on top");
|
||||
}
|
||||
let root = connection.setup().roots[0].root;
|
||||
let event = ClientMessageEvent {
|
||||
response_type: CLIENT_MESSAGE_EVENT,
|
||||
@@ -53,7 +47,7 @@ pub fn configure(window: &ApplicationWindow) {
|
||||
sequence: 0,
|
||||
window: xid,
|
||||
type_: state.atom,
|
||||
data: ClientMessageData::from([1, above.atom, 0, 0, 0]),
|
||||
data: ClientMessageData::from([if always_on_top { 1 } else { 0 }, above.atom, 0, 0, 0]),
|
||||
};
|
||||
match connection.send_event(
|
||||
false,
|
||||
@@ -63,15 +57,17 @@ pub fn configure(window: &ApplicationWindow) {
|
||||
) {
|
||||
Ok(cookie) => {
|
||||
if let Err(error) = cookie.check() {
|
||||
tracing::debug!(%error, "window manager rejected always-on-top request");
|
||||
tracing::debug!(%error, always_on_top, "window manager rejected always-on-top request");
|
||||
}
|
||||
}
|
||||
Err(error) => tracing::debug!(%error, "could not send always-on-top request"),
|
||||
Err(error) => {
|
||||
tracing::debug!(%error, always_on_top, "could not send always-on-top request")
|
||||
}
|
||||
}
|
||||
let _ = connection.flush();
|
||||
}
|
||||
|
||||
pub fn set_active_opacity(window: &ApplicationWindow) {
|
||||
pub fn set_active_opacity(window: &ApplicationWindow, inactive_opacity: f64) {
|
||||
let Some(surface) = window.surface() else {
|
||||
return;
|
||||
};
|
||||
@@ -90,7 +86,7 @@ pub fn set_active_opacity(window: &ApplicationWindow) {
|
||||
let value = if window.is_active() {
|
||||
ACTIVE_OPACITY
|
||||
} else {
|
||||
INACTIVE_OPACITY
|
||||
inactive_opacity
|
||||
};
|
||||
let scaled = (value * u32::MAX as f64).round() as u32;
|
||||
if let Err(error) = connection.change_property32(
|
||||
|
||||
@@ -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<Path>) -> Result<bool> {
|
||||
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<Path>, passphrase: &str) -> Result<Self> {
|
||||
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::<rusqlite::Result<Vec<_>>>()?;
|
||||
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<Path>) -> Result<usize> {
|
||||
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<Path>, passphrase: Option<&str>) -> Result<Self> {
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user