diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index 3decc58..ecc4130 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -1,33 +1,55 @@ +use std::{path::Path, sync::Mutex, time::Duration}; + use rusqlite::{Connection, OptionalExtension, params}; use thiserror::Error; +pub const CURRENT_SCHEMA_VERSION: u32 = 1; + +pub struct ApplicationDatabase { + store: Mutex, +} + +impl ApplicationDatabase { + pub fn open(path: impl AsRef) -> Result { + Ok(Self { + store: Mutex::new(ProfileMessageStore::open(path)?), + }) + } + + pub fn schema_version(&self) -> Result { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .schema_version() + } +} + pub struct ProfileMessageStore { connection: Connection, } impl ProfileMessageStore { - pub fn in_memory() -> Result { - let connection = Connection::open_in_memory()?; - let store = Self { connection }; - store.migrate()?; - Ok(store) + pub fn open(path: impl AsRef) -> Result { + Self::from_connection(Connection::open(path)?, true) } - fn migrate(&self) -> Result<(), DatabaseError> { - self.connection.execute_batch( - " - PRAGMA foreign_keys = ON; - CREATE TABLE IF NOT EXISTS messages ( - profile_id TEXT NOT NULL, - server_instance_id TEXT NOT NULL, - conversation_id TEXT NOT NULL, - message_id TEXT NOT NULL, - content TEXT NOT NULL, - PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id) - ); - ", - )?; - Ok(()) + pub fn in_memory() -> Result { + Self::from_connection(Connection::open_in_memory()?, false) + } + + fn from_connection( + mut connection: Connection, + persistent: bool, + ) -> Result { + configure_connection(&connection, persistent)?; + migrate(&mut connection)?; + Ok(Self { connection }) + } + + pub fn schema_version(&self) -> Result { + Ok(self + .connection + .pragma_query_value(None, "user_version", |row| row.get(0))?) } pub fn insert_message( @@ -84,16 +106,128 @@ impl ProfileMessageStore { } } +fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> { + connection.pragma_update(None, "foreign_keys", "ON")?; + connection.busy_timeout(Duration::from_secs(5))?; + if persistent { + connection.pragma_update(None, "journal_mode", "WAL")?; + } + Ok(()) +} + +fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> { + let found: u32 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?; + + if found > CURRENT_SCHEMA_VERSION { + return Err(DatabaseError::UnsupportedSchemaVersion { + found, + supported: CURRENT_SCHEMA_VERSION, + }); + } + + if found == 0 { + let transaction = connection.transaction()?; + transaction.execute_batch( + " + CREATE TABLE messages ( + profile_id TEXT NOT NULL, + server_instance_id TEXT NOT NULL, + conversation_id TEXT NOT NULL, + message_id TEXT NOT NULL, + content TEXT NOT NULL, + PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id) + ); + PRAGMA user_version = 1; + ", + )?; + transaction.commit()?; + } + + Ok(()) +} + #[derive(Debug, Error)] pub enum DatabaseError { #[error("SQLite operation failed")] Sqlite(#[from] rusqlite::Error), + #[error("database schema version {found} is newer than supported version {supported}")] + UnsupportedSchemaVersion { found: u32, supported: u32 }, + #[error("database state lock is unavailable")] + LockPoisoned, } #[cfg(test)] mod tests { use super::*; + #[test] + fn creates_and_reopens_a_persistent_migrated_database() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("desktop.sqlite3"); + + { + let store = ProfileMessageStore::open(&path).expect("open database"); + assert_eq!( + store.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + store + .insert_message( + "profile-a", + "server-a", + "conversation-a", + "message-a", + "persisted", + ) + .expect("insert message"); + } + + let reopened = ProfileMessageStore::open(&path).expect("reopen database"); + assert_eq!( + reopened.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + assert_eq!( + reopened + .message_content("profile-a", "server-a", "conversation-a", "message-a") + .expect("query message") + .as_deref(), + Some("persisted") + ); + } + + #[test] + fn refuses_a_database_from_a_newer_schema_version() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("future.sqlite3"); + let connection = Connection::open(&path).expect("create database"); + connection + .pragma_update(None, "user_version", CURRENT_SCHEMA_VERSION + 1) + .expect("set future version"); + drop(connection); + + assert!(matches!( + ProfileMessageStore::open(path), + Err(DatabaseError::UnsupportedSchemaVersion { + found: 2, + supported: CURRENT_SCHEMA_VERSION + }) + )); + } + + #[test] + fn repeated_migration_is_idempotent() { + let store = ProfileMessageStore::in_memory().expect("store"); + assert_eq!( + store.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + assert_eq!( + store.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + } + #[test] fn identical_remote_ids_remain_isolated_by_profile_and_server() { let store = ProfileMessageStore::in_memory().expect("store"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 216b0c2..8c27438 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,11 +1,14 @@ pub mod database; pub mod diagnostics; pub mod file_transfer; +pub mod logging; pub mod networking; pub mod secure_store; pub mod windows; +use database::ApplicationDatabase; use serde::Serialize; + use tauri::{ Manager, WindowEvent, menu::{Menu, MenuItem}, @@ -16,30 +19,31 @@ use tauri::{ #[serde(rename_all = "camelCase")] struct BootstrapStatus { app_version: &'static str, + database_schema_version: u32, platform: &'static str, rust_core: &'static str, protocol_version: &'static str, } #[tauri::command] -fn bootstrap_status() -> BootstrapStatus { - BootstrapStatus { +fn bootstrap_status( + database: tauri::State<'_, ApplicationDatabase>, +) -> Result { + let database_schema_version = database + .schema_version() + .map_err(|_| "database status is unavailable".to_owned())?; + + Ok(BootstrapStatus { app_version: env!("CARGO_PKG_VERSION"), platform: "windows", rust_core: "ready", protocol_version: desktop_protocol::PROTOCOL_VERSION, - } + database_schema_version, + }) } pub fn run() { - tracing_subscriber::fmt() - .with_env_filter( - tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), - ) - .with_target(false) - .compact() - .init(); + logging::init(); tauri::Builder::default() .plugin(tauri_plugin_single_instance::init(|app, _, _| { @@ -49,6 +53,12 @@ pub fn run() { } })) .setup(|app| { + let app_data_dir = app.path().app_data_dir()?; + std::fs::create_dir_all(&app_data_dir)?; + app.manage(ApplicationDatabase::open( + app_data_dir.join("astrbot-desktop.sqlite3"), + )?); + let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; let menu = Menu::with_items(app, &[&show, &quit])?; diff --git a/src-tauri/src/logging.rs b/src-tauri/src/logging.rs new file mode 100644 index 0000000..23c009e --- /dev/null +++ b/src-tauri/src/logging.rs @@ -0,0 +1,170 @@ +use std::io::{self, Write}; + +use tracing_subscriber::fmt::MakeWriter; + +use crate::diagnostics::redaction::Redactor; + +#[derive(Clone)] +pub struct RedactingMakeWriter { + inner: M, + redactor: Redactor, +} + +impl RedactingMakeWriter { + pub fn new(inner: M) -> Self { + Self { + inner, + redactor: Redactor::default(), + } + } + + #[cfg(test)] + fn with_redactor(inner: M, redactor: Redactor) -> Self { + Self { inner, redactor } + } +} + +impl<'writer, M> MakeWriter<'writer> for RedactingMakeWriter +where + M: MakeWriter<'writer>, + M::Writer: Write, +{ + type Writer = RedactingWriter; + + fn make_writer(&'writer self) -> Self::Writer { + RedactingWriter { + inner: self.inner.make_writer(), + redactor: self.redactor.clone(), + buffer: Vec::new(), + } + } +} + +pub struct RedactingWriter { + inner: W, + redactor: Redactor, + buffer: Vec, +} + +impl RedactingWriter { + fn flush_redacted(&mut self) -> io::Result<()> { + if self.buffer.is_empty() { + return Ok(()); + } + + let rendered = String::from_utf8_lossy(&self.buffer); + let redacted = self.redactor.redact(&rendered); + self.inner.write_all(redacted.as_bytes())?; + self.buffer.clear(); + Ok(()) + } +} + +impl Write for RedactingWriter { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.buffer.extend_from_slice(buffer); + Ok(buffer.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.flush_redacted()?; + self.inner.flush() + } +} + +impl Drop for RedactingWriter { + fn drop(&mut self) { + let _ = self.flush_redacted(); + let _ = self.inner.flush(); + } +} + +pub fn init() { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .with_target(false) + .compact() + .with_writer(RedactingMakeWriter::new(std::io::stderr)) + .init(); +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use super::*; + + #[derive(Clone, Default)] + struct SharedMakeWriter { + output: Arc>>, + } + + impl SharedMakeWriter { + fn contents(&self) -> String { + String::from_utf8(self.output.lock().expect("output lock").clone()) + .expect("UTF-8 output") + } + } + + struct SharedWriter { + output: Arc>>, + } + + impl Write for SharedWriter { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.output + .lock() + .expect("output lock") + .extend_from_slice(buffer); + Ok(buffer.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + impl<'writer> MakeWriter<'writer> for SharedMakeWriter { + type Writer = SharedWriter; + + fn make_writer(&'writer self) -> Self::Writer { + SharedWriter { + output: self.output.clone(), + } + } + } + + #[test] + fn redacts_structured_fields_and_message_content_before_writing() { + let sink = SharedMakeWriter::default(); + let known_secret = format!("canary-{}", uuid::Uuid::new_v4()); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_target(false) + .with_writer(RedactingMakeWriter::with_redactor( + sink.clone(), + Redactor::new([&known_secret]), + )) + .finish(); + + tracing::subscriber::with_default(subscriber, || { + tracing::info!( + password = "test-password", + authorization = "Bearer abcdefghijklmnop", + endpoint = "https://alice:password@example.test/path", + "known={known_secret}" + ); + }); + + let output = sink.contents(); + assert!(!output.contains("test-password")); + assert!(!output.contains("abcdefghijklmnop")); + assert!(!output.contains("alice:password")); + assert!(!output.contains(&known_secret)); + assert!(output.contains(crate::diagnostics::redaction::REDACTED)); + } +} diff --git a/src/App.test.tsx b/src/App.test.tsx index 8830a1f..265439b 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -15,6 +15,7 @@ describe("App", () => { platform: "windows", rustCore: "ready", protocolVersion: "desktop-v1alpha1", + databaseSchemaVersion: 1, }); }); @@ -24,4 +25,19 @@ describe("App", () => { expect(await screen.findByText("ready")).toBeInTheDocument(); expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument(); }); + + it("rejects an invalid Rust IPC payload", async () => { + vi.mocked(invoke).mockResolvedValueOnce({ + appVersion: "0.1.0-alpha.0", + platform: "windows", + rustCore: "unexpected", + protocolVersion: "desktop-v1alpha1", + databaseSchemaVersion: 1, + }); + + render(); + + expect(await screen.findByText(/IPC unavailable:/)).toBeInTheDocument(); + expect(screen.queryByText("unexpected")).not.toBeInTheDocument(); + }); }); diff --git a/src/App.tsx b/src/App.tsx index e9ecf5d..e967145 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,13 +1,14 @@ import { invoke } from "@tauri-apps/api/core"; import { useCallback, useEffect, useState } from "react"; -import type { BootstrapStatus } from "./types/bootstrap"; +import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; const initialStatus: BootstrapStatus = { appVersion: "unknown", platform: "unknown", rustCore: "pending", protocolVersion: "desktop-v1alpha1", + databaseSchemaVersion: 1, }; export function App() { @@ -16,8 +17,8 @@ export function App() { const refreshStatus = useCallback(async () => { try { - const result = await invoke("bootstrap_status"); - setStatus(result); + const result = await invoke("bootstrap_status"); + setStatus(bootstrapStatusSchema.parse(result)); setError(null); } catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)); @@ -44,6 +45,10 @@ export function App() { + {error ?

IPC unavailable: {error}

: null} diff --git a/src/types/bootstrap.ts b/src/types/bootstrap.ts index 6589e90..797d206 100644 --- a/src/types/bootstrap.ts +++ b/src/types/bootstrap.ts @@ -1,6 +1,13 @@ -export interface BootstrapStatus { - appVersion: string; - platform: string; - rustCore: "ready" | "pending"; - protocolVersion: string; -} +import { z } from "zod"; + +export const bootstrapStatusSchema = z + .object({ + appVersion: z.string().min(1), + platform: z.string().min(1), + rustCore: z.enum(["ready", "pending"]), + protocolVersion: z.string().min(1), + databaseSchemaVersion: z.number().int().positive(), + }) + .strict(); + +export type BootstrapStatus = z.infer;