mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-28 11:12:38 +01:00
Proxy GUI pass (#793)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
96ab0a8a60
commit
e82ffc53ad
73 files changed
+6003
-1257
No files matched your search
@@ -5,8 +5,8 @@ use ts_rs::TS;
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub enum GlobalAction {
|
||||
ProxyStart,
|
||||
ProxyStop,
|
||||
/// Pauses or resumes storing flows.
|
||||
RecordingToggle,
|
||||
FlowsClear,
|
||||
}
|
||||
|
||||
@@ -33,17 +33,11 @@ fn default_hotkey(mac: &str, other: &str) -> Option<String> {
|
||||
pub fn all_global_actions() -> Vec<(ActionInvocation, ActionMetadata)> {
|
||||
vec![
|
||||
(
|
||||
ActionInvocation::Global { action: GlobalAction::ProxyStart },
|
||||
ActionInvocation::Global { action: GlobalAction::RecordingToggle },
|
||||
ActionMetadata {
|
||||
label: "Start Proxy".into(),
|
||||
default_hotkey: default_hotkey("Meta+Shift+P", "Ctrl+Shift+P"),
|
||||
},
|
||||
),
|
||||
(
|
||||
ActionInvocation::Global { action: GlobalAction::ProxyStop },
|
||||
ActionMetadata {
|
||||
label: "Stop Proxy".into(),
|
||||
default_hotkey: default_hotkey("Meta+Shift+S", "Ctrl+Shift+S"),
|
||||
label: "Pause or Resume Recording".into(),
|
||||
// Not Cmd+Shift+R, which reloads the window in development builds.
|
||||
default_hotkey: default_hotkey("Meta+R", "Ctrl+Shift+R"),
|
||||
},
|
||||
),
|
||||
(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,8 @@
|
||||
use crate::bodies::{self, DecodedBody};
|
||||
use crate::ca::CaStatus;
|
||||
use crate::control::{
|
||||
self, ControlInfo, ControlStatus, ErrorBody, StartRequest, SystemProxyRequest, TRUNCATED_HEADER,
|
||||
self, ControlInfo, ControlStatus, ErrorBody, RecordingRequest, StartRequest,
|
||||
SystemProxyRequest, TRUNCATED_HEADER,
|
||||
};
|
||||
use crate::db::ProxyQueryManager;
|
||||
use crate::flows::{self, FlowDetail, FlowFilter};
|
||||
@@ -127,6 +128,11 @@ impl ControlClient {
|
||||
self.post("/ca/trust", &serde_json::json!({})).await
|
||||
}
|
||||
|
||||
/// Resumes or pauses storing flows in the owner's engine.
|
||||
pub async fn set_recording(&self, enabled: bool) -> Result<ControlStatus, String> {
|
||||
self.post("/recording", &RecordingRequest { enabled }).await
|
||||
}
|
||||
|
||||
pub async fn system_proxy(&self) -> Result<SystemProxyStatus, String> {
|
||||
self.get("/system-proxy").await
|
||||
}
|
||||
|
||||
@@ -205,6 +205,8 @@ pub struct ControlStatus {
|
||||
pub proxy_port: Option<u16>,
|
||||
/// The port the engine starts on.
|
||||
pub configured_port: u16,
|
||||
/// Flows are stored. Paused, traffic still passes through, unrecorded.
|
||||
pub recording: bool,
|
||||
pub flow_count: usize,
|
||||
pub ca: CaStatus,
|
||||
/// `None` when it could not be read.
|
||||
@@ -222,6 +224,11 @@ pub struct SystemProxyRequest {
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RecordingRequest {
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ClearResponse {
|
||||
/// How many flows were deleted.
|
||||
@@ -344,11 +351,14 @@ impl ControlServer {
|
||||
}
|
||||
|
||||
pub(crate) fn already_owned(owner: &ControlInfo) -> String {
|
||||
let who = match owner.owner {
|
||||
format!("The proxy is already running in {} (pid {})", owner_name(owner.owner), owner.pid)
|
||||
}
|
||||
|
||||
pub(crate) fn owner_name(owner: Owner) -> &'static str {
|
||||
match owner {
|
||||
Owner::App => "Yaak Proxy",
|
||||
Owner::Cli => "the yaak CLI",
|
||||
};
|
||||
format!("The proxy is already running in {who} (pid {})", owner.pid)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ControlServer {
|
||||
@@ -472,6 +482,11 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
|
||||
let _ = state.stop_tx.send(());
|
||||
json(&status(ctx).await?)
|
||||
}
|
||||
(&Method::POST, ["recording"]) => {
|
||||
let body: RecordingRequest = read_json(req).await?;
|
||||
ctx.set_recording(body.enabled);
|
||||
json(&status(ctx).await?)
|
||||
}
|
||||
(&Method::GET, ["flows"]) => {
|
||||
let filter = FlowFilter::from_query(&query).map_err(bad_request)?;
|
||||
json(&flows::list(&ctx.db, &filter)?)
|
||||
@@ -509,6 +524,7 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
|
||||
let ca = CaStore::load_or_create(&ctx.ca_dir())
|
||||
.map_err(|e| format!("Failed to load proxy CA: {e}"))?;
|
||||
ca::trust(ca.cert_path()).await.map_err(bad_request)?;
|
||||
ctx.forget_passthrough();
|
||||
json(&ca::status(ca.cert_path()).await?)
|
||||
}
|
||||
(&Method::GET, ["system-proxy"]) => {
|
||||
@@ -541,6 +557,7 @@ async fn status(ctx: &ProxyCtx) -> Result<ControlStatus, ApiError> {
|
||||
state: if proxy_port.is_some() { ProxyState::Running } else { ProxyState::Stopped },
|
||||
proxy_port,
|
||||
configured_port: ctx.settings()?.port,
|
||||
recording: ctx.recording(),
|
||||
flow_count: flows::count(&ctx.db)?,
|
||||
ca,
|
||||
system_proxy,
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::models::{Flow, find_header};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
use ts_rs::TS;
|
||||
use yaak_models::models::{HttpRequest, HttpRequestHeader, HttpUrlParameter};
|
||||
|
||||
// The client's body types (`apps/yaak-client/lib/model_util.ts`).
|
||||
@@ -28,16 +29,18 @@ const HOP_BY_HOP: &[&str] = &[
|
||||
/// Yaak works these out itself when it sends the request.
|
||||
const AUTOMATIC: &[&str] = &["host", "content-length", "accept-encoding"];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct DroppedHeader {
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
pub reason: DropReason,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub enum DropReason {
|
||||
/// Only meant for the hop between the app and the proxy.
|
||||
HopByHop,
|
||||
@@ -72,8 +75,8 @@ pub fn flow_to_request(flow: &Flow, body: &DecodedBody) -> Conversion {
|
||||
));
|
||||
}
|
||||
|
||||
// No name, as in Yaak, which then shows the URL.
|
||||
let request = HttpRequest {
|
||||
name: default_name(&url),
|
||||
method: flow.method.clone(),
|
||||
url,
|
||||
url_parameters,
|
||||
@@ -228,16 +231,6 @@ fn graphql_body(flow: &Flow, text: &str) -> Option<BTreeMap<String, Value>> {
|
||||
Some(fields)
|
||||
}
|
||||
|
||||
/// The path, or the host for a request to the root.
|
||||
fn default_name(url: &str) -> String {
|
||||
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
|
||||
match rest.split_once('/') {
|
||||
Some((_, path)) if !path.is_empty() => format!("/{path}"),
|
||||
Some((host, _)) => host.to_string(),
|
||||
None => rest.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -287,7 +280,7 @@ mod tests {
|
||||
let r = &c.request;
|
||||
assert_eq!(r.method, "GET");
|
||||
assert_eq!(r.url, "https://api.github.com/search/issues");
|
||||
assert_eq!(r.name, "/search/issues");
|
||||
assert_eq!(r.name, "");
|
||||
let params: Vec<(&str, &str)> =
|
||||
r.url_parameters.iter().map(|p| (p.name.as_str(), p.value.as_str())).collect();
|
||||
assert_eq!(params, vec![("q", "is:open label:bug"), ("per_page", "5")]);
|
||||
@@ -391,7 +384,7 @@ mod tests {
|
||||
{ "enabled": true, "name": "note", "value": "hello world!" },
|
||||
])
|
||||
);
|
||||
assert_eq!(c.request.name, "/login");
|
||||
assert_eq!(c.request.name, "", "unnamed, so Yaak shows its URL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -412,7 +405,7 @@ mod tests {
|
||||
let c = flow_to_request(&f, &body("hello"));
|
||||
assert_eq!(c.request.body_type.as_deref(), Some("other"));
|
||||
assert_eq!(c.request.body["text"], "hello");
|
||||
assert_eq!(c.request.name, "x.test");
|
||||
assert_eq!(c.request.name, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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::time::Duration;
|
||||
@@ -76,10 +77,23 @@ pub fn open_blobs_read_only(path: &Path) -> Result<BlobManager> {
|
||||
Ok(BlobManager::new(readers.clone(), readers))
|
||||
}
|
||||
|
||||
/// `sidebar_path(url)`, the app sidebar's place for a URL, for filtering by its nodes.
|
||||
fn add_functions(conn: &mut rusqlite::Connection) -> rusqlite::Result<()> {
|
||||
conn.create_scalar_function(
|
||||
"sidebar_path",
|
||||
1,
|
||||
FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
|
||||
|ctx| Ok(crate::flows::sidebar_path(&ctx.get::<String>(0)?)),
|
||||
)
|
||||
}
|
||||
|
||||
fn read_only_pool(path: &Path) -> Result<SqlitePool> {
|
||||
let manager = SqliteConnectionManager::file(path)
|
||||
.with_flags(OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX)
|
||||
.with_init(|conn| conn.busy_timeout(Duration::from_millis(5000)));
|
||||
.with_init(|conn| {
|
||||
conn.busy_timeout(Duration::from_millis(5000))?;
|
||||
add_functions(conn)
|
||||
});
|
||||
Pool::builder()
|
||||
.max_size(2)
|
||||
.connection_timeout(Duration::from_secs(10))
|
||||
@@ -91,7 +105,8 @@ fn file_pool(path: &Path, max_size: u32) -> Result<SqlitePool> {
|
||||
let manager = SqliteConnectionManager::file(path).with_init(|conn| {
|
||||
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||
conn.pragma_update(None, "synchronous", "NORMAL")?;
|
||||
conn.busy_timeout(Duration::from_millis(5000))
|
||||
conn.busy_timeout(Duration::from_millis(5000))?;
|
||||
add_functions(conn)
|
||||
});
|
||||
Pool::builder()
|
||||
.max_size(max_size)
|
||||
@@ -117,10 +132,14 @@ mod tests {
|
||||
let path = dir.path().join("proxy.db");
|
||||
drop(ProxyQueryManager::new(&path).unwrap());
|
||||
|
||||
// As a build from before the saved request column left it.
|
||||
// As a build from before the saved request and client columns left it.
|
||||
let conn = Connection::open(&path).unwrap();
|
||||
conn.execute_batch(
|
||||
"ALTER TABLE flows DROP COLUMN saved_request_id;
|
||||
ALTER TABLE flows DROP COLUMN client_pid;
|
||||
ALTER TABLE flows DROP COLUMN client_name;
|
||||
ALTER TABLE flows DROP COLUMN client_bundle_id;
|
||||
ALTER TABLE flows DROP COLUMN client_path;
|
||||
INSERT INTO flows (id, url, method) VALUES ('fl_old', 'https://example.com', 'GET');",
|
||||
)
|
||||
.unwrap();
|
||||
@@ -130,6 +149,7 @@ mod tests {
|
||||
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));
|
||||
assert_eq!((flows[0].client_pid, flows[0].client_name.as_deref()), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -169,6 +189,22 @@ mod tests {
|
||||
|
||||
let flow_columns = columns(&conn, "flows");
|
||||
assert!(flow_columns.contains(&"response_truncated".to_string()));
|
||||
for column in [
|
||||
"client_pid",
|
||||
"client_name",
|
||||
"client_bundle_id",
|
||||
"client_path",
|
||||
] {
|
||||
assert!(flow_columns.contains(&column.to_string()), "{column} in {flow_columns:?}");
|
||||
}
|
||||
let indexes: Vec<String> = conn
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'flows' AND sql IS NOT NULL")
|
||||
.unwrap()
|
||||
.query_map([], |r| r.get(0))
|
||||
.unwrap()
|
||||
.map(|i| i.unwrap())
|
||||
.collect();
|
||||
assert_eq!(indexes, vec!["idx_flows_started_at_id"]);
|
||||
assert!(!flow_columns.iter().any(|c| c.contains("body")), "{flow_columns:?}");
|
||||
|
||||
let journal_mode: String = conn.query_row("PRAGMA journal_mode", [], |r| r.get(0)).unwrap();
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::db::ProxyQueryManager;
|
||||
use crate::models::{Flow, FlowBody, FlowIden};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use rusqlite::types::Value;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ts_rs::TS;
|
||||
use yaak_database::UpsertModelInfo;
|
||||
@@ -13,9 +14,21 @@ use yaak_models::blob_manager::BlobManager;
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct FlowFilter {
|
||||
/// Search terms, any case, each of which must match the URL (host, path or query), the
|
||||
/// method, the status (`404`, `40`, `4xx`) or the content type: `stripe post 4xx`.
|
||||
#[ts(optional)]
|
||||
pub q: Option<String>,
|
||||
/// Part of the host, any case: `stripe` matches `api.stripe.com`.
|
||||
#[ts(optional)]
|
||||
pub host: Option<String>,
|
||||
/// Only flows under one of these hosts or paths, as the app's sidebar names them:
|
||||
/// `api.stripe.com` or `api.stripe.com/v1/charges`, with any port after the host.
|
||||
#[ts(optional)]
|
||||
pub under: Option<Vec<String>>,
|
||||
/// Only flows from one of these apps, by bundle id, or by path for a process outside an
|
||||
/// app bundle.
|
||||
#[ts(optional)]
|
||||
pub app: Option<Vec<String>>,
|
||||
/// The method, any case.
|
||||
#[ts(optional)]
|
||||
pub method: Option<String>,
|
||||
@@ -36,14 +49,17 @@ pub struct FlowFilter {
|
||||
}
|
||||
|
||||
impl FlowFilter {
|
||||
/// The filter from a query string's `host`, `method`, `status`, `limit`, `after` and
|
||||
/// `before`.
|
||||
/// The filter from a query string's `q`, `host`, `under`, `app`, `method`, `status`,
|
||||
/// `limit`, `after` and `before`. `under` and `app` 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()) {
|
||||
let value = Some(value.into_owned()).filter(|v| !v.is_empty());
|
||||
match key.as_ref() {
|
||||
"q" => filter.q = value,
|
||||
"host" => filter.host = value,
|
||||
"under" => filter.under.get_or_insert_default().extend(value),
|
||||
"app" => filter.app.get_or_insert_default().extend(value),
|
||||
"method" => filter.method = value,
|
||||
"status" => filter.status = value,
|
||||
"after" => filter.after = value,
|
||||
@@ -62,8 +78,17 @@ impl FlowFilter {
|
||||
pub fn to_query(&self) -> String {
|
||||
let mut query = url::form_urlencoded::Serializer::new(String::new());
|
||||
let limit = self.limit.map(|l| l.to_string());
|
||||
for (key, value) in [("q", &self.q), ("host", &self.host)] {
|
||||
if let Some(value) = value {
|
||||
query.append_pair(key, value);
|
||||
}
|
||||
}
|
||||
for (key, values) in [("under", &self.under), ("app", &self.app)] {
|
||||
for value in values.iter().flatten() {
|
||||
query.append_pair(key, value);
|
||||
}
|
||||
}
|
||||
for (key, value) in [
|
||||
("host", &self.host),
|
||||
("method", &self.method),
|
||||
("status", &self.status),
|
||||
("limit", &limit),
|
||||
@@ -77,56 +102,175 @@ impl FlowFilter {
|
||||
query.finish()
|
||||
}
|
||||
|
||||
pub fn matches(&self, flow: &Flow) -> bool {
|
||||
if let Some(host) = &self.host
|
||||
&& !host_of(&flow.url).to_ascii_lowercase().contains(&host.to_ascii_lowercase())
|
||||
{
|
||||
return false;
|
||||
/// Narrows more than `after`, `before` and `limit` do, so it covers fewer than all flows.
|
||||
pub fn narrows(&self) -> bool {
|
||||
let given = |v: &Option<String>| v.as_deref().is_some_and(|v| !v.trim().is_empty());
|
||||
given(&self.q)
|
||||
|| given(&self.host)
|
||||
|| given(&self.method)
|
||||
|| given(&self.status)
|
||||
|| self.under.is_some()
|
||||
|| self.app.is_some()
|
||||
}
|
||||
|
||||
/// The SQL condition for every field but `after`, `before` and `limit`, and its parameters.
|
||||
fn condition(&self) -> (String, Vec<Value>) {
|
||||
let mut sql = String::from("1");
|
||||
let mut params: Vec<Value> = Vec::new();
|
||||
for term in self.q.iter().flat_map(|q| q.split_whitespace()) {
|
||||
let term = term.to_lowercase();
|
||||
sql.push_str(
|
||||
" AND (instr(lower(url), ?) > 0 OR lower(method) = ? \
|
||||
OR instr(lower(content_type), ?) > 0",
|
||||
);
|
||||
params.extend([
|
||||
term.clone().into(),
|
||||
term.clone().into(),
|
||||
term.clone().into(),
|
||||
]);
|
||||
if let Some(status) = status_condition(&term, &mut params) {
|
||||
sql.push_str(" OR ");
|
||||
sql.push_str(&status);
|
||||
}
|
||||
sql.push(')');
|
||||
}
|
||||
if let Some(method) = &self.method
|
||||
&& !flow.method.eq_ignore_ascii_case(method)
|
||||
{
|
||||
return false;
|
||||
if let Some(host) = self.host.as_deref().filter(|h| !h.is_empty()) {
|
||||
sql.push_str(&format!(" AND instr(lower({HOST_SQL}), ?) > 0"));
|
||||
params.push(host.to_lowercase().into());
|
||||
}
|
||||
if let Some(under) = &self.under {
|
||||
// The node itself, or anything below it, by the sidebar's rules.
|
||||
let mut any = Vec::new();
|
||||
for node in under {
|
||||
let node = normalize_node(node);
|
||||
any.push("(sidebar_path(url) = ? OR substr(sidebar_path(url), 1, ?) = ?)");
|
||||
let below = format!("{node}/");
|
||||
params.extend([
|
||||
node.into(),
|
||||
(below.chars().count() as i64).into(),
|
||||
below.into(),
|
||||
]);
|
||||
}
|
||||
let any = if any.is_empty() { "0".to_string() } else { any.join(" OR ") };
|
||||
sql.push_str(&format!(" AND ({any})"));
|
||||
}
|
||||
if let Some(apps) = &self.app {
|
||||
let marks = vec!["?"; apps.len()].join(", ");
|
||||
sql.push_str(&format!(" AND coalesce(client_bundle_id, client_path) IN ({marks})"));
|
||||
params.extend(apps.iter().map(|a| a.clone().into()));
|
||||
}
|
||||
if let Some(method) = self.method.as_deref().filter(|m| !m.is_empty()) {
|
||||
sql.push_str(" AND lower(method) = ?");
|
||||
params.push(method.to_lowercase().into());
|
||||
}
|
||||
match self.status.as_deref().map(str::trim) {
|
||||
None | Some("") => true,
|
||||
Some(s) if s.eq_ignore_ascii_case("error") => flow.error.is_some(),
|
||||
Some(s) => match (flow.status, s.to_ascii_lowercase().strip_suffix("xx")) {
|
||||
(Some(status), Some(class)) => class.parse() == Ok(status / 100),
|
||||
(Some(status), None) => s.parse() == Ok(status),
|
||||
(None, _) => false,
|
||||
None | Some("") => {}
|
||||
Some(s) if s.eq_ignore_ascii_case("error") => sql.push_str(" AND error IS NOT NULL"),
|
||||
// A whole status or a class, not the start of one as a search term may be.
|
||||
Some(s) if s.len() == 3 => match status_condition(&s.to_ascii_lowercase(), &mut params)
|
||||
{
|
||||
Some(status) => {
|
||||
sql.push_str(" AND ");
|
||||
sql.push_str(&status);
|
||||
}
|
||||
None => sql.push_str(" AND 0"),
|
||||
},
|
||||
Some(_) => sql.push_str(" AND 0"),
|
||||
}
|
||||
(sql, params)
|
||||
}
|
||||
}
|
||||
|
||||
/// `host[:port]` of a captured URL.
|
||||
fn host_of(url: &str) -> &str {
|
||||
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
|
||||
rest.split(['/', '?', '#']).next().unwrap_or_default()
|
||||
/// The host and port of `url`, in SQL: what follows `://` up to the first `/`, `?` or `#`.
|
||||
const HOST_SQL: &str = "(SELECT CASE WHEN instr(r, '/') > 0 THEN substr(r, 1, instr(r, '/') - 1) \
|
||||
ELSE r END FROM (SELECT replace(replace(CASE WHEN instr(url, '://') > 0 \
|
||||
THEN substr(url, instr(url, '://') + 3) ELSE url END, '?', '/'), '#', '/') AS r))";
|
||||
|
||||
/// Where the app's sidebar places a URL: its host, lowercased and without its scheme's default
|
||||
/// port, then its path's non-empty segments, joined by `/`, as in `api.stripe.com/v1/charges`.
|
||||
/// A URL without a scheme is a host of its own. `sidebarPath` in the app's `lib/search.ts`
|
||||
/// follows the same rules, and the sidebar's nodes are built from it.
|
||||
pub fn sidebar_path(url: &str) -> String {
|
||||
let Some((scheme, rest)) = url.split_once("://") else {
|
||||
return url.to_string();
|
||||
};
|
||||
let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
|
||||
let (authority, rest) = rest.split_at(end);
|
||||
let mut host = authority.to_ascii_lowercase();
|
||||
let default_port = match scheme.to_ascii_lowercase().as_str() {
|
||||
"http" | "ws" => Some(":80"),
|
||||
"https" | "wss" => Some(":443"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(port) = default_port
|
||||
&& host.ends_with(port)
|
||||
{
|
||||
host.truncate(host.len() - port.len());
|
||||
}
|
||||
let path = rest.split(['?', '#']).next().unwrap_or_default();
|
||||
let mut key = host;
|
||||
for segment in path.split('/').filter(|s| !s.is_empty()) {
|
||||
key.push('/');
|
||||
key.push_str(segment);
|
||||
}
|
||||
key
|
||||
}
|
||||
|
||||
/// The flows `filter` covers, newest first: by start, then by id. Reads only as far into the
|
||||
/// table as the limit needs, so a page costs the same however many flows there are.
|
||||
/// A sidebar node as `sidebar_path` writes it, its host lowercased.
|
||||
fn normalize_node(node: &str) -> String {
|
||||
match node.split_once('/') {
|
||||
Some((host, path)) => format!("{}/{path}", host.to_ascii_lowercase()),
|
||||
None => node.to_ascii_lowercase(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The SQL condition for a status term: `404` exactly, `40` as the start of one, or a class
|
||||
/// such as `4xx`. None when the term is not one.
|
||||
fn status_condition(term: &str, params: &mut Vec<Value>) -> Option<String> {
|
||||
if let Some(class) = term.strip_suffix("xx")
|
||||
&& let Ok(class @ 1..=9) = class.parse::<i64>()
|
||||
{
|
||||
params.push(class.into());
|
||||
return Some("status / 100 = ?".into());
|
||||
}
|
||||
if term.is_empty() || term.len() > 3 || !term.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
if term.len() == 3 {
|
||||
params.push(term.parse::<i64>().ok()?.into());
|
||||
return Some("status = ?".into());
|
||||
}
|
||||
params.push(format!("{term}%").into());
|
||||
Some("CAST(status AS TEXT) LIKE ?".into())
|
||||
}
|
||||
|
||||
/// The flows `filter` covers, newest first: by start, then by id. Reads the table in that order
|
||||
/// through its index and stops at the limit, so a page of a common match costs the same however
|
||||
/// many flows there are.
|
||||
pub fn list(db: &ProxyQueryManager, filter: &FlowFilter) -> Result<Vec<Flow>, String> {
|
||||
db.with_conn(|c| list_in(c.conn().resolve(), filter))
|
||||
}
|
||||
|
||||
/// [`list`] and the count of every flow, read from one snapshot of the database, so the count
|
||||
/// takes in exactly the flows written before the page was read.
|
||||
pub fn page(db: &ProxyQueryManager, filter: &FlowFilter) -> Result<(Vec<Flow>, usize), String> {
|
||||
/// takes in exactly the flows written before the page was read. With a filter that narrows,
|
||||
/// also the count of the flows it covers, whatever the limit.
|
||||
pub fn page(
|
||||
db: &ProxyQueryManager,
|
||||
filter: &FlowFilter,
|
||||
) -> Result<(Vec<Flow>, usize, Option<usize>), String> {
|
||||
db.with_conn(|c| {
|
||||
let tx = c.conn().resolve().unchecked_transaction().map_err(|e| e.to_string())?;
|
||||
let flows = list_in(&tx, filter)?;
|
||||
let total = count_in(&tx)?;
|
||||
let matching = if filter.narrows() { Some(count_matching(&tx, filter)?) } else { None };
|
||||
tx.commit().map_err(|e| e.to_string())?;
|
||||
Ok((flows, total))
|
||||
Ok((flows, total, matching))
|
||||
})
|
||||
}
|
||||
|
||||
fn list_in(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<Vec<Flow>, String> {
|
||||
let mut sql = String::from("SELECT * FROM flows WHERE 1");
|
||||
let mut params: Vec<rusqlite::types::Value> = Vec::new();
|
||||
let (condition, mut params) = filter.condition();
|
||||
let mut sql = format!("SELECT * FROM flows WHERE {condition}");
|
||||
if let Some(id) = &filter.after {
|
||||
// By rowid, which only grows as flows are written.
|
||||
let rowid: i64 = conn
|
||||
@@ -136,7 +280,7 @@ fn list_in(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<Vec<Flow>
|
||||
params.push(rowid.into());
|
||||
}
|
||||
if let Some(id) = &filter.before {
|
||||
let started_at: rusqlite::types::Value = conn
|
||||
let started_at: Value = conn
|
||||
.query_row("SELECT started_at FROM flows WHERE id = ?", [id], |r| r.get(0))
|
||||
.map_err(|_| format!("No flow {id}"))?;
|
||||
sql.push_str(" AND (started_at, id) < (?, ?)");
|
||||
@@ -144,21 +288,26 @@ fn list_in(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<Vec<Flow>
|
||||
params.push(id.clone().into());
|
||||
}
|
||||
sql.push_str(" ORDER BY started_at DESC, id DESC");
|
||||
if let Some(limit) = filter.limit {
|
||||
sql.push_str(" LIMIT ?");
|
||||
params.push((limit.min(i64::MAX as usize) as i64).into());
|
||||
}
|
||||
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let rows = stmt
|
||||
.query_map(rusqlite::params_from_iter(params), Flow::from_row)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut flows = Vec::new();
|
||||
for flow in rows {
|
||||
if flows.len() >= filter.limit.unwrap_or(usize::MAX) {
|
||||
break;
|
||||
}
|
||||
let flow = flow.map_err(|e| e.to_string())?;
|
||||
if filter.matches(&flow) {
|
||||
flows.push(flow);
|
||||
}
|
||||
}
|
||||
Ok(flows)
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn count_matching(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<usize, String> {
|
||||
let (condition, params) = filter.condition();
|
||||
conn.query_row(
|
||||
&format!("SELECT COUNT(*) FROM flows WHERE {condition}"),
|
||||
rusqlite::params_from_iter(params),
|
||||
|r| r.get::<_, i64>(0),
|
||||
)
|
||||
.map(|n| n as usize)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Deletes every flow and their bodies, in a transaction in each database. The flows' deletion
|
||||
@@ -288,26 +437,218 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A database of `flows`, started a second apart in the order given, and a function that
|
||||
/// lists the urls a filter covers, newest first.
|
||||
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();
|
||||
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 };
|
||||
db.with_tx(|tx| tx.upsert(&flow, &UpdateSource::Background)).unwrap();
|
||||
}
|
||||
(dir, db)
|
||||
}
|
||||
|
||||
fn urls(db: &ProxyQueryManager, filter: FlowFilter) -> Vec<String> {
|
||||
list(db, &filter).unwrap().into_iter().map(|f| f.url).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters() {
|
||||
let ok = flow("https://api.stripe.com:8443/v1/charges?x=1", "POST", Some(200), None);
|
||||
let missing = flow("http://example.com/missing", "GET", Some(404), None);
|
||||
let failed = flow("https://down.example.com/", "GET", None, Some("refused"));
|
||||
|
||||
let by = |filter: FlowFilter| {
|
||||
[&ok, &missing, &failed].iter().filter(|f| filter.matches(f)).count()
|
||||
};
|
||||
let (_dir, db) = db_of(vec![
|
||||
flow("https://api.stripe.com:8443/v1/charges?x=1", "POST", Some(200), None),
|
||||
flow("http://example.com/missing", "GET", Some(404), None),
|
||||
flow("https://down.example.com/", "GET", None, Some("refused")),
|
||||
]);
|
||||
let by = |filter: FlowFilter| urls(&db, filter).len();
|
||||
assert_eq!(by(FlowFilter::default()), 3);
|
||||
assert_eq!(by(FlowFilter { host: Some("STRIPE".into()), ..Default::default() }), 1);
|
||||
assert_eq!(by(FlowFilter { host: Some("example.com".into()), ..Default::default() }), 2);
|
||||
assert_eq!(by(FlowFilter { host: Some("charges".into()), ..Default::default() }), 0);
|
||||
assert_eq!(by(FlowFilter { host: Some("8443".into()), ..Default::default() }), 1);
|
||||
assert_eq!(by(FlowFilter { method: Some("get".into()), ..Default::default() }), 2);
|
||||
assert_eq!(by(FlowFilter { status: Some("404".into()), ..Default::default() }), 1);
|
||||
assert_eq!(by(FlowFilter { status: Some("2xx".into()), ..Default::default() }), 1);
|
||||
assert_eq!(by(FlowFilter { status: Some("5XX".into()), ..Default::default() }), 0);
|
||||
assert_eq!(by(FlowFilter { status: Some("40".into()), ..Default::default() }), 0);
|
||||
assert_eq!(by(FlowFilter { status: Some("error".into()), ..Default::default() }), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_matches_url_method_status_and_content_type() {
|
||||
let json = |url: &str, method: &str, status| Flow {
|
||||
content_type: Some("application/json; charset=utf-8".into()),
|
||||
..flow(url, method, Some(status), None)
|
||||
};
|
||||
let (_dir, db) = db_of(vec![
|
||||
json("https://api.stripe.com/v1/charges?customer=cus_9", "POST", 200),
|
||||
json("https://api.github.com/repos/yaak", "GET", 404),
|
||||
Flow {
|
||||
content_type: Some("image/png".into()),
|
||||
..flow("https://images.ctfassets.net/logo.png", "GET", Some(200), None)
|
||||
},
|
||||
flow("http://localhost:3000/health", "HEAD", Some(503), None),
|
||||
]);
|
||||
let search = |q: &str| {
|
||||
let filter = FlowFilter { q: Some(q.into()), ..Default::default() };
|
||||
let mut found = urls(&db, filter);
|
||||
found.sort();
|
||||
found
|
||||
};
|
||||
let stripe = "https://api.stripe.com/v1/charges?customer=cus_9";
|
||||
let github = "https://api.github.com/repos/yaak";
|
||||
let logo = "https://images.ctfassets.net/logo.png";
|
||||
let health = "http://localhost:3000/health";
|
||||
// The host, the path and the query, any case.
|
||||
assert_eq!(search("STRIPE"), vec![stripe]);
|
||||
assert_eq!(search("/repos/"), vec![github]);
|
||||
assert_eq!(search("cus_9"), vec![stripe]);
|
||||
// The method, whole.
|
||||
assert_eq!(search("head"), vec![health]);
|
||||
assert_eq!(search("ead"), Vec::<&str>::new());
|
||||
// A status, its start, or its class.
|
||||
assert_eq!(search("404"), vec![github]);
|
||||
assert_eq!(search("50"), vec![health]);
|
||||
assert_eq!(search("2xx"), vec![stripe, logo]);
|
||||
// The content type.
|
||||
assert_eq!(search("png"), vec![logo]);
|
||||
assert_eq!(search("json"), vec![github, stripe]);
|
||||
// Every term must match, each anywhere.
|
||||
assert_eq!(search("json get"), vec![github]);
|
||||
assert_eq!(search(" json 2xx "), vec![stripe]);
|
||||
assert_eq!(search("json 5xx"), Vec::<&str>::new());
|
||||
// `%` and `_` are plain characters, not patterns.
|
||||
assert_eq!(search("%"), Vec::<&str>::new());
|
||||
assert_eq!(search("cus_"), vec![stripe]);
|
||||
assert_eq!(search(""), vec![health, github, stripe, logo]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_matches_a_host_or_a_path_as_the_sidebar_does() {
|
||||
let (_dir, db) = db_of(vec![
|
||||
flow("https://api.stripe.com/v1/charges", "GET", Some(200), None),
|
||||
flow("https://api.stripe.com/v1/charges/ch_1?expand=x", "GET", Some(200), None),
|
||||
flow("https://api.stripe.com/v1/chargesx", "GET", Some(200), None),
|
||||
flow("https://api.stripe.com:8443/v1/charges", "GET", Some(200), None),
|
||||
flow("http://api.stripe.com", "GET", Some(200), None),
|
||||
flow("https://api.stripe.community/", "GET", Some(200), None),
|
||||
flow("https://example.com/v1//users", "GET", Some(200), None),
|
||||
flow("http://x.com:80/a", "GET", Some(200), None),
|
||||
flow("https://x.com:443/a", "GET", Some(200), None),
|
||||
]);
|
||||
let under = |nodes: &[&str]| {
|
||||
let nodes = nodes.iter().map(|n| n.to_string()).collect();
|
||||
urls(&db, FlowFilter { under: Some(nodes), ..Default::default() }).len()
|
||||
};
|
||||
// A host on another port is a node of its own, as in the sidebar.
|
||||
assert_eq!(under(&["api.stripe.com"]), 4);
|
||||
assert_eq!(under(&["api.stripe.com:8443"]), 1);
|
||||
assert_eq!(under(&["api.stripe.com/v1/charges"]), 2);
|
||||
// Empty segments and default ports are left out, as the sidebar leaves them.
|
||||
assert_eq!(under(&["example.com/v1/users"]), 1);
|
||||
assert_eq!(under(&["x.com/a"]), 2);
|
||||
assert_eq!(under(&["api.stripe.com/v1/charges", "example.com"]), 3);
|
||||
assert_eq!(under(&[]), 0);
|
||||
// The sidebar lowercases hosts; paths keep their case.
|
||||
assert_eq!(under(&["API.stripe.com/v1/charges"]), 2);
|
||||
assert_eq!(under(&["api.stripe.com/V1/charges"]), 0);
|
||||
}
|
||||
|
||||
/// The cases `lib/search.test.ts` checks `sidebarPath` against, so the two agree.
|
||||
#[test]
|
||||
fn sidebar_path_rules() {
|
||||
for (url, path) in [
|
||||
("https://example.com/v1//users", "example.com/v1/users"),
|
||||
("http://x.com:80/a", "x.com/a"),
|
||||
("https://x.com:443/a?q=1#f", "x.com/a"),
|
||||
("http://x.com:443/a", "x.com:443/a"),
|
||||
("https://API.Stripe.com:8443/", "api.stripe.com:8443"),
|
||||
("https://api.stripe.com", "api.stripe.com"),
|
||||
("https://api.stripe.com?x=/y", "api.stripe.com"),
|
||||
("http://[::1]:80/a/B", "[::1]/a/B"),
|
||||
("/api", "/api"),
|
||||
] {
|
||||
assert_eq!(sidebar_path(url), path, "{url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_matches_a_bundle_id_or_a_path() {
|
||||
let from = |bundle_id: Option<&str>, path: &str| Flow {
|
||||
client_bundle_id: bundle_id.map(String::from),
|
||||
client_path: Some(path.into()),
|
||||
..flow("https://example.com/", "GET", Some(200), None)
|
||||
};
|
||||
let (_dir, db) = db_of(vec![
|
||||
from(Some("com.google.Chrome"), "/Applications/Google Chrome.app"),
|
||||
from(Some("com.google.Chrome"), "/Applications/Google Chrome.app"),
|
||||
from(None, "/usr/bin/curl"),
|
||||
flow("https://example.com/", "GET", Some(200), None),
|
||||
]);
|
||||
let app = |apps: &[&str]| {
|
||||
let apps = apps.iter().map(|a| a.to_string()).collect();
|
||||
urls(&db, FlowFilter { app: Some(apps), ..Default::default() }).len()
|
||||
};
|
||||
assert_eq!(app(&["com.google.Chrome"]), 2);
|
||||
assert_eq!(app(&["/usr/bin/curl"]), 1);
|
||||
assert_eq!(app(&["/Applications/Google Chrome.app"]), 0);
|
||||
assert_eq!(app(&["com.google.Chrome", "/usr/bin/curl"]), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_search_pages_back_and_counts_what_it_matches() {
|
||||
// Every third flow is a POST, newest last.
|
||||
let (_dir, db) = db_of(
|
||||
(0..30)
|
||||
.map(|i| {
|
||||
let method = if i % 3 == 0 { "POST" } else { "GET" };
|
||||
flow(&format!("https://api.example.com/{i}"), method, Some(200), None)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let search = |before: Option<String>| FlowFilter {
|
||||
q: Some("post".into()),
|
||||
before,
|
||||
limit: Some(4),
|
||||
..Default::default()
|
||||
};
|
||||
let (first, total, matching) = page(&db, &search(None)).unwrap();
|
||||
let ids = |flows: &[Flow]| flows.iter().map(|f| f.id.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(ids(&first), vec!["fl_027", "fl_024", "fl_021", "fl_018"]);
|
||||
assert_eq!((total, matching), (30, Some(10)));
|
||||
let (second, _, _) = page(&db, &search(Some("fl_018".into()))).unwrap();
|
||||
assert_eq!(ids(&second), vec!["fl_015", "fl_012", "fl_009", "fl_006"]);
|
||||
let (last, _, _) = page(&db, &search(Some("fl_006".into()))).unwrap();
|
||||
assert_eq!(ids(&last), vec!["fl_003", "fl_000"]);
|
||||
// Without a narrowing filter there is nothing more to count.
|
||||
let (_, _, matching) =
|
||||
page(&db, &FlowFilter { limit: Some(1), ..Default::default() }).unwrap();
|
||||
assert_eq!(matching, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_search_reads_the_newest_page_through_the_index() {
|
||||
let (_dir, db) = db_of(vec![]);
|
||||
let plan: Vec<String> = db.with_conn(|c| {
|
||||
let conn = c.conn().resolve();
|
||||
let (condition, params) =
|
||||
FlowFilter { q: Some("stripe".into()), ..Default::default() }.condition();
|
||||
let sql = format!(
|
||||
"EXPLAIN QUERY PLAN SELECT * FROM flows WHERE {condition} \
|
||||
ORDER BY started_at DESC, id DESC LIMIT 500"
|
||||
);
|
||||
let mut stmt = conn.prepare(&sql).unwrap();
|
||||
stmt.query_map(rusqlite::params_from_iter(params), |r| r.get::<_, String>(3))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect()
|
||||
});
|
||||
assert!(plan.iter().any(|p| p.contains("idx_flows_started_at_id")), "{plan:?}");
|
||||
assert!(!plan.iter().any(|p| p.contains("TEMP B-TREE")), "{plan:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_follows_flows_as_they_are_recorded() {
|
||||
use yaak_database::UpdateSource;
|
||||
@@ -412,12 +753,19 @@ mod tests {
|
||||
#[test]
|
||||
fn query_round_trip() {
|
||||
let filter = FlowFilter {
|
||||
q: Some("post json".into()),
|
||||
host: Some("api.stripe.com".into()),
|
||||
under: Some(vec!["api.stripe.com/v1".into(), "example.com".into()]),
|
||||
app: Some(vec!["com.google.Chrome".into()]),
|
||||
status: Some("4xx".into()),
|
||||
limit: Some(20),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(filter.to_query(), "host=api.stripe.com&status=4xx&limit=20");
|
||||
assert_eq!(
|
||||
filter.to_query(),
|
||||
"q=post+json&host=api.stripe.com&under=api.stripe.com%2Fv1&under=example.com\
|
||||
&app=com.google.Chrome&status=4xx&limit=20"
|
||||
);
|
||||
assert_eq!(FlowFilter::from_query(&filter.to_query()).unwrap(), filter);
|
||||
assert_eq!(FlowFilter::from_query("").unwrap(), FlowFilter::default());
|
||||
assert!(FlowFilter::from_query("limit=lots").is_err());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod actions;
|
||||
pub mod attribution;
|
||||
pub mod bodies;
|
||||
pub mod ca;
|
||||
pub mod client;
|
||||
@@ -13,8 +14,11 @@ pub mod save;
|
||||
pub mod settings;
|
||||
|
||||
use crate::actions::{ActionInvocation, ActionMetadata, GlobalAction};
|
||||
use crate::attribution::Attribution;
|
||||
use crate::ca::CaStatus;
|
||||
use crate::control::{ControlFile, ControlInfo, Owner};
|
||||
use crate::client::ControlClient;
|
||||
use crate::control::{ControlFile, ControlInfo, ControlServer, Owner};
|
||||
use crate::convert::DroppedHeader;
|
||||
use crate::db::ProxyQueryManager;
|
||||
use crate::macos::{SystemProxyBackend, SystemProxyStatus};
|
||||
use crate::models::{Flow, FlowBody, FlowIden, ModelPayload, ProxyHeader, find_header};
|
||||
@@ -26,10 +30,12 @@ use chrono::{DateTime, Utc};
|
||||
use log::{debug, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, SystemTime};
|
||||
use ts_rs::TS;
|
||||
use yaak_database::{ModelChangeEvent, UpdateSource, UpsertModelInfo};
|
||||
use yaak_models::blob_manager::{BlobManager, BodyChunkWriter};
|
||||
@@ -46,10 +52,19 @@ pub struct ProxyCtx {
|
||||
owner: Owner,
|
||||
client_data_dir: PathBuf,
|
||||
control: Arc<Mutex<Option<ControlFile>>>,
|
||||
/// The control API this app serves while it owns the engine. Not the CLI daemon's, which
|
||||
/// holds its own.
|
||||
control_server: Arc<Mutex<Option<ControlServer>>>,
|
||||
/// Held through each system proxy change, password dialog included, so they apply in turn.
|
||||
system_proxy_turn: Arc<Mutex<()>>,
|
||||
/// The port the engine last ran on, which the system proxy may still point at.
|
||||
last_port: Arc<Mutex<Option<u16>>>,
|
||||
/// Flows are stored. While paused, traffic still passes through, untouched and unrecorded.
|
||||
recording: Arc<Mutex<RecordingLog>>,
|
||||
/// This Mac's web traffic is meant to point at the running engine.
|
||||
system_proxy_on: Arc<AtomicBool>,
|
||||
/// Why the engine last failed to start, until it starts.
|
||||
start_error: Arc<Mutex<Option<String>>>,
|
||||
pub db: ProxyQueryManager,
|
||||
pub blobs: BlobManager,
|
||||
pub events: RpcEventEmitter,
|
||||
@@ -68,8 +83,12 @@ impl ProxyCtx {
|
||||
owner: Owner::App,
|
||||
client_data_dir: save::client_data_dir(),
|
||||
control: Arc::new(Mutex::new(None)),
|
||||
control_server: Arc::new(Mutex::new(None)),
|
||||
system_proxy_turn: Arc::new(Mutex::new(())),
|
||||
last_port: Arc::new(Mutex::new(None)),
|
||||
recording: Arc::new(Mutex::new(RecordingLog::default())),
|
||||
system_proxy_on: Arc::new(AtomicBool::new(false)),
|
||||
start_error: Arc::new(Mutex::new(None)),
|
||||
db,
|
||||
blobs,
|
||||
events,
|
||||
@@ -115,8 +134,26 @@ impl ProxyCtx {
|
||||
|
||||
/// Starts the engine on `port`, or the one in `settings.json`. Does nothing if it is
|
||||
/// running. Points the system proxy at it when the settings ask for that. Refused while
|
||||
/// another process owns the engine, so there are never two.
|
||||
/// another process owns the engine, so there are never two. A failure is kept until the
|
||||
/// next start, for the app to show.
|
||||
pub fn start_on(&self, port: Option<u16>) -> Result<(), String> {
|
||||
let started = self.start_engine(port);
|
||||
if let Ok(mut start_error) = self.start_error.lock() {
|
||||
*start_error = started.as_ref().err().cloned();
|
||||
}
|
||||
if started.is_err() {
|
||||
self.events
|
||||
.emit("proxy_state_changed", &ProxyStatePayload { state: ProxyState::Stopped });
|
||||
}
|
||||
started
|
||||
}
|
||||
|
||||
/// Why the engine last failed to start, if it has not started since.
|
||||
pub fn start_error(&self) -> Option<String> {
|
||||
self.start_error.lock().ok()?.clone()
|
||||
}
|
||||
|
||||
fn start_engine(&self, port: Option<u16>) -> Result<(), String> {
|
||||
if let Some(owner) = control::live_owner(&self.data_dir)
|
||||
&& owner.pid != std::process::id()
|
||||
{
|
||||
@@ -132,13 +169,30 @@ impl ProxyCtx {
|
||||
.map_err(|e| format!("Failed to load proxy CA: {e}"))?;
|
||||
let mut config = ProxyConfig::new(port.unwrap_or(settings.port), Arc::new(ca));
|
||||
config.capture_body_limit = settings.capture_body_limit;
|
||||
// Filled once the engine has bound, since the lookup matches sockets by its port.
|
||||
let attribution_slot: Arc<OnceLock<Attribution>> = Arc::new(OnceLock::new());
|
||||
let slot = attribution_slot.clone();
|
||||
config.on_accept = Some(Arc::new(move |connection, client_addr| {
|
||||
// A client that is answered quickly may exit soon after, so it is found before
|
||||
// anything is read from it: a few milliseconds once per connection at most.
|
||||
if let Some(attribution) = slot.get() {
|
||||
attribution.begin(connection, client_addr);
|
||||
attribution.get(connection, ACCEPT_ATTRIBUTION_WAIT);
|
||||
}
|
||||
}));
|
||||
let mut proxy_handle = yaak_proxy::start_proxy(config)?;
|
||||
let attribution = Attribution::new(proxy_handle.port);
|
||||
let _ = attribution_slot.set(attribution.clone());
|
||||
|
||||
if let Some(event_rx) = proxy_handle.take_event_rx() {
|
||||
let db = self.db.clone();
|
||||
let blobs = self.blobs.clone();
|
||||
let events = self.events.clone();
|
||||
std::thread::spawn(move || run_event_loop(event_rx, db, blobs, events));
|
||||
let sink = FlowSink {
|
||||
db: self.db.clone(),
|
||||
blobs: self.blobs.clone(),
|
||||
events: self.events.clone(),
|
||||
attribution,
|
||||
recording: self.recording.clone(),
|
||||
};
|
||||
std::thread::spawn(move || run_event_loop(event_rx, sink));
|
||||
}
|
||||
|
||||
let bound = proxy_handle.port;
|
||||
@@ -148,13 +202,18 @@ impl ProxyCtx {
|
||||
if let Ok(mut last_port) = self.last_port.lock() {
|
||||
*last_port = Some(bound);
|
||||
}
|
||||
if settings.system_proxy {
|
||||
self.system_proxy_on.store(settings.system_proxy_at_launch, Ordering::SeqCst);
|
||||
if settings.system_proxy_at_launch {
|
||||
// The password dialog can sit open for a while; the engine is up regardless.
|
||||
let ctx = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(e) = ctx.change_system_proxy(true, bound, true) {
|
||||
warn!("Failed to turn on the system proxy: {e}");
|
||||
ctx.system_proxy_on.store(false, Ordering::SeqCst);
|
||||
}
|
||||
// So the app reads the system proxy again once the dialog is answered.
|
||||
ctx.events
|
||||
.emit("proxy_state_changed", &ProxyStatePayload { state: ProxyState::Running });
|
||||
});
|
||||
}
|
||||
self.events.emit("proxy_state_changed", &ProxyStatePayload { state: ProxyState::Running });
|
||||
@@ -163,6 +222,7 @@ impl ProxyCtx {
|
||||
|
||||
/// Stops the engine and turns off a system proxy that points at it.
|
||||
pub fn stop(&self) -> Result<(), String> {
|
||||
self.system_proxy_on.store(false, Ordering::SeqCst);
|
||||
let port = self.take_handle()?;
|
||||
if let Some(port) = port {
|
||||
let ctx = self.clone();
|
||||
@@ -218,6 +278,83 @@ impl ProxyCtx {
|
||||
self.control.lock().ok()?.as_ref().map(|c| c.info.clone())
|
||||
}
|
||||
|
||||
/// Claims the engine for this app and serves the control API, unless it already does.
|
||||
/// Fails while another live owner, the CLI daemon, has it. Resets a system proxy a crashed
|
||||
/// owner left pointing at its port.
|
||||
pub fn serve_control_api(&self) -> Result<(), String> {
|
||||
let mut slot = self.control_server.lock().map_err(|_| "lock poisoned".to_string())?;
|
||||
if slot.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
// Read first: a crashed owner's file names the port its system proxy may still point at.
|
||||
let previous = control::read(&self.data_dir);
|
||||
*slot = Some(ControlServer::start(self.clone())?);
|
||||
drop(slot);
|
||||
|
||||
let mut ports: Vec<u16> = previous.and_then(|p| p.proxy_port).into_iter().collect();
|
||||
ports.extend(self.settings().ok().map(|s| s.port));
|
||||
let ctx = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(e) = ctx.reset_stale_system_proxy(&ports) {
|
||||
warn!("Failed to reset a stale system proxy: {e}");
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stops serving the control API and gives up the claim on the engine.
|
||||
pub fn stop_control_api(&self) {
|
||||
let server = self.control_server.lock().ok().and_then(|mut s| s.take());
|
||||
drop(server);
|
||||
}
|
||||
|
||||
/// Another live owner of the engine, such as the CLI daemon.
|
||||
pub fn other_owner(&self) -> Option<ControlInfo> {
|
||||
let ours = self.control_info().map(|c| c.token);
|
||||
control::live_owner(&self.data_dir).filter(|o| Some(&o.token) != ours.as_ref())
|
||||
}
|
||||
|
||||
/// Stops the engine in the process that owns it, waits for that process to give it up,
|
||||
/// then claims it here and starts it. Fails, leaving things as they are, when the owner
|
||||
/// does not let go.
|
||||
pub async fn take_over(&self) -> Result<(), String> {
|
||||
if let Some(owner) = self.other_owner() {
|
||||
// Stopped through the control API, another app halts its engine but keeps the claim,
|
||||
// so only the CLI daemon, which exits on it, can be taken over.
|
||||
if owner.owner == Owner::App {
|
||||
return Err(ANOTHER_APP_OWNS.to_string());
|
||||
}
|
||||
ControlClient::new(owner.clone()).stop().await?;
|
||||
let ctx = self.clone();
|
||||
let released = tokio::task::spawn_blocking(move || {
|
||||
let deadline = std::time::Instant::now() + TAKE_OVER_WAIT;
|
||||
while std::time::Instant::now() < deadline {
|
||||
if ctx.other_owner().is_none() {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
false
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !released {
|
||||
return Err(format!(
|
||||
"The proxy in {} (pid {}) stopped but did not let go of it",
|
||||
control::owner_name(owner.owner),
|
||||
owner.pid
|
||||
));
|
||||
}
|
||||
}
|
||||
let ctx = self.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ctx.serve_control_api()?;
|
||||
ctx.start()
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
}
|
||||
|
||||
fn set_control_proxy_port(&self, port: Option<u16>) {
|
||||
if let Ok(mut control) = self.control.lock()
|
||||
&& let Some(control) = control.as_mut()
|
||||
@@ -240,23 +377,59 @@ impl ProxyCtx {
|
||||
macos::status(port, self.system_proxy_backend())
|
||||
}
|
||||
|
||||
/// Turns the system proxy on or off and remembers the choice. Turned on while the engine
|
||||
/// is stopped, it waits for the engine to start, so the Mac is never pointed at nothing.
|
||||
/// Blocks, through the password dialog.
|
||||
/// Points this Mac's web traffic at the running engine, or stops, at once, through the
|
||||
/// password dialog. Not saved: the `systemProxyAtLaunch` setting decides whether it turns
|
||||
/// on as the engine starts. Blocks.
|
||||
pub fn set_system_proxy(&self, enabled: bool) -> Result<SystemProxyStatus, String> {
|
||||
let mut settings = self.settings()?;
|
||||
let previous = settings.system_proxy;
|
||||
settings.system_proxy = enabled;
|
||||
settings.save(&self.settings_path())?;
|
||||
let port = self.port().unwrap_or(settings.port);
|
||||
let Some(port) = self.port() else {
|
||||
if enabled {
|
||||
return Err("The proxy is not running, so there is nothing to route to".into());
|
||||
}
|
||||
// Clears one left pointing at the configured port; asks for nothing otherwise.
|
||||
self.change_system_proxy(false, self.settings()?.port, false)?;
|
||||
return self.system_proxy_status();
|
||||
};
|
||||
let previous = self.system_proxy_on.swap(enabled, Ordering::SeqCst);
|
||||
if let Err(e) = self.change_system_proxy(enabled, port, enabled) {
|
||||
settings.system_proxy = previous;
|
||||
let _ = settings.save(&self.settings_path());
|
||||
self.system_proxy_on.store(previous, Ordering::SeqCst);
|
||||
return Err(e);
|
||||
}
|
||||
self.system_proxy_status()
|
||||
}
|
||||
|
||||
/// Whether the system proxy turns on as the engine starts, saved in `settings.json`.
|
||||
pub fn set_system_proxy_at_launch(&self, enabled: bool) -> Result<(), String> {
|
||||
let mut settings = self.settings()?;
|
||||
settings.system_proxy_at_launch = enabled;
|
||||
settings.save(&self.settings_path())
|
||||
}
|
||||
|
||||
/// Intercepts again the hosts passed through after clients rejected the CA, as they no
|
||||
/// longer will once it is trusted.
|
||||
pub fn forget_passthrough(&self) {
|
||||
if let Ok(handle) = self.handle.lock()
|
||||
&& let Some(handle) = handle.as_ref()
|
||||
{
|
||||
handle.forget_passthrough();
|
||||
}
|
||||
}
|
||||
|
||||
/// Flows are being stored.
|
||||
pub fn recording(&self) -> bool {
|
||||
self.recording.lock().map(|r| r.is_on()).unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Resumes or pauses storing flows. Paused, traffic still passes through the engine, but no
|
||||
/// new flow is stored; one already under way is finished.
|
||||
pub fn set_recording(&self, recording: bool) {
|
||||
let changed = self.recording.lock().map(|mut r| r.set(recording)).unwrap_or(false);
|
||||
if changed {
|
||||
let state =
|
||||
if self.port().is_some() { ProxyState::Running } else { ProxyState::Stopped };
|
||||
self.events.emit("proxy_state_changed", &ProxyStatePayload { state });
|
||||
}
|
||||
}
|
||||
|
||||
/// Points the system proxy at `port`, or turns it off there, once the changes before it
|
||||
/// are done. With `follow_engine`, the change is dropped if the engine has moved on by its
|
||||
/// turn: an enable once the engine is off `port` or the setting is off, a disable once the
|
||||
@@ -271,7 +444,8 @@ impl ProxyCtx {
|
||||
let _turn = self.system_proxy_turn.lock().map_err(|_| "lock poisoned".to_string())?;
|
||||
if follow_engine {
|
||||
let on_port = self.port() == Some(port);
|
||||
let current = if enabled { on_port && self.settings()?.system_proxy } else { !on_port };
|
||||
let wanted = self.system_proxy_on.load(Ordering::SeqCst);
|
||||
let current = if enabled { on_port && wanted } else { !on_port };
|
||||
if !current {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -302,6 +476,11 @@ impl ProxyCtx {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Yaak has run on this machine, so there is a database to save into.
|
||||
pub fn client_exists(&self) -> bool {
|
||||
ClientDb::exists(&self.client_data_dir)
|
||||
}
|
||||
|
||||
/// Yaak's workspaces and their folders, to save a flow into.
|
||||
pub fn workspaces(&self) -> Result<Vec<WorkspaceSummary>, String> {
|
||||
ClientDb::open(&self.client_data_dir)?.workspaces()
|
||||
@@ -354,6 +533,52 @@ fn is_listening(port: u16) -> bool {
|
||||
TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok()
|
||||
}
|
||||
|
||||
// -- Recording --
|
||||
|
||||
/// Changes to recording kept, so a request whose events are read late is still judged by when
|
||||
/// it started.
|
||||
const RECORDING_CHANGES: usize = 64;
|
||||
|
||||
/// Whether flows are stored, and when that changed.
|
||||
struct RecordingLog {
|
||||
/// Oldest first, starting from recording since the beginning.
|
||||
changes: std::collections::VecDeque<(SystemTime, bool)>,
|
||||
}
|
||||
|
||||
impl Default for RecordingLog {
|
||||
fn default() -> Self {
|
||||
Self { changes: [(SystemTime::UNIX_EPOCH, true)].into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl RecordingLog {
|
||||
fn is_on(&self) -> bool {
|
||||
self.changes.back().is_none_or(|(_, on)| *on)
|
||||
}
|
||||
|
||||
/// Returns whether it changed.
|
||||
fn set(&mut self, on: bool) -> bool {
|
||||
if self.is_on() == on {
|
||||
return false;
|
||||
}
|
||||
self.changes.push_back((SystemTime::now(), on));
|
||||
while self.changes.len() > RECORDING_CHANGES {
|
||||
self.changes.pop_front();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether flows were stored at `time`.
|
||||
fn was_on_at(&self, time: SystemTime) -> bool {
|
||||
self.changes
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(at, _)| *at <= time)
|
||||
.or(self.changes.front())
|
||||
.is_none_or(|(_, on)| *on)
|
||||
}
|
||||
}
|
||||
|
||||
// -- Proxy state --
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
@@ -391,6 +616,9 @@ pub struct ListFlowsResponse {
|
||||
/// Flows in the database, whatever the filter.
|
||||
#[ts(type = "number")]
|
||||
pub total: usize,
|
||||
/// Flows the filter covers, whatever the limit, when it narrows to fewer than all of them.
|
||||
#[ts(type = "number | null")]
|
||||
pub matching: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
@@ -412,6 +640,130 @@ pub struct GetProxyStateResponse {
|
||||
pub state: ProxyState,
|
||||
/// The port the engine is bound to, while it runs.
|
||||
pub port: Option<u16>,
|
||||
/// The port the engine starts on.
|
||||
pub configured_port: u16,
|
||||
/// Flows are stored. Paused, traffic still passes through, unrecorded.
|
||||
pub recording: bool,
|
||||
/// The system proxy turns on as the engine starts.
|
||||
pub system_proxy_at_launch: bool,
|
||||
/// Why the engine last failed to start, until it starts.
|
||||
pub start_error: Option<String>,
|
||||
/// 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.
|
||||
pub other_owner: Option<OtherOwner>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OtherOwner {
|
||||
pub owner: Owner,
|
||||
pub pid: u32,
|
||||
pub started_at: DateTime<Utc>,
|
||||
/// The engine's port while it runs.
|
||||
pub proxy_port: Option<u16>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct TakeOverRequest {}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct SetRecordingRequest {
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct SetSystemProxyAtLaunchRequest {
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct AppIconRequest {
|
||||
/// A flow's `clientPath`.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ListWorkspacesRequest {}
|
||||
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ListWorkspacesResponse {
|
||||
/// Yaak has run on this machine. Without it there is nothing to save into.
|
||||
pub yaak_found: bool,
|
||||
pub workspaces: Vec<WorkspaceSummary>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PreviewSaveRequest {
|
||||
pub flow_id: String,
|
||||
}
|
||||
|
||||
/// What saving a flow as a Yaak request writes, for the save dialog.
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SavePreview {
|
||||
pub method: String,
|
||||
pub url: String,
|
||||
/// The URL as saved, its query split out into parameters, which Yaak shows for an unnamed
|
||||
/// request.
|
||||
pub request_url: String,
|
||||
/// The saved body type, which Yaak shows for an unnamed GraphQL request with no URL.
|
||||
pub body_type: Option<String>,
|
||||
/// Headers Yaak sets itself or that only meant something to the proxy.
|
||||
pub dropped_headers: Vec<DroppedHeader>,
|
||||
/// Headers saved as captured, Authorization among them.
|
||||
#[ts(type = "number")]
|
||||
pub kept_headers: usize,
|
||||
/// The body as it is saved: "JSON", "form URL-encoded with 7 fields". None without a body.
|
||||
pub body: Option<String>,
|
||||
/// What does not carry over exactly, one sentence each.
|
||||
pub warnings: Vec<String>,
|
||||
/// An Authorization header is saved in plain text.
|
||||
pub authorization: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SaveFlowToYaakRequest {
|
||||
pub flow_id: String,
|
||||
pub workspace_id: String,
|
||||
#[ts(optional)]
|
||||
pub folder_id: Option<String>,
|
||||
/// None or blank leaves the request unnamed, and Yaak shows its URL.
|
||||
#[ts(optional)]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SavedFlow {
|
||||
pub request_id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExportHarRequest {
|
||||
/// The file to write.
|
||||
pub path: String,
|
||||
/// These flows, or else every flow the filter covers.
|
||||
#[ts(optional)]
|
||||
pub ids: Option<Vec<String>>,
|
||||
#[ts(optional)]
|
||||
pub filter: Option<flows::FlowFilter>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
@@ -492,8 +844,7 @@ pub struct SystemProxySetRequest {
|
||||
fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool, RpcError> {
|
||||
match invocation {
|
||||
ActionInvocation::Global { action } => match action {
|
||||
GlobalAction::ProxyStart => ctx.start().map_err(|message| RpcError { message })?,
|
||||
GlobalAction::ProxyStop => ctx.stop().map_err(|message| RpcError { message })?,
|
||||
GlobalAction::RecordingToggle => ctx.set_recording(!ctx.recording()),
|
||||
GlobalAction::FlowsClear => {
|
||||
ctx.clear_flows().map_err(|message| RpcError { message })?;
|
||||
}
|
||||
@@ -502,13 +853,137 @@ fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool,
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn get_proxy_state(
|
||||
ctx: &ProxyCtx,
|
||||
async fn get_proxy_state(
|
||||
ctx: ProxyCtx,
|
||||
_req: GetProxyStateRequest,
|
||||
) -> Result<GetProxyStateResponse, RpcError> {
|
||||
let port = ctx.port();
|
||||
let state = if port.is_some() { ProxyState::Running } else { ProxyState::Stopped };
|
||||
Ok(GetProxyStateResponse { state, port })
|
||||
// The owner check takes a file lock and a connection, so off the async threads.
|
||||
blocking(move || {
|
||||
let port = ctx.port();
|
||||
let state = if port.is_some() { ProxyState::Running } else { ProxyState::Stopped };
|
||||
let settings = ctx.settings()?;
|
||||
let other_owner = ctx.other_owner().map(|o| OtherOwner {
|
||||
owner: o.owner,
|
||||
pid: o.pid,
|
||||
started_at: o.started_at,
|
||||
proxy_port: o.proxy_port,
|
||||
});
|
||||
Ok(GetProxyStateResponse {
|
||||
state,
|
||||
port,
|
||||
configured_port: settings.port,
|
||||
recording: ctx.recording(),
|
||||
system_proxy_at_launch: settings.system_proxy_at_launch,
|
||||
start_error: ctx.start_error(),
|
||||
other_owner,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn set_recording(ctx: &ProxyCtx, req: SetRecordingRequest) -> Result<bool, RpcError> {
|
||||
ctx.set_recording(req.enabled);
|
||||
Ok(ctx.recording())
|
||||
}
|
||||
|
||||
fn set_system_proxy_at_launch(
|
||||
ctx: &ProxyCtx,
|
||||
req: SetSystemProxyAtLaunchRequest,
|
||||
) -> Result<bool, RpcError> {
|
||||
ctx.set_system_proxy_at_launch(req.enabled).map_err(rpc_error)?;
|
||||
Ok(req.enabled)
|
||||
}
|
||||
|
||||
async fn take_over(ctx: ProxyCtx, _req: TakeOverRequest) -> Result<bool, RpcError> {
|
||||
ctx.take_over().await.map_err(rpc_error)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn app_icon(_ctx: ProxyCtx, req: AppIconRequest) -> Result<Option<String>, RpcError> {
|
||||
let png = blocking(move || attribution::app_icon_png(&req.path)).await?;
|
||||
Ok(png.map(|png| BASE64.encode(png)))
|
||||
}
|
||||
|
||||
async fn list_workspaces(
|
||||
ctx: ProxyCtx,
|
||||
_req: ListWorkspacesRequest,
|
||||
) -> Result<ListWorkspacesResponse, RpcError> {
|
||||
blocking(move || {
|
||||
if !ctx.client_exists() {
|
||||
return Ok(ListWorkspacesResponse { yaak_found: false, workspaces: Vec::new() });
|
||||
}
|
||||
Ok(ListWorkspacesResponse { yaak_found: true, workspaces: ctx.workspaces()? })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn preview_save(ctx: ProxyCtx, req: PreviewSaveRequest) -> Result<SavePreview, RpcError> {
|
||||
let flow = find_flow(&ctx, &req.flow_id)?;
|
||||
let limit = settings(&ctx)?.capture_body_limit;
|
||||
let body =
|
||||
bodies::read_body(&ctx.blobs, &flow, FlowBody::Request, limit).await.map_err(rpc_error)?;
|
||||
let conversion = convert::flow_to_request(&flow, &body);
|
||||
let request = conversion.request;
|
||||
let body = request.body_type.as_deref().map(|body_type| match body_type {
|
||||
"application/json" => "JSON".to_string(),
|
||||
"text/xml" => "XML".to_string(),
|
||||
"graphql" => "GraphQL".to_string(),
|
||||
"application/x-www-form-urlencoded" => {
|
||||
let fields = request.body.get("form").and_then(|f| f.as_array()).map_or(0, Vec::len);
|
||||
match fields {
|
||||
1 => "form URL-encoded with 1 field".to_string(),
|
||||
n => format!("form URL-encoded with {n} fields"),
|
||||
}
|
||||
}
|
||||
_ => "text".to_string(),
|
||||
});
|
||||
let authorization =
|
||||
request.headers.iter().any(|h| h.name.eq_ignore_ascii_case("authorization"));
|
||||
Ok(SavePreview {
|
||||
method: flow.method.clone(),
|
||||
url: flow.url.clone(),
|
||||
request_url: request.url.clone(),
|
||||
body_type: request.body_type.clone(),
|
||||
dropped_headers: conversion.dropped_headers,
|
||||
kept_headers: request.headers.len(),
|
||||
body,
|
||||
warnings: conversion.warnings,
|
||||
authorization,
|
||||
})
|
||||
}
|
||||
|
||||
async fn save_flow(ctx: ProxyCtx, req: SaveFlowToYaakRequest) -> Result<SavedFlow, RpcError> {
|
||||
let target = SaveFlowRequest {
|
||||
workspace_id: req.workspace_id,
|
||||
folder_id: req.folder_id,
|
||||
name: req.name,
|
||||
};
|
||||
let saved = ctx.save_flow(&req.flow_id, &target).await.map_err(rpc_error)?;
|
||||
Ok(SavedFlow { request_id: saved.request.id, name: saved.request.name })
|
||||
}
|
||||
|
||||
async fn export_har(ctx: ProxyCtx, req: ExportHarRequest) -> Result<usize, RpcError> {
|
||||
let flows = match req.ids {
|
||||
Some(ids) => ids.iter().map(|id| flows::get(&ctx.db, id)).collect::<Result<Vec<_>, _>>(),
|
||||
None => {
|
||||
let filter = flows::FlowFilter { limit: None, ..req.filter.unwrap_or_default() };
|
||||
flows::list(&ctx.db, &filter)
|
||||
}
|
||||
}
|
||||
.map_err(rpc_error)?;
|
||||
let limit = settings(&ctx)?.capture_body_limit;
|
||||
let har = har::export(&ctx.blobs, &flows, limit).await.map_err(rpc_error)?;
|
||||
let path = PathBuf::from(req.path);
|
||||
blocking(move || {
|
||||
let file = std::fs::File::create(&path)
|
||||
.map_err(|e| format!("Failed to create {}: {e}", path.display()))?;
|
||||
let mut out = std::io::BufWriter::new(file);
|
||||
serde_json::to_writer_pretty(&mut out, &har)
|
||||
.map_err(|e| format!("Failed to write {}: {e}", path.display()))?;
|
||||
out.flush().map_err(|e| format!("Failed to write {}: {e}", path.display()))
|
||||
})
|
||||
.await?;
|
||||
Ok(flows.len())
|
||||
}
|
||||
|
||||
fn format_body(_ctx: &ProxyCtx, req: FormatBodyRequest) -> Result<String, RpcError> {
|
||||
@@ -573,6 +1048,7 @@ async fn ca_trust(ctx: ProxyCtx, _req: CaTrustRequest) -> Result<CaStatus, RpcEr
|
||||
let ca = CaStore::load_or_create(&ctx.ca_dir())
|
||||
.map_err(|e| rpc_error(format!("Failed to load proxy CA: {e}")))?;
|
||||
ca::trust(ca.cert_path()).await.map_err(rpc_error)?;
|
||||
ctx.forget_passthrough();
|
||||
ca::status(ca.cert_path()).await.map_err(rpc_error)
|
||||
}
|
||||
|
||||
@@ -616,8 +1092,8 @@ fn list_actions(
|
||||
}
|
||||
|
||||
fn list_flows(ctx: &ProxyCtx, req: flows::FlowFilter) -> Result<ListFlowsResponse, RpcError> {
|
||||
let (flows, total) = flows::page(&ctx.db, &req).map_err(rpc_error)?;
|
||||
Ok(ListFlowsResponse { flows, total })
|
||||
let (flows, total, matching) = flows::page(&ctx.db, &req).map_err(rpc_error)?;
|
||||
Ok(ListFlowsResponse { flows, total, matching })
|
||||
}
|
||||
|
||||
async fn clear_flows(ctx: ProxyCtx, _req: ClearFlowsRequest) -> Result<usize, RpcError> {
|
||||
@@ -626,25 +1102,62 @@ async fn clear_flows(ctx: ProxyCtx, _req: ClearFlowsRequest) -> Result<usize, Rp
|
||||
|
||||
// -- Event loop --
|
||||
|
||||
/// Why the engine cannot be taken over from another app.
|
||||
pub const ANOTHER_APP_OWNS: &str =
|
||||
"Another Yaak Proxy window owns the engine. Quit it to use this one.";
|
||||
|
||||
/// How long taking over waits for the owner to let go of the engine.
|
||||
const TAKE_OVER_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// The longest a new client connection waits for its app to be found before it is served.
|
||||
const ACCEPT_ATTRIBUTION_WAIT: Duration = Duration::from_millis(20);
|
||||
|
||||
/// The longest a flow's end waits for its app to be found, which almost always it already is:
|
||||
/// the lookup starts with the request and takes a few milliseconds.
|
||||
const ATTRIBUTION_WAIT: Duration = Duration::from_millis(100);
|
||||
|
||||
/// A flow between its `RequestStart` and its end, with its bodies being written as they
|
||||
/// stream.
|
||||
struct InFlight {
|
||||
flow: Flow,
|
||||
/// The client connection it came on.
|
||||
connection: u64,
|
||||
request_body: Option<BodyChunkWriter>,
|
||||
response_body: Option<BodyChunkWriter>,
|
||||
}
|
||||
|
||||
fn run_event_loop(
|
||||
rx: std::sync::mpsc::Receiver<ProxyEvent>,
|
||||
/// Where the event loop stores flows, and whether it does.
|
||||
struct FlowSink {
|
||||
db: ProxyQueryManager,
|
||||
blobs: BlobManager,
|
||||
events: RpcEventEmitter,
|
||||
) {
|
||||
attribution: Attribution,
|
||||
recording: Arc<Mutex<RecordingLog>>,
|
||||
}
|
||||
|
||||
fn run_event_loop(rx: std::sync::mpsc::Receiver<ProxyEvent>, sink: FlowSink) {
|
||||
let FlowSink { db, blobs, events, attribution, recording } = sink;
|
||||
let mut in_flight: HashMap<u64, InFlight> = HashMap::new();
|
||||
|
||||
while let Ok(event) = rx.recv() {
|
||||
match event {
|
||||
ProxyEvent::RequestStart { id, started_at, method, url, http_version } => {
|
||||
ProxyEvent::RequestStart {
|
||||
id,
|
||||
started_at,
|
||||
method,
|
||||
url,
|
||||
http_version,
|
||||
connection,
|
||||
client_addr,
|
||||
} => {
|
||||
// Paused when it started: it passes through, and none of its events are kept.
|
||||
// Judged by its start rather than now, as the loop can run behind.
|
||||
if !recording.lock().map(|r| r.was_on_at(started_at)).unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
// Begun as the connection was accepted; this covers one accepted before the
|
||||
// engine's port was known.
|
||||
attribution.begin(connection, client_addr);
|
||||
let flow_id = Flow::generate_id();
|
||||
let request_body = Flow::body_id(&flow_id, FlowBody::Request);
|
||||
let response_body = Flow::body_id(&flow_id, FlowBody::Response);
|
||||
@@ -660,6 +1173,7 @@ fn run_event_loop(
|
||||
id,
|
||||
InFlight {
|
||||
flow,
|
||||
connection,
|
||||
request_body: Some(BodyChunkWriter::new(blobs.clone(), request_body)),
|
||||
response_body: Some(BodyChunkWriter::new(blobs.clone(), response_body)),
|
||||
},
|
||||
@@ -710,14 +1224,14 @@ fn run_event_loop(
|
||||
f.flow.response_truncated = truncated;
|
||||
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
|
||||
f.flow.error = error;
|
||||
finish_flow(&db, &events, f);
|
||||
finish_flow(&db, &events, &attribution, f);
|
||||
}
|
||||
}
|
||||
ProxyEvent::Error { id, error, elapsed_ms } => {
|
||||
if let Some(mut f) = in_flight.remove(&id) {
|
||||
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
|
||||
f.flow.error = Some(error);
|
||||
finish_flow(&db, &events, f);
|
||||
finish_flow(&db, &events, &attribution, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -749,12 +1263,23 @@ fn finish_body(writer: Option<BodyChunkWriter>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_flow(db: &ProxyQueryManager, events: &RpcEventEmitter, f: InFlight) {
|
||||
fn finish_flow(
|
||||
db: &ProxyQueryManager,
|
||||
events: &RpcEventEmitter,
|
||||
attribution: &Attribution,
|
||||
f: InFlight,
|
||||
) {
|
||||
finish_body(f.request_body);
|
||||
finish_body(f.response_body);
|
||||
|
||||
let mut flow = f.flow;
|
||||
flow.content_type = find_header(&flow.response_headers, "content-type").map(String::from);
|
||||
if let Some(app) = attribution.get(f.connection, ATTRIBUTION_WAIT) {
|
||||
flow.client_pid = Some(app.pid);
|
||||
flow.client_name = Some(app.name);
|
||||
flow.client_bundle_id = app.bundle_id;
|
||||
flow.client_path = Some(app.path);
|
||||
}
|
||||
let written = db.with_tx(|ctx| {
|
||||
let (saved, created) = ctx.upsert(&flow, &UpdateSource::Background)?;
|
||||
// Sent while this holds the writer, before the commit, so a clear's event, sent after
|
||||
@@ -777,18 +1302,26 @@ define_rpc! {
|
||||
commands {
|
||||
execute_action(ActionInvocation) -> bool,
|
||||
format_body(FormatBodyRequest) -> String,
|
||||
get_proxy_state(GetProxyStateRequest) -> GetProxyStateResponse,
|
||||
list_actions(ListActionsRequest) -> ListActionsResponse,
|
||||
list_flows(flows::FlowFilter) -> ListFlowsResponse,
|
||||
set_recording(SetRecordingRequest) -> bool,
|
||||
set_system_proxy_at_launch(SetSystemProxyAtLaunchRequest) -> bool,
|
||||
}
|
||||
async_commands {
|
||||
app_icon(AppIconRequest) -> Option<String>,
|
||||
ca_status(CaStatusRequest) -> CaStatus,
|
||||
ca_trust(CaTrustRequest) -> CaStatus,
|
||||
clear_flows(ClearFlowsRequest) -> usize,
|
||||
export_har(ExportHarRequest) -> usize,
|
||||
filter_body(FilterBodyRequest) -> FilterBodyResponse,
|
||||
get_flow_body(GetFlowBodyRequest) -> GetFlowBodyResponse,
|
||||
get_proxy_state(GetProxyStateRequest) -> GetProxyStateResponse,
|
||||
list_workspaces(ListWorkspacesRequest) -> ListWorkspacesResponse,
|
||||
preview_save(PreviewSaveRequest) -> SavePreview,
|
||||
save_flow(SaveFlowToYaakRequest) -> SavedFlow,
|
||||
system_proxy_set(SystemProxySetRequest) -> SystemProxyStatus,
|
||||
system_proxy_status(SystemProxyStatusRequest) -> SystemProxyStatus,
|
||||
take_over(TakeOverRequest) -> bool,
|
||||
}
|
||||
events {
|
||||
flows_cleared(FlowsClearedPayload),
|
||||
@@ -801,6 +1334,24 @@ define_rpc! {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_request_is_recorded_by_the_state_when_it_started() {
|
||||
let mut log = RecordingLog::default();
|
||||
let before = SystemTime::now();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
assert!(log.set(false));
|
||||
assert!(!log.set(false), "no change");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
let while_paused = SystemTime::now();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
assert!(log.set(true));
|
||||
// Read after recording resumed, each is judged by when it started.
|
||||
assert!(log.is_on());
|
||||
assert!(log.was_on_at(before));
|
||||
assert!(!log.was_on_at(while_paused));
|
||||
assert!(log.was_on_at(SystemTime::now()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_app_still_hears_why_a_body_failed_to_decode() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -55,6 +55,14 @@ pub struct Flow {
|
||||
pub error: Option<String>,
|
||||
/// The id of the Yaak request this flow was last saved as.
|
||||
pub saved_request_id: Option<String>,
|
||||
/// The process that opened the client connection, where the platform can tell (macOS).
|
||||
pub client_pid: Option<i32>,
|
||||
/// Its app's name, or its executable's outside an app: "Google Chrome", "curl".
|
||||
pub client_name: Option<String>,
|
||||
/// Its app's bundle id.
|
||||
pub client_bundle_id: Option<String>,
|
||||
/// Its app bundle's path, or its executable's outside an app.
|
||||
pub client_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
@@ -148,6 +156,10 @@ impl UpsertModelInfo for Flow {
|
||||
(ElapsedMs, self.elapsed_ms.into()),
|
||||
(Error, self.error.into()),
|
||||
(SavedRequestId, self.saved_request_id.into()),
|
||||
(ClientPid, self.client_pid.into()),
|
||||
(ClientName, self.client_name.into()),
|
||||
(ClientBundleId, self.client_bundle_id.into()),
|
||||
(ClientPath, self.client_path.into()),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -172,6 +184,10 @@ impl UpsertModelInfo for Flow {
|
||||
FlowIden::ElapsedMs,
|
||||
FlowIden::Error,
|
||||
FlowIden::SavedRequestId,
|
||||
FlowIden::ClientPid,
|
||||
FlowIden::ClientName,
|
||||
FlowIden::ClientBundleId,
|
||||
FlowIden::ClientPath,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -202,11 +218,19 @@ impl UpsertModelInfo for Flow {
|
||||
elapsed_headers_ms: r.get("elapsed_headers_ms")?,
|
||||
elapsed_ms: r.get("elapsed_ms")?,
|
||||
error: r.get("error")?,
|
||||
// Absent from a database read before its migrations have run.
|
||||
saved_request_id: match r.get("saved_request_id") {
|
||||
Err(rusqlite::Error::InvalidColumnName(_)) => None,
|
||||
v => v?,
|
||||
},
|
||||
saved_request_id: added_column(r, "saved_request_id")?,
|
||||
client_pid: added_column(r, "client_pid")?,
|
||||
client_name: added_column(r, "client_name")?,
|
||||
client_bundle_id: added_column(r, "client_bundle_id")?,
|
||||
client_path: added_column(r, "client_path")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A column added by a later migration, absent from a database read before it has run.
|
||||
fn added_column<T: rusqlite::types::FromSql>(r: &Row, name: &str) -> rusqlite::Result<Option<T>> {
|
||||
match r.get(name) {
|
||||
Err(rusqlite::Error::InvalidColumnName(_)) => Ok(None),
|
||||
v => v,
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use crate::convert::{self, DroppedHeader};
|
||||
use crate::models::Flow;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
use ts_rs::TS;
|
||||
use yaak_models::models::HttpRequest;
|
||||
use yaak_models::query_manager::QueryManager;
|
||||
use yaak_models::util::UpdateSource;
|
||||
@@ -17,16 +18,18 @@ pub fn client_data_dir() -> PathBuf {
|
||||
yaak_common::data_dir::resolve_data_dir(app_id)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct WorkspaceSummary {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub folders: Vec<FolderSummary>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct FolderSummary {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
@@ -39,7 +42,7 @@ pub struct FolderSummary {
|
||||
pub struct SaveFlowRequest {
|
||||
pub workspace_id: String,
|
||||
pub folder_id: Option<String>,
|
||||
/// Defaults to the URL's path.
|
||||
/// None or blank leaves the request unnamed, and Yaak shows its URL.
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
@@ -56,11 +59,16 @@ pub struct ClientDb {
|
||||
}
|
||||
|
||||
impl ClientDb {
|
||||
/// Yaak has run on this machine, so there is a database to save into.
|
||||
pub fn exists(data_dir: &Path) -> bool {
|
||||
data_dir.join("db.sqlite").exists()
|
||||
}
|
||||
|
||||
/// Opens `db.sqlite` in Yaak's data directory `data_dir`. Fails when there is none, rather
|
||||
/// than creating a database for a Yaak that has never run.
|
||||
pub fn open(data_dir: &Path) -> Result<Self, String> {
|
||||
let db_path = data_dir.join("db.sqlite");
|
||||
if !db_path.exists() {
|
||||
if !Self::exists(data_dir) {
|
||||
return Err(format!(
|
||||
"Yaak's database was not found at {}. Install Yaak and open it once.",
|
||||
db_path.display()
|
||||
|
||||
@@ -7,15 +7,22 @@ use yaak_proxy::DEFAULT_CAPTURE_BODY_LIMIT;
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ProxySettings {
|
||||
pub port: u16,
|
||||
/// Whether the system proxy points at the engine while it runs.
|
||||
pub system_proxy: bool,
|
||||
/// Point this Mac's web traffic at the engine as it starts. It is turned off again as the
|
||||
/// engine stops, and can be turned on and off any time between. Read from the earlier
|
||||
/// `systemProxy` too, so a saved choice to keep it off carries over.
|
||||
#[serde(alias = "systemProxy")]
|
||||
pub system_proxy_at_launch: bool,
|
||||
/// Bytes of each request and response body stored per flow.
|
||||
pub capture_body_limit: usize,
|
||||
}
|
||||
|
||||
impl Default for ProxySettings {
|
||||
fn default() -> Self {
|
||||
Self { port: 9090, system_proxy: false, capture_body_limit: DEFAULT_CAPTURE_BODY_LIMIT }
|
||||
Self {
|
||||
port: 9090,
|
||||
system_proxy_at_launch: true,
|
||||
capture_body_limit: DEFAULT_CAPTURE_BODY_LIMIT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +53,7 @@ mod tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings::load(&dir.path().join("settings.json")).unwrap();
|
||||
assert_eq!(settings.port, 9090);
|
||||
assert!(!settings.system_proxy);
|
||||
assert!(settings.system_proxy_at_launch);
|
||||
assert_eq!(settings.capture_body_limit, 10 * 1024 * 1024);
|
||||
}
|
||||
|
||||
@@ -63,7 +70,8 @@ mod tests {
|
||||
fn round_trip() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("settings.json");
|
||||
let settings = ProxySettings { port: 8080, system_proxy: true, capture_body_limit: 1024 };
|
||||
let settings =
|
||||
ProxySettings { port: 8080, system_proxy_at_launch: false, capture_body_limit: 1024 };
|
||||
settings.save(&path).unwrap();
|
||||
assert_eq!(ProxySettings::load(&path).unwrap(), settings);
|
||||
|
||||
@@ -71,10 +79,28 @@ mod tests {
|
||||
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
json,
|
||||
serde_json::json!({"port": 8080, "systemProxy": true, "captureBodyLimit": 1024})
|
||||
serde_json::json!({"port": 8080, "systemProxyAtLaunch": false, "captureBodyLimit": 1024})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_earlier_system_proxy_key_carries_over() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("settings.json");
|
||||
std::fs::write(&path, r#"{"port": 9090, "systemProxy": false}"#).unwrap();
|
||||
assert!(!ProxySettings::load(&path).unwrap().system_proxy_at_launch);
|
||||
std::fs::write(&path, r#"{"systemProxy": true}"#).unwrap();
|
||||
assert!(ProxySettings::load(&path).unwrap().system_proxy_at_launch);
|
||||
|
||||
// Saved again under the new key only.
|
||||
let settings = ProxySettings { system_proxy_at_launch: false, ..Default::default() };
|
||||
settings.save(&path).unwrap();
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
|
||||
assert_eq!(json["systemProxyAtLaunch"], false);
|
||||
assert!(json.get("systemProxy").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_json_is_an_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in new issue
Block a user