mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-05 14:26:23 +01:00
Detail card, settings window and small fixes for Yaak Proxy (#824)
This commit is contained in:
1 parent
4538123d88
commit
2ca2bc5f00
75 files changed
+4574
-1147
No files matched your search
@@ -165,6 +165,9 @@ fn missing_data_key(data_dir: &Path) -> String {
|
||||
pub struct Stores {
|
||||
pub db: ProxyQueryManager,
|
||||
pub blobs: BlobManager,
|
||||
/// `blobs.sqlite` and its key, for measuring it: its pools are its manager's own.
|
||||
blobs_path: PathBuf,
|
||||
key: Option<DatabaseKey>,
|
||||
}
|
||||
|
||||
impl Stores {
|
||||
@@ -173,9 +176,26 @@ impl Stores {
|
||||
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)
|
||||
let blobs_path = data_dir.join(BLOBS_DB);
|
||||
let blobs = open_blobs(&blobs_path, key)
|
||||
.map_err(|e| format!("Failed to open proxy blob store: {e}"))?;
|
||||
Ok(Self { db, blobs })
|
||||
Ok(Self { db, blobs, blobs_path, key: Some(key.clone()) })
|
||||
}
|
||||
|
||||
/// Bytes the captured traffic takes, as [`used_bytes`] counts them, in both databases.
|
||||
pub fn used_bytes(&self) -> std::result::Result<u64, String> {
|
||||
let fail = |e: rusqlite::Error| format!("Failed to measure captured traffic: {e}");
|
||||
let flows = self.db.with_conn(|c| used_bytes(c.conn().resolve())).map_err(fail)?;
|
||||
let conn = rusqlite::Connection::open_with_flags(
|
||||
&self.blobs_path,
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)
|
||||
.map_err(fail)?;
|
||||
if let Some(key) = &self.key {
|
||||
encryption::apply_key(&conn, key).map_err(fail)?;
|
||||
}
|
||||
conn.busy_timeout(Duration::from_millis(5000)).map_err(fail)?;
|
||||
Ok(flows + used_bytes(&conn).map_err(fail)?)
|
||||
}
|
||||
|
||||
/// The databases in `data_dir` for reading, with the data key the master key in `keys`
|
||||
@@ -198,10 +218,58 @@ impl Stores {
|
||||
.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 })
|
||||
Ok(Self { db, blobs, blobs_path, key })
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes the data in a database takes: its pages less the free ones. SQLite reuses free pages
|
||||
/// but gives none back to the file without a vacuum, so this shrinks as rows are deleted where
|
||||
/// the file does not. The WAL is left out, as its pages are copies of ones counted here.
|
||||
pub fn used_bytes(conn: &rusqlite::Connection) -> rusqlite::Result<u64> {
|
||||
use rusqlite::types::Value;
|
||||
// SQLCipher answers `page_size` with its own as text.
|
||||
let pragma = |name: &str| {
|
||||
let value = conn.query_row(&format!("PRAGMA {name}"), [], |r| r.get::<_, Value>(0))?;
|
||||
let n = match &value {
|
||||
Value::Integer(n) => Some(*n),
|
||||
Value::Text(s) => s.trim().parse().ok(),
|
||||
_ => None,
|
||||
};
|
||||
n.ok_or_else(|| rusqlite::Error::InvalidColumnType(0, name.into(), value.data_type()))
|
||||
};
|
||||
let used = (pragma("page_count")? - pragma("freelist_count")?) * pragma("page_size")?;
|
||||
Ok(used.max(0) as u64)
|
||||
}
|
||||
|
||||
/// The databases' files and what goes with them: their WAL and shared memory.
|
||||
fn database_files(data_dir: &Path) -> impl Iterator<Item = PathBuf> + '_ {
|
||||
[PROXY_DB, BLOBS_DB]
|
||||
.into_iter()
|
||||
.flat_map(|name| ["", "-wal", "-shm"].map(|suffix| format!("{name}{suffix}")))
|
||||
.map(move |name| data_dir.join(name))
|
||||
}
|
||||
|
||||
/// Bytes the databases' files take on disk, free pages and WAL included, for when they are
|
||||
/// locked and cannot be measured as [`Stores::used_bytes`] does.
|
||||
pub fn file_bytes(data_dir: &Path) -> u64 {
|
||||
database_files(data_dir).filter_map(|p| std::fs::metadata(p).ok()).map(|m| m.len()).sum()
|
||||
}
|
||||
|
||||
/// Deletes the databases and the data key that encrypts them, for good. Nothing may write to
|
||||
/// them meanwhile.
|
||||
pub fn remove_captured(data_dir: &Path) -> std::result::Result<(), String> {
|
||||
let key = data_key_path(data_dir);
|
||||
for path in database_files(data_dir).chain([key.with_extension("tmp"), key]) {
|
||||
match std::fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
|
||||
return Err(format!("Failed to delete {}: {e}", path.display()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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]
|
||||
@@ -443,6 +511,7 @@ mod tests {
|
||||
"_sqlx_migrations",
|
||||
"flow_clear_mark",
|
||||
"flow_messages",
|
||||
"flow_sweep_pending",
|
||||
"flows",
|
||||
"grpc_schemas"
|
||||
]
|
||||
@@ -530,7 +599,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.map(|v| v.unwrap())
|
||||
.collect();
|
||||
assert_eq!(&applied[applied.len() - 3..], ["00000007", "00000008", "00000009"]);
|
||||
assert_eq!(&applied[6..], ["00000007", "00000008", "00000009", "00000010", "00000011"]);
|
||||
let mark_columns = columns(&conn, "flow_clear_mark");
|
||||
assert_eq!(mark_columns, ["id", "max_rowid", "cleaner", "cleaner_at"]);
|
||||
drop(conn);
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Keeps background database work from running into SQLCipher's teardown as the process exits.
|
||||
//!
|
||||
//! SQLCipher frees its global state (the key shield, its private heap) in an `atexit` handler it
|
||||
//! registers the first time a database is keyed. A thread still reading or writing a database,
|
||||
//! or closing its last connection, then crashes inside SQLCipher. The threads this crate starts
|
||||
//! (the event loop writing flows, deleting cleared flows, keeping traffic under its cap) hold
|
||||
//! [`hold`] around each unit of work. [`install`], called once a database is open and so after
|
||||
//! SQLCipher's handler, registers one that runs before it, as handlers run last registered
|
||||
//! first: it stops any more work starting, waits for work in flight to finish, for a few seconds
|
||||
//! at most, and lets the process exit with that work parked.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Once, RwLock, RwLockReadGuard, TryLockError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
static GATE: RwLock<()> = RwLock::new(());
|
||||
/// Set as the process exits: no more work starts.
|
||||
static EXITING: AtomicBool = AtomicBool::new(false);
|
||||
static INSTALL: Once = Once::new();
|
||||
|
||||
/// The longest the exit handler waits for work in flight before letting the process go on
|
||||
/// exiting regardless, so a stuck thread never hangs a quit.
|
||||
const EXIT_WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Held around a unit of background database work, a batch, closing connections included. Once
|
||||
/// the process is exiting, this parks the thread for good instead: the work never starts.
|
||||
pub(crate) fn hold() -> RwLockReadGuard<'static, ()> {
|
||||
if EXITING.load(Ordering::SeqCst) {
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
GATE.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Registers the exit handler, once per process. Call after a database is open, so SQLCipher's
|
||||
/// own handler is registered first and runs after this one.
|
||||
pub(crate) fn install() {
|
||||
INSTALL.call_once(|| {
|
||||
// SAFETY: `close_gate` is an `extern "C" fn()` that never unwinds.
|
||||
let failed = unsafe { atexit(close_gate) } != 0;
|
||||
if failed {
|
||||
log::warn!("Failed to register the database exit handler");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
fn atexit(callback: extern "C" fn()) -> std::ffi::c_int;
|
||||
}
|
||||
|
||||
/// Stops more work starting, then waits for the work in flight to finish its batch and keeps
|
||||
/// the gate shut for the rest of the process's life.
|
||||
extern "C" fn close_gate() {
|
||||
EXITING.store(true, Ordering::SeqCst);
|
||||
wait_for_work(EXIT_WAIT);
|
||||
}
|
||||
|
||||
/// Takes the gate for good once no work holds it, or gives up after `wait`. Returns whether it
|
||||
/// was taken. Polled, as a blocking write can't be given up on; with no new work starting, the
|
||||
/// work in flight can't starve it.
|
||||
fn wait_for_work(wait: Duration) -> bool {
|
||||
let deadline = Instant::now() + wait;
|
||||
loop {
|
||||
match GATE.try_write() {
|
||||
Ok(guard) => {
|
||||
std::mem::forget(guard);
|
||||
return true;
|
||||
}
|
||||
Err(TryLockError::Poisoned(e)) => {
|
||||
std::mem::forget(e.into_inner());
|
||||
return true;
|
||||
}
|
||||
Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
Err(TryLockError::WouldBlock) => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
const SELF: &str = "exit_gate::tests::exiting_waits_for_work_in_flight_and_starts_no_more";
|
||||
|
||||
/// A batch in flight finishes before the gate shuts, however busy other work keeps it, and
|
||||
/// no work starts after. Run in a process of its own, as shutting the gate parks every
|
||||
/// thread that would hold it, which the other tests' threads would be.
|
||||
#[test]
|
||||
fn exiting_waits_for_work_in_flight_and_starts_no_more() {
|
||||
if std::env::var("YAAK_EXIT_GATE_CHILD").is_err() {
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", SELF, "--test-threads", "1"])
|
||||
.env("YAAK_EXIT_GATE_CHILD", "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
return;
|
||||
}
|
||||
|
||||
// Busy work, taking the gate again as soon as it lets go, as the event loop does.
|
||||
let busy = Arc::new(AtomicBool::new(false));
|
||||
for _ in 0..4 {
|
||||
let busy = busy.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
let _held = hold();
|
||||
busy.store(true, Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
}
|
||||
// A batch in flight, a slow one.
|
||||
let (holding_tx, holding_rx) = channel();
|
||||
let (finished_tx, finished_rx) = channel();
|
||||
std::thread::spawn(move || {
|
||||
let _batch = hold();
|
||||
holding_tx.send(()).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
finished_tx.send(Instant::now()).unwrap();
|
||||
});
|
||||
holding_rx.recv().unwrap();
|
||||
while !busy.load(Ordering::SeqCst) {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
|
||||
EXITING.store(true, Ordering::SeqCst);
|
||||
assert!(wait_for_work(Duration::from_secs(5)), "not starved by the busy work");
|
||||
let finished = finished_rx.try_recv().expect("the batch finished before the gate shut");
|
||||
assert!(finished <= Instant::now());
|
||||
// Nothing holds the gate after, the busy work included: it is all parked.
|
||||
assert!(GATE.try_read().is_err(), "shut for good");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::bodies;
|
||||
use crate::db::ProxyQueryManager;
|
||||
use crate::db::{ProxyQueryManager, Stores};
|
||||
use crate::models::{Flow, FlowBody};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
@@ -31,6 +31,10 @@ pub struct FlowFilter {
|
||||
/// it ran in (`fieldwork`).
|
||||
#[ts(optional)]
|
||||
pub app: Option<Vec<String>>,
|
||||
/// Only flows from a process that ran in one of these working directories: the whole path,
|
||||
/// or its folder's name in any case (`fieldwork`). With `app`, a program in a folder.
|
||||
#[ts(optional)]
|
||||
pub cwd: Option<Vec<String>>,
|
||||
/// Only flows from macOS's own daemons (true), or none of them (false), as [`is_system`]
|
||||
/// tells them by their executable.
|
||||
#[ts(optional)]
|
||||
@@ -65,8 +69,8 @@ pub struct FlowFilter {
|
||||
}
|
||||
|
||||
impl FlowFilter {
|
||||
/// The filter from a query string's `q`, `host`, `under`, `app`, `system`, `method`,
|
||||
/// `status`, `limit`, `after` and `before`. `under` and `app` may repeat.
|
||||
/// The filter from a query string's `q`, `host`, `under`, `app`, `cwd`, `system`, `method`,
|
||||
/// `status`, `limit`, `after` and `before`. `under`, `app` and `cwd` may repeat.
|
||||
pub fn from_query(query: &str) -> Result<Self, String> {
|
||||
let mut filter = Self::default();
|
||||
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
|
||||
@@ -76,6 +80,7 @@ impl FlowFilter {
|
||||
"host" => filter.host = value,
|
||||
"under" => filter.under.get_or_insert_default().extend(value),
|
||||
"app" => filter.app.get_or_insert_default().extend(value),
|
||||
"cwd" => filter.cwd.get_or_insert_default().extend(value),
|
||||
"system" => {
|
||||
filter.system = value
|
||||
.map(|v| v.parse().map_err(|_| format!("Invalid system {v:?}")))
|
||||
@@ -116,7 +121,11 @@ impl FlowFilter {
|
||||
query.append_pair(key, value);
|
||||
}
|
||||
}
|
||||
for (key, values) in [("under", &self.under), ("app", &self.app)] {
|
||||
for (key, values) in [
|
||||
("under", &self.under),
|
||||
("app", &self.app),
|
||||
("cwd", &self.cwd),
|
||||
] {
|
||||
for value in values.iter().flatten() {
|
||||
query.append_pair(key, value);
|
||||
}
|
||||
@@ -144,6 +153,7 @@ impl FlowFilter {
|
||||
|| given(&self.status)
|
||||
|| self.under.is_some()
|
||||
|| self.app.is_some()
|
||||
|| self.cwd.is_some()
|
||||
|| self.system.is_some()
|
||||
|| self.tunnelled.is_some()
|
||||
|| self.any.as_ref().is_some_and(|groups| groups.iter().any(FlowFilter::narrows))
|
||||
@@ -224,6 +234,19 @@ impl FlowFilter {
|
||||
}
|
||||
sql.push(')');
|
||||
}
|
||||
if let Some(cwds) = &self.cwd {
|
||||
if has_cwd && !cwds.is_empty() {
|
||||
let marks = vec!["?"; cwds.len()].join(", ");
|
||||
sql.push_str(&format!(
|
||||
" AND (client_cwd IN ({marks}) OR lower(folder_name(client_cwd)) IN ({marks}))"
|
||||
));
|
||||
params.extend(cwds.iter().map(|c| c.clone().into()));
|
||||
params.extend(cwds.iter().map(|c| c.to_lowercase().into()));
|
||||
} else {
|
||||
// None, or a database from before the column, which has no folders.
|
||||
sql.push_str(" AND 0");
|
||||
}
|
||||
}
|
||||
match self.system {
|
||||
Some(true) => sql.push_str(" AND is_system(client_bundle_id, client_path)"),
|
||||
Some(false) => sql.push_str(" AND NOT is_system(client_bundle_id, client_path)"),
|
||||
@@ -665,6 +688,142 @@ pub fn clear_mark_in(db: &ProxyQueryManager) -> i64 {
|
||||
db.with_conn(|c| clear_mark(c.conn().resolve()))
|
||||
}
|
||||
|
||||
/// When captured traffic takes more than `cap` bytes, as [`Stores::used_bytes`] counts them,
|
||||
/// deletes the flows written first, with their bodies and messages: as many as the average flow
|
||||
/// says would bring it under, from one to [`DELETE_BATCH`]. Returns the ids deleted, none once it
|
||||
/// is under or no flow is left, so a caller sweeps a batch per call until then. Cleared flows are
|
||||
/// left to [`delete_cleared`], and a stream still open is never swept: its writer would go on
|
||||
/// adding messages to it.
|
||||
pub fn sweep_oldest(stores: &Stores, cap: u64) -> Result<Vec<String>, String> {
|
||||
// Bodies a sweep that failed partway left behind go first: they count against the cap.
|
||||
let pending = pending_sweeps(stores)?;
|
||||
delete_swept_bodies(stores, &pending)?;
|
||||
let used = stores.used_bytes()?;
|
||||
if used <= cap {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let count = count(&stores.db)? as u64;
|
||||
if count == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let average = (used / count).max(1);
|
||||
let batch = (used - cap).div_ceil(average).clamp(1, DELETE_BATCH as u64);
|
||||
let rows = sweepable(stores, batch as usize)?;
|
||||
let deleted = delete_swept_rows(stores, rows)?;
|
||||
delete_swept_bodies(stores, &deleted)?;
|
||||
Ok(deleted)
|
||||
}
|
||||
|
||||
/// Flows whose rows a sweep deleted and whose bodies it may not have, at most a batch of them.
|
||||
pub(crate) fn pending_sweeps(stores: &Stores) -> Result<Vec<String>, String> {
|
||||
stores
|
||||
.db
|
||||
.with_conn(|c| {
|
||||
let conn = c.conn().resolve();
|
||||
let mut stmt = conn.prepare("SELECT flow_id FROM flow_sweep_pending LIMIT ?")?;
|
||||
stmt.query_map([DELETE_BATCH as i64], |r| r.get(0))?.collect::<rusqlite::Result<_>>()
|
||||
})
|
||||
.map_err(sweep_failed)
|
||||
}
|
||||
|
||||
/// A stream still open: it has no end yet, and its writer goes on adding messages to it.
|
||||
const OPEN_STREAM: &str =
|
||||
"stream_kind IS NOT NULL AND elapsed_ms IS NULL AND error IS NULL AND NOT cancelled";
|
||||
|
||||
/// Fail messages for sweeping, all of a kind.
|
||||
fn sweep_failed(e: impl std::fmt::Display) -> String {
|
||||
format!("Failed to delete the oldest flows: {e}")
|
||||
}
|
||||
|
||||
/// Up to `limit` of the oldest flows that are neither cleared nor an open stream, by rowid.
|
||||
pub(crate) fn sweepable(stores: &Stores, limit: usize) -> Result<Vec<(i64, String)>, String> {
|
||||
stores
|
||||
.db
|
||||
.with_conn(|c| {
|
||||
let conn = c.conn().resolve();
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT rowid, id FROM flows WHERE rowid > ?
|
||||
AND NOT ({OPEN_STREAM})
|
||||
ORDER BY rowid LIMIT ?"
|
||||
))?;
|
||||
stmt.query_map(rusqlite::params![clear_mark(conn), limit as i64], |r| {
|
||||
Ok((r.get(0)?, r.get(1)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()
|
||||
})
|
||||
.map_err(sweep_failed)
|
||||
}
|
||||
|
||||
/// Deletes the flows' rows and their messages' rows in one transaction, first, so nothing
|
||||
/// written for them after this has an owner left to count under, and records them as pending
|
||||
/// until their bodies go, so a failure before then is finished by the next sweep. A flow that
|
||||
/// changed or was cleared since it was chosen is kept. Returns the ids deleted.
|
||||
pub(crate) fn delete_swept_rows(
|
||||
stores: &Stores,
|
||||
rows: Vec<(i64, String)>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
stores
|
||||
.db
|
||||
.with_tx(|c| {
|
||||
let conn = c.conn().resolve();
|
||||
let mut delete = conn.prepare(&format!(
|
||||
"DELETE FROM flows WHERE rowid = ? AND id = ?
|
||||
AND NOT ({OPEN_STREAM})"
|
||||
))?;
|
||||
let mut delete_messages =
|
||||
conn.prepare("DELETE FROM flow_messages WHERE flow_id = ?")?;
|
||||
let mut pending =
|
||||
conn.prepare("INSERT OR IGNORE INTO flow_sweep_pending (flow_id) VALUES (?)")?;
|
||||
let mut deleted = Vec::with_capacity(rows.len());
|
||||
for (rowid, id) in rows {
|
||||
if delete.execute(rusqlite::params![rowid, id])? > 0 {
|
||||
delete_messages.execute([&id])?;
|
||||
pending.execute([&id])?;
|
||||
deleted.push(id);
|
||||
}
|
||||
}
|
||||
Ok::<_, yaak_database::Error>(deleted)
|
||||
})
|
||||
.map_err(sweep_failed)
|
||||
}
|
||||
|
||||
/// Deletes the bodies and message payloads of flows whose rows are gone, then once more the
|
||||
/// message rows: anything a writer added for them while the rows went is an orphan, which
|
||||
/// would otherwise go on counting against the cap with nothing to sweep it by. The flows stop
|
||||
/// being pending once this is done.
|
||||
pub(crate) fn delete_swept_bodies(stores: &Stores, ids: &[String]) -> Result<(), String> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
stores
|
||||
.blobs
|
||||
.with_tx(|b| {
|
||||
for id in ids {
|
||||
b.delete_chunks(&Flow::body_id(id, FlowBody::Request))?;
|
||||
b.delete_chunks(&Flow::body_id(id, FlowBody::Response))?;
|
||||
b.delete_chunks_like(&format!("{id}.msg.%"))?;
|
||||
}
|
||||
Ok::<_, yaak_models::error::Error>(())
|
||||
})
|
||||
.map_err(|e| sweep_failed(format!("flow bodies: {e}")))?;
|
||||
stores
|
||||
.db
|
||||
.with_tx(|c| {
|
||||
let conn = c.conn().resolve();
|
||||
let mut orphans = conn.prepare(
|
||||
"DELETE FROM flow_messages WHERE flow_id = ?
|
||||
AND NOT EXISTS (SELECT 1 FROM flows WHERE flows.id = flow_messages.flow_id)",
|
||||
)?;
|
||||
let mut done = conn.prepare("DELETE FROM flow_sweep_pending WHERE flow_id = ?")?;
|
||||
for id in ids {
|
||||
orphans.execute([id])?;
|
||||
done.execute([id])?;
|
||||
}
|
||||
Ok::<_, yaak_database::Error>(())
|
||||
})
|
||||
.map_err(sweep_failed)
|
||||
}
|
||||
|
||||
/// A flow by id, with its number. None once it is cleared, though its row may not be deleted
|
||||
/// yet.
|
||||
pub fn find(db: &ProxyQueryManager, flow_id: &str) -> Option<Flow> {
|
||||
@@ -1014,6 +1173,42 @@ mod tests {
|
||||
assert_eq!(app(&["com.google.Chrome", "/usr/bin/curl"]), 3);
|
||||
}
|
||||
|
||||
/// A program in a folder: its working directory by the whole path, or its folder's name in
|
||||
/// any case, along with whatever else the filter asks.
|
||||
#[test]
|
||||
fn cwd_matches_a_path_or_a_folder_name() {
|
||||
let node_in = |cwd: Option<&str>| Flow {
|
||||
client_name: Some("node".into()),
|
||||
client_path: Some("/usr/local/bin/node".into()),
|
||||
client_cwd: cwd.map(String::from),
|
||||
..flow("https://example.com/", "GET", Some(200), None)
|
||||
};
|
||||
let (_dir, db) = db_of(vec![
|
||||
node_in(Some("/Users/ada/Workspace/fieldwork")),
|
||||
node_in(Some("/Users/ada/Workspace/fieldwork")),
|
||||
node_in(Some("/Users/ada/Workspace/Ledger")),
|
||||
node_in(None),
|
||||
Flow { client_cwd: Some("/tmp/fieldwork".into()), ..node_in(None) },
|
||||
Flow { client_path: Some("/usr/bin/curl".into()), ..node_in(Some("/tmp/ledger")) },
|
||||
]);
|
||||
let count = |app: Option<&str>, cwds: &[&str]| {
|
||||
let cwd = Some(cwds.iter().map(|c| c.to_string()).collect());
|
||||
let app = app.map(|a| vec![a.to_string()]);
|
||||
urls(&db, FlowFilter { app, cwd, ..Default::default() }).len()
|
||||
};
|
||||
assert_eq!(count(None, &["/Users/ada/Workspace/fieldwork"]), 2, "the whole path");
|
||||
assert_eq!(count(None, &["/users/ada/workspace/fieldwork"]), 0, "a path exactly");
|
||||
assert_eq!(count(None, &["FieldWork"]), 3, "a folder name, any case");
|
||||
assert_eq!(count(None, &["fieldwork", "ledger"]), 5, "any of them");
|
||||
assert_eq!(count(Some("/usr/local/bin/node"), &["ledger"]), 1, "and the program");
|
||||
assert_eq!(count(Some("/usr/bin/curl"), &["ledger"]), 1);
|
||||
assert_eq!(count(None, &[]), 0);
|
||||
let query = FlowFilter { cwd: Some(vec!["a".into(), "/b".into()]), ..Default::default() };
|
||||
assert_eq!(query.to_query(), "cwd=a&cwd=%2Fb");
|
||||
assert_eq!(FlowFilter::from_query(&query.to_query()).unwrap(), query);
|
||||
assert!(query.narrows());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_search_pages_back_and_counts_what_it_matches() {
|
||||
// Every third flow is a POST, newest last.
|
||||
@@ -1460,4 +1655,54 @@ mod tests {
|
||||
("/wD+", BodyEncoding::Base64, 3)
|
||||
);
|
||||
}
|
||||
|
||||
/// Sweeping takes the flows written first, with their bodies, until the traffic is under the
|
||||
/// cap, and no more; under it, nothing goes.
|
||||
#[test]
|
||||
fn sweeping_deletes_the_oldest_until_under_the_cap() {
|
||||
use yaak_database::UpdateSource;
|
||||
use yaak_models::blob_manager::BodyChunkWriter;
|
||||
const BODY: usize = 64 * 1024;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let stores = Stores::open(dir.path(), &crate::db::test_key()).unwrap();
|
||||
let empty = stores.used_bytes().unwrap();
|
||||
let ids: Vec<String> = (0..20).map(|i| format!("fl_{i:02}")).collect();
|
||||
for id in &ids {
|
||||
let flow = Flow { id: id.clone(), ..Default::default() };
|
||||
stores.db.with_tx(|tx| tx.upsert(&flow, &UpdateSource::Background)).unwrap();
|
||||
let body_id = Flow::body_id(id, FlowBody::Response);
|
||||
let mut writer = BodyChunkWriter::new(stores.blobs.clone(), body_id);
|
||||
writer.write(&[7; BODY]).unwrap();
|
||||
writer.finish().unwrap();
|
||||
}
|
||||
let full = stores.used_bytes().unwrap();
|
||||
assert!(full > empty + (20 * BODY) as u64, "{empty} {full}");
|
||||
|
||||
assert_eq!(sweep_oldest(&stores, full).unwrap(), Vec::<String>::new(), "under the cap");
|
||||
|
||||
let cap = (empty + full) / 2;
|
||||
let mut removed = Vec::new();
|
||||
loop {
|
||||
let swept = sweep_oldest(&stores, cap).unwrap();
|
||||
if swept.is_empty() {
|
||||
break;
|
||||
}
|
||||
removed.extend(swept);
|
||||
}
|
||||
assert!(stores.used_bytes().unwrap() <= cap);
|
||||
// About half went, oldest first, and no more than had to.
|
||||
assert_eq!(removed, ids[..removed.len()]);
|
||||
assert!((8..=11).contains(&removed.len()), "{removed:?}");
|
||||
let kept: Vec<String> = list(&stores.db, &FlowFilter::default())
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|f| f.id)
|
||||
.collect();
|
||||
assert_eq!(kept, ids[removed.len()..]);
|
||||
let bodies = stores.blobs.connect();
|
||||
let has_body = |id: &str| bodies.body_exists(&Flow::body_id(id, FlowBody::Response));
|
||||
assert!(removed.iter().all(|id| !has_body(id).unwrap()));
|
||||
assert!(kept.iter().all(|id| has_body(id).unwrap()));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -59,6 +59,18 @@ pub struct Flow {
|
||||
pub elapsed_headers_ms: Option<i32>,
|
||||
/// Milliseconds from `started_at` to the end of the response.
|
||||
pub elapsed_ms: Option<i32>,
|
||||
/// Milliseconds from `started_at` to the TCP connection to the server, and to the end of
|
||||
/// its TLS handshake. Only for intercepted HTTPS on a connection opened for this flow.
|
||||
pub elapsed_connect_ms: Option<i32>,
|
||||
pub elapsed_tls_ms: Option<i32>,
|
||||
/// Milliseconds from `started_at` to the request body being sent whole. None without one.
|
||||
pub elapsed_request_ms: Option<i32>,
|
||||
/// The client's end of its connection: `127.0.0.1:54321`.
|
||||
pub client_addr: Option<String>,
|
||||
/// The TLS negotiated with the server for intercepted HTTPS: `TLSv1.3`.
|
||||
pub upstream_tls_version: Option<String>,
|
||||
/// `TLS13_AES_128_GCM_SHA256`.
|
||||
pub upstream_tls_cipher: Option<String>,
|
||||
pub error: Option<String>,
|
||||
/// The client gave up before the response ended, by resetting its HTTP/2 stream or closing
|
||||
/// the connection. Not an error.
|
||||
@@ -244,6 +256,12 @@ impl UpsertModelInfo for Flow {
|
||||
(GrpcStatus, self.grpc_status.into()),
|
||||
(GrpcMessage, self.grpc_message.into()),
|
||||
(Tunnelled, self.tunnelled.into()),
|
||||
(ElapsedConnectMs, self.elapsed_connect_ms.into()),
|
||||
(ElapsedTlsMs, self.elapsed_tls_ms.into()),
|
||||
(ElapsedRequestMs, self.elapsed_request_ms.into()),
|
||||
(ClientAddr, self.client_addr.into()),
|
||||
(UpstreamTlsVersion, self.upstream_tls_version.into()),
|
||||
(UpstreamTlsCipher, self.upstream_tls_cipher.into()),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -281,6 +299,12 @@ impl UpsertModelInfo for Flow {
|
||||
FlowIden::GrpcStatus,
|
||||
FlowIden::GrpcMessage,
|
||||
FlowIden::Tunnelled,
|
||||
FlowIden::ElapsedConnectMs,
|
||||
FlowIden::ElapsedTlsMs,
|
||||
FlowIden::ElapsedRequestMs,
|
||||
FlowIden::ClientAddr,
|
||||
FlowIden::UpstreamTlsVersion,
|
||||
FlowIden::UpstreamTlsCipher,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -311,6 +335,12 @@ impl UpsertModelInfo for Flow {
|
||||
response_truncated: r.get("response_truncated")?,
|
||||
elapsed_headers_ms: r.get("elapsed_headers_ms")?,
|
||||
elapsed_ms: r.get("elapsed_ms")?,
|
||||
elapsed_connect_ms: added_column(r, "elapsed_connect_ms")?,
|
||||
elapsed_tls_ms: added_column(r, "elapsed_tls_ms")?,
|
||||
elapsed_request_ms: added_column(r, "elapsed_request_ms")?,
|
||||
client_addr: added_column(r, "client_addr")?,
|
||||
upstream_tls_version: added_column(r, "upstream_tls_version")?,
|
||||
upstream_tls_cipher: added_column(r, "upstream_tls_cipher")?,
|
||||
error: r.get("error")?,
|
||||
cancelled: added_column(r, "cancelled")?.unwrap_or_default(),
|
||||
saved_request_id: added_column(r, "saved_request_id")?,
|
||||
|
||||
@@ -15,6 +15,9 @@ pub struct ProxySettings {
|
||||
pub system_proxy_at_launch: bool,
|
||||
/// Bytes of each request and response body stored per flow.
|
||||
pub capture_body_limit: usize,
|
||||
/// The most captured traffic kept, in bytes of the databases' used pages; the oldest flows
|
||||
/// are deleted past it. None keeps everything.
|
||||
pub keep_traffic_bytes: Option<u64>,
|
||||
/// The HTTP versions offered to clients in intercepted HTTPS.
|
||||
pub http_version: HttpVersion,
|
||||
/// The user's decrypt entries, in order: `host:api.example.com`, `app:Google Chrome`, `*`,
|
||||
@@ -31,6 +34,7 @@ impl Default for ProxySettings {
|
||||
port: 9090,
|
||||
system_proxy_at_launch: true,
|
||||
capture_body_limit: DEFAULT_CAPTURE_BODY_LIMIT,
|
||||
keep_traffic_bytes: None,
|
||||
http_version: HttpVersion::Auto,
|
||||
decrypt: Vec::new(),
|
||||
decrypt_built_ins_removed: Vec::new(),
|
||||
@@ -178,6 +182,7 @@ mod tests {
|
||||
assert_eq!(settings.port, 9090);
|
||||
assert!(settings.system_proxy_at_launch);
|
||||
assert_eq!(settings.capture_body_limit, 10 * 1024 * 1024);
|
||||
assert_eq!(settings.keep_traffic_bytes, None, "everything is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -197,6 +202,7 @@ mod tests {
|
||||
port: 8080,
|
||||
system_proxy_at_launch: false,
|
||||
capture_body_limit: 1024,
|
||||
keep_traffic_bytes: Some(1 << 30),
|
||||
http_version: HttpVersion::Http1Only,
|
||||
decrypt: vec!["host:api.example.com".into()],
|
||||
decrypt_built_ins_removed: vec!["!host:*.zoom.us".into()],
|
||||
@@ -212,6 +218,7 @@ mod tests {
|
||||
"port": 8080,
|
||||
"systemProxyAtLaunch": false,
|
||||
"captureBodyLimit": 1024,
|
||||
"keepTrafficBytes": 1073741824,
|
||||
"httpVersion": "http1Only",
|
||||
"decrypt": ["host:api.example.com"],
|
||||
"decryptBuiltInsRemoved": ["!host:*.zoom.us"],
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Opens a terminal whose shell has the proxy's environment set, so what runs in it goes through
|
||||
//! the proxy. macOS's Terminal only for now.
|
||||
|
||||
/// The script Terminal runs: it deletes itself, exports `vars`, then becomes a fresh interactive
|
||||
/// login shell, the user's own. Fails on a name a shell could not export.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn script(vars: &[(String, String)]) -> Result<String, String> {
|
||||
let mut script = String::from("#!/bin/sh\nrm -f \"$0\"\n");
|
||||
for (name, value) in vars {
|
||||
let valid = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
if !valid {
|
||||
return Err(format!("{name:?} is not a name an environment variable can have"));
|
||||
}
|
||||
script.push_str(&format!("export {name}='{}'\n", value.replace('\'', r"'\''")));
|
||||
}
|
||||
script.push_str("exec \"${SHELL:-/bin/zsh}\" -l\n");
|
||||
Ok(script)
|
||||
}
|
||||
|
||||
/// Opens a Terminal window whose shell starts with `vars` set, through a `.command` script in
|
||||
/// the temporary directory that deletes itself as it runs.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn open(vars: &[(String, String)]) -> Result<(), String> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let script = script(vars)?;
|
||||
let name = format!("yaak-proxy-{}.command", yaak_database::generate_prefixed_id("sh"));
|
||||
let path = std::env::temp_dir().join(name);
|
||||
let fail = |e: std::io::Error| format!("Failed to write {}: {e}", path.display());
|
||||
std::fs::write(&path, script).map_err(fail)?;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).map_err(fail)?;
|
||||
let output = std::process::Command::new("/usr/bin/open")
|
||||
.args(["-a", "Terminal"])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run open: {e}"))?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
Err(if stderr.is_empty() { format!("open exited with {}", output.status) } else { stderr })
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn open(_vars: &[(String, String)]) -> Result<(), String> {
|
||||
Err("Opening a terminal with the proxy set is only supported on macOS so far".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_script_exports_each_variable_quoted_then_starts_a_login_shell() {
|
||||
let vars = vec![
|
||||
("HTTPS_PROXY".to_string(), "http://127.0.0.1:9090".to_string()),
|
||||
("NOTE".to_string(), "it's $HOME".to_string()),
|
||||
];
|
||||
assert_eq!(
|
||||
script(&vars).unwrap(),
|
||||
"#!/bin/sh\nrm -f \"$0\"\nexport HTTPS_PROXY='http://127.0.0.1:9090'\n\
|
||||
export NOTE='it'\\''s $HOME'\nexec \"${SHELL:-/bin/zsh}\" -l\n"
|
||||
);
|
||||
for name in ["", "1A", "A B", "A;rm"] {
|
||||
assert!(script(&[(name.to_string(), "x".to_string())]).is_err(), "{name:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_script_runs_as_a_shell_sets_them() {
|
||||
let vars = vec![("YAAK_TEST".to_string(), "a 'b' $c".to_string())];
|
||||
// Without deleting itself, as `$0` is no script here, or starting a shell.
|
||||
let script = script(&vars)
|
||||
.unwrap()
|
||||
.replace("rm -f \"$0\"\n", "")
|
||||
.replace("exec \"${SHELL:-/bin/zsh}\" -l\n", "");
|
||||
let output = std::process::Command::new("sh")
|
||||
.args(["-c", &format!("{script}printf %s \"$YAAK_TEST\"")])
|
||||
.output();
|
||||
// Only where there is a POSIX shell.
|
||||
if let Ok(output) = output {
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout), "a 'b' $c");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user