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

+5 -2
View File
@@ -26,12 +26,14 @@ tokio = { workspace = true, features = ["io-util", "macros", "net", "process", "
ts-rs = { workspace = true, features = ["chrono-impl"] }
url = "2"
yaak-common = { workspace = true }
yaak-database = { workspace = true }
yaak-crypto = { workspace = true }
# Its databases are encrypted whole with SQLCipher.
yaak-database = { workspace = true, features = ["sqlcipher"] }
yaak-filter = { workspace = true }
yaak-grpc = { workspace = true }
yaak-http = { workspace = true }
yaak-lifecycle = { workspace = true }
yaak-models = { workspace = true }
yaak-models = { workspace = true, features = ["sqlcipher"] }
yaak-proxy = { workspace = true }
yaak-proxy-helper = { workspace = true, features = ["ts"] }
yaak-rpc = { workspace = true }
@@ -82,4 +84,5 @@ tonic-reflection = "0.14.6"
reqwest = { workspace = true }
tempfile = "3"
tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "time"] }
yaak-crypto = { workspace = true, features = ["test-support"] }
yaak-proxy-helper = { workspace = true, features = ["test-support"] }
+23
View File
@@ -250,6 +250,15 @@ httpVersion: HttpVersion,
* Why the engine last failed to start, until it starts.
*/
startError: string | null,
/**
* How far encrypting traffic stored before encryption has got, from 0 to 1, while it
* runs. The engine starts once it is done.
*/
encrypting: number | null,
/**
* Captured traffic cannot be read: its key is unavailable, or it is being encrypted.
*/
locked: ProxyLock | null,
/**
* Another process that owns the engine, such as the CLI daemon. While one does, this app
* cannot start its own, and new flows reach it only through the database.
@@ -336,6 +345,20 @@ export type Owner = "app" | "cli";
export type PreviewSaveRequest = { flowId: string, };
/**
* Why captured traffic cannot be read, for the window's locked state.
*/
export type ProxyLock = {
/**
* What every refused read says.
*/
message: string,
/**
* The keychain would not give up the key, or has not been asked yet, so allowing Yaak
* Proxy in Keychain Access is the way out.
*/
keychain: boolean, };
export type ProxySetting = { enabled: boolean, server: string, port: number, };
export type ProxyState = "running" | "stopped";
+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
@@ -0,0 +1,531 @@
//! Captured traffic encrypted at rest: `proxy.db` and `blobs.sqlite` with SQLCipher, keyed from
//! a data key the master key in the keychain wraps, and `ca.key` with the data key.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use yaak_crypto::data_key::DataKey;
use yaak_database::UpdateSource;
use yaak_database::encryption::{FileState, apply_key, file_state};
use yaak_models::blob_manager::BodyChunkWriter;
use yaak_proxy::CaStore;
use yaak_proxy_lib::bodies::read_raw_body;
use yaak_proxy_lib::client::ProxyConnection;
use yaak_proxy_lib::db::{BLOBS_DB, DATA_KEY, PROXY_DB, database_key};
use yaak_proxy_lib::flows::{self, FlowFilter};
use yaak_proxy_lib::models::{Flow, FlowBody, ProxyHeader};
use yaak_proxy_lib::settings::ProxySettings;
use yaak_proxy_lib::{MasterKeySource, ProxyCtx};
use yaak_rpc::RpcEventEmitter;
const HEADER_SECRET: &str = "sk_live_HEADERSECRET123";
const QUERY_SECRET: &str = "QUERYSECRET456";
const BODY_SECRET: &str = "BODYSECRET789";
const FLOWS: usize = 3_000;
fn open_ctx(dir: &Path, keys: MasterKeySource) -> ProxyCtx {
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
settings.save(&dir.join("settings.json")).unwrap();
let (events, _rx) = RpcEventEmitter::new();
ProxyCtx::new(dir, events, keys).unwrap()
}
/// `n` flows, each with a bearer token in a header, an API key in its query and a token in a
/// 1 KB response body.
fn write_flows(ctx: &ProxyCtx, n: usize) {
let flows: Vec<Flow> = (0..n)
.map(|i| Flow {
id: format!("fl_{i:05}"),
method: if i % 3 == 0 { "POST" } else { "GET" }.into(),
url: format!("https://api.example.com/v1/items/{i}?api_key={QUERY_SECRET}"),
status: Some(if i % 10 == 0 { 404 } else { 200 }),
content_type: Some("application/json".into()),
request_headers: vec![ProxyHeader {
name: "authorization".into(),
value: format!("Bearer {HEADER_SECRET}"),
}],
started_at: chrono::DateTime::from_timestamp(1_700_000_000 + i as i64, 0)
.unwrap()
.naive_utc(),
elapsed_ms: Some(5),
..Default::default()
})
.collect();
ctx.db()
.unwrap()
.with_tx(|tx| {
flows.iter().try_for_each(|f| tx.upsert(f, &UpdateSource::Background).map(|_| ()))
})
.unwrap();
for flow in &flows {
let mut writer =
BodyChunkWriter::new(ctx.blobs().unwrap(), Flow::body_id(&flow.id, FlowBody::Response));
let body = format!("{{\"token\":\"{BODY_SECRET}\",\"pad\":\"{}\"}}", "x".repeat(1000));
writer.write(body.as_bytes()).unwrap();
writer.finish().unwrap();
}
}
/// Every file under `dir`, recursively.
fn files(dir: &Path) -> Vec<PathBuf> {
let mut found = vec![];
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
found.extend(files(&path));
} else {
found.push(path);
}
}
found
}
/// The files under `dir` that hold `needle` as it is. One gone by the time it is read, a WAL
/// its last connection closed meanwhile, holds nothing.
fn holding(dir: &Path, needle: &str) -> Vec<PathBuf> {
files(dir)
.into_iter()
.filter(|p| {
std::fs::read(p)
.map(|b| b.windows(needle.len()).any(|w| w == needle.as_bytes()))
.unwrap_or(false)
})
.collect()
}
fn assert_no_plaintext(dir: &Path) {
for secret in [HEADER_SECRET, QUERY_SECRET, BODY_SECRET, "PRIVATE KEY"] {
assert_eq!(holding(dir, secret), Vec::<PathBuf>::new(), "{secret} in plaintext");
}
}
/// `dir`'s databases as a build from before encryption left them: the same tables and rows,
/// plain, with a plaintext CA key.
fn make_plain(dir: &Path, keys: &MasterKeySource) {
let data_key = DataKey::load_file(keys, &dir.join(DATA_KEY)).unwrap().unwrap();
let key = database_key(&data_key);
for name in [PROXY_DB, BLOBS_DB] {
let path = dir.join(name);
let plain = dir.join(format!("{name}.plain-export"));
let conn = rusqlite::Connection::open(&path).unwrap();
apply_key(&conn, &key).unwrap();
conn.execute("ATTACH DATABASE ?1 AS plain KEY ''", [plain.to_string_lossy()]).unwrap();
conn.query_row("SELECT sqlcipher_export('plain')", [], |_| Ok(())).unwrap();
conn.execute_batch("DETACH DATABASE plain").unwrap();
drop(conn);
for suffix in ["", "-wal", "-shm"] {
let _ = std::fs::remove_file(dir.join(format!("{name}{suffix}")));
}
std::fs::rename(&plain, &path).unwrap();
assert_eq!(file_state(&path).unwrap(), FileState::Plain);
}
std::fs::remove_file(dir.join(DATA_KEY)).unwrap();
// The CA as it was written before: its key in plaintext PEM.
let ca_dir = dir.join("ca");
std::fs::remove_dir_all(&ca_dir).ok();
CaStore::load_or_create(&ca_dir).unwrap();
}
/// A data directory with `FLOWS` flows in plain databases, as before encryption.
fn plain_capture() -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
let keys = MasterKeySource::memory();
let ctx = open_ctx(dir.path(), keys.clone());
write_flows(&ctx, FLOWS);
drop(ctx);
make_plain(dir.path(), &keys);
assert!(!holding(dir.path(), BODY_SECRET).is_empty());
assert!(!holding(dir.path(), "PRIVATE KEY").is_empty());
dir
}
#[test]
fn stores_nothing_in_plaintext_and_reads_back_with_the_key() {
let dir = tempfile::tempdir().unwrap();
let keys = MasterKeySource::memory();
let ctx = open_ctx(dir.path(), keys.clone());
ctx.load_ca().unwrap();
write_flows(&ctx, 20);
// Through the WAL and checkpointed alike.
assert_no_plaintext(dir.path());
for name in [PROXY_DB, BLOBS_DB] {
assert_eq!(file_state(&dir.path().join(name)).unwrap(), FileState::Encrypted);
}
drop(ctx);
assert_no_plaintext(dir.path());
// Opened again with the key, everything is there.
let ctx = open_ctx(dir.path(), keys.clone());
assert_eq!(flows::count(&ctx.db().unwrap()).unwrap(), 20);
let body = read_raw_body(&ctx.blobs().unwrap(), "fl_00007", FlowBody::Response).unwrap();
assert!(String::from_utf8(body).unwrap().contains(BODY_SECRET));
drop(ctx);
// Read offline, as the CLI does, with the same keychain.
let offline = ProxyConnection::Offline(
yaak_proxy_lib::client::OfflineStore::open(dir.path(), &keys).unwrap(),
);
let rt = tokio::runtime::Runtime::new().unwrap();
let listed = rt.block_on(offline.flows(&FlowFilter::default())).unwrap();
assert_eq!(listed.len(), 20);
// Without the master key that wraps it, nothing opens.
let err = yaak_proxy_lib::client::OfflineStore::open(dir.path(), &MasterKeySource::memory())
.err()
.unwrap();
assert!(err.contains("The encryption key is missing from the keychain"), "{err}");
let err = yaak_proxy_lib::client::OfflineStore::open(
dir.path(),
&MasterKeySource::refusing("User canceled the operation"),
)
.err()
.unwrap();
assert!(err.contains("couldn't read its key from the keychain"), "{err}");
// Nor without any key at all.
let raw = rusqlite::Connection::open(dir.path().join(PROXY_DB)).unwrap();
let err = raw.query_row("SELECT count(*) FROM flows", [], |r| r.get::<_, i64>(0)).unwrap_err();
assert!(err.to_string().contains("file is not a database"), "{err}");
}
/// A capture from before encryption, 3,000 flows with bodies, is converted on first launch:
/// the engine starts once it is done, the app hears how far it has got, nothing is lost and no
/// secret is left readable in any file.
#[test]
fn converts_a_plain_capture_on_first_launch() {
let dir = plain_capture();
let pem_before = std::fs::read_to_string(dir.path().join("ca/ca.pem")).unwrap();
let keys = MasterKeySource::memory();
// Flows deleted since, as a clear leaves gaps in their numbers.
let plain = rusqlite::Connection::open(dir.path().join(PROXY_DB)).unwrap();
let deleted = plain.execute("DELETE FROM flows WHERE id < 'fl_00010'", []).unwrap();
let number: i64 =
plain.query_row("SELECT rowid FROM flows WHERE id = 'fl_01234'", [], |r| r.get(0)).unwrap();
drop(plain);
let ctx = open_ctx(dir.path(), keys.clone());
let seen = Arc::new(Mutex::new(Vec::<f64>::new()));
let watching = Arc::new(AtomicBool::new(true));
let watcher = std::thread::spawn({
let (ctx, seen, watching) = (ctx.clone(), seen.clone(), watching.clone());
move || {
while watching.load(Ordering::Relaxed) {
if let Some(fraction) = ctx.encrypting() {
seen.lock().unwrap().push(fraction);
}
std::thread::sleep(Duration::from_micros(200));
}
}
});
// Waits for the conversion, then starts.
ctx.start().unwrap();
watching.store(false, Ordering::Relaxed);
watcher.join().unwrap();
assert!(ctx.port().is_some());
assert_eq!(ctx.encrypting(), None);
let seen = seen.lock().unwrap();
assert!(!seen.is_empty(), "no progress shown");
assert!(seen.iter().all(|f| (0.0..=1.0).contains(f)), "{seen:?}");
for name in [PROXY_DB, BLOBS_DB] {
assert_eq!(file_state(&dir.path().join(name)).unwrap(), FileState::Encrypted);
}
assert!(dir.path().join(DATA_KEY).exists());
let leftovers: Vec<_> = files(dir.path())
.into_iter()
.filter(|p| {
let name = p.file_name().unwrap().to_string_lossy();
name.ends_with("-plain") || name.ends_with("-encrypting")
})
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
// Every flow and body came across, each flow under its own number.
assert_eq!(flows::count(&ctx.db().unwrap()).unwrap(), FLOWS - deleted);
let body = read_raw_body(&ctx.blobs().unwrap(), "fl_02999", FlowBody::Response).unwrap();
assert!(String::from_utf8(body).unwrap().contains(BODY_SECRET));
let flow = flows::get(&ctx.db().unwrap(), "fl_01234").unwrap();
assert_eq!(flow.request_headers[0].value, format!("Bearer {HEADER_SECRET}"));
assert_eq!(flow.number, number);
// The same CA, so it stays trusted, its key now encrypted.
let ca = ctx.load_ca().unwrap();
assert_eq!(ca.pem(), pem_before);
ctx.stop().unwrap();
drop(ctx);
assert_no_plaintext(dir.path());
}
/// Search, the `q` filter, paging and the sidebar's filters read the encrypted database as
/// they read a plain one, and a full-text table works inside it.
#[test]
fn search_reaches_inside_the_encrypted_database() {
let dir = plain_capture();
let ctx = open_ctx(dir.path(), MasterKeySource::memory());
ctx.load_ca().unwrap();
let db = ctx.db().unwrap();
// Query strings are searchable, being inside the encrypted file.
let q = |q: &str| FlowFilter { q: Some(q.into()), limit: Some(50), ..Default::default() };
let (page, total, matching) = flows::page(&db, &q(QUERY_SECRET)).unwrap();
assert_eq!((page.len(), total, matching), (50, FLOWS, Some(FLOWS)));
let (page, _, matching) = flows::page(&db, &q("items/2999")).unwrap();
assert_eq!((page[0].id.as_str(), matching), ("fl_02999", Some(1)));
let posts_not_found = FlowFilter {
method: Some("post".into()),
status: Some("4xx".into()),
limit: Some(1),
..Default::default()
};
let (_, _, matching) = flows::page(&db, &posts_not_found).unwrap();
assert_eq!(matching, Some((0..FLOWS).filter(|i| i % 3 == 0 && i % 10 == 0).count()));
// Paging back from the newest, as the list does.
let mut before = None;
let mut seen = 0;
loop {
let filter = FlowFilter { limit: Some(500), before: before.clone(), ..Default::default() };
let (page, _, _) = flows::page(&db, &filter).unwrap();
if page.is_empty() {
break;
}
seen += page.len();
before = page.last().map(|f| f.id.clone());
}
assert_eq!(seen, FLOWS);
// The sidebar's site and path filters, which run the database's own functions.
let under = |u: &str| FlowFilter { under: Some(vec![u.into()]), ..Default::default() };
assert_eq!(flows::list(&db, &under("api.example.com")).unwrap().len(), FLOWS);
assert_eq!(flows::list(&db, &under("*.example.com")).unwrap().len(), FLOWS);
assert_eq!(flows::list(&db, &under("api.example.com/v1/items/42")).unwrap().len(), 1);
// A full-text table, as body search will want, made and searched in the encrypted file.
let hits: i64 = db
.with_tx(|tx| {
let conn = tx.conn().resolve();
conn.execute_batch(&format!(
"CREATE VIRTUAL TABLE fts_probe USING fts5(body);
INSERT INTO fts_probe VALUES ('{{\"token\":\"{BODY_SECRET}\"}}'), ('nothing');"
))?;
let hits = conn.query_row(
&format!(
"SELECT count(*) FROM fts_probe WHERE fts_probe MATCH '\"{BODY_SECRET}\"'"
),
[],
|r| r.get(0),
)?;
conn.execute_batch("DROP TABLE fts_probe")?;
Ok::<_, yaak_database::Error>(hits)
})
.unwrap();
assert_eq!(hits, 1);
drop((db, ctx));
assert_no_plaintext(dir.path());
}
/// Two first launches at once, as the app and the CLI daemon might: one data key, one
/// conversion, one CA, and both read everything.
#[test]
fn concurrent_first_unlocks_agree() {
let dir = plain_capture();
let keys = MasterKeySource::memory();
let barrier = std::sync::Barrier::new(2);
let pems: Vec<String> = std::thread::scope(|s| {
let handles: Vec<_> = (0..2)
.map(|_| {
s.spawn(|| {
barrier.wait();
let ctx = open_ctx(dir.path(), keys.clone());
let pem = ctx.load_ca().unwrap().pem().to_string();
assert_eq!(flows::count(&ctx.db().unwrap()).unwrap(), FLOWS);
pem
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
assert_eq!(pems[0], pems[1]);
let ctx = open_ctx(dir.path(), keys);
assert_eq!(flows::count(&ctx.db().unwrap()).unwrap(), FLOWS);
drop(ctx);
assert_no_plaintext(dir.path());
}
/// A keychain that refuses leaves capture refused, saying why, and touches nothing: no key or
/// database is made, and traffic from before stays as it was until the key can be read.
#[test]
fn a_refused_key_refuses_capture() {
let refusing = MasterKeySource::refusing("User canceled the operation");
let empty = tempfile::tempdir().unwrap();
let ctx = open_ctx(empty.path(), refusing.clone());
let err = ctx.start().unwrap_err();
assert_eq!(
err,
"Yaak Proxy stores traffic encrypted and couldn't read its key from the keychain: \
Encryption error: User canceled the operation. Allow it access, then retry."
);
assert_eq!(ctx.start_error().as_deref(), Some(err.as_str()));
assert_eq!(ctx.port(), None);
assert!(ctx.load_ca().is_err());
// Nothing is open: what reads or writes captured traffic is refused, saying why.
let locked = ctx.db().err().unwrap();
assert_eq!(locked.to_string(), format!("Traffic is locked: {err}"));
assert!(ctx.blobs().is_err());
let lock = ctx.locked().unwrap();
assert!(lock.keychain);
assert_eq!(lock.message, locked.to_string());
let made: Vec<_> = files(empty.path())
.into_iter()
.filter(|p| p.extension().is_none_or(|e| e != "lock") && !p.ends_with("settings.json"))
.collect();
assert!(made.is_empty(), "{made:?}");
let dir = plain_capture();
let ctx = open_ctx(dir.path(), refusing);
let refused = ctx.start().unwrap_err();
assert_eq!(ctx.encrypting(), None);
for name in [PROXY_DB, BLOBS_DB] {
assert_eq!(file_state(&dir.path().join(name)).unwrap(), FileState::Plain);
}
// Clear is refused too, so the captured flows are not left to come back.
assert_eq!(ctx.clear_flows().unwrap_err(), format!("Traffic is locked: {refused}"));
// Retrying with access allowed converts it then, every flow still there.
drop(ctx);
let ctx = open_ctx(dir.path(), MasterKeySource::memory());
ctx.start().unwrap();
assert_eq!(flows::count(&ctx.db().unwrap()).unwrap(), FLOWS);
// And clears them now.
assert_eq!(ctx.clear_flows().unwrap(), FLOWS);
assert_eq!(flows::count(&ctx.db().unwrap()).unwrap(), 0);
}
/// A build from before encryption that owns the engine, a CLI daemon, keeps its plain databases
/// until it lets go: converting them under it would pull them away from its connections.
#[cfg(unix)]
#[test]
fn waits_for_an_older_owner_before_converting() {
use yaak_proxy_lib::control::{ControlInfo, Owner, control_path};
let dir = plain_capture();
let ca_key = std::fs::read(dir.path().join("ca/ca.key")).unwrap();
// Another live process owns it: this one's parent, answering on a port of its own.
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let owner = ControlInfo {
pid: std::os::unix::process::parent_id(),
control_port: listener.local_addr().unwrap().port(),
proxy_port: None,
token: "tok".into(),
owner: Owner::Cli,
started_at: chrono::Utc::now(),
};
let control = control_path(dir.path());
std::fs::write(&control, serde_json::to_string(&owner).unwrap()).unwrap();
let ctx = open_ctx(dir.path(), MasterKeySource::memory());
assert!(ctx.load_ca().err().unwrap().contains("can't be encrypted yet"));
assert!(ctx.start().unwrap_err().starts_with("The proxy is already running in the yaak CLI"));
for name in [PROXY_DB, BLOBS_DB] {
assert_eq!(file_state(&dir.path().join(name)).unwrap(), FileState::Plain);
}
assert_eq!(std::fs::read(dir.path().join("ca/ca.key")).unwrap(), ca_key, "CA left as it was");
// Once it has let go, starting converts them.
drop(listener);
std::fs::remove_file(&control).unwrap();
ctx.start().unwrap();
assert_eq!(flows::count(&ctx.db().unwrap()).unwrap(), FLOWS);
for name in [PROXY_DB, BLOBS_DB] {
assert_eq!(file_state(&dir.path().join(name)).unwrap(), FileState::Encrypted);
}
}
/// The data key's file gone from beside encrypted databases is refused too, rather than a new
/// key being made that could open nothing and would replace the trusted CA.
#[test]
fn a_lost_data_key_is_not_replaced() {
let dir = tempfile::tempdir().unwrap();
let keys = MasterKeySource::memory();
let ctx = open_ctx(dir.path(), keys.clone());
let pem = ctx.load_ca().unwrap().pem().to_string();
write_flows(&ctx, 3);
drop(ctx);
std::fs::remove_file(dir.path().join(DATA_KEY)).unwrap();
let ctx = open_ctx(dir.path(), keys);
let err = ctx.start().unwrap_err();
assert!(err.starts_with("The proxy's captured traffic is encrypted, but its key is missing"));
assert!(!dir.path().join(DATA_KEY).exists());
assert_eq!(std::fs::read_to_string(dir.path().join("ca/ca.pem")).unwrap(), pem);
assert!(ctx.db().is_err(), "locked");
assert!(!ctx.locked().unwrap().keychain, "not the keychain's doing");
}
/// While locked, every RPC that reads or writes captured traffic is refused with why, and so is
/// the control API, with 503; the proxy's state says so, and starting, once the key can be
/// read, opens the databases.
#[tokio::test(flavor = "multi_thread")]
async fn locked_rpcs_and_control_api_refuse() {
let dir = plain_capture();
let ctx = open_ctx(dir.path(), MasterKeySource::refusing("User canceled the operation"));
let router = yaak_proxy_lib::build_router();
let rpc = |cmd: &'static str, payload: serde_json::Value| {
let (router, ctx) = (&router, ctx.clone());
async move { router.dispatch(cmd, payload, &ctx).await.map_err(|e| e.message) }
};
let flow_id = "fl_00001";
for (cmd, payload) in [
("list_flows", serde_json::json!({})),
("clear_flows", serde_json::json!({})),
("list_messages", serde_json::json!({ "flowId": flow_id })),
("get_flow_body", serde_json::json!({ "flowId": flow_id, "which": "response" })),
("preview_save", serde_json::json!({ "flowId": flow_id })),
("list_grpc_schemas", serde_json::json!({})),
("remove_grpc_schema", serde_json::json!({ "id": "gs_1" })),
("execute_action", serde_json::json!({ "scope": "global", "action": "flows_clear" })),
] {
let err = rpc(cmd, payload).await.unwrap_err();
assert!(err.starts_with("Traffic is locked: "), "{cmd}: {err}");
}
let state = rpc("get_proxy_state", serde_json::json!({})).await.unwrap();
assert_eq!(state["locked"]["keychain"], true);
assert!(state["locked"]["message"].as_str().unwrap().starts_with("Traffic is locked: "));
ctx.serve_control_api().unwrap();
let info = ctx.control_info().unwrap();
let http = reqwest::Client::builder().no_proxy().build().unwrap();
for path in ["/flows", &format!("/flows/{flow_id}"), "/har"] {
let resp = http
.get(format!("{}{path}", info.base_url()))
.bearer_auth(&info.token)
.send()
.await
.unwrap();
assert_eq!(resp.status(), 503, "{path}");
assert!(resp.text().await.unwrap().contains("Traffic is locked: "), "{path}");
}
let cleared = http
.post(format!("{}/flows/clear", info.base_url()))
.bearer_auth(&info.token)
.send()
.await
.unwrap();
assert_eq!(cleared.status(), 503);
// The status still answers, saying why.
let status: serde_json::Value = http
.get(format!("{}/status", info.base_url()))
.bearer_auth(&info.token)
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(status["flowCount"], 0);
assert!(status["locked"].as_str().unwrap().starts_with("Traffic is locked: "));
ctx.stop_control_api();
// Nothing was cleared or converted meanwhile.
for name in [PROXY_DB, BLOBS_DB] {
assert_eq!(file_state(&dir.path().join(name)).unwrap(), FileState::Plain);
}
}
+23 -12
View File
@@ -20,7 +20,7 @@ use yaak_proxy_lib::flows::{BodyEncoding, FlowFilter};
use yaak_proxy_lib::models::{Flow, FlowBody};
use yaak_proxy_lib::save::SaveFlowRequest;
use yaak_proxy_lib::settings::ProxySettings;
use yaak_proxy_lib::{ProxyCtx, ProxyState};
use yaak_proxy_lib::{MasterKeySource, ProxyCtx, ProxyState};
use yaak_rpc::RpcEventEmitter;
async fn route(_req: Request<Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
@@ -44,12 +44,18 @@ async fn spawn_upstream() -> SocketAddr {
addr
}
/// The keychain every context and reader here shares, as the app and the CLI share one.
fn keys() -> MasterKeySource {
static KEYS: std::sync::OnceLock<MasterKeySource> = std::sync::OnceLock::new();
KEYS.get_or_init(MasterKeySource::memory).clone()
}
/// A context over `dir` whose engine picks a free port, saving into Yaak's data in `client`.
fn ctx(dir: &Path, client: &Path) -> ProxyCtx {
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
settings.save(&dir.join("settings.json")).unwrap();
let (events, _rx) = RpcEventEmitter::new();
ProxyCtx::new(dir, events).unwrap().with_client_data_dir(client)
ProxyCtx::new(dir, events, keys()).unwrap().with_client_data_dir(client)
}
/// Sends one POST through the engine and waits for its flow.
@@ -72,7 +78,7 @@ async fn capture_flow(ctx: &ProxyCtx) -> Flow {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let flows = ctx.db.with_conn(|db| db.find_all::<Flow>().unwrap());
let flows = ctx.db().unwrap().with_conn(|db| db.find_all::<Flow>().unwrap());
if let Some(flow) = flows.into_iter().find(|f| f.url == url) {
return flow;
}
@@ -117,7 +123,8 @@ async fn round_trip() {
let wrong = http.get(&url).bearer_auth("not-the-token").send().await.unwrap();
assert_eq!(wrong.status(), 401);
let ProxyConnection::Live(client) = ProxyConnection::connect(dir.path()).unwrap() else {
let ProxyConnection::Live(client) = ProxyConnection::connect(dir.path(), &keys()).unwrap()
else {
panic!("expected the live owner");
};
let status = client.status().await.unwrap();
@@ -268,7 +275,7 @@ async fn offline_reads_proxy_db() {
flow
};
let connection = ProxyConnection::connect(dir.path()).unwrap();
let connection = ProxyConnection::connect(dir.path(), &keys()).unwrap();
assert!(matches!(connection, ProxyConnection::Offline(_)));
let flows = connection.flows(&FlowFilter::default()).await.unwrap();
assert_eq!(flows.iter().map(|f| &f.id).collect::<Vec<_>>(), vec![&flow.id]);
@@ -280,7 +287,7 @@ async fn offline_reads_proxy_db() {
assert_eq!(connection.har(&posts).await.unwrap().log.entries.len(), 1);
let empty = tempfile::tempdir().unwrap();
let err = ProxyConnection::connect(empty.path()).err().unwrap();
let err = ProxyConnection::connect(empty.path(), &keys()).err().unwrap();
assert!(err.starts_with("No captured traffic yet"), "{err}");
}
@@ -365,7 +372,7 @@ async fn save_writes_the_request_into_yaak() {
assert!(source.contains("sync"), "{source}");
// The flow remembers what it was saved as.
let flow = yaak_proxy_lib::flows::get(&ctx.db, &flow.id).unwrap();
let flow = yaak_proxy_lib::flows::get(&ctx.db().unwrap(), &flow.id).unwrap();
assert_eq!(flow.saved_request_id, Some(saved.request.id));
// Without a name, through the control API as the CLI saves, it stays unnamed, as Yaak
@@ -564,7 +571,8 @@ async fn the_save_dialog_reads_workspaces_previews_and_saves() {
(workspace.id.as_str(), Some(folder.id.as_str()))
);
let stored = ctx
.db
.db()
.unwrap()
.with_conn(|db| db.find_one::<Flow>(yaak_proxy_lib::models::FlowIden::Id, &flow.id))
.unwrap();
assert_eq!(stored.saved_request_id.as_deref(), Some(request_id));
@@ -636,7 +644,7 @@ async fn flows_name_the_app_that_sent_them() {
let deadline = Instant::now() + Duration::from_secs(5);
let flow = loop {
let flows = ctx.db.with_conn(|db| db.find_all::<Flow>().unwrap());
let flows = ctx.db().unwrap().with_conn(|db| db.find_all::<Flow>().unwrap());
if let Some(flow) = flows.into_iter().find(|f| f.url == url) {
break flow;
}
@@ -650,7 +658,7 @@ async fn flows_name_the_app_that_sent_them() {
// The search and the sidebar's Apps group find it by its path.
let filter = FlowFilter { app: Some(vec!["/usr/bin/curl".into()]), ..Default::default() };
assert_eq!(yaak_proxy_lib::flows::list(&ctx.db, &filter).unwrap().len(), 1);
assert_eq!(yaak_proxy_lib::flows::list(&ctx.db().unwrap(), &filter).unwrap().len(), 1);
}
/// Sends one GET through the engine, without waiting for a flow.
@@ -682,9 +690,12 @@ async fn pausing_stores_no_flows_and_resuming_stores_them_again() {
assert_eq!((state["state"].as_str(), &state["recording"]), (Some("running"), &json!(false)));
let paused = send_through(&ctx, "/while-paused").await;
tokio::time::sleep(Duration::from_millis(300)).await;
let flows = ctx.db.with_conn(|db| db.find_all::<Flow>().unwrap());
let flows = ctx.db().unwrap().with_conn(|db| db.find_all::<Flow>().unwrap());
assert!(flows.iter().all(|f| f.url != paused), "a flow was stored while paused");
assert!(ctx.blobs.connect().list_body_ids().unwrap().is_empty(), "a body was stored");
assert!(
ctx.blobs().unwrap().connect().list_body_ids().unwrap().is_empty(),
"a body was stored"
);
// Resumed through the control API, as the CLI would.
let status = client.set_recording(true).await.unwrap();
+105 -14
View File
@@ -16,10 +16,10 @@ use hyper::{Request, Response};
use hyper_util::rt::TokioIo;
use serde_json::{Value, json};
use tokio::net::TcpListener;
use yaak_proxy_lib::ProxyCtx;
use yaak_proxy_lib::bodies::{DecodedBody, read_body, read_raw_body};
use yaak_proxy_lib::models::{Flow, FlowBody};
use yaak_proxy_lib::settings::ProxySettings;
use yaak_proxy_lib::{MasterKeySource, ProxyCtx};
use yaak_rpc::RpcEventEmitter;
const CAPTURE_LIMIT: usize = 1024;
@@ -95,7 +95,7 @@ async fn spawn_upstream() -> SocketAddr {
async fn wait_for_flow(ctx: &ProxyCtx, url: &str) -> Flow {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let flows = ctx.db.with_conn(|db| db.find_all::<Flow>().unwrap());
let flows = ctx.db().unwrap().with_conn(|db| db.find_all::<Flow>().unwrap());
if let Some(flow) = flows.into_iter().find(|f| f.url == url) {
return flow;
}
@@ -116,7 +116,7 @@ async fn flow_is_stored_with_its_bodies() {
settings.save(&dir.path().join("settings.json")).unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
ctx.start().unwrap();
let port = ctx.port().unwrap();
assert!(dir.path().join("ca/ca.pem").exists());
@@ -149,10 +149,23 @@ async fn flow_is_stored_with_its_bodies() {
assert!(flow.request_headers.iter().any(|h| h.name == "content-length"));
assert_eq!(flow.error, None);
assert_eq!(read_raw_body(&ctx.blobs, &flow.id, FlowBody::Request).unwrap(), b"hello proxy");
assert_eq!(read_raw_body(&ctx.blobs, &flow.id, FlowBody::Response).unwrap(), compressed);
let decoded =
read_body(&ctx.db, &ctx.blobs, &flow, FlowBody::Response, CAPTURE_LIMIT).await.unwrap();
assert_eq!(
read_raw_body(&ctx.blobs().unwrap(), &flow.id, FlowBody::Request).unwrap(),
b"hello proxy"
);
assert_eq!(
read_raw_body(&ctx.blobs().unwrap(), &flow.id, FlowBody::Response).unwrap(),
compressed
);
let decoded = read_body(
&ctx.db().unwrap(),
&ctx.blobs().unwrap(),
&flow,
FlowBody::Response,
CAPTURE_LIMIT,
)
.await
.unwrap();
let expected = DecodedBody {
data: b"hello proxy".to_vec(),
stored_size: compressed.len(),
@@ -170,9 +183,15 @@ async fn flow_is_stored_with_its_bodies() {
assert_eq!(flow.request_size, 0);
assert_eq!(flow.response_size, BIG_BODY as i64);
assert!(flow.response_truncated);
let stored = read_raw_body(&ctx.blobs, &flow.id, FlowBody::Response).unwrap();
let stored = read_raw_body(&ctx.blobs().unwrap(), &flow.id, FlowBody::Response).unwrap();
assert_eq!(stored, vec![b'x'; CAPTURE_LIMIT]);
assert!(!ctx.blobs.connect().body_exists(&Flow::body_id(&flow.id, FlowBody::Request)).unwrap());
assert!(
!ctx.blobs()
.unwrap()
.connect()
.body_exists(&Flow::body_id(&flow.id, FlowBody::Request))
.unwrap()
);
ctx.stop().unwrap();
assert_eq!(ctx.port(), None);
@@ -190,7 +209,7 @@ async fn early_response_keeps_request_totals() {
settings.save(&dir.path().join("settings.json")).unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
ctx.start().unwrap();
let port = ctx.port().unwrap();
@@ -205,7 +224,8 @@ async fn early_response_keeps_request_totals() {
let flow = wait_for_flow(&ctx, &url).await;
assert_eq!(flow.status, Some(200));
let stored = read_raw_body(&ctx.blobs, &flow.id, FlowBody::Request).unwrap().len() as i64;
let stored =
read_raw_body(&ctx.blobs().unwrap(), &flow.id, FlowBody::Request).unwrap().len() as i64;
assert!(stored > 0);
assert!(flow.request_size >= stored, "{} < {stored}", flow.request_size);
assert_eq!(flow.request_truncated, flow.request_size > stored);
@@ -223,7 +243,7 @@ async fn cancelled_flow_is_not_an_error() {
settings.save(&dir.path().join("settings.json")).unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
ctx.start().unwrap();
let port = ctx.port().unwrap();
@@ -251,7 +271,7 @@ async fn http_version_setting_applies_to_new_connections() {
settings.save(&dir.path().join("settings.json")).unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
ctx.start().unwrap();
let port = ctx.port().unwrap();
let ca = std::fs::read(dir.path().join("ca/ca.pem")).unwrap();
@@ -296,7 +316,7 @@ async fn body_rpcs() {
settings.save(&dir.path().join("settings.json")).unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
ctx.start().unwrap();
let port = ctx.port().unwrap();
@@ -311,6 +331,8 @@ async fn body_rpcs() {
"systemProxyAtLaunch": false,
"httpVersion": "auto",
"startError": null,
"encrypting": null,
"locked": null,
"otherOwner": null,
})
);
@@ -393,3 +415,72 @@ async fn body_rpcs() {
let formatted = rpc(&ctx, "format_body", json!({"text": r#"{"a":[1,2]}"#})).await.unwrap();
assert_eq!(formatted, json!("{\n \"a\": [\n 1,\n 2\n ]\n}"));
}
/// Capture throughput through the engine, end to end: 3,000 requests, 16 at a time over
/// kept-alive connections, each with a 4 KB response, timed until every flow is stored, and how
/// long opening one then takes. Run in release: `cargo test --release -p yaak-proxy-lib --test
/// flow times_capture -- --ignored --nocapture`.
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn times_capture_through_the_engine() {
const FLOWS: usize = 3_000;
const AT_ONCE: usize = 16;
let upstream = spawn_upstream().await;
let dir = tempfile::tempdir().unwrap();
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
settings.save(&dir.path().join("settings.json")).unwrap();
let (events, _rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
ctx.start().unwrap();
let proxy = format!("http://127.0.0.1:{}", ctx.port().unwrap());
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::http(&proxy).unwrap())
.pool_max_idle_per_host(AT_ONCE)
.build()
.unwrap();
let started = Instant::now();
let next = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let workers: Vec<_> = (0..AT_ONCE)
.map(|_| {
let (client, next) = (client.clone(), next.clone());
tokio::spawn(async move {
loop {
let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if i >= FLOWS {
return;
}
let url = format!("http://{upstream}/v1/items/{i}?api_key=sk_test_123");
let resp = client.get(&url).header("authorization", "Bearer abc").send();
assert_eq!(resp.await.unwrap().bytes().await.unwrap().len(), BIG_BODY);
}
})
})
.collect();
for worker in workers {
worker.await.unwrap();
}
let db = ctx.db().unwrap();
while yaak_proxy_lib::flows::count(&db).unwrap() < FLOWS {
tokio::time::sleep(Duration::from_millis(1)).await;
}
let capture = started.elapsed();
let ids: Vec<String> = yaak_proxy_lib::flows::list(&db, &Default::default())
.unwrap()
.into_iter()
.map(|f| f.id)
.collect();
let blobs = ctx.blobs().unwrap();
let started = Instant::now();
for id in &ids {
let flow = yaak_proxy_lib::flows::get(&db, id).unwrap();
read_raw_body(&blobs, &flow.id, FlowBody::Response).unwrap();
}
let open = started.elapsed() / ids.len() as u32;
ctx.stop().unwrap();
eprintln!(
"{FLOWS} flows through the engine in {capture:?}: {:.0} flows/s; opening one: {open:?}",
FLOWS as f64 / capture.as_secs_f64()
);
}
+15 -8
View File
@@ -22,7 +22,7 @@ use tokio::net::TcpListener;
use yaak_proxy_lib::bodies::read_raw_body;
use yaak_proxy_lib::models::{Flow, FlowBody};
use yaak_proxy_lib::settings::ProxySettings;
use yaak_proxy_lib::{GrpcConfig, ProxyCtx};
use yaak_proxy_lib::{GrpcConfig, MasterKeySource, ProxyCtx};
use yaak_rpc::RpcEventEmitter;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
@@ -210,7 +210,7 @@ fn start(dir: &Path) -> (ProxyCtx, std::sync::mpsc::Receiver<yaak_rpc::RpcEvent>
};
settings.save(&dir.join("settings.json")).unwrap();
let (events, event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir, events).unwrap().with_protoc(protoc());
let ctx = ProxyCtx::new(dir, events, MasterKeySource::memory()).unwrap().with_protoc(protoc());
ctx.start().unwrap();
(ctx, event_rx)
}
@@ -228,7 +228,7 @@ async fn rpc(ctx: &ProxyCtx, cmd: &str, payload: Value) -> Result<Value, String>
async fn wait_for(ctx: &ProxyCtx, url: &str, check: impl Fn(&Flow) -> bool) -> Flow {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let flows = ctx.db.with_conn(|db| db.find_all::<Flow>().unwrap());
let flows = ctx.db().unwrap().with_conn(|db| db.find_all::<Flow>().unwrap());
if let Some(flow) = flows.into_iter().find(|f| f.url == url && check(f)) {
return flow;
}
@@ -280,7 +280,9 @@ async fn server_sent_events_are_stored_while_the_stream_is_open() {
// The events are the body's record: nothing of it went to the blob store, and it reads
// back as the client read it.
assert!(read_raw_body(&ctx.blobs, &ended.id, FlowBody::Response).unwrap().is_empty());
assert!(
read_raw_body(&ctx.blobs().unwrap(), &ended.id, FlowBody::Response).unwrap().is_empty()
);
let body = rpc(&ctx, "get_flow_body", json!({ "flowId": ended.id, "which": "response" }))
.await
.unwrap();
@@ -342,7 +344,10 @@ async fn grpc_web_calls_are_stored_and_decoded() {
(FlowBody::Request, "request"),
(FlowBody::Response, "response"),
] {
assert!(read_raw_body(&ctx.blobs, &flow.id, which).unwrap().is_empty(), "{side}");
assert!(
read_raw_body(&ctx.blobs().unwrap(), &flow.id, which).unwrap().is_empty(),
"{side}"
);
}
let read =
|which: &str| rpc(&ctx, "get_flow_body", json!({ "flowId": flow.id, "which": which }));
@@ -381,7 +386,7 @@ async fn grpc_web_calls_are_stored_and_decoded() {
.unwrap();
let down = wait_for(&ctx, &gateway, |f| f.elapsed_ms.is_some()).await;
assert_eq!(
read_raw_body(&ctx.blobs, &down.id, FlowBody::Response).unwrap(),
read_raw_body(&ctx.blobs().unwrap(), &down.id, FlowBody::Response).unwrap(),
b"upstream down"
);
let page = rpc(&ctx, "get_flow_body", json!({ "flowId": down.id, "which": "response" }))
@@ -515,11 +520,13 @@ async fn grpc_web_calls_are_stored_and_decoded() {
assert!(rpc(&ctx, "list_messages", json!({ "flowId": flow.id })).await.is_err());
// The rows go with the background delete the clear starts.
let deadline = Instant::now() + Duration::from_secs(10);
while ctx.db.with_conn(|c| yaak_proxy_lib::flows::clear_mark(c.conn().resolve())) > 0 {
while ctx.db().unwrap().with_conn(|c| yaak_proxy_lib::flows::clear_mark(c.conn().resolve()))
> 0
{
assert!(Instant::now() < deadline, "cleared flows were not deleted");
tokio::time::sleep(Duration::from_millis(10)).await;
}
let left: i64 = ctx.db.with_conn(|c| {
let left: i64 = ctx.db().unwrap().with_conn(|c| {
c.conn()
.resolve()
.query_row("SELECT COUNT(*) FROM flow_messages", [], |r| r.get(0))