mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-05 14:26:23 +01:00
Make HTTPS decryption opt-in with a decrypt list (#822)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
91696c2d1f
commit
4538123d88
44 files changed
+3259
-66
No files matched your search
+7
-1
@@ -104,7 +104,13 @@ grpcStatus: number | null,
|
||||
/**
|
||||
* A gRPC call's `grpc-message`, decoded.
|
||||
*/
|
||||
grpcMessage: string | null, };
|
||||
grpcMessage: string | null,
|
||||
/**
|
||||
* An HTTPS connection passed through undecrypted, as the decrypt list leaves it out or its
|
||||
* client rejected the proxy's certificate: method `CONNECT`, its URL the host, its sizes
|
||||
* the bytes each way, and no headers or bodies. Open until `elapsedMs` or `error` is set.
|
||||
*/
|
||||
tunnelled: boolean, };
|
||||
|
||||
export type FlowBody = "request" | "response";
|
||||
|
||||
|
||||
+62
-2
@@ -87,10 +87,40 @@ schema: GrpcSchema | null,
|
||||
*/
|
||||
note: string | null, };
|
||||
|
||||
/**
|
||||
* What HTTPS is decrypted: the user's entries in order, then the built-in exclusions not
|
||||
* removed. A connection is decrypted when a positive entry matches it and no exclusion does.
|
||||
*/
|
||||
export type DecryptList = { entries: Array<DecryptListEntry>, };
|
||||
|
||||
/**
|
||||
* The decrypt list changed, here or through the control API.
|
||||
*/
|
||||
export type DecryptListChangedPayload = { list: DecryptList, };
|
||||
|
||||
/**
|
||||
* One entry of the decrypt list, as the app shows it.
|
||||
*/
|
||||
export type DecryptListEntry = {
|
||||
/**
|
||||
* As stored: `host:*.example.com`, `app:Google Chrome`, `!host:*.apple.com`, `*`.
|
||||
*/
|
||||
entry: string,
|
||||
/**
|
||||
* Shipped with the app: an exclusion of Apple's services or a pinned app's hosts.
|
||||
*/
|
||||
builtIn: boolean, };
|
||||
|
||||
export type DropReason = "hop_by_hop" | "set_by_sending" | "body_decoded";
|
||||
|
||||
export type DroppedHeader = { name: string, value: string, reason: DropReason, };
|
||||
|
||||
/**
|
||||
* Entries to add after the user's own and to remove, applied to the list as it is when the
|
||||
* change lands. Each is normalized first.
|
||||
*/
|
||||
export type EditDecryptListRequest = { add: Array<string>, remove: Array<string>, };
|
||||
|
||||
export type ExportHarRequest = {
|
||||
/**
|
||||
* The file to write.
|
||||
@@ -145,6 +175,10 @@ app?: Array<string>,
|
||||
* tells them by their executable.
|
||||
*/
|
||||
system?: boolean,
|
||||
/**
|
||||
* Only HTTPS connections tunnelled undecrypted (true), or none of them (false).
|
||||
*/
|
||||
tunnelled?: boolean,
|
||||
/**
|
||||
* Only flows one of these groups covers, each judged on its own: several sidebar rows
|
||||
* selected, `@app:Slack @host:a.com OR @app:Chrome @host:b.com`, are two groups and not every
|
||||
@@ -186,6 +220,8 @@ folderId: string | null, };
|
||||
|
||||
export type FormatBodyRequest = { text: string, };
|
||||
|
||||
export type GetDecryptListRequest = Record<string, never>;
|
||||
|
||||
export type GetFlowBodyRequest = { flowId: string, which: FlowBody, };
|
||||
|
||||
export type GetFlowBodyResponse = {
|
||||
@@ -319,6 +355,8 @@ messages: Array<FlowMessage>,
|
||||
*/
|
||||
total: number, };
|
||||
|
||||
export type ListSeenRequest = Record<string, never>;
|
||||
|
||||
export type ListWorkspacesRequest = Record<string, never>;
|
||||
|
||||
export type ListWorkspacesResponse = {
|
||||
@@ -374,9 +412,9 @@ host: string, };
|
||||
|
||||
export type RemoveGrpcSchemaRequest = { id: string, };
|
||||
|
||||
export type RpcEventSchema = { flows_cleared: FlowsClearedPayload, message_write: MessagePayload, model_write: ModelPayload, proxy_state_changed: ProxyStatePayload, };
|
||||
export type RpcEventSchema = { decrypt_list_changed: DecryptListChangedPayload, flows_cleared: FlowsClearedPayload, message_write: MessagePayload, model_write: ModelPayload, proxy_state_changed: ProxyStatePayload, };
|
||||
|
||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], format_body: [FormatBodyRequest, string], get_message_payload: [GetMessagePayloadRequest, GetMessagePayloadResponse], list_actions: [ListActionsRequest, ListActionsResponse], list_flows: [FlowFilter, ListFlowsResponse], list_grpc_schemas: [ListGrpcSchemasRequest, Array<GrpcSchema>], list_messages: [ListMessagesRequest, ListMessagesResponse], remove_grpc_schema: [RemoveGrpcSchemaRequest, boolean], set_recording: [SetRecordingRequest, boolean], set_system_proxy_at_launch: [SetSystemProxyAtLaunchRequest, boolean], set_http_version: [SetHttpVersionRequest, HttpVersion], add_grpc_schema: [AddGrpcSchemaRequest, GrpcSchema], app_icon: [AppIconRequest, string | null], ca_status: [CaStatusRequest, CaStatus], ca_trust: [CaTrustRequest, CaStatus], clear_flows: [ClearFlowsRequest, number], decode_grpc_message: [DecodeGrpcMessageRequest, DecodedGrpcMessage], export_har: [ExportHarRequest, number], filter_body: [FilterBodyRequest, FilterBodyResponse], get_flow_body: [GetFlowBodyRequest, GetFlowBodyResponse], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], helper_register: [HelperRegisterRequest, SystemProxyStatus], helper_unregister: [HelperUnregisterRequest, SystemProxyStatus], list_workspaces: [ListWorkspacesRequest, ListWorkspacesResponse], preview_save: [PreviewSaveRequest, SavePreview], reflect_grpc_host: [ReflectGrpcHostRequest, GrpcSchema], save_flow: [SaveFlowToYaakRequest, SavedFlow], save_flow_body: [SaveFlowBodyRequest, SaveFlowBodyResponse], system_proxy_set: [SystemProxySetRequest, SystemProxyStatus], system_proxy_status: [SystemProxyStatusRequest, SystemProxyStatus], take_over: [TakeOverRequest, boolean], };
|
||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], format_body: [FormatBodyRequest, string], get_decrypt_list: [GetDecryptListRequest, DecryptList], get_message_payload: [GetMessagePayloadRequest, GetMessagePayloadResponse], list_actions: [ListActionsRequest, ListActionsResponse], list_flows: [FlowFilter, ListFlowsResponse], list_grpc_schemas: [ListGrpcSchemasRequest, Array<GrpcSchema>], list_messages: [ListMessagesRequest, ListMessagesResponse], remove_grpc_schema: [RemoveGrpcSchemaRequest, boolean], set_recording: [SetRecordingRequest, boolean], set_system_proxy_at_launch: [SetSystemProxyAtLaunchRequest, boolean], set_http_version: [SetHttpVersionRequest, HttpVersion], add_grpc_schema: [AddGrpcSchemaRequest, GrpcSchema], app_icon: [AppIconRequest, string | null], ca_status: [CaStatusRequest, CaStatus], ca_trust: [CaTrustRequest, CaStatus], clear_flows: [ClearFlowsRequest, number], decode_grpc_message: [DecodeGrpcMessageRequest, DecodedGrpcMessage], export_har: [ExportHarRequest, number], filter_body: [FilterBodyRequest, FilterBodyResponse], get_flow_body: [GetFlowBodyRequest, GetFlowBodyResponse], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], helper_register: [HelperRegisterRequest, SystemProxyStatus], helper_unregister: [HelperUnregisterRequest, SystemProxyStatus], edit_decrypt_list: [EditDecryptListRequest, DecryptList], list_seen: [ListSeenRequest, SeenTargets], set_decrypt_list: [SetDecryptListRequest, DecryptList], list_workspaces: [ListWorkspacesRequest, ListWorkspacesResponse], preview_save: [PreviewSaveRequest, SavePreview], reflect_grpc_host: [ReflectGrpcHostRequest, GrpcSchema], save_flow: [SaveFlowToYaakRequest, SavedFlow], save_flow_body: [SaveFlowBodyRequest, SaveFlowBodyResponse], system_proxy_set: [SystemProxySetRequest, SystemProxyStatus], system_proxy_status: [SystemProxyStatusRequest, SystemProxyStatus], take_over: [TakeOverRequest, boolean], };
|
||||
|
||||
export type SaveFlowBodyRequest = { flowId: string, which: FlowBody,
|
||||
/**
|
||||
@@ -440,6 +478,21 @@ authorization: boolean, };
|
||||
|
||||
export type SavedFlow = { requestId: string, name: string, };
|
||||
|
||||
export type SeenApp = { name: string, bundleId: string | null, };
|
||||
|
||||
/**
|
||||
* The hosts and apps flows have gone to and come from, for the decrypt list's suggestions.
|
||||
*/
|
||||
export type SeenTargets = {
|
||||
/**
|
||||
* Hosts as the sidebar names them, with a port other than the scheme's: most recent first.
|
||||
*/
|
||||
hosts: Array<string>,
|
||||
/**
|
||||
* Apps by name and bundle id, most recent first.
|
||||
*/
|
||||
apps: Array<SeenApp>, };
|
||||
|
||||
export type ServiceProxy = {
|
||||
/**
|
||||
* The network service, as System Settings names it: "Wi-Fi", "USB 10/100/1000 LAN".
|
||||
@@ -451,6 +504,13 @@ name: string,
|
||||
*/
|
||||
id?: string, http: ProxySetting, https: ProxySetting, };
|
||||
|
||||
export type SetDecryptListRequest = {
|
||||
/**
|
||||
* Every entry, in order, as typed: a bare hostname is a `host:` entry. A built-in
|
||||
* exclusion left out is removed.
|
||||
*/
|
||||
entries: Array<string>, };
|
||||
|
||||
export type SetHttpVersionRequest = { httpVersion: HttpVersion, };
|
||||
|
||||
export type SetRecordingRequest = { enabled: boolean, };
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- An HTTPS connection passed through undecrypted, recorded with only its host and sizes.
|
||||
ALTER TABLE flows ADD COLUMN tunnelled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
@@ -5,8 +5,8 @@
|
||||
use crate::bodies::{self, DecodedBody};
|
||||
use crate::ca::CaStatus;
|
||||
use crate::control::{
|
||||
self, ControlInfo, ControlStatus, ErrorBody, NOTE_HEADER, RecordingRequest, StartRequest,
|
||||
SystemProxyRequest, TRUNCATED_HEADER,
|
||||
self, ControlInfo, ControlStatus, DecryptRequest, ErrorBody, NOTE_HEADER, RecordingRequest,
|
||||
StartRequest, SystemProxyRequest, TRUNCATED_HEADER,
|
||||
};
|
||||
use crate::db::ProxyQueryManager;
|
||||
use crate::db::Stores;
|
||||
@@ -15,7 +15,7 @@ use crate::har::{self, Har};
|
||||
use crate::macos::SystemProxyStatus;
|
||||
use crate::models::{Flow, FlowBody};
|
||||
use crate::save::{SaveFlowRequest, SaveFlowResponse, WorkspaceSummary};
|
||||
use crate::settings::ProxySettings;
|
||||
use crate::settings::{DecryptList, ProxySettings};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::path::Path;
|
||||
@@ -146,6 +146,38 @@ impl ControlClient {
|
||||
self.post("/system-proxy", &SystemProxyRequest { enabled }).await
|
||||
}
|
||||
|
||||
pub async fn decrypt_list(&self) -> Result<DecryptList, String> {
|
||||
self.get("/decrypt").await
|
||||
}
|
||||
|
||||
/// Adds and removes entries in the owner's decrypt list as it is there.
|
||||
pub async fn edit_decrypt_list(
|
||||
&self,
|
||||
edit: &crate::EditDecryptListRequest,
|
||||
) -> Result<DecryptList, String> {
|
||||
let body = serde_json::to_vec(edit).map_err(|e| e.to_string())?;
|
||||
let req = self
|
||||
.http
|
||||
.patch(self.url("/decrypt"))
|
||||
.header("content-type", "application/json")
|
||||
.body(body);
|
||||
let resp = self.send(req).await?;
|
||||
resp.json().await.map_err(|e| format!("Invalid response from the proxy: {e}"))
|
||||
}
|
||||
|
||||
/// Replaces the decrypt list in the owner, which saves it and applies it to its engine.
|
||||
pub async fn set_decrypt_list(&self, entries: &[String]) -> Result<DecryptList, String> {
|
||||
let body = serde_json::to_vec(&DecryptRequest { entries: entries.to_vec() })
|
||||
.map_err(|e| e.to_string())?;
|
||||
let req = self
|
||||
.http
|
||||
.put(self.url("/decrypt"))
|
||||
.header("content-type", "application/json")
|
||||
.body(body);
|
||||
let resp = self.send(req).await?;
|
||||
resp.json().await.map_err(|e| format!("Invalid response from the proxy: {e}"))
|
||||
}
|
||||
|
||||
pub async fn workspaces(&self) -> Result<Vec<WorkspaceSummary>, String> {
|
||||
self.get("/workspaces").await
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ use crate::messages::{self, FlowMessage, MessageKind};
|
||||
use crate::models::{FlowBody, find_header};
|
||||
use crate::save::SaveFlowRequest;
|
||||
use crate::{
|
||||
AddGrpcSchemaRequest, ListMessagesResponse, ProxyCtx, ProxyState, ReflectGrpcHostRequest,
|
||||
bodies,
|
||||
AddGrpcSchemaRequest, EditDecryptListRequest, ListMessagesResponse, ProxyCtx, ProxyState,
|
||||
ReflectGrpcHostRequest, bodies,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use chrono::{DateTime, Utc};
|
||||
@@ -237,6 +237,13 @@ pub struct RecordingRequest {
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// `PUT /decrypt`: every entry of the decrypt list, in order. A built-in exclusion left out is
|
||||
/// removed.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DecryptRequest {
|
||||
pub entries: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ClearResponse {
|
||||
/// How many flows were deleted.
|
||||
@@ -527,6 +534,15 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
|
||||
ctx.set_recording(body.enabled);
|
||||
json(&status(ctx).await?)
|
||||
}
|
||||
(&Method::GET, ["decrypt"]) => json(&ctx.decrypt_list()?),
|
||||
(&Method::PATCH, ["decrypt"]) => {
|
||||
let body: EditDecryptListRequest = read_json(req).await?;
|
||||
json(&ctx.edit_decrypt_list(&body.add, &body.remove).map_err(bad_request)?)
|
||||
}
|
||||
(&Method::PUT, ["decrypt"]) => {
|
||||
let body: DecryptRequest = read_json(req).await?;
|
||||
json(&ctx.set_decrypt_list(&body.entries).map_err(bad_request)?)
|
||||
}
|
||||
(&Method::GET, ["flows"]) => {
|
||||
let filter = FlowFilter::from_query(&query).map_err(bad_request)?;
|
||||
json(&flows::list(&ctx.db()?, &filter)?)
|
||||
|
||||
@@ -25,6 +25,23 @@ pub const BLOBS_DB: &str = "blobs.sqlite";
|
||||
/// The key both are encrypted with, wrapped by the app's master key in the keychain.
|
||||
pub const DATA_KEY: &str = "data.key";
|
||||
|
||||
/// A pre-release build added `flows.tunnelled` in migration 8. A database it made has the
|
||||
/// column without migration 9 recorded, which would fail adding it again, so it is recorded
|
||||
/// as applied first.
|
||||
fn record_early_tunnelled_column(pool: &SqlitePool) -> Result<()> {
|
||||
let conn = pool.get()?;
|
||||
let has_column = conn.prepare("SELECT tunnelled FROM flows LIMIT 0").is_ok();
|
||||
let has_tracking = conn.prepare("SELECT version FROM _sqlx_migrations LIMIT 0").is_ok();
|
||||
if has_column && has_tracking {
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO _sqlx_migrations (version, description) \
|
||||
VALUES ('00000009', '00000009_flow_tunnelled.sql')",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads come from a pool; writes go through one connection, as in yaak-models'
|
||||
/// `QueryManager`. WAL lets the CLI read `proxy.db` while the app writes it.
|
||||
#[derive(Clone)]
|
||||
@@ -42,6 +59,7 @@ impl ProxyQueryManager {
|
||||
}
|
||||
encryption::encrypt_in_place(db_path, key, &|_| {})?;
|
||||
let writer = file_pool(db_path, 1, key)?;
|
||||
record_early_tunnelled_column(&writer)?;
|
||||
run_migrations(&writer, &MIGRATIONS)?;
|
||||
Ok(Self { readers: file_pool(db_path, 5, key)?, writer })
|
||||
}
|
||||
@@ -512,7 +530,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.map(|v| v.unwrap())
|
||||
.collect();
|
||||
assert_eq!(&applied[applied.len() - 2..], ["00000007", "00000008"]);
|
||||
assert_eq!(&applied[applied.len() - 3..], ["00000007", "00000008", "00000009"]);
|
||||
let mark_columns = columns(&conn, "flow_clear_mark");
|
||||
assert_eq!(mark_columns, ["id", "max_rowid", "cleaner", "cleaner_at"]);
|
||||
drop(conn);
|
||||
@@ -532,4 +550,109 @@ mod tests {
|
||||
);
|
||||
assert_eq!(crate::messages::count(&db, "fl_ws").unwrap(), 0);
|
||||
}
|
||||
|
||||
/// A database a pre-release build made, with `tunnelled` added by its migration 8, opens
|
||||
/// without adding the column twice.
|
||||
#[test]
|
||||
fn opens_a_database_whose_migration_8_added_tunnelled() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("proxy.db");
|
||||
let conn = Connection::open(&path).unwrap();
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE _sqlx_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
description TEXT NOT NULL,
|
||||
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);",
|
||||
)
|
||||
.unwrap();
|
||||
let mut files: Vec<_> = MIGRATIONS
|
||||
.files()
|
||||
.map(|f| (f.path().to_string_lossy().into_owned(), f.contents_utf8().unwrap()))
|
||||
.filter(|(name, _)| name.as_str() < "00000009")
|
||||
.collect();
|
||||
files.sort();
|
||||
for (name, sql) in files {
|
||||
conn.execute_batch(sql).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO _sqlx_migrations (version, description) VALUES (?, ?)",
|
||||
[&name[..8], &name],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
conn.execute_batch(
|
||||
"ALTER TABLE flows ADD COLUMN tunnelled BOOLEAN NOT NULL DEFAULT FALSE;",
|
||||
)
|
||||
.unwrap();
|
||||
drop(conn);
|
||||
|
||||
let db = ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap();
|
||||
let tunnel = crate::models::Flow {
|
||||
id: "fl_tunnel".into(),
|
||||
url: "https://a.com".into(),
|
||||
tunnelled: true,
|
||||
..Default::default()
|
||||
};
|
||||
db.with_tx(|c| c.upsert(&tunnel, &yaak_database::UpdateSource::Background).map(|_| ()))
|
||||
.unwrap();
|
||||
assert!(crate::flows::find(&db, "fl_tunnel").unwrap().tunnelled);
|
||||
drop(db);
|
||||
// And again, with everything recorded.
|
||||
drop(ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap());
|
||||
}
|
||||
|
||||
/// A database that ran every migration up to the clear cleaner's, as the build before
|
||||
/// tunnelled flows left it, takes the `tunnelled` column and stores tunnelled flows.
|
||||
#[test]
|
||||
fn adds_tunnelled_to_a_database_at_migration_8() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("proxy.db");
|
||||
let conn = Connection::open(&path).unwrap();
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE _sqlx_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
description TEXT NOT NULL,
|
||||
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);",
|
||||
)
|
||||
.unwrap();
|
||||
let mut files: Vec<_> = MIGRATIONS
|
||||
.files()
|
||||
.map(|f| (f.path().to_string_lossy().into_owned(), f.contents_utf8().unwrap()))
|
||||
.filter(|(name, _)| name.as_str() < "00000009")
|
||||
.collect();
|
||||
files.sort();
|
||||
assert_eq!(files.len(), 8);
|
||||
for (name, sql) in files {
|
||||
conn.execute_batch(sql).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO _sqlx_migrations (version, description) VALUES (?, ?)",
|
||||
[&name[..8], &name],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO flows (id, url, method) VALUES ('fl_old', 'https://a.com/', 'GET')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!columns(&conn, "flows").contains(&"tunnelled".to_string()));
|
||||
drop(conn);
|
||||
|
||||
let db = ProxyQueryManager::new(&path, &crate::db::test_key()).unwrap();
|
||||
let tunnel = crate::models::Flow {
|
||||
id: "fl_tunnel".into(),
|
||||
method: "CONNECT".into(),
|
||||
url: "https://bank.example.com".into(),
|
||||
tunnelled: true,
|
||||
..Default::default()
|
||||
};
|
||||
db.with_tx(|c| c.upsert(&tunnel, &yaak_database::UpdateSource::Background).map(|_| ()))
|
||||
.unwrap();
|
||||
let filter = crate::flows::FlowFilter { tunnelled: Some(true), ..Default::default() };
|
||||
let listed = crate::flows::list(&db, &filter).unwrap();
|
||||
assert_eq!(listed.iter().map(|f| f.id.as_str()).collect::<Vec<_>>(), ["fl_tunnel"]);
|
||||
let old = crate::flows::find(&db, "fl_old").unwrap();
|
||||
assert!(!old.tunnelled);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,9 @@ pub struct FlowFilter {
|
||||
/// tells them by their executable.
|
||||
#[ts(optional)]
|
||||
pub system: Option<bool>,
|
||||
/// Only HTTPS connections tunnelled undecrypted (true), or none of them (false).
|
||||
#[ts(optional)]
|
||||
pub tunnelled: Option<bool>,
|
||||
/// Only flows one of these groups covers, each judged on its own: several sidebar rows
|
||||
/// selected, `@app:Slack @host:a.com OR @app:Chrome @host:b.com`, are two groups and not every
|
||||
/// pairing of their apps and hosts. A group's `after`, `before` and `limit` do not apply. Not
|
||||
@@ -78,6 +81,11 @@ impl FlowFilter {
|
||||
.map(|v| v.parse().map_err(|_| format!("Invalid system {v:?}")))
|
||||
.transpose()?
|
||||
}
|
||||
"tunnelled" => {
|
||||
filter.tunnelled = value
|
||||
.map(|v| v.parse().map_err(|_| format!("Invalid tunnelled {v:?}")))
|
||||
.transpose()?
|
||||
}
|
||||
"method" => filter.method = value,
|
||||
"status" => filter.status = value,
|
||||
"after" => filter.after = value,
|
||||
@@ -97,7 +105,13 @@ impl FlowFilter {
|
||||
let mut query = url::form_urlencoded::Serializer::new(String::new());
|
||||
let limit = self.limit.map(|l| l.to_string());
|
||||
let system = self.system.map(|s| s.to_string());
|
||||
for (key, value) in [("q", &self.q), ("host", &self.host), ("system", &system)] {
|
||||
let tunnelled = self.tunnelled.map(|t| t.to_string());
|
||||
for (key, value) in [
|
||||
("q", &self.q),
|
||||
("host", &self.host),
|
||||
("system", &system),
|
||||
("tunnelled", &tunnelled),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
query.append_pair(key, value);
|
||||
}
|
||||
@@ -131,6 +145,7 @@ impl FlowFilter {
|
||||
|| self.under.is_some()
|
||||
|| self.app.is_some()
|
||||
|| self.system.is_some()
|
||||
|| self.tunnelled.is_some()
|
||||
|| self.any.as_ref().is_some_and(|groups| groups.iter().any(FlowFilter::narrows))
|
||||
}
|
||||
|
||||
@@ -138,12 +153,17 @@ impl FlowFilter {
|
||||
/// for the database `conn` reads, which may be from before the folder or gRPC columns, when
|
||||
/// read without migrating.
|
||||
fn condition_in(&self, conn: &rusqlite::Connection) -> (String, Vec<Value>) {
|
||||
self.condition(has_column(conn, "client_cwd"), has_column(conn, "grpc_status"))
|
||||
let columns = Columns {
|
||||
cwd: has_column(conn, "client_cwd"),
|
||||
grpc: has_column(conn, "grpc_status"),
|
||||
tunnelled: has_column(conn, "tunnelled"),
|
||||
};
|
||||
self.condition(columns)
|
||||
}
|
||||
|
||||
/// [`Self::condition_in`], told which of the later columns the database has: `has_cwd`,
|
||||
/// the folder a program ran in, and `grpc`, gRPC statuses.
|
||||
fn condition(&self, has_cwd: bool, grpc: bool) -> (String, Vec<Value>) {
|
||||
/// [`Self::condition_in`], told which of the later columns the database has.
|
||||
fn condition(&self, columns: Columns) -> (String, Vec<Value>) {
|
||||
let Columns { cwd: has_cwd, grpc, tunnelled } = columns;
|
||||
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()) {
|
||||
@@ -209,11 +229,18 @@ impl FlowFilter {
|
||||
Some(false) => sql.push_str(" AND NOT is_system(client_bundle_id, client_path)"),
|
||||
None => {}
|
||||
}
|
||||
match (self.tunnelled, tunnelled) {
|
||||
(Some(true), true) => sql.push_str(" AND tunnelled"),
|
||||
(Some(false), true) => sql.push_str(" AND NOT tunnelled"),
|
||||
// A database from before tunnelled flows has none.
|
||||
(Some(true), false) => sql.push_str(" AND 0"),
|
||||
_ => {}
|
||||
}
|
||||
// Each group whole, then any of them.
|
||||
if let Some(groups) = self.any.as_ref().filter(|g| !g.is_empty()) {
|
||||
let mut any = Vec::new();
|
||||
for group in groups {
|
||||
let (condition, group_params) = group.condition(has_cwd, grpc);
|
||||
let (condition, group_params) = group.condition(columns);
|
||||
any.push(format!("({condition})"));
|
||||
params.extend(group_params);
|
||||
}
|
||||
@@ -245,6 +272,17 @@ impl FlowFilter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of the columns later migrations added a database has, as one opened read-only before
|
||||
/// they ran may not.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Columns {
|
||||
/// The folder a program ran in.
|
||||
cwd: bool,
|
||||
/// gRPC statuses.
|
||||
grpc: bool,
|
||||
tunnelled: bool,
|
||||
}
|
||||
|
||||
/// 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 \
|
||||
@@ -647,6 +685,73 @@ pub fn get(db: &ProxyQueryManager, flow_id: &str) -> Result<Flow, String> {
|
||||
find(db, flow_id).ok_or_else(|| format!("No flow {flow_id}"))
|
||||
}
|
||||
|
||||
/// The hosts and apps flows have gone to and come from, for the decrypt list's suggestions.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct SeenTargets {
|
||||
/// Hosts as the sidebar names them, with a port other than the scheme's: most recent first.
|
||||
pub hosts: Vec<String>,
|
||||
/// Apps by name and bundle id, most recent first.
|
||||
pub apps: Vec<SeenApp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct SeenApp {
|
||||
pub name: String,
|
||||
pub bundle_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Distinct hosts and apps listed by [`seen`] at most.
|
||||
const SEEN_LIMIT: i64 = 1000;
|
||||
|
||||
/// The distinct hosts and apps of the flows not cleared, most recent first, up to
|
||||
/// [`SEEN_LIMIT`] of each.
|
||||
pub fn seen(db: &ProxyQueryManager) -> Result<SeenTargets, String> {
|
||||
db.with_conn(|c| {
|
||||
let conn = c.conn().resolve();
|
||||
let mut params: Vec<Value> = Vec::new();
|
||||
let mut cleared = String::new();
|
||||
push_clear_mark(conn, &mut cleared, &mut params);
|
||||
params.push(SEEN_LIMIT.into());
|
||||
// The newest flow of each host, whose URL names it as the sidebar does.
|
||||
let sql = format!(
|
||||
"SELECT url FROM flows WHERE rowid IN (SELECT max(rowid) FROM flows WHERE 1{cleared} \
|
||||
GROUP BY lower({HOST_SQL})) ORDER BY rowid DESC LIMIT ?"
|
||||
);
|
||||
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let urls = stmt
|
||||
.query_map(rusqlite::params_from_iter(params.clone()), |r| r.get::<_, String>(0))
|
||||
.map_err(|e| e.to_string())?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut hosts: Vec<String> = Vec::new();
|
||||
for url in urls {
|
||||
let path = sidebar_path(&url);
|
||||
let host = path.split('/').next().unwrap_or_default().to_string();
|
||||
if !host.is_empty() && !hosts.contains(&host) {
|
||||
hosts.push(host);
|
||||
}
|
||||
}
|
||||
|
||||
let sql = format!(
|
||||
"SELECT client_name, client_bundle_id FROM flows WHERE client_name IS NOT NULL{cleared} \
|
||||
GROUP BY client_name, client_bundle_id ORDER BY max(rowid) DESC LIMIT ?"
|
||||
);
|
||||
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let apps = stmt
|
||||
.query_map(rusqlite::params_from_iter(params), |r| {
|
||||
Ok(SeenApp { name: r.get(0)?, bundle_id: r.get(1)? })
|
||||
})
|
||||
.map_err(|e| e.to_string())?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(SeenTargets { hosts, apps })
|
||||
})
|
||||
}
|
||||
|
||||
pub fn count(db: &ProxyQueryManager) -> Result<usize, String> {
|
||||
db.with_conn(|c| count_in(c.conn().resolve()))
|
||||
}
|
||||
@@ -1326,6 +1431,12 @@ mod tests {
|
||||
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());
|
||||
|
||||
let tunnelled = FlowFilter { tunnelled: Some(true), ..Default::default() };
|
||||
assert_eq!(tunnelled.to_query(), "tunnelled=true");
|
||||
assert_eq!(FlowFilter::from_query("tunnelled=true").unwrap(), tunnelled);
|
||||
assert!(tunnelled.narrows());
|
||||
assert!(FlowFilter::from_query("tunnelled=maybe").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -29,7 +29,7 @@ use crate::macos::{SystemProxyBackend, SystemProxyStatus};
|
||||
use crate::messages::FlowMessage;
|
||||
use crate::models::{Flow, FlowBody, ModelPayload, ProxyHeader, StreamKind, find_header};
|
||||
use crate::save::{ClientDb, SaveFlowRequest, SaveFlowResponse, WorkspaceSummary};
|
||||
use crate::settings::{HttpVersion, ProxySettings};
|
||||
use crate::settings::{DecryptList, HttpVersion, ProxySettings};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use chrono::{DateTime, Utc};
|
||||
@@ -80,6 +80,9 @@ pub struct ProxyCtx {
|
||||
/// This context's name as the one deleting cleared flows, which the database leases to one
|
||||
/// process at a time.
|
||||
cleaner_id: String,
|
||||
/// Held through each change to the decrypt list, so concurrent edits apply in turn, each to
|
||||
/// the list the last one left.
|
||||
decrypt_edits: Arc<Mutex<()>>,
|
||||
/// Where the master key that unwraps the data key is kept: the keychain, normally.
|
||||
keys: MasterKeySource,
|
||||
/// The data key, once read. Held while it is read and the databases converted and opened,
|
||||
@@ -127,6 +130,7 @@ impl ProxyCtx {
|
||||
start_error: Arc::new(Mutex::new(None)),
|
||||
deleting_cleared: Arc::new(Mutex::new(false)),
|
||||
cleaner_id: yaak_database::generate_prefixed_id("cln"),
|
||||
decrypt_edits: Arc::new(Mutex::new(())),
|
||||
keys,
|
||||
unlocked: Arc::new(Mutex::new(None)),
|
||||
encrypting: Arc::new(Mutex::new(None)),
|
||||
@@ -370,9 +374,15 @@ impl ProxyCtx {
|
||||
let mut config = ProxyConfig::new(port.unwrap_or(settings.port), Arc::new(ca));
|
||||
config.capture_body_limit = settings.capture_body_limit;
|
||||
config.http2 = settings.http_version == HttpVersion::Auto;
|
||||
config.decrypt = settings.decrypt_policy();
|
||||
// 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.app_of = Some(Arc::new(move |connection| {
|
||||
let app = slot.get()?.get(connection, ATTRIBUTION_WAIT)?;
|
||||
Some(yaak_proxy::DecryptApp { name: app.name, bundle_id: app.bundle_id })
|
||||
}));
|
||||
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.
|
||||
@@ -430,11 +440,17 @@ impl ProxyCtx {
|
||||
return;
|
||||
};
|
||||
let ended = db.with_tx(|c| {
|
||||
c.conn().resolve().execute(
|
||||
let conn = c.conn().resolve();
|
||||
conn.execute(
|
||||
"UPDATE flows SET error = ?1 WHERE stream_kind IS NOT NULL \
|
||||
AND elapsed_ms IS NULL AND error IS NULL AND NOT cancelled",
|
||||
[STOPPED_MID_STREAM],
|
||||
)?;
|
||||
conn.execute(
|
||||
"UPDATE flows SET error = ?1 WHERE tunnelled \
|
||||
AND elapsed_ms IS NULL AND error IS NULL",
|
||||
[STOPPED_MID_TUNNEL],
|
||||
)?;
|
||||
Ok::<_, yaak_database::Error>(())
|
||||
});
|
||||
if let Err(e) = ended {
|
||||
@@ -687,6 +703,47 @@ impl ProxyCtx {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What HTTPS is decrypted, as `settings.json` has it.
|
||||
pub fn decrypt_list(&self) -> Result<DecryptList, String> {
|
||||
Ok(self.settings()?.decrypt_list())
|
||||
}
|
||||
|
||||
/// Replaces the decrypt list, saved in `settings.json` and applied to the running engine's
|
||||
/// next connections. Connections already open stay as they were.
|
||||
pub fn set_decrypt_list(&self, entries: &[String]) -> Result<DecryptList, String> {
|
||||
self.change_decrypt_list(|settings| settings.set_decrypt_list(entries))
|
||||
}
|
||||
|
||||
/// Adds and removes entries in the list as it is now, so edits made together each keep
|
||||
/// the other's, unlike replacing the whole list from a copy read earlier.
|
||||
pub fn edit_decrypt_list(
|
||||
&self,
|
||||
add: &[String],
|
||||
remove: &[String],
|
||||
) -> Result<DecryptList, String> {
|
||||
self.change_decrypt_list(|settings| settings.edit_decrypt_list(add, remove))
|
||||
}
|
||||
|
||||
/// Changes the list in `settings.json`, one change at a time, applies it to the running
|
||||
/// engine, and tells the app.
|
||||
fn change_decrypt_list(
|
||||
&self,
|
||||
change: impl FnOnce(&mut ProxySettings) -> Result<(), String>,
|
||||
) -> Result<DecryptList, String> {
|
||||
let _turn = self.decrypt_edits.lock().map_err(|_| "lock poisoned".to_string())?;
|
||||
let mut settings = self.settings()?;
|
||||
change(&mut settings)?;
|
||||
settings.save(&self.settings_path())?;
|
||||
if let Ok(handle) = self.handle.lock()
|
||||
&& let Some(handle) = handle.as_ref()
|
||||
{
|
||||
handle.set_decrypt_policy(settings.decrypt_policy());
|
||||
}
|
||||
let list = settings.decrypt_list();
|
||||
self.events.emit("decrypt_list_changed", &DecryptListChangedPayload { list: list.clone() });
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
@@ -947,6 +1004,13 @@ pub enum ProxyState {
|
||||
Stopped,
|
||||
}
|
||||
|
||||
/// The decrypt list changed, here or through the control API.
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct DecryptListChangedPayload {
|
||||
pub list: DecryptList,
|
||||
}
|
||||
|
||||
#[derive(Serialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ProxyStatePayload {
|
||||
@@ -1090,6 +1154,32 @@ pub struct SetHttpVersionRequest {
|
||||
pub http_version: HttpVersion,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct GetDecryptListRequest {}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct SetDecryptListRequest {
|
||||
/// Every entry, in order, as typed: a bare hostname is a `host:` entry. A built-in
|
||||
/// exclusion left out is removed.
|
||||
pub entries: Vec<String>,
|
||||
}
|
||||
|
||||
/// Entries to add after the user's own and to remove, applied to the list as it is when the
|
||||
/// change lands. Each is normalized first.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)]
|
||||
#[serde(default)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct EditDecryptListRequest {
|
||||
pub add: Vec<String>,
|
||||
pub remove: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct ListSeenRequest {}
|
||||
|
||||
#[derive(Deserialize, TS)]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct AppIconRequest {
|
||||
@@ -1498,6 +1588,42 @@ fn set_http_version(ctx: &ProxyCtx, req: SetHttpVersionRequest) -> Result<HttpVe
|
||||
Ok(req.http_version)
|
||||
}
|
||||
|
||||
fn get_decrypt_list(ctx: &ProxyCtx, _req: GetDecryptListRequest) -> Result<DecryptList, RpcError> {
|
||||
ctx.decrypt_list().map_err(rpc_error)
|
||||
}
|
||||
|
||||
/// Saved and applied here, or, while another process such as the CLI daemon owns the engine,
|
||||
/// there, as its engine is the one that reads it.
|
||||
async fn set_decrypt_list(
|
||||
ctx: ProxyCtx,
|
||||
req: SetDecryptListRequest,
|
||||
) -> Result<DecryptList, RpcError> {
|
||||
if ctx.port().is_none()
|
||||
&& let Some(owner) = ctx.other_owner()
|
||||
{
|
||||
return ControlClient::new(owner).set_decrypt_list(&req.entries).await.map_err(rpc_error);
|
||||
}
|
||||
blocking(move || ctx.set_decrypt_list(&req.entries)).await
|
||||
}
|
||||
|
||||
/// [`set_decrypt_list`], adding and removing entries rather than replacing them all.
|
||||
async fn edit_decrypt_list(
|
||||
ctx: ProxyCtx,
|
||||
req: EditDecryptListRequest,
|
||||
) -> Result<DecryptList, RpcError> {
|
||||
if ctx.port().is_none()
|
||||
&& let Some(owner) = ctx.other_owner()
|
||||
{
|
||||
return ControlClient::new(owner).edit_decrypt_list(&req).await.map_err(rpc_error);
|
||||
}
|
||||
blocking(move || ctx.edit_decrypt_list(&req.add, &req.remove)).await
|
||||
}
|
||||
|
||||
async fn list_seen(ctx: ProxyCtx, _req: ListSeenRequest) -> Result<flows::SeenTargets, RpcError> {
|
||||
let db = ctx.db()?;
|
||||
blocking(move || flows::seen(&db)).await
|
||||
}
|
||||
|
||||
async fn take_over(ctx: ProxyCtx, _req: TakeOverRequest) -> Result<bool, RpcError> {
|
||||
ctx.take_over().await.map_err(rpc_error)?;
|
||||
Ok(true)
|
||||
@@ -1802,6 +1928,9 @@ const DUE_CHECK_INTERVAL: Duration = Duration::from_millis(50);
|
||||
/// Why a stream still open when the engine stopped ended.
|
||||
const STOPPED_MID_STREAM: &str = "Yaak Proxy stopped before the stream ended";
|
||||
|
||||
/// Why a tunnel still open when the engine stopped ended.
|
||||
const STOPPED_MID_TUNNEL: &str = "Yaak Proxy stopped before the connection closed";
|
||||
|
||||
/// A flow between its `RequestStart` and its end, with its bodies being written as they
|
||||
/// stream.
|
||||
struct InFlight {
|
||||
@@ -1956,7 +2085,8 @@ fn run_event_loop(rx: std::sync::mpsc::Receiver<ProxyEvent>, sink: FlowSink) {
|
||||
// as they always have been. Every flow that ended is written.
|
||||
for (_, mut f) in in_flight.drain() {
|
||||
if f.persisted {
|
||||
f.flow.error = Some(STOPPED_MID_STREAM.to_string());
|
||||
let why = if f.flow.tunnelled { STOPPED_MID_TUNNEL } else { STOPPED_MID_STREAM };
|
||||
f.flow.error = Some(why.to_string());
|
||||
sink.finish_flow(f);
|
||||
}
|
||||
}
|
||||
@@ -2061,6 +2191,44 @@ impl FlowSink {
|
||||
},
|
||||
);
|
||||
}
|
||||
ProxyEvent::TunnelStart { id, started_at, authority, connection, client_addr } => {
|
||||
if !recording.lock().map(|r| r.was_on_at(started_at)).unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
attribution.begin(connection, client_addr);
|
||||
let flow = Flow {
|
||||
id: Flow::generate_id(),
|
||||
started_at: DateTime::<Utc>::from(started_at).naive_utc(),
|
||||
method: "CONNECT".to_string(),
|
||||
url: format!("https://{authority}"),
|
||||
client_http_version: "HTTP/1.1".to_string(),
|
||||
tunnelled: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut f = InFlight {
|
||||
flow,
|
||||
connection,
|
||||
request_body: None,
|
||||
response_body: None,
|
||||
persisted: false,
|
||||
cleared: false,
|
||||
next_seq: 0,
|
||||
dirty: false,
|
||||
last_write: None,
|
||||
};
|
||||
// Shown while it is open, as tunnels often stay open for minutes.
|
||||
self.write_stream_flow(&mut f);
|
||||
in_flight.insert(id, f);
|
||||
}
|
||||
ProxyEvent::TunnelEnd { id, sent, received, elapsed_ms, error } => {
|
||||
if let Some(mut f) = in_flight.remove(&id) {
|
||||
f.flow.request_size = sent as i64;
|
||||
f.flow.response_size = received as i64;
|
||||
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
|
||||
f.flow.error = error;
|
||||
self.finish_flow(f);
|
||||
}
|
||||
}
|
||||
ProxyEvent::StreamStart { id, kind } => {
|
||||
if let Some(f) = in_flight.get_mut(&id) {
|
||||
let kind = StreamKind::from(kind);
|
||||
@@ -2479,6 +2647,7 @@ define_rpc! {
|
||||
commands {
|
||||
execute_action(ActionInvocation) -> bool,
|
||||
format_body(FormatBodyRequest) -> String,
|
||||
get_decrypt_list(GetDecryptListRequest) -> DecryptList,
|
||||
get_message_payload(GetMessagePayloadRequest) -> GetMessagePayloadResponse,
|
||||
list_actions(ListActionsRequest) -> ListActionsResponse,
|
||||
list_flows(flows::FlowFilter) -> ListFlowsResponse,
|
||||
@@ -2502,6 +2671,9 @@ define_rpc! {
|
||||
get_proxy_state(GetProxyStateRequest) -> GetProxyStateResponse,
|
||||
helper_register(HelperRegisterRequest) -> SystemProxyStatus,
|
||||
helper_unregister(HelperUnregisterRequest) -> SystemProxyStatus,
|
||||
edit_decrypt_list(EditDecryptListRequest) -> DecryptList,
|
||||
list_seen(ListSeenRequest) -> flows::SeenTargets,
|
||||
set_decrypt_list(SetDecryptListRequest) -> DecryptList,
|
||||
list_workspaces(ListWorkspacesRequest) -> ListWorkspacesResponse,
|
||||
preview_save(PreviewSaveRequest) -> SavePreview,
|
||||
reflect_grpc_host(ReflectGrpcHostRequest) -> GrpcSchema,
|
||||
@@ -2512,6 +2684,7 @@ define_rpc! {
|
||||
take_over(TakeOverRequest) -> bool,
|
||||
}
|
||||
events {
|
||||
decrypt_list_changed(DecryptListChangedPayload),
|
||||
flows_cleared(FlowsClearedPayload),
|
||||
message_write(MessagePayload),
|
||||
model_write(ModelPayload),
|
||||
|
||||
@@ -91,6 +91,10 @@ pub struct Flow {
|
||||
pub grpc_status: Option<i32>,
|
||||
/// A gRPC call's `grpc-message`, decoded.
|
||||
pub grpc_message: Option<String>,
|
||||
/// An HTTPS connection passed through undecrypted, as the decrypt list leaves it out or its
|
||||
/// client rejected the proxy's certificate: method `CONNECT`, its URL the host, its sizes
|
||||
/// the bytes each way, and no headers or bodies. Open until `elapsedMs` or `error` is set.
|
||||
pub tunnelled: bool,
|
||||
}
|
||||
|
||||
/// The streaming protocol a flow carries.
|
||||
@@ -239,6 +243,7 @@ impl UpsertModelInfo for Flow {
|
||||
(GrpcMethod, self.grpc_method.into()),
|
||||
(GrpcStatus, self.grpc_status.into()),
|
||||
(GrpcMessage, self.grpc_message.into()),
|
||||
(Tunnelled, self.tunnelled.into()),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -275,6 +280,7 @@ impl UpsertModelInfo for Flow {
|
||||
FlowIden::GrpcMethod,
|
||||
FlowIden::GrpcStatus,
|
||||
FlowIden::GrpcMessage,
|
||||
FlowIden::Tunnelled,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -320,6 +326,7 @@ impl UpsertModelInfo for Flow {
|
||||
grpc_method: added_column(r, "grpc_method")?,
|
||||
grpc_status: added_column(r, "grpc_status")?,
|
||||
grpc_message: added_column(r, "grpc_message")?,
|
||||
tunnelled: added_column(r, "tunnelled")?.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use ts_rs::TS;
|
||||
use yaak_proxy::DEFAULT_CAPTURE_BODY_LIMIT;
|
||||
use yaak_proxy::{BUILT_IN_EXCLUSIONS, DEFAULT_CAPTURE_BODY_LIMIT, DecryptEntry, DecryptPolicy};
|
||||
|
||||
/// `settings.json` in the proxy data directory. Missing keys take their defaults.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -17,6 +17,12 @@ pub struct ProxySettings {
|
||||
pub capture_body_limit: usize,
|
||||
/// 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`, `*`,
|
||||
/// `!host:*.bank.com`. Empty, so HTTPS is tunnelled, until hosts or apps are added. The
|
||||
/// built-in exclusions are not kept here; see [`Self::decrypt_list`].
|
||||
pub decrypt: Vec<String>,
|
||||
/// The built-in exclusions the user removed.
|
||||
pub decrypt_built_ins_removed: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for ProxySettings {
|
||||
@@ -26,10 +32,32 @@ impl Default for ProxySettings {
|
||||
system_proxy_at_launch: true,
|
||||
capture_body_limit: DEFAULT_CAPTURE_BODY_LIMIT,
|
||||
http_version: HttpVersion::Auto,
|
||||
decrypt: Vec::new(),
|
||||
decrypt_built_ins_removed: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of the decrypt list, as the app shows it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct DecryptListEntry {
|
||||
/// As stored: `host:*.example.com`, `app:Google Chrome`, `!host:*.apple.com`, `*`.
|
||||
pub entry: String,
|
||||
/// Shipped with the app: an exclusion of Apple's services or a pinned app's hosts.
|
||||
pub built_in: bool,
|
||||
}
|
||||
|
||||
/// What HTTPS is decrypted: the user's entries in order, then the built-in exclusions not
|
||||
/// removed. A connection is decrypted when a positive entry matches it and no exclusion does.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_rpc.ts")]
|
||||
pub struct DecryptList {
|
||||
pub entries: Vec<DecryptListEntry>,
|
||||
}
|
||||
|
||||
/// The HTTP versions offered to clients in intercepted HTTPS. Upstream, the engine speaks
|
||||
/// whichever the server picks either way.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
@@ -44,6 +72,84 @@ pub enum HttpVersion {
|
||||
}
|
||||
|
||||
impl ProxySettings {
|
||||
/// The user's entries, then the built-in exclusions they kept.
|
||||
pub fn decrypt_list(&self) -> DecryptList {
|
||||
let user =
|
||||
self.decrypt.iter().map(|e| DecryptListEntry { entry: e.clone(), built_in: false });
|
||||
let built_in = BUILT_IN_EXCLUSIONS
|
||||
.iter()
|
||||
.filter(|e| !self.decrypt_built_ins_removed.iter().any(|r| r == *e))
|
||||
.map(|e| DecryptListEntry { entry: e.to_string(), built_in: true });
|
||||
DecryptList { entries: user.chain(built_in).collect() }
|
||||
}
|
||||
|
||||
/// Replaces the list with `entries`, as the user may type them: each is normalized, a bare
|
||||
/// hostname becoming `host:`, and repeats are dropped. A built-in exclusion left out is
|
||||
/// removed, and one written again is restored. Fails, changing nothing, on an entry that
|
||||
/// does not parse.
|
||||
pub fn set_decrypt_list<S: AsRef<str>>(&mut self, entries: &[S]) -> Result<(), String> {
|
||||
let mut user: Vec<String> = Vec::new();
|
||||
let mut kept_built_ins: Vec<String> = Vec::new();
|
||||
for entry in entries {
|
||||
let parsed = DecryptEntry::parse(entry.as_ref())?;
|
||||
let normalized = parsed.to_string();
|
||||
let list = if parsed.built_in { &mut kept_built_ins } else { &mut user };
|
||||
if !list.contains(&normalized) {
|
||||
list.push(normalized);
|
||||
}
|
||||
}
|
||||
self.decrypt = user;
|
||||
self.decrypt_built_ins_removed = BUILT_IN_EXCLUSIONS
|
||||
.iter()
|
||||
.filter(|e| !kept_built_ins.iter().any(|k| k == *e))
|
||||
.map(|e| e.to_string())
|
||||
.collect();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes `remove` from the list as it is and adds `add` after the user's own entries,
|
||||
/// each normalized, as [`Self::set_decrypt_list`] would take the result. A built-in removed
|
||||
/// is remembered as removed, and one added is restored. Fails, changing nothing, on an
|
||||
/// entry that does not parse.
|
||||
pub fn edit_decrypt_list<S: AsRef<str>>(
|
||||
&mut self,
|
||||
add: &[S],
|
||||
remove: &[S],
|
||||
) -> Result<(), String> {
|
||||
let normalize = |e: &str| DecryptEntry::parse(e).ok().map(|p| p.to_string());
|
||||
let add = add
|
||||
.iter()
|
||||
.map(|e| DecryptEntry::parse(e.as_ref()).map(|p| p.to_string()))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// An entry goes as stored, so one edited by hand, odd case or malformed, can go too.
|
||||
let removed = |stored: &str| {
|
||||
remove.iter().any(|r| {
|
||||
let r = r.as_ref();
|
||||
r == stored || normalize(r).is_some_and(|r| Some(r) == normalize(stored))
|
||||
})
|
||||
};
|
||||
let mut entries: Vec<String> = self
|
||||
.decrypt_list()
|
||||
.entries
|
||||
.into_iter()
|
||||
.map(|e| e.entry)
|
||||
.filter(|e| !removed(e))
|
||||
.collect();
|
||||
entries.extend(add);
|
||||
self.set_decrypt_list(&entries)
|
||||
}
|
||||
|
||||
/// The engine's policy from the list. An entry saved by hand that does not parse is left
|
||||
/// out, with a warning, rather than stopping the engine.
|
||||
pub fn decrypt_policy(&self) -> DecryptPolicy {
|
||||
let entries = self.decrypt_list().entries.into_iter().filter_map(|e| {
|
||||
DecryptEntry::parse(&e.entry)
|
||||
.inspect_err(|err| log::warn!("Ignoring decrypt entry: {err}"))
|
||||
.ok()
|
||||
});
|
||||
DecryptPolicy { entries: entries.collect() }
|
||||
}
|
||||
|
||||
/// The settings at `path`, or the defaults when there is no file.
|
||||
pub fn load(path: &Path) -> Result<Self, String> {
|
||||
match std::fs::read_to_string(path) {
|
||||
@@ -92,6 +198,8 @@ mod tests {
|
||||
system_proxy_at_launch: false,
|
||||
capture_body_limit: 1024,
|
||||
http_version: HttpVersion::Http1Only,
|
||||
decrypt: vec!["host:api.example.com".into()],
|
||||
decrypt_built_ins_removed: vec!["!host:*.zoom.us".into()],
|
||||
};
|
||||
settings.save(&path).unwrap();
|
||||
assert_eq!(ProxySettings::load(&path).unwrap(), settings);
|
||||
@@ -105,6 +213,8 @@ mod tests {
|
||||
"systemProxyAtLaunch": false,
|
||||
"captureBodyLimit": 1024,
|
||||
"httpVersion": "http1Only",
|
||||
"decrypt": ["host:api.example.com"],
|
||||
"decryptBuiltInsRemoved": ["!host:*.zoom.us"],
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -137,6 +247,90 @@ mod tests {
|
||||
assert!(json.get("systemProxy").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_decrypt_list_starts_with_only_the_built_in_exclusions() {
|
||||
let settings = ProxySettings::default();
|
||||
let list = settings.decrypt_list();
|
||||
assert!(!list.entries.is_empty());
|
||||
assert!(list.entries.iter().all(|e| e.built_in && e.entry.starts_with('!')));
|
||||
let policy = settings.decrypt_policy();
|
||||
assert!(!policy.decrypts_anything(), "nothing is decrypted by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_the_decrypt_list() {
|
||||
let mut settings = ProxySettings::default();
|
||||
let mut entries: Vec<String> = vec![
|
||||
"api.example.com".into(),
|
||||
"*".into(),
|
||||
"host:API.example.com".into(),
|
||||
"app:Google Chrome".into(),
|
||||
];
|
||||
// Every built-in exclusion but zoom.us, kept.
|
||||
entries.extend(
|
||||
BUILT_IN_EXCLUSIONS.iter().filter(|e| **e != "!host:*.zoom.us").map(|e| e.to_string()),
|
||||
);
|
||||
settings.set_decrypt_list(&entries).unwrap();
|
||||
assert_eq!(settings.decrypt, ["host:api.example.com", "*", "app:Google Chrome"]);
|
||||
assert_eq!(settings.decrypt_built_ins_removed, ["!host:*.zoom.us"]);
|
||||
let list = settings.decrypt_list();
|
||||
assert_eq!(
|
||||
list.entries[0],
|
||||
DecryptListEntry { entry: "host:api.example.com".into(), built_in: false }
|
||||
);
|
||||
assert!(list.entries[3].built_in);
|
||||
assert!(!list.entries.iter().any(|e| e.entry == "!host:*.zoom.us"));
|
||||
|
||||
// Written again, a built-in exclusion is restored.
|
||||
let mut again: Vec<String> = list.entries.iter().map(|e| e.entry.clone()).collect();
|
||||
again.push("!host:*.zoom.us".into());
|
||||
settings.set_decrypt_list(&again).unwrap();
|
||||
assert!(settings.decrypt_built_ins_removed.is_empty());
|
||||
|
||||
// An invalid entry changes nothing.
|
||||
let before = settings.clone();
|
||||
assert!(settings.set_decrypt_list(&["host:a b"]).is_err());
|
||||
assert_eq!(settings, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_applies_to_the_list_as_it_is() {
|
||||
let mut settings =
|
||||
ProxySettings { decrypt: vec!["host:a.com".into()], ..Default::default() };
|
||||
// Two edits made from the same earlier copy both land.
|
||||
settings.edit_decrypt_list(&["b.com"], &[]).unwrap();
|
||||
settings.edit_decrypt_list(&["app:Slack"], &["host:a.com"]).unwrap();
|
||||
assert_eq!(settings.decrypt, ["host:b.com", "app:Slack"]);
|
||||
// A built-in removed and restored.
|
||||
settings.edit_decrypt_list(&[], &["!host:*.zoom.us"]).unwrap();
|
||||
assert_eq!(settings.decrypt_built_ins_removed, ["!host:*.zoom.us"]);
|
||||
settings.edit_decrypt_list(&["!host:*.zoom.us"], &[]).unwrap();
|
||||
assert!(settings.decrypt_built_ins_removed.is_empty());
|
||||
let before = settings.clone();
|
||||
assert!(settings.edit_decrypt_list(&["host:a b"], &[]).is_err());
|
||||
assert_eq!(settings, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_edited_by_hand_can_be_removed() {
|
||||
let mut settings = ProxySettings {
|
||||
decrypt: vec!["API.example.com".into(), "host:a b".into(), "b.com".into()],
|
||||
..Default::default()
|
||||
};
|
||||
settings.edit_decrypt_list(&[], &["host:api.example.com", "host:a b"]).unwrap();
|
||||
assert_eq!(settings.decrypt, ["host:b.com"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hand_edited_entry_that_does_not_parse_is_skipped() {
|
||||
let settings = ProxySettings {
|
||||
decrypt: vec!["host:a b".into(), "x.com".into()],
|
||||
..Default::default()
|
||||
};
|
||||
let policy = settings.decrypt_policy();
|
||||
assert_eq!(policy.entries.iter().filter(|e| !e.negated).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_json_is_an_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -772,3 +772,112 @@ async fn another_app_owning_the_engine_is_not_taken_over() {
|
||||
assert_eq!(app.port(), None);
|
||||
other.stop().unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_decrypt_list_is_read_and_replaced_over_the_control_api() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let client_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = ctx(dir.path(), client_dir.path());
|
||||
let _server = ControlServer::start(ctx.clone()).unwrap();
|
||||
let info = control::read(dir.path()).unwrap();
|
||||
let http = reqwest::Client::builder().no_proxy().build().unwrap();
|
||||
let url = format!("{}/decrypt", info.base_url());
|
||||
|
||||
assert_eq!(http.get(&url).send().await.unwrap().status(), 401);
|
||||
let list: Value =
|
||||
http.get(&url).bearer_auth(&info.token).send().await.unwrap().json().await.unwrap();
|
||||
assert!(list["entries"].as_array().unwrap().iter().all(|e| e["builtIn"] == true));
|
||||
|
||||
let put = http
|
||||
.put(&url)
|
||||
.bearer_auth(&info.token)
|
||||
.json(&json!({"entries": ["*", "!host:*.bank.example"]}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(put.status(), 200);
|
||||
let list: Value = put.json().await.unwrap();
|
||||
assert_eq!(
|
||||
list["entries"],
|
||||
json!([
|
||||
{"entry": "*", "builtIn": false},
|
||||
{"entry": "!host:*.bank.example", "builtIn": false},
|
||||
]),
|
||||
"every built-in exclusion left out is removed"
|
||||
);
|
||||
let read: Value =
|
||||
http.get(&url).bearer_auth(&info.token).send().await.unwrap().json().await.unwrap();
|
||||
assert_eq!(read, list);
|
||||
|
||||
let bad = http
|
||||
.put(&url)
|
||||
.bearer_auth(&info.token)
|
||||
.json(&json!({"entries": ["app:"]}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(bad.status(), 400);
|
||||
}
|
||||
|
||||
/// While the CLI owns the engine, the app's change to the decrypt list goes to the CLI, whose
|
||||
/// engine decrypts the next connection by it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_decrypt_list_reaches_the_cli_that_owns_the_engine() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let client_dir = tempfile::tempdir().unwrap();
|
||||
let cli = ctx(dir.path(), client_dir.path()).with_owner(Owner::Cli);
|
||||
let _server = ControlServer::start(cli.clone()).unwrap();
|
||||
cli.start().unwrap();
|
||||
let app = ctx(dir.path(), client_dir.path());
|
||||
|
||||
let list = rpc(&app, "set_decrypt_list", json!({"entries": ["*"]})).await.unwrap();
|
||||
assert_eq!(list["entries"][0], json!({"entry": "*", "builtIn": false}));
|
||||
|
||||
// Decrypted, the request is a flow of its own: a 502, as nothing listens there.
|
||||
let ca = std::fs::read(dir.path().join("ca/ca.pem")).unwrap();
|
||||
let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port();
|
||||
let client = reqwest::Client::builder()
|
||||
.proxy(reqwest::Proxy::all(format!("http://127.0.0.1:{}", cli.port().unwrap())).unwrap())
|
||||
.add_root_certificate(reqwest::Certificate::from_pem(&ca).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
let url = format!("https://localhost:{closed}/forwarded");
|
||||
assert_eq!(client.get(&url).send().await.unwrap().status(), 502);
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let flows = cli.db().unwrap().with_conn(|db| db.find_all::<Flow>().unwrap());
|
||||
if let Some(flow) = flows.iter().find(|f| f.url == url) {
|
||||
assert!(!flow.tunnelled);
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no decrypted flow for {url}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_decrypt_list_is_edited_over_the_control_api() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let client_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = ctx(dir.path(), client_dir.path());
|
||||
let _server = ControlServer::start(ctx.clone()).unwrap();
|
||||
let info = control::read(dir.path()).unwrap();
|
||||
let http = reqwest::Client::builder().no_proxy().build().unwrap();
|
||||
let url = format!("{}/decrypt", info.base_url());
|
||||
|
||||
for add in ["a.com", "b.com"] {
|
||||
let resp =
|
||||
http.patch(&url).bearer_auth(&info.token).json(&json!({"add": [add]})).send().await;
|
||||
assert_eq!(resp.unwrap().status(), 200);
|
||||
}
|
||||
let resp = http
|
||||
.patch(&url)
|
||||
.bearer_auth(&info.token)
|
||||
.json(&json!({"remove": ["host:a.com"]}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let list: Value = resp.json().await.unwrap();
|
||||
assert_eq!(list["entries"][0], json!({"entry": "host:b.com", "builtIn": false}));
|
||||
assert_eq!(list["entries"][1]["builtIn"], true);
|
||||
}
|
||||
@@ -267,7 +267,13 @@ async fn cancelled_flow_is_not_an_error() {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn http_version_setting_applies_to_new_connections() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
|
||||
// Decrypted, as only intercepted HTTPS offers the client a version.
|
||||
let settings = ProxySettings {
|
||||
port: 0,
|
||||
system_proxy_at_launch: false,
|
||||
decrypt: vec!["*".into()],
|
||||
..Default::default()
|
||||
};
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
@@ -416,6 +422,213 @@ async fn body_rpcs() {
|
||||
assert_eq!(formatted, json!("{\n \"a\": [\n 1,\n 2\n ]\n}"));
|
||||
}
|
||||
|
||||
/// A TCP server that echoes what it reads, then closes once the client does.
|
||||
async fn spawn_echo() -> SocketAddr {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let (mut tcp, _) = listener.accept().await.unwrap();
|
||||
tokio::spawn(async move {
|
||||
let (mut read, mut write) = tcp.split();
|
||||
let _ = tokio::io::copy(&mut read, &mut write).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
addr
|
||||
}
|
||||
|
||||
/// Opens a CONNECT tunnel to `target` through the engine on `port`.
|
||||
async fn connect_through(port: u16, target: &str) -> tokio::net::TcpStream {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let mut tcp = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||||
let connect = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n");
|
||||
tcp.write_all(connect.as_bytes()).await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
head.push(tcp.read_u8().await.unwrap());
|
||||
}
|
||||
assert!(head.starts_with(b"HTTP/1.1 200"), "{}", String::from_utf8_lossy(&head));
|
||||
tcp
|
||||
}
|
||||
|
||||
async fn wait_for(ctx: &ProxyCtx, check: impl Fn(&Flow) -> bool) -> Flow {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let flows = ctx.db().unwrap().with_conn(|db| db.find_all::<Flow>().unwrap());
|
||||
if let Some(flow) = flows.into_iter().find(|f| check(f)) {
|
||||
return flow;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no such flow");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// With the default, empty decrypt list, a CONNECT is tunnelled untouched and recorded as a flow
|
||||
/// with its host and the bytes each way, shown while open and finished once closed.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_tunnelled_connect_is_recorded_with_its_sizes() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
|
||||
ctx.start().unwrap();
|
||||
let port = ctx.port().unwrap();
|
||||
let echo = spawn_echo().await;
|
||||
let target = format!("localhost:{}", echo.port());
|
||||
let url = format!("https://{target}");
|
||||
|
||||
let mut tcp = connect_through(port, &target).await;
|
||||
// TLS-looking bytes, which a decrypting engine would have taken for a ClientHello.
|
||||
let sent = b"\x16\x03\x01 not decrypted";
|
||||
tcp.write_all(sent).await.unwrap();
|
||||
let mut echoed = vec![0u8; sent.len()];
|
||||
tcp.read_exact(&mut echoed).await.unwrap();
|
||||
assert_eq!(&echoed, sent, "bytes pass untouched");
|
||||
|
||||
let open = wait_for(&ctx, |f| f.url == url).await;
|
||||
assert!(open.tunnelled);
|
||||
assert_eq!(open.method, "CONNECT");
|
||||
assert_eq!(open.elapsed_ms, None, "open while the tunnel is");
|
||||
|
||||
drop(tcp);
|
||||
let done = wait_for(&ctx, |f| f.url == url && f.elapsed_ms.is_some()).await;
|
||||
assert_eq!(done.id, open.id);
|
||||
assert_eq!((done.request_size, done.response_size), (sent.len() as i64, sent.len() as i64));
|
||||
assert_eq!(done.error, None);
|
||||
assert!(done.request_headers.is_empty() && done.response_headers.is_empty());
|
||||
|
||||
let tunnelled = rpc(&ctx, "list_flows", json!({"tunnelled": true})).await.unwrap();
|
||||
assert_eq!(tunnelled["flows"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(tunnelled["flows"][0]["tunnelled"], true);
|
||||
let decrypted = rpc(&ctx, "list_flows", json!({"tunnelled": false})).await.unwrap();
|
||||
assert_eq!(decrypted["flows"].as_array().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_decrypt_list_rpcs_save_and_apply() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
|
||||
|
||||
let list = rpc(&ctx, "get_decrypt_list", json!({})).await.unwrap();
|
||||
let entries = list["entries"].as_array().unwrap();
|
||||
assert!(entries.iter().all(|e| e["builtIn"] == true), "only the built-ins: {list}");
|
||||
assert!(entries.iter().any(|e| e["entry"] == "!host:*.apple.com"));
|
||||
|
||||
let set = json!({"entries": ["API.example.com", "app:Google Chrome", "!host:*.apple.com"]});
|
||||
let list = rpc(&ctx, "set_decrypt_list", set).await.unwrap();
|
||||
assert_eq!(
|
||||
list["entries"],
|
||||
json!([
|
||||
{"entry": "host:api.example.com", "builtIn": false},
|
||||
{"entry": "app:Google Chrome", "builtIn": false},
|
||||
{"entry": "!host:*.apple.com", "builtIn": true},
|
||||
])
|
||||
);
|
||||
let saved = ProxySettings::load(&dir.path().join("settings.json")).unwrap();
|
||||
assert_eq!(saved.decrypt, ["host:api.example.com", "app:Google Chrome"]);
|
||||
assert!(saved.decrypt_built_ins_removed.contains(&"!host:*.icloud.com".to_string()));
|
||||
|
||||
let invalid = rpc(&ctx, "set_decrypt_list", json!({"entries": ["host:a b"]})).await;
|
||||
assert!(invalid.unwrap_err().contains("Invalid host"));
|
||||
assert_eq!(rpc(&ctx, "get_decrypt_list", json!({})).await.unwrap(), list);
|
||||
|
||||
// Applied to the running engine's next connection: decrypting everything intercepts a
|
||||
// CONNECT, which a client that does not trust the CA then rejects.
|
||||
ctx.start().unwrap();
|
||||
rpc(&ctx, "set_decrypt_list", json!({"entries": ["*"]})).await.unwrap();
|
||||
let echo = spawn_echo().await;
|
||||
let client = reqwest::Client::builder()
|
||||
.proxy(reqwest::Proxy::all(format!("http://127.0.0.1:{}", ctx.port().unwrap())).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
let err = client.get(format!("https://localhost:{}/", echo.port())).send().await.unwrap_err();
|
||||
assert!(err.is_connect() || err.is_request(), "{err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn seen_lists_hosts_and_apps_most_recent_first() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
|
||||
let flow = |url: &str, app: Option<(&str, Option<&str>)>, at: i64| Flow {
|
||||
id: format!("fl_{at}"),
|
||||
url: url.into(),
|
||||
method: "GET".into(),
|
||||
started_at: chrono::DateTime::from_timestamp(at, 0).unwrap().naive_utc(),
|
||||
client_name: app.map(|(n, _)| n.to_string()),
|
||||
client_bundle_id: app.and_then(|(_, b)| b.map(String::from)),
|
||||
..Default::default()
|
||||
};
|
||||
let chrome = Some(("Google Chrome", Some("com.google.Chrome")));
|
||||
ctx.db()
|
||||
.unwrap()
|
||||
.with_tx(|c| {
|
||||
for f in [
|
||||
flow("https://api.example.com/v1", chrome, 1),
|
||||
flow("https://API.example.com:443/v2", None, 2),
|
||||
flow("https://example.com:8443/", Some(("curl", None)), 3),
|
||||
flow("http://localhost:80/x", chrome, 4),
|
||||
] {
|
||||
c.upsert(&f, &yaak_database::UpdateSource::Background)?;
|
||||
}
|
||||
Ok::<_, yaak_database::Error>(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let seen = rpc(&ctx, "list_seen", json!({})).await.unwrap();
|
||||
assert_eq!(seen["hosts"], json!(["localhost", "example.com:8443", "api.example.com"]));
|
||||
assert_eq!(
|
||||
seen["apps"],
|
||||
json!([
|
||||
{"name": "Google Chrome", "bundleId": "com.google.Chrome"},
|
||||
{"name": "curl", "bundleId": null},
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/// Edits made together each land on the list the other left, and every change is announced to
|
||||
/// the app, so a list changed elsewhere shows at once.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn decrypt_list_edits_apply_to_the_latest_list_and_are_announced() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
let (events, event_rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
|
||||
|
||||
let (a, b) = tokio::join!(
|
||||
rpc(&ctx, "edit_decrypt_list", json!({"add": ["a.com"]})),
|
||||
rpc(&ctx, "edit_decrypt_list", json!({"add": ["app:Slack"]})),
|
||||
);
|
||||
a.unwrap();
|
||||
b.unwrap();
|
||||
let list =
|
||||
rpc(&ctx, "edit_decrypt_list", json!({"remove": ["!host:*.zoom.us"]})).await.unwrap();
|
||||
let user: Vec<&str> = list["entries"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|e| e["builtIn"] == false)
|
||||
.map(|e| e["entry"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(user.len(), 2);
|
||||
assert!(user.contains(&"host:a.com") && user.contains(&"app:Slack"), "{user:?}");
|
||||
assert!(!list["entries"].as_array().unwrap().iter().any(|e| e["entry"] == "!host:*.zoom.us"));
|
||||
|
||||
let changes: Vec<_> =
|
||||
event_rx.try_iter().filter(|e| e.event == "decrypt_list_changed").collect();
|
||||
assert_eq!(changes.len(), 3);
|
||||
assert_eq!(changes[2].payload["list"], list);
|
||||
}
|
||||
|
||||
/// Capture throughput through the engine, end to end: 3,000 requests, 16 at a time over
|
||||
/// kept-alive connections, each with a 4 KB response, timed until every flow is stored, and how
|
||||
/// long opening one then takes. Run in release: `cargo test --release -p yaak-proxy-lib --test
|
||||
|
||||
Reference in new issue
Block a user