Harden local runtime file permissions

This commit is contained in:
2026-09-10 20:33:54 +02:00
commit c5e512223f
5 changed files with 515 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
# Clipb(h)oard hardening and completion checklist
This is the persistent implementation checklist for the long-horizon audit goal.
Items are checked only after the live code has been built/tested and the relevant
behavior has evidence. Documentation and comments are not acceptance evidence.
## Iteration protocol
Each bounded iteration must:
1. make a small, reviewable change;
2. run the narrowest relevant tests plus the build/check needed for the change;
3. update this checklist with observed evidence;
4. commit the iteration;
5. re-enter Nova Emergent guidance before selecting the next iteration.
## Privacy and data protection
- [ ] Create database, log, config, lock, and runtime directories with private permissions.
- [ ] Handle pre-existing overly-permissive database/log permissions safely.
- [ ] Add tests/probes for file modes under permissive umasks.
- [ ] Confirm no normal log path emits clipboard contents.
- [ ] Add bounded log rotation or an explicit retention policy.
## Clipboard capture and X11 behavior
- [ ] Keep clipboard monitoring event-driven on the normal X11 path.
- [ ] Replace the fallback 250 ms blocking clipboard poll with a safe degraded mode.
- [ ] Move clipboard reads/writes and paste preparation off the GTK main thread.
- [ ] Support the intended textual X11 targets and document/verify compatibility.
- [ ] Make self-generated clipboard suppression deterministic and race-resistant.
- [ ] Ensure failed internal clipboard writes cannot poison suppression state.
- [ ] Verify global shortcut registration, cleanup, conflicts, and configured shortcuts.
- [ ] Verify previous-focus capture and paste behavior against real X11 applications.
- [ ] Preserve clipboard contents and show an actionable error when paste fails.
## UI and lifecycle
- [ ] Make popup close hide the window while the background process continues.
- [ ] Center the popup on the configured/active monitor.
- [ ] Preserve search query and selection after refresh-triggering actions.
- [ ] Keep keyboard pause state synchronized with button and status text.
- [ ] Implement complete keyboard-first navigation and commands.
- [ ] Ensure copy, paste, pin, delete, clear, pause, and resume have consistent UI feedback.
- [ ] Verify tray activation/menu behavior and graceful tray unavailability.
- [ ] Verify second invocation/show behavior including diagnostics.
## Configuration and application state
- [ ] Apply `log_level` from configuration or remove the setting.
- [ ] Apply `popup_position` from configuration or remove the setting.
- [ ] Validate zero/invalid limits and malformed shortcuts with actionable errors.
- [ ] Ensure configured history, pinned, and byte limits are applied consistently.
- [ ] Remove or integrate the duplicate unused in-memory `History` implementation.
- [ ] Make database mutations report missing rows and preserve UI state on failure.
## Storage and migrations
- [ ] Enforce deduplication at the database level with an appropriate constraint/index.
- [ ] Add migration coverage and recovery behavior for schema failures.
- [ ] Test persistence, trimming, pinning, deletion, and clear-history failure paths.
- [ ] Confirm startup cleanup and shutdown cleanup under crashes and interrupted runs.
## Build, packaging, and acceptance evidence
- [x] Core tests pass: 15 tests observed on 2026-09-10.
- [x] Rust formatting check passes on 2026-09-10.
- [x] X11-only cargo check passes on 2026-09-10.
- [ ] Full GTK/X11 build passes in the declared Docker environment.
- [ ] Clippy passes with warnings treated as errors.
- [ ] Package contents and runtime dependencies are verified from a fresh build.
- [ ] Manual Cinnamon/X11 acceptance run completed.
- [ ] Automated smoke coverage exists for the primary copy → search → copy/paste flow.
## Current evidence gaps
- Full GTK/X11 checking is currently blocked locally because GTK/GLib development
packages are not installed; the Docker path is not yet re-run for this goal.
- Clippy is unavailable in the current Rust toolchain.
- No GUI, X11, Cinnamon, or packaging integration tests are present in the tree.
- The repository has no prior committed baseline; the initial implementation is
currently untracked and must be committed as the first checkpoint.

79
src/config.rs Normal file
View File

