Encrypt Yaak Proxy's databases at rest with SQLCipher (#823)

This commit is contained in:
Gregory Schier authored and GitHub committed 2026-11-06 21:07:38 -07:00
1 parent cc382b9226
commit 91696c2d1f
42 files changed
+3366 -286

No files matched your search

+2 -1
View File
@@ -322,7 +322,8 @@ mod tests {
fn proxy_db() -> (tempfile::TempDir, ProxyQueryManager) {
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
(dir, db)
}
+12 -9
View File
@@ -9,6 +9,7 @@ use crate::control::{
SystemProxyRequest, TRUNCATED_HEADER,
};
use crate::db::ProxyQueryManager;
use crate::db::Stores;
use crate::flows::{self, FlowDetail, FlowFilter};
use crate::har::{self, Har};
use crate::macos::SystemProxyStatus;
@@ -18,6 +19,7 @@ use crate::settings::ProxySettings;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::path::Path;
use yaak_crypto::MasterKeySource;
use yaak_models::blob_manager::BlobManager;
/// Where captured traffic is read from.
@@ -29,11 +31,13 @@ pub enum ProxyConnection {
}
impl ProxyConnection {
/// The live owner in `data_dir`, or its databases when there is none.
pub fn connect(data_dir: &Path) -> Result<Self, String> {
/// The live owner in `data_dir`, or its databases when there is none, read with the data
/// key the master key in `keys` unwraps. The app's keychain item, so on macOS a CLI asking
/// for it is prompted to be allowed.
pub fn connect(data_dir: &Path, keys: &MasterKeySource) -> Result<Self, String> {
match control::live_owner(data_dir) {
Some(info) => Ok(Self::Live(ControlClient::new(info))),
None => Ok(Self::Offline(OfflineStore::open(data_dir)?)),
None => Ok(Self::Offline(OfflineStore::open(data_dir, keys)?)),
}
}
@@ -200,18 +204,17 @@ pub struct OfflineStore {
}
impl OfflineStore {
pub fn open(data_dir: &Path) -> Result<Self, String> {
let db_path = data_dir.join("proxy.db");
/// Opens the databases in `data_dir`, decrypting with the data key the master key in `keys`
/// unwraps. Ones from before encryption, not yet converted, are read as they are.
pub fn open(data_dir: &Path, keys: &MasterKeySource) -> Result<Self, String> {
let db_path = data_dir.join(crate::db::PROXY_DB);
if !db_path.exists() {
return Err(format!(
"No captured traffic yet: {} does not exist. Start Yaak Proxy to capture some.",
db_path.display()
));
}
let db = ProxyQueryManager::open_read_only(&db_path)
.map_err(|e| format!("Failed to open {}: {e}", db_path.display()))?;
let blobs = crate::db::open_blobs_read_only(&data_dir.join("blobs.sqlite"))
.map_err(|e| format!("Failed to open the proxy's blob store: {e}"))?;
let Stores { db, blobs, .. } = Stores::open_read_only(data_dir, keys)?;
let settings = ProxySettings::load(&data_dir.join("settings.json"))?;
Ok(Self { db, blobs, capture_body_limit: settings.capture_body_limit })
}
+51 -23
View File
@@ -33,7 +33,6 @@ use std::sync::mpsc as std_mpsc;
use std::time::Duration;
use tokio::net::TcpListener;
use ts_rs::TS;
use yaak_proxy::CaStore;
pub const CONTROL_FILE: &str = "control.json";
const LOCK_FILE: &str = "control.lock";
@@ -212,10 +211,14 @@ pub struct ControlStatus {
pub configured_port: u16,
/// Flows are stored. Paused, traffic still passes through, unrecorded.
pub recording: bool,
/// Flows stored; zero while they are locked.
pub flow_count: usize,
pub ca: CaStatus,
/// `None` when it could not be read.
pub system_proxy: Option<SystemProxyStatus>,
/// Why captured traffic cannot be read, while it cannot.
#[serde(default)]
pub locked: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -458,10 +461,21 @@ impl ApiError {
impl From<String> for ApiError {
fn from(message: String) -> Self {
// Locked, said through a call that returns its reason as text.
if message.starts_with(crate::LOCKED) {
return Self::new(StatusCode::SERVICE_UNAVAILABLE, message);
}
Self::new(StatusCode::INTERNAL_SERVER_ERROR, message)
}
}
/// Captured traffic is locked for now: unavailable, not missing or broken.
impl From<crate::Locked> for ApiError {
fn from(locked: crate::Locked) -> Self {
Self::new(StatusCode::SERVICE_UNAVAILABLE, locked.to_string())
}
}
async fn handle(state: &ServerState, req: Request<Incoming>) -> ControlResponse {
if !authorized(&req, &state.token) {
return error_response(ApiError::new(
@@ -515,7 +529,7 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
}
(&Method::GET, ["flows"]) => {
let filter = FlowFilter::from_query(&query).map_err(bad_request)?;
json(&flows::list(&ctx.db, &filter)?)
json(&flows::list(&ctx.db()?, &filter)?)
}
(&Method::POST, ["flows", "clear"]) => {
let ctx = ctx.clone();
@@ -524,7 +538,7 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
(&Method::GET, ["flows", id]) => {
found(ctx, id)?;
let limit = body_limit(&query)?;
json(&flows::detail(&ctx.db, &ctx.blobs, id, limit).await?)
json(&flows::detail(&ctx.db()?, &ctx.blobs()?, id, limit).await?)
}
(&Method::GET, ["flows", id, "request-body"]) => raw_body(ctx, id, FlowBody::Request).await,
(&Method::GET, ["flows", id, "response-body"]) => {
@@ -533,20 +547,20 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
(&Method::GET, ["flows", id, "messages"]) => {
found(ctx, id)?;
let (after_seq, limit) = message_page(&query)?;
let messages = messages::list(&ctx.db, id, after_seq, limit)?;
let total = messages::count(&ctx.db, id)?;
let messages = messages::list(&ctx.db()?, id, after_seq, limit)?;
let total = messages::count(&ctx.db()?, id)?;
json(&ListMessagesResponse { messages, total })
}
(&Method::GET, ["flows", id, "messages", seq]) => {
let flow = flows::find(&ctx.db, id)
let flow = flows::find(&ctx.db()?, id)
.ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, format!("No flow {id}")))?;
let seq: i64 = seq.parse().map_err(|_| bad_request(format!("Invalid seq {seq:?}")))?;
let message = messages::find(&ctx.db, id, seq)?.ok_or_else(|| {
let message = messages::find(&ctx.db()?, id, seq)?.ok_or_else(|| {
ApiError::new(StatusCode::NOT_FOUND, format!("No message {seq} in flow {id}"))
})?;
let payload = messages::payload(&ctx.db, &ctx.blobs, &message)?;
let payload = messages::payload(&ctx.db()?, &ctx.blobs()?, &message)?;
let (decoded, decode_error) = if message.kind == MessageKind::GrpcMessage {
match grpc::decode(&ctx.db, &ctx.blobs, &ctx.grpc, &flow, seq, false).await {
match grpc::decode(&ctx.db()?, &ctx.blobs()?, &ctx.grpc, &flow, seq, false).await {
Ok(decoded) => (Some(decoded), None),
Err(e) => (None, Some(e)),
}
@@ -556,20 +570,22 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
let payload = BodyPreview::new(&payload, message.truncated);
json(&MessageDetail { message, payload, decoded, decode_error })
}
(&Method::GET, ["grpc-schemas"]) => json(&grpc::list(&ctx.db)?),
(&Method::GET, ["grpc-schemas"]) => json(&grpc::list(&ctx.db()?)?),
(&Method::POST, ["grpc-schemas"]) => {
let body: AddGrpcSchemaRequest = read_json(req).await?;
let added = grpc::add(&ctx.db, &ctx.grpc, &body.host_pattern, &body.proto_paths);
let db = ctx.db()?;
let added = grpc::add(&db, &ctx.grpc, &body.host_pattern, &body.proto_paths);
json(&added.await.map_err(bad_request)?)
}
(&Method::POST, ["grpc-schemas", "reflect"]) => {
let body: ReflectGrpcHostRequest = read_json(req).await?;
let (host, plaintext) = grpc::reflection_host(&body.host);
let reflected = grpc::reflect(&ctx.db, &ctx.grpc, &host, plaintext).await;
let db = ctx.db()?;
let reflected = grpc::reflect(&db, &ctx.grpc, &host, plaintext).await;
json(&reflected.map_err(bad_request)?)
}
(&Method::DELETE, ["grpc-schemas", id]) => {
json(&RemovedResponse { removed: grpc::remove(&ctx.db, &ctx.grpc, id)? })
json(&RemovedResponse { removed: grpc::remove(&ctx.db()?, &ctx.grpc, id)? })
}
(&Method::POST, ["flows", id, "save"]) => {
found(ctx, id)?;
@@ -579,17 +595,23 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
}
(&Method::GET, ["har"]) => {
let filter = FlowFilter::from_query(&query).map_err(bad_request)?;
let flows = flows::list(&ctx.db, &filter)?;
json(&har::export(&ctx.db, &ctx.blobs, &flows, ctx.capture_body_limit()?).await?)
let flows = flows::list(&ctx.db()?, &filter)?;
json(&har::export(&ctx.db()?, &ctx.blobs()?, &flows, ctx.capture_body_limit()?).await?)
}
(&Method::GET, ["ca"]) => {
let ca = CaStore::load_or_create(&ctx.ca_dir())
.map_err(|e| format!("Failed to load proxy CA: {e}"))?;
// Off the runtime's few workers: it may wait for the keychain or a conversion.
let ca = {
let ctx = ctx.clone();
blocking(move || ctx.load_ca()).await?
};
Ok(response(StatusCode::OK, "application/x-pem-file", ca.pem().to_string()))
}
(&Method::POST, ["ca", "trust"]) => {
let ca = CaStore::load_or_create(&ctx.ca_dir())
.map_err(|e| format!("Failed to load proxy CA: {e}"))?;
// Off the runtime's few workers: it may wait for the keychain or a conversion.
let ca = {
let ctx = ctx.clone();
blocking(move || ctx.load_ca()).await?
};
ca::trust(ca.cert_path()).await.map_err(bad_request)?;
ctx.forget_passthrough();
json(&ca::status(ca.cert_path()).await?)
@@ -625,24 +647,30 @@ async fn status(ctx: &ProxyCtx) -> Result<ControlStatus, ApiError> {
proxy_port,
configured_port: ctx.settings()?.port,
recording: ctx.recording(),
flow_count: flows::count(&ctx.db)?,
// Answered while locked too, saying so.
flow_count: match ctx.db() {
Ok(db) => flows::count(&db)?,
Err(_) => 0,
},
ca,
system_proxy,
locked: ctx.locked().map(|lock| lock.message),
})
}
fn found(ctx: &ProxyCtx, id: &str) -> Result<(), ApiError> {
match flows::find(&ctx.db, id) {
match flows::find(&ctx.db()?, id) {
Some(_) => Ok(()),
None => Err(ApiError::new(StatusCode::NOT_FOUND, format!("No flow {id}"))),
}
}
async fn raw_body(ctx: &ProxyCtx, id: &str, which: FlowBody) -> Result<ControlResponse, ApiError> {
let flow = flows::find(&ctx.db, id)
let flow = flows::find(&ctx.db()?, id)
.ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, format!("No flow {id}")))?;
let body =
bodies::read_body(&ctx.db, &ctx.blobs, &flow, which, ctx.capture_body_limit()?).await?;
bodies::read_body(&ctx.db()?, &ctx.blobs()?, &flow, which, ctx.capture_body_limit()?)
.await?;
let content_type =
find_header(flow.headers(which), "content-type").unwrap_or("application/octet-stream");
let mut resp = response(StatusCode::OK, content_type, body.data);
+214 -24
View File
@@ -1,15 +1,30 @@
//! The one place the proxy's databases are opened. `proxy.db` and `blobs.sqlite` are encrypted
//! whole with SQLCipher, keyed from the data key [`Stores::open`] is given: every connection is
//! keyed as it opens, and a plain database left by a build from before is converted before
//! anything writes to it. Only reading, an unconverted one is read as it is.
use include_dir::{Dir, include_dir};
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::functions::FunctionFlags;
use rusqlite::{OpenFlags, Transaction, TransactionBehavior};
use std::path::Path;
use std::path::{Path, PathBuf};
use std::time::Duration;
use yaak_crypto::MasterKeySource;
use yaak_crypto::data_key::DataKey;
use yaak_database::encryption::{self, DatabaseKey, FileState};
use yaak_database::{ConnectionOrTx, DbContext, Error, Result, SqlitePool, run_migrations};
use yaak_models::blob_manager::BlobManager;
static MIGRATIONS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/migrations");
/// Flows, their headers and messages.
pub const PROXY_DB: &str = "proxy.db";
/// Request and response bodies, and message payloads.
pub const BLOBS_DB: &str = "blobs.sqlite";
/// The key both are encrypted with, wrapped by the app's master key in the keychain.
pub const DATA_KEY: &str = "data.key";
/// Reads come from a pool; writes go through one connection, as in yaak-models'
/// `QueryManager`. WAL lets the CLI read `proxy.db` while the app writes it.
#[derive(Clone)]
@@ -19,19 +34,23 @@ pub struct ProxyQueryManager {
}
impl ProxyQueryManager {
pub fn new(db_path: &Path) -> Result<Self> {
/// Opens `proxy.db` encrypted with `key`, made so when it is new and converted when a build
/// from before left it plain, and brings its schema up to date.
pub fn new(db_path: &Path, key: &DatabaseKey) -> Result<Self> {
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent)?;
}
let writer = file_pool(db_path, 1)?;
encryption::encrypt_in_place(db_path, key, &|_| {})?;
let writer = file_pool(db_path, 1, key)?;
run_migrations(&writer, &MIGRATIONS)?;
Ok(Self { readers: file_pool(db_path, 5)?, writer })
Ok(Self { readers: file_pool(db_path, 5, key)?, writer })
}
/// `proxy.db` for reading while another process may be writing it, or none is. Writes
/// fail. No migrations run, so an older database reads as it is.
pub fn open_read_only(db_path: &Path) -> Result<Self> {
let readers = read_only_pool(db_path)?;
/// fail. No migrations run, so an older database reads as it is. An encrypted one needs
/// `key`; a plain one, not yet converted, is read without it.
pub fn open_read_only(db_path: &Path, key: Option<&DatabaseKey>) -> Result<Self> {
let readers = read_only_pool(db_path, key)?;
Ok(Self { writer: readers.clone(), readers })
}
@@ -71,12 +90,150 @@ impl ProxyQueryManager {
}
}
/// `blobs.sqlite` encrypted with `key`, converted first when it is plain, migrated.
pub fn open_blobs(path: &Path, key: &DatabaseKey) -> Result<BlobManager> {
encryption::encrypt_in_place(path, key, &|_| {})?;
yaak_models::init_encrypted_blob_store(path, key).map_err(|e| Error::Database(e.to_string()))
}
/// `blobs.sqlite` for reading, alongside [`ProxyQueryManager::open_read_only`].
pub fn open_blobs_read_only(path: &Path) -> Result<BlobManager> {
let readers = read_only_pool(path)?;
pub fn open_blobs_read_only(path: &Path, key: Option<&DatabaseKey>) -> Result<BlobManager> {
let readers = read_only_pool(path, key)?;
Ok(BlobManager::new(readers.clone(), readers))
}
/// The SQLCipher key for the databases, from the data key.
pub fn database_key(data_key: &DataKey) -> DatabaseKey {
DatabaseKey::from_bytes(data_key.raw_bytes())
}
/// Where the data key is kept in `data_dir`.
pub fn data_key_path(data_dir: &Path) -> PathBuf {
data_dir.join(DATA_KEY)
}
/// The data key for the databases in `data_dir`, unwrapped with the master key in `keys`, and
/// made the first time. Not made again once a database is encrypted, should its file go: a new
/// one could not open it, and would replace the CA.
pub fn load_or_create_data_key(
keys: &MasterKeySource,
data_dir: &Path,
) -> std::result::Result<DataKey, String> {
let path = data_key_path(data_dir);
if any_encrypted(data_dir) {
DataKey::load_file(keys, &path)
.map_err(|e| key_unavailable(&e.to_string()))?
.ok_or_else(|| missing_data_key(data_dir))
} else {
DataKey::load_or_create_file(keys, &path).map_err(|e| key_unavailable(&e.to_string()))
}
}
fn any_encrypted(data_dir: &Path) -> bool {
[PROXY_DB, BLOBS_DB]
.iter()
.any(|name| encryption::file_state(&data_dir.join(name)).ok() == Some(FileState::Encrypted))
}
fn missing_data_key(data_dir: &Path) -> String {
format!(
"The proxy's captured traffic is encrypted, but its key is missing from {}",
data_dir.display()
)
}
/// Both databases, opened together.
#[derive(Clone)]
pub struct Stores {
pub db: ProxyQueryManager,
pub blobs: BlobManager,
}
impl Stores {
/// The databases in `data_dir`, encrypted with `key`. Ones a build from before left plain
/// are converted first, without progress; [`encrypt_existing`] shows it.
pub fn open(data_dir: &Path, key: &DatabaseKey) -> std::result::Result<Self, String> {
let db = ProxyQueryManager::new(&data_dir.join(PROXY_DB), key)
.map_err(|e| format!("Failed to open proxy database: {e}"))?;
let blobs = open_blobs(&data_dir.join(BLOBS_DB), key)
.map_err(|e| format!("Failed to open proxy blob store: {e}"))?;
Ok(Self { db, blobs })
}
/// The databases in `data_dir` for reading, with the data key the master key in `keys`
/// unwraps. Asks the keychain only when one is encrypted, and never makes a key.
pub fn open_read_only(
data_dir: &Path,
keys: &MasterKeySource,
) -> std::result::Result<Self, String> {
let db_path = data_dir.join(PROXY_DB);
let blobs_path = data_dir.join(BLOBS_DB);
let key = if any_encrypted(data_dir) {
let data_key = DataKey::load_file(keys, &data_key_path(data_dir))
.map_err(|e| key_unavailable(&e.to_string()))?
.ok_or_else(|| missing_data_key(data_dir))?;
Some(database_key(&data_key))
} else {
None
};
let db = ProxyQueryManager::open_read_only(&db_path, key.as_ref())
.map_err(|e| format!("Failed to open {}: {e}", db_path.display()))?;
let blobs = open_blobs_read_only(&blobs_path, key.as_ref())
.map_err(|e| format!("Failed to open the proxy's blob store: {e}"))?;
Ok(Self { db, blobs })
}
}
/// Either database in `data_dir` is plain, left by a build from before encryption.
pub fn needs_encrypting(data_dir: &Path) -> bool {
[PROXY_DB, BLOBS_DB]
.iter()
.any(|name| encryption::file_state(&data_dir.join(name)).ok() == Some(FileState::Plain))
}
/// Converts the plain databases in `data_dir` to ones encrypted with `key`, telling `progress`
/// how far it has got, from 0 to 1. Returns whether there were any. Nothing may have them
/// open meanwhile.
pub fn encrypt_existing(
data_dir: &Path,
key: &DatabaseKey,
progress: &(dyn Fn(f64) + Sync),
) -> std::result::Result<bool, String> {
let paths: Vec<PathBuf> = [PROXY_DB, BLOBS_DB]
.iter()
.map(|name| data_dir.join(name))
.filter(|p| encryption::file_state(p).ok() == Some(FileState::Plain))
.collect();
let total = paths.iter().map(|p| encryption::plain_size(p)).sum::<u64>().max(1) as f64;
let mut before = 0u64;
let mut converted = false;
for path in &paths {
let size = encryption::plain_size(path);
let done = before;
let file_progress = move |written: u64| {
progress(((done + written.min(size)) as f64 / total).min(1.0));
};
converted |= encryption::encrypt_in_place(path, key, &file_progress)
.map_err(|e| format!("Failed to encrypt {}: {e}", path.display()))?;
before += size;
}
progress(1.0);
Ok(converted)
}
const KEY_UNAVAILABLE: &str =
"Yaak Proxy stores traffic encrypted and couldn't read its key from the keychain";
/// Why the databases cannot be opened, or the CA made, without the data key.
pub fn key_unavailable(reason: &str) -> String {
format!("{KEY_UNAVAILABLE}: {reason}. Allow it access, then retry.")
}
/// `reason` is [`key_unavailable`]'s: the keychain would not give up the key.
pub fn is_key_unavailable(reason: &str) -> bool {
reason.starts_with(KEY_UNAVAILABLE)
}
/// The functions filters use: `sidebar_path(url)`, the app sidebar's place for a URL, and
/// `under_site(url, site)`, for filtering by its nodes; `folder_name(dir)`, for naming a program
/// by its folder; and `is_system(bundle_id, path)`, for macOS's own daemons.
@@ -99,10 +256,24 @@ fn add_functions(conn: &mut rusqlite::Connection) -> rusqlite::Result<()> {
})
}
fn read_only_pool(path: &Path) -> Result<SqlitePool> {
fn read_only_pool(path: &Path, key: Option<&DatabaseKey>) -> Result<SqlitePool> {
encryption::init_crypto();
let key = match (encryption::file_state(path)?, key) {
(FileState::Plain, _) => None,
(_, Some(key)) => Some(key.clone()),
(_, None) => {
return Err(Error::Database(format!(
"{} is encrypted, with no key to read it",
path.display()
)));
}
};
let manager = SqliteConnectionManager::file(path)
.with_flags(OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX)
.with_init(|conn| {
.with_init(move |conn| {
if let Some(key) = &key {
encryption::apply_key(conn, key)?;
}
conn.busy_timeout(Duration::from_millis(5000))?;
add_functions(conn)
});
@@ -113,8 +284,11 @@ fn read_only_pool(path: &Path) -> Result<SqlitePool> {
.map_err(|e| Error::Database(e.to_string()))
}
fn file_pool(path: &Path, max_size: u32) -> Result<SqlitePool> {
let manager = SqliteConnectionManager::file(path).with_init(|conn| {
fn file_pool(path: &Path, max_size: u32, key: &DatabaseKey) -> Result<SqlitePool> {
encryption::init_crypto();
let key = key.clone();
let manager = SqliteConnectionManager::file(path).with_init(move |conn| {
encryption::apply_key(conn, &key)?;
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.busy_timeout(Duration::from_millis(5000))?;
@@ -127,6 +301,21 @@ fn file_pool(path: &Path, max_size: u32) -> Result<SqlitePool> {
.map_err(|e| Error::Database(e.to_string()))
}
/// The key unit tests encrypt their databases with.
#[cfg(test)]
pub(crate) fn test_key() -> DatabaseKey {
DatabaseKey::from_bytes([7; 32])
}
/// A connection to a database encrypted with [`test_key`], for altering it as another build
/// would have.
#[cfg(test)]
pub(crate) fn test_conn(path: &Path) -> rusqlite::Connection {
let conn = rusqlite::Connection::open(path).unwrap();
encryption::apply_key(&conn, &test_key()).unwrap();
conn
}
#[cfg(test)]
mod tests {
use super::*;
@@ -142,10 +331,10 @@ mod tests {
use crate::models::Flow;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("proxy.db");
drop(ProxyQueryManager::new(&path).unwrap());
drop(ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap());
// As a build from before the saved request and client columns left it.
let conn = Connection::open(&path).unwrap();
let conn = test_conn(&path);
conn.execute_batch(
"ALTER TABLE flows DROP COLUMN saved_request_id;
ALTER TABLE flows DROP COLUMN client_pid;
@@ -164,7 +353,7 @@ mod tests {
.unwrap();
drop(conn);
let db = ProxyQueryManager::open_read_only(&path).unwrap();
let db = ProxyQueryManager::open_read_only(&path, Some(&test_key())).unwrap();
let flows = db.with_conn(|c| c.find_all::<Flow>()).unwrap();
assert_eq!(flows.len(), 1);
assert_eq!((flows[0].id.as_str(), flows[0].saved_request_id.as_deref()), ("fl_old", None));
@@ -178,7 +367,7 @@ mod tests {
// Filters by app work without the folder column, and count without the clear mark.
drop(db);
let conn = Connection::open(&path).unwrap();
let conn = test_conn(&path);
conn.execute_batch(
"ALTER TABLE flows ADD COLUMN client_name TEXT;
ALTER TABLE flows ADD COLUMN client_bundle_id TEXT;
@@ -189,7 +378,7 @@ mod tests {
)
.unwrap();
drop(conn);
let db = ProxyQueryManager::open_read_only(&path).unwrap();
let db = ProxyQueryManager::open_read_only(&path, Some(&test_key())).unwrap();
let filter =
crate::flows::FlowFilter { app: Some(vec!["curl".into()]), ..Default::default() };
let (page, total, matching) = crate::flows::page(&db, &filter).unwrap();
@@ -219,10 +408,10 @@ mod tests {
.unwrap();
drop(conn);
let db = ProxyQueryManager::new(&path).unwrap();
let db = ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap();
drop(db);
let conn = Connection::open(&path).unwrap();
let conn = test_conn(&path);
let tables: Vec<String> = conn
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
.unwrap()
@@ -312,9 +501,9 @@ mod tests {
.unwrap();
drop(conn);
drop(ProxyQueryManager::new(&path).unwrap());
drop(ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap());
let conn = Connection::open(&path).unwrap();
let conn = test_conn(&path);
assert!(columns(&conn, "flows").contains(&"client_cwd".to_string()));
let applied: Vec<String> = conn
.prepare("SELECT version FROM _sqlx_migrations ORDER BY version")
@@ -329,8 +518,9 @@ mod tests {
drop(conn);
// The stream and its messages come through, and clearing then deleting takes both.
let db = ProxyQueryManager::new(&path).unwrap();
let blobs = yaak_models::init_blob_store(dir.path().join("blobs.sqlite")).unwrap();
let db = ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap();
let blobs = crate::db::open_blobs(&dir.path().join("blobs.sqlite"), &crate::db::test_key())
.unwrap();
let listed = crate::flows::list(&db, &Default::default()).unwrap();
assert_eq!(listed.len(), 1);
assert_eq!((listed[0].id.as_str(), listed[0].message_count), ("fl_ws", 2));
+23 -10
View File
@@ -753,7 +753,8 @@ mod tests {
fn db_of(flows: Vec<Flow>) -> (tempfile::TempDir, ProxyQueryManager) {
use yaak_database::UpdateSource;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
for (i, flow) in flows.into_iter().enumerate() {
let started_at = chrono::DateTime::from_timestamp(i as i64, 0).unwrap().naive_utc();
let flow = Flow { id: format!("fl_{i:03}"), started_at, ..flow };
@@ -964,7 +965,8 @@ mod tests {
fn after_follows_flows_as_they_are_recorded() {
use yaak_database::UpdateSource;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
let at = |s| chrono::DateTime::from_timestamp(s, 0).unwrap().naive_utc();
// A slow flow that started first but ended, and so was written, after a quick one.
for (id, started) in [("fl_quick", 20), ("fl_slow", 10), ("fl_next", 30)] {
@@ -986,7 +988,8 @@ mod tests {
fn before_pages_back_through_older_flows() {
use yaak_database::UpdateSource;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
let at = |s| chrono::DateTime::from_timestamp(s, 0).unwrap().naive_utc();
// Two started together, which their ids order.
for (id, started) in [
@@ -1033,8 +1036,10 @@ mod tests {
use yaak_database::UpdateSource;
use yaak_models::blob_manager::BodyChunkWriter;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let blobs = yaak_models::init_blob_store(dir.path().join("blobs.sqlite")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
let blobs = crate::db::open_blobs(&dir.path().join("blobs.sqlite"), &crate::db::test_key())
.unwrap();
let write_body = |id: &str, which| {
let mut writer = BodyChunkWriter::new(blobs.clone(), Flow::body_id(id, which));
writer.write(b"body").unwrap();
@@ -1079,7 +1084,11 @@ mod tests {
assert_eq!(page(&db, &narrowed).unwrap().1, 1);
// Bodies that fail to delete keep their flows, to delete again.
let read_only = crate::db::open_blobs_read_only(&dir.path().join("blobs.sqlite")).unwrap();
let read_only = crate::db::open_blobs_read_only(
&dir.path().join("blobs.sqlite"),
Some(&crate::db::test_key()),
)
.unwrap();
assert!(delete_cleared(&db, &read_only, 2, "cln_a").is_err());
assert_eq!(rows(), 4);
@@ -1117,8 +1126,10 @@ mod tests {
fn one_cleaner_at_a_time_and_never_a_reused_rowid() {
use yaak_database::UpdateSource;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let blobs = yaak_models::init_blob_store(dir.path().join("blobs.sqlite")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
let blobs = crate::db::open_blobs(&dir.path().join("blobs.sqlite"), &crate::db::test_key())
.unwrap();
let write_flow = |id: &str| {
let flow = Flow { id: id.into(), ..Default::default() };
db.with_tx(|tx| tx.upsert(&flow, &UpdateSource::Background)).unwrap().0
@@ -1169,7 +1180,8 @@ mod tests {
fn numbers_flows_by_rowid_and_keeps_it_on_update() {
use yaak_database::UpdateSource;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
let write = |flow: &Flow| db.with_tx(|tx| tx.upsert(flow, &UpdateSource::Background));
let (a, _) = write(&Flow { id: "fl_a".into(), ..Default::default() }).unwrap();
let (b, _) = write(&Flow { id: "fl_b".into(), ..Default::default() }).unwrap();
@@ -1186,7 +1198,8 @@ mod tests {
fn filters_by_app_name_folder_site_and_system() {
use yaak_database::UpdateSource;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
let flows = [
Flow {
id: "fl_slack".into(),
+2 -1
View File
@@ -469,7 +469,8 @@ mod tests {
};
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let db =
ProxyQueryManager::new(&dir.path().join("proxy.db"), &crate::db::test_key()).unwrap();
let har = export(&db, &blobs, &[flow], 1024 * 1024).await.unwrap();
let entry = &har.log.entries[0];
let text_kept = entry.response.content.text.as_deref().unwrap();
File diff suppressed because it is too large. Load diff