Capture WebSocket, SSE and gRPC (#814)

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 09:53:56 -07:00
1 parent 08a98d5f82
commit 1129f7aa93
32 files changed
+5228 -100

No files matched your search

+1 -1
View File
@@ -230,6 +230,6 @@ impl OfflineStore {
pub async fn har(&self, filter: &FlowFilter) -> Result<Har, String> {
let flows = flows::list(&self.db, filter)?;
har::export(&self.blobs, &flows, self.capture_body_limit).await
har::export(&self.db, &self.blobs, &flows, self.capture_body_limit).await
}
}
+89 -3
View File
@@ -4,12 +4,17 @@
//! time: a file whose process is gone, or whose port no longer answers, is stale and replaced.
use crate::ca::{self, CaStatus};
use crate::flows::{self, FlowFilter};
use crate::flows::{self, BodyPreview, FlowFilter};
use crate::grpc::{self, DecodedGrpcMessage};
use crate::har;
use crate::macos::SystemProxyStatus;
use crate::messages::{self, FlowMessage, MessageKind};
use crate::models::{FlowBody, find_header};
use crate::save::SaveFlowRequest;
use crate::{ProxyCtx, ProxyState, bodies};
use crate::{
AddGrpcSchemaRequest, ListMessagesResponse, ProxyCtx, ProxyState, ReflectGrpcHostRequest,
bodies,
};
use bytes::Bytes;
use chrono::{DateTime, Utc};
use http_body_util::{BodyExt, Full, Limited};
@@ -240,6 +245,25 @@ pub struct ErrorBody {
pub error: String,
}
/// `GET /flows/{id}/messages/{seq}`: a message with its payload, and a gRPC message decoded.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MessageDetail {
pub message: FlowMessage,
pub payload: BodyPreview,
/// A gRPC message as JSON, with its schema or without one.
#[serde(skip_serializing_if = "Option::is_none")]
pub decoded: Option<DecodedGrpcMessage>,
/// Why a gRPC message could not be decoded.
#[serde(skip_serializing_if = "Option::is_none")]
pub decode_error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemovedResponse {
pub removed: bool,
}
/// Raw body headers: whether the body is cut short, at the capture limit or on the wire.
pub const TRUNCATED_HEADER: &str = "x-yaak-truncated";
@@ -504,6 +528,47 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
(&Method::GET, ["flows", id, "response-body"]) => {
raw_body(ctx, id, FlowBody::Response).await
}
(&Method::GET, ["flows", id, "messages"]) => {
found(ctx, id)?;
let (after_seq, limit) = message_page(&query)?;
let messages = messages::list(&ctx.db, id, after_seq, limit)?;
let total = messages::count(&ctx.db, id)?;
json(&ListMessagesResponse { messages, total })
}
(&Method::GET, ["flows", id, "messages", seq]) => {
let flow = flows::find(&ctx.db, id)
.ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, format!("No flow {id}")))?;
let seq: i64 = seq.parse().map_err(|_| bad_request(format!("Invalid seq {seq:?}")))?;
let message = messages::find(&ctx.db, id, seq)?.ok_or_else(|| {
ApiError::new(StatusCode::NOT_FOUND, format!("No message {seq} in flow {id}"))
})?;
let payload = messages::payload(&ctx.db, &ctx.blobs, &message)?;
let (decoded, decode_error) = if message.kind == MessageKind::GrpcMessage {
match grpc::decode(&ctx.db, &ctx.blobs, &ctx.grpc, &flow, seq).await {
Ok(decoded) => (Some(decoded), None),
Err(e) => (None, Some(e)),
}
} else {
(None, None)
};
let payload = BodyPreview::new(&payload, message.truncated);
json(&MessageDetail { message, payload, decoded, decode_error })
}
(&Method::GET, ["grpc-schemas"]) => json(&grpc::list(&ctx.db)?),
(&Method::POST, ["grpc-schemas"]) => {
let body: AddGrpcSchemaRequest = read_json(req).await?;
let added = grpc::add(&ctx.db, &ctx.grpc, &body.host_pattern, &body.proto_paths);
json(&added.await.map_err(bad_request)?)
}
(&Method::POST, ["grpc-schemas", "reflect"]) => {
let body: ReflectGrpcHostRequest = read_json(req).await?;
let (host, plaintext) = grpc::reflection_host(&body.host);
let reflected = grpc::reflect(&ctx.db, &ctx.grpc, &host, plaintext).await;
json(&reflected.map_err(bad_request)?)
}
(&Method::DELETE, ["grpc-schemas", id]) => {
json(&RemovedResponse { removed: grpc::remove(&ctx.db, &ctx.grpc, id)? })
}
(&Method::POST, ["flows", id, "save"]) => {
found(ctx, id)?;
let id = id.to_string();
@@ -513,7 +578,7 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
(&Method::GET, ["har"]) => {
let filter = FlowFilter::from_query(&query).map_err(bad_request)?;
let flows = flows::list(&ctx.db, &filter)?;
json(&har::export(&ctx.blobs, &flows, ctx.capture_body_limit()?).await?)
json(&har::export(&ctx.db, &ctx.blobs, &flows, ctx.capture_body_limit()?).await?)
}
(&Method::GET, ["ca"]) => {
let ca = CaStore::load_or_create(&ctx.ca_dir())
@@ -582,6 +647,27 @@ async fn raw_body(ctx: &ProxyCtx, id: &str, which: FlowBody) -> Result<ControlRe
Ok(resp)
}
/// `after` (a seq) and `limit` from a messages query.
fn message_page(query: &str) -> Result<(Option<i64>, Option<usize>), ApiError> {
let (mut after, mut limit) = (None, None);
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
match key.as_ref() {
"after" => {
after = Some(
value.parse().map_err(|_| bad_request(format!("Invalid after {value:?}")))?,
)
}
"limit" => {
limit = Some(
value.parse().map_err(|_| bad_request(format!("Invalid limit {value:?}")))?,
)
}
_ => {}
}
}
Ok((after, limit))
}
fn body_limit(query: &str) -> Result<usize, ApiError> {
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
if key == "bodyLimit" {
+18 -1
View File
@@ -141,6 +141,12 @@ mod tests {
ALTER TABLE flows DROP COLUMN client_bundle_id;
ALTER TABLE flows DROP COLUMN client_path;
ALTER TABLE flows DROP COLUMN cancelled;
ALTER TABLE flows DROP COLUMN stream_kind;
ALTER TABLE flows DROP COLUMN message_count;
ALTER TABLE flows DROP COLUMN grpc_service;
ALTER TABLE flows DROP COLUMN grpc_method;
ALTER TABLE flows DROP COLUMN grpc_status;
ALTER TABLE flows DROP COLUMN grpc_message;
INSERT INTO flows (id, url, method) VALUES ('fl_old', 'https://example.com', 'GET');",
)
.unwrap();
@@ -152,6 +158,11 @@ mod tests {
assert_eq!((flows[0].id.as_str(), flows[0].saved_request_id.as_deref()), ("fl_old", None));
assert_eq!((flows[0].client_pid, flows[0].client_name.as_deref()), (None, None));
assert!(!flows[0].cancelled);
assert_eq!((flows[0].stream_kind, flows[0].message_count), (None, 0));
// Failed flows are found without the gRPC status column too.
let failed =
crate::flows::FlowFilter { status: Some("error".into()), ..Default::default() };
assert_eq!(crate::flows::list(&db, &failed).unwrap().len(), 0);
}
#[test]
@@ -187,7 +198,7 @@ mod tests {
.unwrap()
.map(|t| t.unwrap())
.collect();
assert_eq!(tables, vec!["_sqlx_migrations", "flows"]);
assert_eq!(tables, vec!["_sqlx_migrations", "flow_messages", "flows", "grpc_schemas"]);
let flow_columns = columns(&conn, "flows");
assert!(flow_columns.contains(&"response_truncated".to_string()));
@@ -197,6 +208,12 @@ mod tests {
"client_bundle_id",
"client_path",
"cancelled",
"stream_kind",
"message_count",
"grpc_service",
"grpc_method",
"grpc_status",
"grpc_message",
] {
assert!(flow_columns.contains(&column.to_string()), "{column} in {flow_columns:?}");
}
+19 -5
View File
@@ -32,7 +32,8 @@ pub struct FlowFilter {
/// The method, any case.
#[ts(optional)]
pub method: Option<String>,
/// A status (`404`), a class of them (`4xx`), or `error` for flows that failed.
/// A status (`404`), a class of them (`4xx`), or `error` for flows that failed, gRPC calls
/// that ended with a status other than OK among them.
#[ts(optional)]
pub status: Option<String>,
/// At most this many flows, the newest.
@@ -114,7 +115,9 @@ impl FlowFilter {
}
/// The SQL condition for every field but `after`, `before` and `limit`, and its parameters.
fn condition(&self) -> (String, Vec<Value>) {
/// `grpc` says the database has gRPC statuses: one opened read-only before its migrations
/// have run may not.
fn condition(&self, grpc: bool) -> (String, Vec<Value>) {
let mut sql = String::from("1");
let mut params: Vec<Value> = Vec::new();
for term in self.q.iter().flat_map(|q| q.split_whitespace()) {
@@ -165,6 +168,10 @@ impl FlowFilter {
}
match self.status.as_deref().map(str::trim) {
None | Some("") => {}
// A gRPC call that ended with a status other than OK failed too.
Some(s) if s.eq_ignore_ascii_case("error") && grpc => {
sql.push_str(" AND (error IS NOT NULL OR coalesce(grpc_status, 0) != 0)")
}
Some(s) if s.eq_ignore_ascii_case("error") => sql.push_str(" AND error IS NOT NULL"),
// A whole status or a class, not the start of one as a search term may be.
Some(s) if s.len() == 3 => match status_condition(&s.to_ascii_lowercase(), &mut params)
@@ -268,8 +275,13 @@ pub fn page(
})
}
/// The database has the gRPC status column, added by a later migration.
fn has_grpc_status(conn: &rusqlite::Connection) -> bool {
conn.prepare("SELECT grpc_status FROM flows LIMIT 0").is_ok()
}
fn list_in(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<Vec<Flow>, String> {
let (condition, mut params) = filter.condition();
let (condition, mut params) = filter.condition(has_grpc_status(conn));
let mut sql = format!("SELECT * FROM flows WHERE {condition}");
if let Some(id) = &filter.after {
// By rowid, which only grows as flows are written.
@@ -300,7 +312,7 @@ fn list_in(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<Vec<Flow>
}
fn count_matching(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<usize, String> {
let (condition, params) = filter.condition();
let (condition, params) = filter.condition(has_grpc_status(conn));
conn.query_row(
&format!("SELECT COUNT(*) FROM flows WHERE {condition}"),
rusqlite::params_from_iter(params),
@@ -319,12 +331,14 @@ pub fn clear(db: &ProxyQueryManager, blobs: &BlobManager) -> Result<usize, Strin
let mut stmt = conn.prepare("SELECT id FROM flows")?;
let ids = stmt.query_map([], |r| r.get(0))?.collect::<Result<Vec<String>, _>>()?;
conn.execute("DELETE FROM flows", [])?;
conn.execute("DELETE FROM flow_messages", [])?;
// Only the deleted flows' bodies, so a flow still in flight keeps what it has written.
blobs
.with_tx(|b| {
for id in &ids {
b.delete_chunks(&Flow::body_id(id, FlowBody::Request))?;
b.delete_chunks(&Flow::body_id(id, FlowBody::Response))?;
b.delete_chunks_like(&format!("{id}.msg.%"))?;
}
Ok::<_, yaak_models::error::Error>(())
})
@@ -634,7 +648,7 @@ mod tests {
let plan: Vec<String> = db.with_conn(|c| {
let conn = c.conn().resolve();
let (condition, params) =
FlowFilter { q: Some("stripe".into()), ..Default::default() }.condition();
FlowFilter { q: Some("stripe".into()), ..Default::default() }.condition(true);
let sql = format!(
"EXPLAIN QUERY PLAN SELECT * FROM flows WHERE {condition} \
ORDER BY started_at DESC, id DESC LIMIT 500"
+595
View File
@@ -0,0 +1,595 @@
//! Decoding captured gRPC messages. A message decodes to JSON with the schema of its call's
//! service, found first in the protos attached to a host pattern, then in the server's own
//! reflection, asked once per host. Without one it decodes schemaless: field numbers, wire
//! types and values, with nested messages guessed.
use crate::db::ProxyQueryManager;
use crate::messages::{self, FlowMessage, MessageDirection, MessageKind};
use crate::models::Flow;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use chrono::NaiveDateTime;
use rusqlite::{Row, params};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use ts_rs::TS;
use yaak_database::generate_prefixed_id;
use yaak_grpc::GrpcConfig;
use yaak_grpc::prost_reflect::{DescriptorPool, DynamicMessage, MessageDescriptor};
use yaak_models::blob_manager::BlobManager;
/// Where a schema's descriptors came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_models.ts")]
pub enum GrpcSchemaSource {
/// `.proto` files the user attached to a host pattern.
Files,
/// The server's reflection service.
Reflection,
}
/// Descriptors for decoding the gRPC calls to hosts that match `hostPattern`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
pub struct GrpcSchema {
pub id: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
/// A host (`api.example.com`), a host and port (`localhost:50051`), any subdomain of one
/// (`*.example.com`), or every host (`*`).
pub host_pattern: String,
pub source: GrpcSchemaSource,
/// The `.proto` files and include directories compiled, for a `files` schema.
pub proto_paths: Vec<String>,
/// The services the descriptors define, by full name.
pub services: Vec<String>,
}
/// A captured gRPC message as JSON.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct DecodedGrpcMessage {
/// Pretty JSON: the message's fields by name with a schema; without one, an array of its
/// fields as `{ field, wireType, value }`, a length-delimited one with its guesses (`string`,
/// `message`, `bytes` in base64).
pub json: String,
/// The message type decoded with: `package.HelloReply`. None when schemaless.
pub message_type: Option<String>,
/// The schema decoded with. None when schemaless.
pub schema: Option<GrpcSchema>,
/// Why it decoded schemaless, or what to know about the decode.
pub note: Option<String>,
}
/// What a host's reflection answered, once it has; decodes that need it while it is being asked
/// wait for the same answer.
type Lookup = Arc<tokio::sync::OnceCell<Result<GrpcSchema, String>>>;
/// The decoded descriptor pools, by schema id, and the hosts reflection was asked of.
#[derive(Clone, Default)]
pub struct GrpcState {
protoc: Arc<Mutex<Option<GrpcConfig>>>,
pools: Arc<Mutex<HashMap<String, DescriptorPool>>>,
/// By `host:port`.
lookups: Arc<Mutex<HashMap<String, Lookup>>>,
}
impl GrpcState {
pub fn set_protoc(&self, config: GrpcConfig) {
if let Ok(mut protoc) = self.protoc.lock() {
*protoc = Some(config);
}
}
/// The protoc set with [`Self::set_protoc`], or else one on `PATH`, with the `include`
/// directory installed beside it.
fn protoc(&self) -> Result<GrpcConfig, String> {
if let Some(config) = self.protoc.lock().ok().and_then(|p| p.clone()) {
return Ok(config);
}
protoc_on_path(std::env::var_os("PATH"))
}
}
/// What to do when there is no protoc to compile attached `.proto` files with.
pub const NO_PROTOC: &str = "Yaak Proxy has no protoc to compile .proto files with. A packaged \
Yaak Proxy includes one; otherwise install protoc (on macOS, `brew install protobuf`) so it \
is on PATH, or let the server's reflection supply the schema.";
/// A `protoc` in one of the directories of `path`, a `PATH` value, with the `include` directory
/// installed beside it.
fn protoc_on_path(path: Option<std::ffi::OsString>) -> Result<GrpcConfig, String> {
let name = if cfg!(windows) { "protoc.exe" } else { "protoc" };
let bin = path
.iter()
.flat_map(std::env::split_paths)
.map(|dir| dir.join(name))
.find(|p| p.is_file())
.ok_or(NO_PROTOC)?;
let include = bin.parent().and_then(|d| d.parent()).map(|d| d.join("include"));
Ok(GrpcConfig { protoc_include_dir: include.unwrap_or_default(), protoc_bin_path: bin })
}
const COLUMNS: &str = "id, created_at, updated_at, host_pattern, source, proto_paths, services";
fn schema_from_row(r: &Row) -> rusqlite::Result<GrpcSchema> {
let source: String = r.get("source")?;
let proto_paths: String = r.get("proto_paths")?;
let services: String = r.get("services")?;
Ok(GrpcSchema {
id: r.get("id")?,
created_at: r.get("created_at")?,
updated_at: r.get("updated_at")?,
host_pattern: r.get("host_pattern")?,
source: if source == "reflection" {
GrpcSchemaSource::Reflection
} else {
GrpcSchemaSource::Files
},
proto_paths: serde_json::from_str(&proto_paths).unwrap_or_default(),
services: serde_json::from_str(&services).unwrap_or_default(),
})
}
pub fn list(db: &ProxyQueryManager) -> Result<Vec<GrpcSchema>, String> {
db.with_conn(|c| {
let conn = c.conn().resolve();
let mut stmt = conn
.prepare(&format!("SELECT {COLUMNS} FROM grpc_schemas ORDER BY created_at, id"))
.map_err(|e| e.to_string())?;
let rows = stmt.query_map([], schema_from_row).map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
})
}
fn get(db: &ProxyQueryManager, id: &str) -> Result<GrpcSchema, String> {
db.with_conn(|c| {
c.conn()
.resolve()
.query_row(
&format!("SELECT {COLUMNS} FROM grpc_schemas WHERE id = ?1"),
[id],
schema_from_row,
)
.map_err(|_| format!("No gRPC schema {id}"))
})
}
fn insert(
db: &ProxyQueryManager,
host_pattern: &str,
source: GrpcSchemaSource,
proto_paths: &[String],
pool: &DescriptorPool,
) -> Result<GrpcSchema, String> {
let id = generate_prefixed_id("gs");
let services: Vec<String> = pool.services().map(|s| s.full_name().to_string()).collect();
let source_name = match source {
GrpcSchemaSource::Files => "files",
GrpcSchemaSource::Reflection => "reflection",
};
db.with_tx(|c| {
let conn = c.conn().resolve();
// A host's reflection is kept once, the latest.
if source == GrpcSchemaSource::Reflection {
conn.execute(
"DELETE FROM grpc_schemas WHERE source = 'reflection' AND host_pattern = ?1",
[host_pattern],
)?;
}
conn.execute(
"INSERT INTO grpc_schemas (id, host_pattern, source, proto_paths, services, descriptor) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
id,
host_pattern,
source_name,
serde_json::to_string(proto_paths).unwrap_or_default(),
serde_json::to_string(&services).unwrap_or_default(),
pool.encode_to_vec(),
],
)?;
Ok::<_, yaak_database::Error>(())
})
.map_err(|e| format!("Failed to save the gRPC schema: {e}"))?;
get(db, &id)
}
/// Compiles `proto_paths` (files, and directories to import from) and attaches them to
/// `host_pattern`.
pub async fn add(
db: &ProxyQueryManager,
state: &GrpcState,
host_pattern: &str,
proto_paths: &[String],
) -> Result<GrpcSchema, String> {
let host_pattern = host_pattern.trim().to_ascii_lowercase();
if host_pattern.is_empty() {
return Err("A host pattern is required".into());
}
if proto_paths.is_empty() {
return Err("At least one .proto file is required".into());
}
let paths: Vec<PathBuf> = proto_paths.iter().map(PathBuf::from).collect();
if let Some(missing) = paths.iter().find(|p| !p.exists()) {
return Err(format!("{} does not exist", missing.display()));
}
let config = state.protoc()?;
let pool = yaak_grpc::fill_pool_from_files(&config, &paths)
.await
.map_err(|e| format!("Failed to compile the protos: {e}"))?;
insert(db, &host_pattern, GrpcSchemaSource::Files, proto_paths, &pool)
}
pub fn remove(db: &ProxyQueryManager, state: &GrpcState, id: &str) -> Result<bool, String> {
let removed = db
.with_tx(|c| {
let removed =
c.conn().resolve().execute("DELETE FROM grpc_schemas WHERE id = ?1", [id])?;
Ok::<_, yaak_database::Error>(removed)
})
.map_err(|e| e.to_string())?;
if let Ok(mut pools) = state.pools.lock() {
pools.remove(id);
}
Ok(removed > 0)
}
/// How long a server has to answer reflection, all of it.
const REFLECTION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
/// A host to ask for reflection, as given to `reflect_grpc_host`: `host`, `host:port`, or
/// either after `http://` or `https://`. Returns `host:port` and whether to ask without TLS;
/// without a scheme, over TLS on 443.
pub fn reflection_host(host: &str) -> (String, bool) {
let host = host.trim().trim_end_matches('/').to_ascii_lowercase();
let (host, plaintext) = match host.strip_prefix("http://") {
Some(rest) => (rest.to_string(), true),
None => (host.strip_prefix("https://").unwrap_or(&host).to_string(), false),
};
let has_port = host.rsplit_once(':').is_some_and(|(_, port)| port.parse::<u16>().is_ok());
if has_port {
return (host, plaintext);
}
(format!("{host}:{}", if plaintext { 80 } else { 443 }), plaintext)
}
/// Asks the server at `authority` (`host:port`) for its services by reflection, without TLS
/// when `plaintext`, and keeps them as the host's schema, also for decodes to come. Fails when
/// it offers none.
pub async fn reflect(
db: &ProxyQueryManager,
state: &GrpcState,
authority: &str,
plaintext: bool,
) -> Result<GrpcSchema, String> {
let authority = authority.trim().to_ascii_lowercase();
let reflected = reflect_uncached(db, &authority, plaintext).await;
if let Ok(mut lookups) = state.lookups.lock() {
let answered = tokio::sync::OnceCell::new_with(Some(reflected.clone()));
lookups.insert(authority, Arc::new(answered));
}
reflected
}
async fn reflect_uncached(
db: &ProxyQueryManager,
authority: &str,
plaintext: bool,
) -> Result<GrpcSchema, String> {
let scheme = if plaintext { "http" } else { "https" };
let uri: hyper::Uri = format!("{scheme}://{authority}")
.parse()
.map_err(|e| format!("Invalid host {authority}: {e}"))?;
// Reflection's client panics on an answer it does not expect; that ends this task alone.
// Timed out inside the task, so a server that stalls leaves nothing running.
let timeout_error = format!("{authority} did not answer reflection in time");
let reflected = tokio::spawn(async move {
let metadata = Default::default();
let reflecting =
yaak_grpc::fill_pool_from_reflection(&uri, &metadata, true, None, 64 << 20);
match tokio::time::timeout(REFLECTION_TIMEOUT, reflecting).await {
Ok(reflected) => reflected.map_err(|e| e.to_string()),
Err(_) => Err(timeout_error),
}
})
.await
.map_err(|_| format!("{authority} answered reflection with something unexpected"))??;
if reflected.services().next().is_none() {
return Err(format!("{authority} offers no services by reflection"));
}
insert(db, authority, GrpcSchemaSource::Reflection, &[], &reflected)
}
/// Whether `pattern` covers `host` (lowercase, no port) at `authority` (`host:port`).
fn matches(pattern: &str, host: &str, authority: &str) -> bool {
if pattern == "*" {
return true;
}
let target = if pattern.contains(':') { authority } else { host };
match pattern.strip_prefix("*.") {
Some(domain) => target.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.')),
None => pattern == target,
}
}
impl GrpcState {
fn pool(&self, db: &ProxyQueryManager, id: &str) -> Result<DescriptorPool, String> {
if let Some(pool) = self.pools.lock().ok().and_then(|p| p.get(id).cloned()) {
return Ok(pool);
}
let bytes: Vec<u8> = db.with_conn(|c| {
c.conn()
.resolve()
.query_row("SELECT descriptor FROM grpc_schemas WHERE id = ?1", [id], |r| r.get(0))
.map_err(|e| e.to_string())
})?;
let pool = DescriptorPool::decode(bytes.as_slice()).map_err(|e| e.to_string())?;
if let Ok(mut pools) = self.pools.lock() {
pools.insert(id.to_string(), pool.clone());
}
Ok(pool)
}
}
/// The schema that defines `service` for the host at `authority`: attached protos first, the
/// most specific pattern first, then the host's reflection, asked of the server once, without
/// TLS when `plaintext`, as the call was made.
async fn find_schema(
db: &ProxyQueryManager,
state: &GrpcState,
authority: &str,
plaintext: bool,
service: &str,
) -> Result<(Option<(GrpcSchema, DescriptorPool)>, Option<String>), String> {
let host = authority.rsplit_once(':').map_or(authority, |(h, _)| h);
let mut schemas: Vec<GrpcSchema> =
list(db)?.into_iter().filter(|s| matches(&s.host_pattern, host, authority)).collect();
// Files before reflection; then exact before wildcards, the narrower first.
schemas.sort_by_key(|s| {
let wildcard = s.host_pattern.starts_with('*');
(
s.source == GrpcSchemaSource::Reflection,
wildcard,
std::cmp::Reverse(s.host_pattern.len()),
)
});
for schema in &schemas {
let pool = state.pool(db, &schema.id)?;
if pool.get_service_by_name(service).is_some() {
return Ok((Some((schema.clone(), pool)), None));
}
}
if schemas.iter().any(|s| s.source == GrpcSchemaSource::Reflection) {
return Ok((None, Some(format!("No schema for {service} on {authority}"))));
}
// Asked once: decodes that come while it is being asked wait for the same answer.
let Some(lookup) =
state.lookups.lock().ok().map(|mut l| l.entry(authority.into()).or_default().clone())
else {
return Ok((None, Some(format!("No schema for {service} on {authority}"))));
};
let answer = lookup.get_or_init(|| reflect_uncached(db, authority, plaintext)).await.clone();
match answer {
// Unless it was removed since.
Ok(schema) => match state.pool(db, &schema.id) {
Ok(pool) if pool.get_service_by_name(service).is_some() => {
Ok((Some((schema, pool)), None))
}
Ok(_) => {
Ok((None, Some(format!("{authority}'s reflection does not include {service}"))))
}
Err(_) => Ok((None, Some(format!("No schema for {service} on {authority}")))),
},
Err(e) => Ok((None, Some(format!("No schema for {service}; reflection failed: {e}")))),
}
}
/// Decodes a captured gRPC message.
pub async fn decode(
db: &ProxyQueryManager,
blobs: &BlobManager,
state: &GrpcState,
flow: &Flow,
seq: i64,
) -> Result<DecodedGrpcMessage, String> {
let message = messages::get(db, &flow.id, seq)?;
if message.kind != MessageKind::GrpcMessage {
return Err(format!("Message {seq} is not a gRPC message"));
}
let payload = messages::payload(db, blobs, &message)?;
if message.compressed && message.error.is_some() {
return Err(message.error.unwrap_or_default());
}
let (Some(service), Some(method)) = (&flow.grpc_service, &flow.grpc_method) else {
return Ok(schemaless(&payload, &message, Some("The call's path names no service".into())));
};
let url = url::Url::parse(&flow.url).map_err(|e| e.to_string())?;
let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
let authority = format!("{host}:{}", url.port_or_known_default().unwrap_or(443));
let plaintext = url.scheme() == "http";
let (found, note) = find_schema(db, state, &authority, plaintext, service).await?;
let Some((schema, pool)) = found else {
return Ok(schemaless(&payload, &message, note));
};
let Some(descriptor) = pool
.get_service_by_name(service)
.and_then(|s| s.methods().find(|m| m.name() == method))
.map(|m| match message.direction {
MessageDirection::Client => m.input(),
MessageDirection::Server => m.output(),
})
else {
let note = format!("{} has no method {method}", service);
return Ok(schemaless(&payload, &message, Some(note)));
};
decode_with(&payload, &message, descriptor, schema)
}
fn decode_with(
payload: &[u8],
message: &FlowMessage,
descriptor: MessageDescriptor,
schema: GrpcSchema,
) -> Result<DecodedGrpcMessage, String> {
let message_type = descriptor.full_name().to_string();
match DynamicMessage::decode(descriptor, payload) {
Ok(decoded) => Ok(DecodedGrpcMessage {
json: yaak_grpc::message_to_json(&decoded)?,
message_type: Some(message_type),
schema: Some(schema),
note: message.truncated.then(|| "The message is cut at the capture limit".into()),
}),
Err(e) => {
Ok(schemaless(payload, message, Some(format!("Did not decode as {message_type}: {e}"))))
}
}
}
fn schemaless(payload: &[u8], message: &FlowMessage, reason: Option<String>) -> DecodedGrpcMessage {
let mut notes: Vec<String> = reason.into_iter().collect();
notes.push("Decoded without a schema: field names and types are guesses".into());
if message.truncated {
notes.push("The message is cut at the capture limit".into());
}
let fields = decode_fields(payload, 0).unwrap_or_else(|| {
notes.push("Not a valid protobuf message: shown as bytes".into());
vec![json!({ "bytes": BASE64.encode(payload) })]
});
DecodedGrpcMessage {
json: serde_json::to_string_pretty(&fields).unwrap_or_default(),
message_type: None,
schema: None,
note: Some(notes.join(". ")),
}
}
const MAX_DEPTH: usize = 16;
/// A message's fields from the protobuf wire format, None when the bytes are not one.
pub fn decode_fields(mut bytes: &[u8], depth: usize) -> Option<Vec<Value>> {
let mut fields = Vec::new();
while !bytes.is_empty() {
let key = read_varint(&mut bytes)?;
let field = key >> 3;
if field == 0 || field > 536_870_911 {
return None;
}
let value = match key & 7 {
0 => {
let v = read_varint(&mut bytes)?;
json!({ "field": field, "wireType": "varint", "value": number(v) })
}
1 => {
let raw: [u8; 8] = bytes.get(..8)?.try_into().ok()?;
bytes = &bytes[8..];
let v = u64::from_le_bytes(raw);
json!({ "field": field, "wireType": "fixed64", "value": number(v), "double": f64::from_le_bytes(raw) })
}
2 => {
let len = usize::try_from(read_varint(&mut bytes)?).ok()?;
let data = bytes.get(..len)?;
bytes = &bytes[len..];
let mut value = json!({ "field": field, "wireType": "len" });
let text = std::str::from_utf8(data)
.ok()
.filter(|s| s.chars().all(|c| !c.is_control() || c.is_whitespace()));
if let Some(text) = text {
value["string"] = json!(text);
}
if depth < MAX_DEPTH
&& !data.is_empty()
&& let Some(nested) = decode_fields(data, depth + 1)
{
value["message"] = json!(nested);
}
if text.is_none() {
value["bytes"] = json!(BASE64.encode(data));
}
value
}
5 => {
let raw: [u8; 4] = bytes.get(..4)?.try_into().ok()?;
bytes = &bytes[4..];
let v = u32::from_le_bytes(raw);
json!({ "field": field, "wireType": "fixed32", "value": v, "float": f32::from_le_bytes(raw) })
}
// Groups are long deprecated; 6 and 7 are no wire type.
_ => return None,
};
fields.push(value);
}
Some(fields)
}
/// A u64 as a JSON number when JavaScript can hold it exactly, else as a string.
fn number(v: u64) -> Value {
if v <= (1 << 53) { json!(v) } else { json!(v.to_string()) }
}
fn read_varint(bytes: &mut &[u8]) -> Option<u64> {
let mut value = 0u64;
for i in 0..10 {
let byte = *bytes.get(i)?;
value |= u64::from(byte & 0x7f) << (7 * i);
if byte & 0x80 == 0 {
*bytes = &bytes[i + 1..];
return Some(value);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn without_protoc_the_error_says_what_to_install() {
let empty = tempfile::tempdir().unwrap();
let err = protoc_on_path(Some(empty.path().as_os_str().to_owned())).err().unwrap();
assert_eq!(err, NO_PROTOC);
assert!(err.contains("brew install protobuf"), "{err}");
assert!(protoc_on_path(None).is_err());
}
#[test]
fn reflection_hosts() {
assert_eq!(reflection_host("api.example.com"), ("api.example.com:443".into(), false));
assert_eq!(reflection_host("localhost:50051"), ("localhost:50051".into(), false));
assert_eq!(reflection_host("http://localhost:50051"), ("localhost:50051".into(), true));
assert_eq!(reflection_host("http://Example.com/"), ("example.com:80".into(), true));
assert_eq!(reflection_host("https://example.com"), ("example.com:443".into(), false));
}
#[test]
fn host_patterns() {
assert!(matches("api.example.com", "api.example.com", "api.example.com:443"));
assert!(!matches("api.example.com", "www.example.com", "www.example.com:443"));
assert!(matches("*.example.com", "a.b.example.com", "a.b.example.com:443"));
assert!(!matches("*.example.com", "example.com", "example.com:443"));
assert!(!matches("*.example.com", "badexample.com", "badexample.com:443"));
assert!(matches("localhost:50051", "localhost", "localhost:50051"));
assert!(!matches("localhost:50051", "localhost", "localhost:50052"));
assert!(matches("*", "anything", "anything:1"));
}
#[test]
fn decodes_the_wire_format_without_a_schema() {
// field 1: varint 150; field 2: "hi"; field 3: nested { field 1: 1 }
let bytes = [
0x08, 0x96, 0x01, 0x12, 0x02, b'h', b'i', 0x1a, 0x02, 0x08, 0x01,
];
let fields = decode_fields(&bytes, 0).unwrap();
assert_eq!(fields[0], json!({ "field": 1, "wireType": "varint", "value": 150 }));
assert_eq!(fields[1]["string"], "hi");
assert_eq!(fields[2]["message"][0]["value"], 1);
assert!(decode_fields(&[0x08], 0).is_none(), "a varint cut short");
}
}
+74 -4
View File
@@ -4,8 +4,12 @@
//! at the capture limit and `_error` on a flow that failed.
use crate::bodies::{self, DecodedBody};
use crate::db::ProxyQueryManager;
use crate::flows::{BodyEncoding, BodyPreview};
use crate::models::{Flow, FlowBody, ProxyHeader, find_header};
use crate::messages::{self, MessageDirection, MessageKind};
use crate::models::{Flow, FlowBody, ProxyHeader, StreamKind, find_header};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use serde::{Deserialize, Serialize};
use yaak_models::blob_manager::BlobManager;
@@ -40,6 +44,26 @@ pub struct HarEntry {
pub server_ip_address: Option<String>,
#[serde(rename = "_error", skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// A WebSocket's data messages, as Chrome's devtools export them.
#[serde(
rename = "_webSocketMessages",
skip_serializing_if = "Option::is_none",
default
)]
pub web_socket_messages: Option<Vec<HarWebSocketMessage>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarWebSocketMessage {
/// `send` from the client, `receive` from the server.
#[serde(rename = "type")]
pub kind: String,
/// Seconds since the epoch.
pub time: f64,
/// 1 for text, 2 for binary.
pub opcode: u8,
/// The text, or a binary message in base64.
pub data: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -118,16 +142,59 @@ pub struct HarTimings {
}
/// A HAR of `flows`, reading each body from `blobs` and keeping at most `limit` bytes of it.
pub async fn export(blobs: &BlobManager, flows: &[Flow], limit: usize) -> Result<Har, String> {
/// A WebSocket's messages are in its entry's `_webSocketMessages`; an event stream's events are
/// its response body, as they came.
pub async fn export(
db: &ProxyQueryManager,
blobs: &BlobManager,
flows: &[Flow],
limit: usize,
) -> Result<Har, String> {
let mut entries = Vec::with_capacity(flows.len());
for flow in flows {
let request = bodies::read_body(blobs, flow, FlowBody::Request, limit).await?;
let response = bodies::read_body(blobs, flow, FlowBody::Response, limit).await?;
entries.push(entry(flow, &request, &response));
let mut entry = entry(flow, &request, &response);
if flow.stream_kind == Some(StreamKind::Websocket) {
entry.web_socket_messages = Some(websocket_messages(db, blobs, flow)?);
}
entries.push(entry);
}
Ok(har(entries))
}
fn websocket_messages(
db: &ProxyQueryManager,
blobs: &BlobManager,
flow: &Flow,
) -> Result<Vec<HarWebSocketMessage>, String> {
let mut out = Vec::new();
for message in messages::list(db, &flow.id, None, None)? {
let opcode = match message.kind {
MessageKind::WebsocketText => 1,
MessageKind::WebsocketBinary => 2,
_ => continue,
};
let payload = messages::payload(db, blobs, &message)?;
let data = if opcode == 1 {
String::from_utf8_lossy(&payload).into_owned()
} else {
BASE64.encode(&payload)
};
out.push(HarWebSocketMessage {
kind: match message.direction {
MessageDirection::Client => "send",
MessageDirection::Server => "receive",
}
.into(),
time: message.timestamp.and_utc().timestamp_micros() as f64 / 1_000_000.0,
opcode,
data,
});
}
Ok(out)
}
pub fn har(entries: Vec<HarEntry>) -> Har {
Har {
log: HarLog {
@@ -186,6 +253,7 @@ pub fn entry(flow: &Flow, request_body: &DecodedBody, response_body: &DecodedBod
.clone()
.or_else(|| response_body.decode_error.clone())
.or_else(|| request_body.decode_error.clone()),
web_socket_messages: None,
}
}
@@ -394,7 +462,9 @@ mod tests {
..Default::default()
};
let har = export(&blobs, &[flow], 1024 * 1024).await.unwrap();
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let har = export(&db, &blobs, &[flow], 1024 * 1024).await.unwrap();
let entry = &har.log.entries[0];
let text_kept = entry.response.content.text.as_deref().unwrap();
assert!(!text_kept.is_empty() && text.starts_with(text_kept.as_bytes()));
File diff suppressed because it is too large. Load diff
+368
View File
@@ -0,0 +1,368 @@
//! The messages of streaming flows: WebSocket frames, server-sent events, and gRPC messages and
//! trailers. Each is a row of `flow_messages`, its payload inline when small, else in
//! `blobs.sqlite`. Like flows, they are never pruned; clearing removes them with their flow.
use crate::db::ProxyQueryManager;
use chrono::{DateTime, NaiveDateTime, Utc};
use rusqlite::{Row, params};
use serde::{Deserialize, Serialize};
use ts_rs::TS;
use yaak_database::generate_prefixed_id;
use yaak_models::blob_manager::BlobManager;
/// Payloads up to this many bytes are kept in the row; larger ones in `blobs.sqlite`.
pub const INLINE_LIMIT: usize = 4096;
/// Characters of a text payload kept as its preview.
pub const PREVIEW_CHARS: usize = 200;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_models.ts")]
pub enum MessageDirection {
Client,
Server,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_models.ts")]
pub enum MessageKind {
WebsocketText,
WebsocketBinary,
WebsocketPing,
WebsocketPong,
WebsocketClose,
SseEvent,
GrpcMessage,
GrpcTrailers,
}
const KINDS: [MessageKind; 8] = [
MessageKind::WebsocketText,
MessageKind::WebsocketBinary,
MessageKind::WebsocketPing,
MessageKind::WebsocketPong,
MessageKind::WebsocketClose,
MessageKind::SseEvent,
MessageKind::GrpcMessage,
MessageKind::GrpcTrailers,
];
impl MessageKind {
pub fn as_str(self) -> &'static str {
match self {
Self::WebsocketText => "websocket_text",
Self::WebsocketBinary => "websocket_binary",
Self::WebsocketPing => "websocket_ping",
Self::WebsocketPong => "websocket_pong",
Self::WebsocketClose => "websocket_close",
Self::SseEvent => "sse_event",
Self::GrpcMessage => "grpc_message",
Self::GrpcTrailers => "grpc_trailers",
}
}
pub fn parse(s: &str) -> Option<Self> {
KINDS.into_iter().find(|k| k.as_str() == s)
}
/// The WebSocket opcode, for HAR's `_webSocketMessages`.
pub fn websocket_opcode(self) -> Option<u8> {
match self {
Self::WebsocketText => Some(1),
Self::WebsocketBinary => Some(2),
Self::WebsocketClose => Some(8),
Self::WebsocketPing => Some(9),
Self::WebsocketPong => Some(10),
_ => None,
}
}
}
/// What a kind of message carries beside its payload. Fields that do not apply are left out.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
pub struct MessageMeta {
/// A WebSocket close frame's status code.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub close_code: Option<u16>,
/// A WebSocket close frame's reason.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub close_reason: Option<String>,
/// An SSE event's `event` field.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub event: Option<String>,
/// An SSE event's `id` field.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub event_id: Option<String>,
/// An SSE event's `retry` field, in milliseconds.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional, type = "number")]
pub retry: Option<u64>,
/// An SSE event's lines as they came, comments included, up to 4 KB.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub raw: Option<String>,
/// gRPC trailers' `grpc-status`.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub grpc_status: Option<i32>,
/// gRPC trailers' `grpc-message`, decoded.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub grpc_message: Option<String>,
}
/// One message of a streaming flow. Its payload is fetched on its own.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
pub struct FlowMessage {
pub id: String,
pub flow_id: String,
/// Its place in the flow, from 0, in the order messages passed the proxy.
#[ts(type = "number")]
pub seq: i64,
pub direction: MessageDirection,
pub kind: MessageKind,
/// When it had passed the proxy whole.
pub timestamp: NaiveDateTime,
/// Bytes it took on the wire: the frames' payloads, the event's lines, the gRPC message
/// without its prefix.
#[ts(type = "number")]
pub size: i64,
/// Bytes of payload stored: unmasked, reassembled, inflated or decompressed, and cut at the
/// capture limit.
#[ts(type = "number")]
pub stored_size: i64,
/// The stored payload is cut short at the capture limit.
pub truncated: bool,
/// It was compressed on the wire (permessage-deflate, gRPC's compressed flag); the payload is
/// stored decompressed unless `error` says otherwise.
pub compressed: bool,
/// Why the payload could not be decoded or stored.
pub error: Option<String>,
pub meta: MessageMeta,
/// The payload's start as text, when it is text.
pub preview: Option<String>,
}
impl FlowMessage {
/// The message as it is stored, from the engine's.
pub fn from_engine(flow_id: &str, seq: i64, message: &yaak_proxy::StreamMessage) -> Self {
use yaak_proxy::MessageKind as K;
let mut meta = MessageMeta::default();
let kind = match &message.kind {
K::WebSocketText => MessageKind::WebsocketText,
K::WebSocketBinary => MessageKind::WebsocketBinary,
K::WebSocketPing => MessageKind::WebsocketPing,
K::WebSocketPong => MessageKind::WebsocketPong,
K::WebSocketClose { code, reason } => {
meta.close_code = *code;
meta.close_reason = Some(reason.clone()).filter(|r| !r.is_empty());
MessageKind::WebsocketClose
}
K::SseEvent { event, id, retry, raw } => {
meta.event = event.clone();
meta.event_id = id.clone();
meta.retry = *retry;
meta.raw = Some(raw.clone());
MessageKind::SseEvent
}
K::GrpcMessage => MessageKind::GrpcMessage,
K::GrpcTrailers { status, message } => {
meta.grpc_status = *status;
meta.grpc_message = message.clone();
MessageKind::GrpcTrailers
}
};
let direction = match message.direction {
yaak_proxy::MessageDirection::Client => MessageDirection::Client,
yaak_proxy::MessageDirection::Server => MessageDirection::Server,
};
let preview = match kind {
// Binary by nature, however it happens to read.
MessageKind::WebsocketBinary | MessageKind::GrpcMessage => None,
MessageKind::WebsocketClose => meta.close_reason.clone(),
_ => text_preview(&message.data, message.truncated),
};
Self {
id: generate_prefixed_id("fm"),
flow_id: flow_id.to_string(),
seq,
direction,
kind,
timestamp: DateTime::<Utc>::from(message.at).naive_utc(),
size: i64::try_from(message.size).unwrap_or(i64::MAX),
stored_size: message.data.len() as i64,
truncated: message.truncated,
compressed: message.compressed,
error: message.error.clone(),
meta,
preview,
}
}
/// Where a payload too large for the row is kept in `blobs.sqlite`.
pub fn blob_id(&self) -> String {
format!("{}.msg.{}", self.flow_id, self.id)
}
fn from_row(r: &Row) -> rusqlite::Result<Self> {
let direction: String = r.get("direction")?;
let kind: String = r.get("kind")?;
let meta: String = r.get("meta")?;
Ok(Self {
id: r.get("id")?,
flow_id: r.get("flow_id")?,
seq: r.get("seq")?,
direction: if direction == "client" {
MessageDirection::Client
} else {
MessageDirection::Server
},
kind: MessageKind::parse(&kind).unwrap_or(MessageKind::WebsocketBinary),
timestamp: r.get("timestamp")?,
size: r.get("size")?,
stored_size: r.get("stored_size")?,
truncated: r.get("truncated")?,
compressed: r.get("compressed")?,
error: r.get("error")?,
meta: serde_json::from_str(&meta).unwrap_or_default(),
preview: r.get("preview")?,
})
}
}
/// The start of `data` as text, if it is UTF-8: a cut can split a character at the end.
fn text_preview(data: &[u8], truncated: bool) -> Option<String> {
let text = match std::str::from_utf8(data) {
Ok(text) => text,
Err(e) if truncated && e.error_len().is_none() => {
std::str::from_utf8(&data[..e.valid_up_to()]).ok()?
}
Err(_) => return None,
};
Some(text.chars().take(PREVIEW_CHARS).collect())
}
/// Writes `message`, with its payload in the row when `inline` has it.
pub fn insert(
conn: &rusqlite::Connection,
message: &FlowMessage,
inline: Option<&[u8]>,
) -> rusqlite::Result<()> {
let meta = serde_json::to_string(&message.meta).unwrap_or_else(|_| "{}".into());
let direction = match message.direction {
MessageDirection::Client => "client",
MessageDirection::Server => "server",
};
conn.execute(
"INSERT INTO flow_messages (id, flow_id, seq, direction, kind, timestamp, size, \
stored_size, truncated, compressed, error, meta, preview, data) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
params![
message.id,
message.flow_id,
message.seq,
direction,
message.kind.as_str(),
message.timestamp,
message.size,
message.stored_size,
message.truncated,
message.compressed,
message.error,
meta,
message.preview,
inline,
],
)?;
Ok(())
}
const COLUMNS: &str = "id, flow_id, seq, direction, kind, timestamp, size, stored_size, \
truncated, compressed, error, meta, preview";
/// A flow's messages in order, after `after_seq` when given, at most `limit` of them.
pub fn list(
db: &ProxyQueryManager,
flow_id: &str,
after_seq: Option<i64>,
limit: Option<usize>,
) -> Result<Vec<FlowMessage>, String> {
db.with_conn(|c| {
let conn = c.conn().resolve();
let limit = limit.map_or(-1, |l| l.min(i64::MAX as usize) as i64);
let mut stmt = conn
.prepare(&format!(
"SELECT {COLUMNS} FROM flow_messages WHERE flow_id = ?1 AND seq > ?2 \
ORDER BY seq LIMIT ?3"
))
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![flow_id, after_seq.unwrap_or(-1), limit], FlowMessage::from_row)
.map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
})
}
/// Messages recorded for a flow.
pub fn count(db: &ProxyQueryManager, flow_id: &str) -> Result<i64, String> {
db.with_conn(|c| {
c.conn()
.resolve()
.query_row("SELECT COUNT(*) FROM flow_messages WHERE flow_id = ?1", [flow_id], |r| {
r.get(0)
})
.map_err(|e| e.to_string())
})
}
pub fn find(
db: &ProxyQueryManager,
flow_id: &str,
seq: i64,
) -> Result<Option<FlowMessage>, String> {
db.with_conn(|c| {
let conn = c.conn().resolve();
let found = conn.query_row(
&format!("SELECT {COLUMNS} FROM flow_messages WHERE flow_id = ?1 AND seq = ?2"),
params![flow_id, seq],
FlowMessage::from_row,
);
match found {
Ok(message) => Ok(Some(message)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(e.to_string()),
}
})
}
pub fn get(db: &ProxyQueryManager, flow_id: &str, seq: i64) -> Result<FlowMessage, String> {
find(db, flow_id, seq)?.ok_or_else(|| format!("No message {seq} in flow {flow_id}"))
}
/// A message's stored payload: decoded, and cut at the capture limit.
pub fn payload(
db: &ProxyQueryManager,
blobs: &BlobManager,
message: &FlowMessage,
) -> Result<Vec<u8>, String> {
let inline: Option<Vec<u8>> = db.with_conn(|c| {
c.conn()
.resolve()
.query_row("SELECT data FROM flow_messages WHERE id = ?1", [&message.id], |r| r.get(0))
.map_err(|e| e.to_string())
})?;
if let Some(data) = inline {
return Ok(data);
}
let chunks = blobs.connect().get_chunks(&message.blob_id()).map_err(|e| e.to_string())?;
Ok(chunks.into_iter().flat_map(|c| c.data).collect())
}
+77
View File
@@ -66,6 +66,64 @@ pub struct Flow {
pub client_bundle_id: Option<String>,
/// Its app bundle's path, or its executable's outside an app.
pub client_path: Option<String>,
/// The flow carries a stream of messages, listed with `list_messages`. It is written as the
/// stream opens and again as messages land; it is open until `elapsedMs`, `error` or
/// `cancelled` is set.
pub stream_kind: Option<StreamKind>,
/// Messages recorded so far.
#[ts(type = "number")]
pub message_count: i64,
/// A gRPC call's service, from its path: `package.Service`.
pub grpc_service: Option<String>,
/// A gRPC call's method, from its path.
pub grpc_method: Option<String>,
/// A gRPC call's status, from its trailers. Not 0 is a failed call.
pub grpc_status: Option<i32>,
/// A gRPC call's `grpc-message`, decoded.
pub grpc_message: Option<String>,
}
/// The streaming protocol a flow carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export, export_to = "gen_models.ts")]
pub enum StreamKind {
Websocket,
Sse,
Grpc,
GrpcWeb,
}
impl StreamKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Websocket => "websocket",
Self::Sse => "sse",
Self::Grpc => "grpc",
Self::GrpcWeb => "grpc_web",
}
}
pub fn parse(s: &str) -> Option<Self> {
[Self::Websocket, Self::Sse, Self::Grpc, Self::GrpcWeb]
.into_iter()
.find(|k| k.as_str() == s)
}
pub fn is_grpc(self) -> bool {
matches!(self, Self::Grpc | Self::GrpcWeb)
}
}
impl From<yaak_proxy::StreamKind> for StreamKind {
fn from(kind: yaak_proxy::StreamKind) -> Self {
match kind {
yaak_proxy::StreamKind::WebSocket => Self::Websocket,
yaak_proxy::StreamKind::Sse => Self::Sse,
yaak_proxy::StreamKind::Grpc => Self::Grpc,
yaak_proxy::StreamKind::GrpcWeb => Self::GrpcWeb,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
@@ -164,6 +222,12 @@ impl UpsertModelInfo for Flow {
(ClientName, self.client_name.into()),
(ClientBundleId, self.client_bundle_id.into()),
(ClientPath, self.client_path.into()),
(FlowIden::StreamKind, self.stream_kind.map(|k| k.as_str()).into()),
(MessageCount, self.message_count.into()),
(GrpcService, self.grpc_service.into()),
(GrpcMethod, self.grpc_method.into()),
(GrpcStatus, self.grpc_status.into()),
(GrpcMessage, self.grpc_message.into()),
])
}
@@ -193,6 +257,12 @@ impl UpsertModelInfo for Flow {
FlowIden::ClientName,
FlowIden::ClientBundleId,
FlowIden::ClientPath,
FlowIden::StreamKind,
FlowIden::MessageCount,
FlowIden::GrpcService,
FlowIden::GrpcMethod,
FlowIden::GrpcStatus,
FlowIden::GrpcMessage,
]
}
@@ -229,6 +299,13 @@ impl UpsertModelInfo for Flow {
client_name: added_column(r, "client_name")?,
client_bundle_id: added_column(r, "client_bundle_id")?,
client_path: added_column(r, "client_path")?,
stream_kind: added_column::<String>(r, "stream_kind")?
.and_then(|k| StreamKind::parse(&k)),
message_count: added_column(r, "message_count")?.unwrap_or_default(),
grpc_service: added_column(r, "grpc_service")?,
grpc_method: added_column(r, "grpc_method")?,
grpc_status: added_column(r, "grpc_status")?,
grpc_message: added_column(r, "grpc_message")?,
})
}
}