@@ -0,0 +1,79 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(default)]
pub struct Config {
pub history_limit: usize,
pub pinned_limit: usize,
pub max_entry_bytes: usize,
pub global_shortcut: String,
pub autostart: bool,
pub popup_position: String,
pub log_level: String,
}
impl Default for Config {
fn default() -> Self {
Self {
history_limit: 100,
pinned_limit: 25,
max_entry_bytes: 1_048_576,
global_shortcut: "Super+V".into(),
autostart: true,
popup_position: "active-monitor-center".into(),
log_level: "info".into(),
}
}
}
impl Config {
pub fn path() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("clipbhoard/config.toml")
}
pub fn load_or_default() -> Result<Self> {
let path = Self::path();
if !path.exists() {
return Ok(Self::default());
}
let text = fs::read_to_string(&path)
.with_context(|| format!("failed to read configuration {}", path.display()))?;
let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
toml::from_str(&text).with_context(|| {
format!(
"invalid configuration {}; fix it or remove it",
path.display()
)
})
}
pub fn ensure_parent(&self) -> Result<()> {
if let Some(parent) = Self::path().parent() {
fs::create_dir_all(parent).context("failed to create configuration directory")?;
}
Ok(())
}
pub fn save(&self) -> Result<()> {
self.ensure_parent()?;
let path = Self::path();
fs::write(&path, toml::to_string_pretty(self)?).context("failed to write configuration")?;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))
.context("failed to restrict configuration permissions")?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_match_bible() {
let c = Config::default();
assert_eq!(c.history_limit, 100);
assert_eq!(c.pinned_limit, 25);
assert_eq!(c.max_entry_bytes, 1_048_576);
assert_eq!(c.global_shortcut, "Super+V");
}
}

135
src/lifecycle.rs Normal file
View File

@@ -0,0 +1,135 @@
use std::{
fs::{self, File},
io::{Read, Write},
os::unix::fs::PermissionsExt,
os::unix::net::{UnixListener, UnixStream},
path::PathBuf,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use anyhow::{Context, Result};
use fs2::FileExt;
pub struct InstanceGuard {
_file: File,
path: PathBuf,
show_requested: Arc<AtomicBool>,
stop: Arc<AtomicBool>,
_listener_thread: std::thread::JoinHandle<()>,
}
impl InstanceGuard {
pub fn acquire() -> Result<Self> {
let path = runtime_dir().join("clipbhoard.lock");
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).with_context(|| {
format!("failed to create runtime directory {}", parent.display())
})?;
fs::set_permissions(parent, fs::Permissions::from_mode(0o700))
.context("failed to restrict runtime directory permissions")?;
}
let file = File::create(&path)
.with_context(|| format!("failed to open instance lock {}", path.display()))?;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))
.context("failed to restrict instance lock permissions")?;
file.try_lock_exclusive().with_context(|| {
format!(
"another Clipb(h)oard instance is already running (lock: {})",
path.display()
)
})?;
let socket_path = socket_path();
let _ = fs::remove_file(&socket_path);
let listener = UnixListener::bind(&socket_path).with_context(|| {
format!(
"failed to bind instance command socket {}",
socket_path.display()
)
})?;
fs::set_permissions(&socket_path, fs::Permissions::from_mode(0o600))
.context("failed to restrict instance socket permissions")?;
listener
.set_nonblocking(true)
.context("failed to configure instance command socket")?;
let show_requested = Arc::new(AtomicBool::new(false));
let stop = Arc::new(AtomicBool::new(false));
let signal = Arc::clone(&show_requested);
let should_stop = Arc::clone(&stop);
let listener_thread = std::thread::Builder::new()
.name("clipbhoard-instance".into())
.spawn(move || {
while !should_stop.load(Ordering::Acquire) {
match listener.accept() {
Ok((mut stream, _)) => {
let mut command = [0; 4];
if stream.read_exact(&mut command).is_ok() && &command == b"show" {
signal.store(true, Ordering::Release);
}
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(std::time::Duration::from_millis(25))
}
Err(error) => {
tracing::debug!(%error, "instance command listener stopped");
break;
}
}
}
})
.context("failed to start instance command listener")?;
Ok(Self {
_file: file,
path,
show_requested,
stop,
_listener_thread: listener_thread,
})
}
pub fn path(&self) -> &std::path::Path {
&self.path
}
pub fn show_requested(&self) -> Arc<AtomicBool> {
Arc::clone(&self.show_requested)
}
pub fn signal_show() -> Result<()> {
let mut stream = UnixStream::connect(socket_path())
.context("could not contact the running Clipb(h)oard instance")?;
stream
.write_all(b"show")
.context("failed to request the running Clipb(h)oard instance to show")?;
Ok(())
}
}
impl Drop for InstanceGuard {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
let _ = fs::remove_file(socket_path());
}
}
pub fn runtime_dir() -> PathBuf {
dirs::runtime_dir()
.unwrap_or_else(|| std::env::temp_dir())
.join("clipbhoard")
}
fn socket_path() -> PathBuf {
runtime_dir().join("clipbhoard.sock")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runtime_path_is_scoped() {
assert!(runtime_dir().ends_with("clipbhoard"));
}
}

