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:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-11-06 21:24:39 -07:00
1 parent 91696c2d1f
commit 4538123d88
44 files changed
+3259 -66

No files matched your search

+35 -3
View File
@@ -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
}
+18 -2
View File
@@ -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)?)
+124 -1
View File
@@ -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);
}
}
+117 -6
View File
@@ -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]
+176 -3
View File
@@ -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(),
})
}
}
+195 -1
View File
@@ -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();