33
src/logging.rs Normal file
View File

@@ -0,0 +1,33 @@
use std::os::unix::fs::PermissionsExt;
use tracing_appender::non_blocking::WorkerGuard;
pub enum LoggingGuard {
File(WorkerGuard),
Stderr,
}
pub fn init() -> LoggingGuard {
let filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into());
let state_dir = dirs::state_dir().map(|path| path.join("clipbhoard"));
if let Some(state_dir) = state_dir {
if std::fs::create_dir_all(&state_dir).is_ok() {
let appender = tracing_appender::rolling::never(state_dir, "clipbhoard.log");
let log_path = dirs::state_dir().map(|path| path.join("clipbhoard/clipbhoard.log"));
let (writer, guard) = tracing_appender::non_blocking(appender);
if tracing_subscriber::fmt()
.with_writer(writer)
.with_env_filter(filter.clone())
.try_init()
.is_ok()
{
if let Some(log_path) = log_path {
let _ =
std::fs::set_permissions(log_path, std::fs::Permissions::from_mode(0o600));
}
return LoggingGuard::File(guard);
}
}
}
let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init();
LoggingGuard::Stderr
}

186
src/storage/mod.rs Normal file
View File

@@ -0,0 +1,186 @@
mod migrations;
use std::{
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
};
use anyhow::{Context, Result};
use rusqlite::{params, Connection};
use crate::core::{content_hash, Entry};
pub struct Database {
path: PathBuf,
connection: Connection,
}
impl Database {
pub fn open_default() -> Result<Self> {
let path = dirs::data_local_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("clipbhoard/clipbhoard.db");
Self::open(path)
}
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref().to_path_buf();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).with_context(|| {
format!("failed to create database directory {}", parent.display())
})?;
}
let connection = Connection::open(&path)
.with_context(|| format!("failed to open database {}", path.display()))?;
if path.exists() {
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).with_context(
|| format!("failed to restrict database permissions {}", path.display()),
)?;
}
connection.pragma_update(None, "foreign_keys", "ON")?;
migrations::run(&connection)?;
Ok(Self { path, connection })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn load_entries(&self) -> Result<Vec<Entry>> {
let mut statement = self.connection.prepare("SELECT id, content, content_hash, created_at, last_used_at, pinned FROM entries ORDER BY pinned DESC, last_used_at DESC, id DESC")?;
let entries = statement
.query_map([], |row| {
Ok(Entry {
id: row.get(0)?,
content: row.get(1)?,
content_hash: row.get(2)?,
created_at: row.get(3)?,
last_used_at: row.get(4)?,
pinned: row.get::<_, i64>(5)? != 0,
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
Ok(entries)
}
pub fn upsert_content(&self, content: &str, now: i64) -> Result<Entry> {
let hash = content_hash(content);
let transaction = self.connection.unchecked_transaction()?;
let existing: Option<Entry> = transaction.query_row("SELECT id, content, content_hash, created_at, last_used_at, pinned FROM entries WHERE content_hash = ?1 AND content = ?2 LIMIT 1", params![hash, content], |row| Ok(Entry { id: row.get(0)?, content: row.get(1)?, content_hash: row.get(2)?, created_at: row.get(3)?, last_used_at: row.get(4)?, pinned: row.get::<_, i64>(5)? != 0 })).optional()?;
let entry = if let Some(mut entry) = existing {
entry.last_used_at = now;
transaction.execute(
"UPDATE entries SET last_used_at = ?1 WHERE id = ?2",
params![now, entry.id],
)?;
entry
} else {
transaction.execute("INSERT INTO entries(content, content_hash, created_at, last_used_at, pinned) VALUES (?1, ?2, ?3, ?3, 0)", params![content, hash, now])?;
Entry {
id: transaction.last_insert_rowid(),
content: content.to_owned(),
content_hash: hash,
created_at: now,
last_used_at: now,
pinned: false,
}
};
transaction.commit()?;
Ok(entry)
}
pub fn set_pinned(&self, id: i64, pinned: bool) -> Result<()> {
self.connection.execute(
"UPDATE entries SET pinned = ?1 WHERE id = ?2",
params![pinned as i64, id],
)?;
Ok(())
}
pub fn toggle_pinned(&self, id: i64, limit: usize) -> Result<bool> {
let transaction = self.connection.unchecked_transaction()?;
let pinned: bool = transaction
.query_row("SELECT pinned FROM entries WHERE id = ?1", [id], |row| {
row.get::<_, i64>(0)
})
.map(|value| value != 0)?;
if !pinned {
let count: usize = transaction
.query_row("SELECT COUNT(*) FROM entries WHERE pinned = 1", [], |row| {
row.get::<_, i64>(0)
})
.map(|value| value as usize)?;
if count >= limit {
anyhow::bail!("the pinned entry limit of {limit} has been reached");
}
}
transaction.execute(
"UPDATE entries SET pinned = ?1 WHERE id = ?2",
params![(!pinned) as i64, id],
)?;
transaction.commit()?;
Ok(!pinned)
}
pub fn delete(&self, id: i64) -> Result<()> {
self.connection
.execute("DELETE FROM entries WHERE id = ?1", params![id])?;
Ok(())
}
pub fn clear_history(&self) -> Result<()> {
self.connection
.execute("DELETE FROM entries WHERE pinned = 0", [])?;
Ok(())
}
pub fn trim_unpinned(&self, limit: usize) -> Result<()> {
self.connection.execute("DELETE FROM entries WHERE pinned = 0 AND id NOT IN (SELECT id FROM entries WHERE pinned = 0 ORDER BY last_used_at DESC, id DESC LIMIT ?1)", params![limit as i64])?;
Ok(())
}
}
trait OptionalRow<T> {
fn optional(self) -> rusqlite::Result<Option<T>>;
}
impl<T> OptionalRow<T> for rusqlite::Result<T> {
fn optional(self) -> rusqlite::Result<Option<T>> {
match self {
Ok(value) => Ok(Some(value)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(error) => Err(error),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn persists_and_deduplicates() {
let db = Database::open("file:clipbhoard-test?mode=memory&cache=shared").unwrap();
let a = db.upsert_content("hello", 1).unwrap();
let b = db.upsert_content("hello", 2).unwrap();
assert_eq!(a.id, b.id);
assert_eq!(db.load_entries().unwrap().len(), 1);
assert_eq!(db.load_entries().unwrap()[0].last_used_at, 2);
}
#[test]
fn clear_keeps_pinned() {
let db = Database::open("file:clipbhoard-clear?mode=memory&cache=shared").unwrap();
let a = db.upsert_content("a", 1).unwrap();
db.upsert_content("b", 2).unwrap();
db.set_pinned(a.id, true).unwrap();
db.clear_history().unwrap();
let entries = db.load_entries().unwrap();
assert_eq!(entries.len(), 1);
assert!(entries[0].pinned);
}
#[test]
fn toggle_pinned_enforces_limit_atomically() {
let db = Database::open("file:clipbhoard-pin?mode=memory&cache=shared").unwrap();
let first = db.upsert_content("a", 1).unwrap();
let second = db.upsert_content("b", 2).unwrap();
assert!(db.toggle_pinned(first.id, 1).unwrap());
assert!(db.toggle_pinned(first.id, 1).unwrap() == false);
assert!(db.toggle_pinned(second.id, 1).unwrap());
}
}