Messages tab for streams, with messages as the single record (#819)

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 18:45:52 -07:00
1 parent f63586f9f0
commit cc382b9226
42 files changed
+3403 -453

No files matched your search

+408 -14
View File
@@ -1,9 +1,45 @@
use crate::models::{Flow, FlowBody, find_header};
use crate::db::ProxyQueryManager;
use crate::messages::{self, FlowMessage, MessageDirection, MessageKind};
use crate::models::{Flow, FlowBody, StreamKind, find_header};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use std::io::Cursor;
use tokio::io::AsyncReadExt;
use yaak_http::decompress::{ContentEncoding, streaming_decoder};
use yaak_models::blob_manager::BlobManager;
/// Messages read at a time while putting a body back together.
const MESSAGE_PAGE: usize = 500;
/// What a WebSocket's response body reads as: it has none.
pub const WEBSOCKET_BODY_NOTE: &str =
"A WebSocket has no body after its 101 response. Its frames are its messages.";
/// Whether a flow's body is its stream's messages rather than bytes stored on their own: an
/// event stream's response, a gRPC call's request, and its response when the server answered
/// in gRPC (a gateway's error page is a body like any other), and a WebSocket's response. Such a
/// body is not written to `blobs.sqlite`; reading it puts it back together from the messages.
///
/// A body with a Content-Encoding keeps its bytes instead: the messages are read from it decoded,
/// but only its bytes can say whether they decoded whole (gzip's checksum, an encoding the
/// stream's reader can't undo), and they read back through the body's decoder as any other.
pub fn from_messages(flow: &Flow, which: FlowBody) -> bool {
let encoding = find_header(flow.headers(which), "content-encoding").map(str::trim);
let encoded = encoding.is_some_and(|e| !e.is_empty() && !e.eq_ignore_ascii_case("identity"));
if encoded && flow.stream_kind != Some(StreamKind::Websocket) {
return false;
}
match (flow.stream_kind, which) {
(None, _) => false,
(Some(StreamKind::Websocket | StreamKind::Sse), FlowBody::Request) => false,
(Some(StreamKind::Websocket | StreamKind::Sse), FlowBody::Response) => true,
(Some(StreamKind::Grpc | StreamKind::GrpcWeb), FlowBody::Request) => true,
(Some(StreamKind::Grpc | StreamKind::GrpcWeb), FlowBody::Response) => {
yaak_proxy::detect_grpc(find_header(&flow.response_headers, "content-type")).is_some()
}
}
}
/// A flow's body as stored: the bytes on the wire, up to the capture limit.
pub fn read_raw_body(
blobs: &BlobManager,
@@ -25,16 +61,32 @@ pub struct DecodedBody {
pub truncated: bool,
/// Why decoding stopped before the end of the stored bytes.
pub decode_error: Option<String>,
/// What to know about the body beyond its bytes, as that a WebSocket has none.
pub note: Option<String>,
}
impl DecodedBody {
pub fn new(data: Vec<u8>, truncated: bool) -> Self {
Self { stored_size: data.len(), data, truncated, decode_error: None, note: None }
}
}
/// A flow's body decoded with its Content-Encoding, at most `limit` bytes of it. A body that
/// fails to decode, as one cut short does, keeps what decoded before the failure.
/// fails to decode, as one cut short does, keeps what decoded before the failure. A body that is
/// a stream's messages is put back together from them, decoded as they are.
pub async fn read_body(
db: &ProxyQueryManager,
blobs: &BlobManager,
flow: &Flow,
body: FlowBody,
limit: usize,
) -> Result<DecodedBody, String> {
// A gRPC call that ended while its upload still went on kept the upload's bytes instead.
if from_messages(flow, body)
&& !blobs.connect().body_exists(&Flow::body_id(&flow.id, body)).unwrap_or(false)
{
return message_body(db, blobs, flow, body, limit);
}
let raw = read_raw_body(blobs, &flow.id, body)?;
let stored_size = raw.len();
// A response that failed or was cancelled after its headers ended short on the wire.
@@ -49,7 +101,7 @@ pub async fn read_body(
let truncated = wire_truncated || raw.len() > limit;
let mut data = raw;
data.truncate(limit);
return Ok(DecodedBody { data, stored_size, truncated, decode_error: None });
return Ok(DecodedBody { data, stored_size, truncated, decode_error: None, note: None });
}
// One byte past the limit tells a body that fills it from one that overflows it.
@@ -64,7 +116,147 @@ pub async fn read_body(
};
let truncated = wire_truncated || decode_error.is_some() || data.len() > limit;
data.truncate(limit);
Ok(DecodedBody { data, stored_size, truncated, decode_error })
Ok(DecodedBody { data, stored_size, truncated, decode_error, note: None })
}
/// A body that is its stream's messages, as it was on the wire once decoded: an event stream's
/// events as they came, comments within an event included, and a gRPC call's messages framed
/// again (uncompressed, so flagged as such), with a gRPC-Web response's trailers frame, in base64
/// for `grpc-web-text`. Blocks of an event stream that were not events, as a keep-alive comment
/// alone is, are not kept, so are not in it.
fn message_body(
db: &ProxyQueryManager,
blobs: &BlobManager,
flow: &Flow,
which: FlowBody,
limit: usize,
) -> Result<DecodedBody, String> {
let Some(kind) = flow.stream_kind else {
return Ok(DecodedBody::new(Vec::new(), false));
};
if kind == StreamKind::Websocket {
return Ok(DecodedBody {
note: Some(WEBSOCKET_BODY_NOTE.into()),
..DecodedBody::new(Vec::new(), false)
});
}
let direction = match which {
FlowBody::Request => MessageDirection::Client,
FlowBody::Response => MessageDirection::Server,
};
let content_type = find_header(flow.headers(which), "content-type");
let base64_text = yaak_proxy::detect_grpc(content_type).is_some_and(|(_, text)| text);
// The status of a trailers-only response came in its headers, not a frame of its body.
let trailers_in_body = kind == StreamKind::GrpcWeb
&& which == FlowBody::Response
&& find_header(&flow.response_headers, "grpc-status").is_none();
// Enough to fill the limit, after base64 makes it a third longer.
let room = if base64_text { limit / 3 * 4 + 4 } else { limit };
// A response that failed or was cancelled after its headers ended short, as `read_body`
// says of one stored whole.
let mut truncated = which == FlowBody::Response
&& flow.status.is_some()
&& (flow.error.is_some() || flow.cancelled);
let mut out = Vec::new();
let mut after = None;
// Read a page at a time, and no further than the limit needs.
'pages: loop {
let page = messages::list(db, &flow.id, after, Some(MESSAGE_PAGE))?;
let Some(last) = page.last() else {
break;
};
after = Some(last.seq);
let full = page.len() == MESSAGE_PAGE;
for message in page {
if out.len() > room {
truncated = true;
break 'pages;
}
if message.direction != direction {
continue;
}
match message.kind {
MessageKind::SseEvent => {
let payload = messages::payload(db, blobs, &message)?;
out.extend_from_slice(&sse_event_lines(&message, &payload));
}
MessageKind::GrpcMessage | MessageKind::GrpcTrailers
if message.kind == MessageKind::GrpcMessage || trailers_in_body =>
{
let payload = messages::payload(db, blobs, &message)?;
let flag = if message.kind == MessageKind::GrpcMessage { 0 } else { 0x80 };
// A frame cut short declares more than it holds, so a reader would take the
// frames after it as its rest: the body ends there, cut.
if !grpc_frame(&mut out, flag, &message, &payload) {
truncated = true;
break 'pages;
}
}
_ => continue,
}
truncated |= message.truncated;
}
if !full {
break;
}
}
if base64_text {
out = BASE64.encode(&out).into_bytes();
}
let stored_size = out.len();
truncated |= out.len() > limit;
out.truncate(limit);
Ok(DecodedBody { data: out, stored_size, truncated, decode_error: None, note: None })
}
/// An event's lines as they came. Its raw lines are kept up to [`yaak_proxy::RAW_LIMIT`]; an
/// event longer than that is written again from its fields, as `event`, `id`, `retry` and a
/// `data` line for each line of its data.
fn sse_event_lines(message: &FlowMessage, payload: &[u8]) -> Vec<u8> {
if let Some(raw) = &message.meta.raw
&& i64::try_from(raw.len()).is_ok_and(|len| len == message.size)
{
return raw.as_bytes().to_vec();
}
let mut out = Vec::new();
let meta = &message.meta;
if let Some(event) = &meta.event {
out.extend_from_slice(format!("event: {event}\n").as_bytes());
}
if let Some(id) = &meta.event_id {
out.extend_from_slice(format!("id: {id}\n").as_bytes());
}
if let Some(retry) = meta.retry {
out.extend_from_slice(format!("retry: {retry}\n").as_bytes());
}
for line in payload.split(|b| *b == b'\n') {
out.extend_from_slice(b"data: ");
out.extend_from_slice(line);
out.push(b'\n');
}
out.push(b'\n');
out
}
/// Appends a gRPC length-prefixed message: its flag byte, its length, and its bytes.
/// A message decompressed is framed again uncompressed, at its decompressed length. One kept as
/// it came (never compressed, or failing to decompress) keeps its flag and the length it was
/// sent with, so one cut short (at the capture limit, or by the body ending partway through it)
/// reads back as it was on the wire, cut.
///
/// Returns whether the frame is whole: false when it declares more bytes than it holds.
fn grpc_frame(out: &mut Vec<u8>, flag: u8, message: &FlowMessage, payload: &[u8]) -> bool {
let as_sent = !message.compressed || message.error.is_some();
let (flag, length) = if as_sent {
(flag | u8::from(message.compressed), usize::try_from(message.size).unwrap_or(usize::MAX))
} else {
(flag, payload.len())
};
out.push(flag);
out.extend_from_slice(&u32::try_from(length).unwrap_or(u32::MAX).to_be_bytes());
out.extend_from_slice(payload);
payload.len() >= length
}
/// A body's text as the app's viewer reads it, as `decodeBodyText` in `@yaakapp-internal/lib`
@@ -107,12 +299,13 @@ fn strict_utf8(data: &[u8], truncated: bool) -> Option<String> {
/// A flow's body decoded as `read_body` does, or, when it fails to decode, the bytes as they were
/// on the wire, with `decode_error` saying why.
pub async fn read_body_or_raw(
db: &ProxyQueryManager,
blobs: &BlobManager,
flow: &Flow,
body: FlowBody,
limit: usize,
) -> Result<DecodedBody, String> {
let decoded = read_body(blobs, flow, body, limit).await?;
let decoded = read_body(db, blobs, flow, body, limit).await?;
if decoded.decode_error.is_none() {
return Ok(decoded);
}
@@ -127,9 +320,16 @@ mod tests {
use super::*;
use yaak_models::blob_manager::BodyChunkWriter;
fn proxy_db() -> (tempfile::TempDir, ProxyQueryManager) {
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
(dir, db)
}
#[tokio::test]
async fn response_failed_after_its_headers_is_truncated() {
let (_db, blobs, _rx) = yaak_models::init_in_memory().unwrap();
let (_dir, db) = proxy_db();
let mut writer =
BodyChunkWriter::new(blobs.clone(), Flow::body_id("fl_cut", FlowBody::Response));
writer.write(b"{\"rows\": [").unwrap();
@@ -141,18 +341,20 @@ mod tests {
..Default::default()
};
let body = read_body(&blobs, &cut, FlowBody::Response, 1024).await.unwrap();
let body = read_body(&db, &blobs, &cut, FlowBody::Response, 1024).await.unwrap();
assert_eq!((body.data.as_slice(), body.truncated), (&b"{\"rows\": ["[..], true));
// The request went out whole; the error is the response's.
let request = read_body(&blobs, &cut, FlowBody::Request, 1024).await.unwrap();
let request = read_body(&db, &blobs, &cut, FlowBody::Request, 1024).await.unwrap();
assert!(!request.truncated);
// With no headers there was never a response body to cut.
let refused = Flow { status: None, ..cut.clone() };
assert!(!read_body(&blobs, &refused, FlowBody::Response, 1024).await.unwrap().truncated);
assert!(
!read_body(&db, &blobs, &refused, FlowBody::Response, 1024).await.unwrap().truncated
);
// The client cancelling partway through cuts it short the same way.
let cancelled = Flow { error: None, cancelled: true, ..cut };
let body = read_body(&blobs, &cancelled, FlowBody::Response, 1024).await.unwrap();
let body = read_body(&db, &blobs, &cancelled, FlowBody::Response, 1024).await.unwrap();
assert_eq!((body.data.as_slice(), body.truncated), (&b"{\"rows\": ["[..], true));
}
@@ -160,6 +362,7 @@ mod tests {
async fn cancelled_gzip_response_keeps_what_decoded() {
use std::io::Write;
let (_db, blobs, _rx) = yaak_models::init_in_memory().unwrap();
let (_dir, db) = proxy_db();
let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gzip.write_all(&[b'z'; 4096]).unwrap();
let gzip = gzip.finish().unwrap();
@@ -178,7 +381,7 @@ mod tests {
..Default::default()
};
let body = read_body(&blobs, &flow, FlowBody::Response, 8192).await.unwrap();
let body = read_body(&db, &blobs, &flow, FlowBody::Response, 8192).await.unwrap();
assert!(body.truncated);
assert_eq!(body.decode_error, None);
}
@@ -240,6 +443,7 @@ mod tests {
async fn deflate_request_bodies_decode_wrapped_or_raw() {
use std::io::Write;
let (_db, blobs, _rx) = yaak_models::init_in_memory().unwrap();
let (_dir, db) = proxy_db();
let logs = br#"[{"message":"hello","service":"browser"}]"#;
let mut zlib = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
zlib.write_all(logs).unwrap();
@@ -252,7 +456,7 @@ mod tests {
("fl_raw", raw.finish().unwrap()),
] {
let flow = deflate_request(&blobs, id, &stored);
let body = read_body(&blobs, &flow, FlowBody::Request, 1024).await.unwrap();
let body = read_body(&db, &blobs, &flow, FlowBody::Request, 1024).await.unwrap();
assert_eq!(body.decode_error, None, "{id}");
assert_eq!((body.data.as_slice(), body.truncated), (&logs[..], false), "{id}");
}
@@ -261,15 +465,205 @@ mod tests {
#[tokio::test]
async fn undecodable_body_reads_as_it_was_on_the_wire() {
let (_db, blobs, _rx) = yaak_models::init_in_memory().unwrap();
let (_dir, db) = proxy_db();
let flow = deflate_request(&blobs, "fl_bad", b"\x00\x01 not deflate");
let decoded = read_body(&blobs, &flow, FlowBody::Request, 1024).await.unwrap();
let decoded = read_body(&db, &blobs, &flow, FlowBody::Request, 1024).await.unwrap();
assert!(decoded.decode_error.is_some());
let raw = read_body_or_raw(&blobs, &flow, FlowBody::Request, 1024).await.unwrap();
let raw = read_body_or_raw(&db, &blobs, &flow, FlowBody::Request, 1024).await.unwrap();
assert_eq!(raw.data, b"\x00\x01 not deflate");
assert!(!raw.truncated);
assert_eq!(raw.decode_error, decoded.decode_error);
let cut = read_body_or_raw(&blobs, &flow, FlowBody::Request, 4).await.unwrap();
let cut = read_body_or_raw(&db, &blobs, &flow, FlowBody::Request, 4).await.unwrap();
assert_eq!((cut.data.as_slice(), cut.truncated), (&b"\x00\x01 n"[..], true));
}
/// Stores `messages` for `flow_id` as the event loop does, payloads inline.
fn store_messages(
db: &ProxyQueryManager,
flow_id: &str,
messages: &[yaak_proxy::StreamMessage],
) {
db.with_conn(|c| {
for (seq, message) in messages.iter().enumerate() {
let row = FlowMessage::from_engine(flow_id, seq as i64, message);
messages::insert(c.conn().resolve(), &row, Some(&message.data)).unwrap();
}
});
}
fn stream_message(
direction: yaak_proxy::MessageDirection,
kind: yaak_proxy::MessageKind,
size: u64,
data: &[u8],
) -> yaak_proxy::StreamMessage {
yaak_proxy::StreamMessage {
direction,
kind,
at: std::time::SystemTime::now(),
size,
data: bytes::Bytes::copy_from_slice(data),
truncated: false,
compressed: false,
error: None,
}
}
/// An event's raw lines are kept up to a limit; past it, the event is written again from its
/// fields. Either way, nothing of the body was stored on its own.
#[tokio::test]
async fn event_stream_body_is_its_events() {
use yaak_proxy::{MessageDirection as D, MessageKind as K};
let (_db, blobs, _rx) = yaak_models::init_in_memory().unwrap();
let (_dir, db) = proxy_db();
let short = ": hello\nevent: tick\ndata: one\n\n";
let long_data = format!("{}\n{}", "a".repeat(3000), "b".repeat(3000));
let long_size = format!(
"event: big\nid: 7\ndata: {}\ndata: {}\n\n",
"a".repeat(3000),
"b".repeat(3000)
)
.len();
let sse = |event: &str, id: Option<&str>, raw: &str| K::SseEvent {
event: Some(event.into()),
id: id.map(String::from),
retry: None,
raw: raw.into(),
};
store_messages(
&db,
"fl_sse",
&[
stream_message(D::Server, sse("tick", None, short), short.len() as u64, b"one"),
stream_message(
D::Server,
sse("big", Some("7"), &"x".repeat(yaak_proxy::RAW_LIMIT)),
long_size as u64,
long_data.as_bytes(),
),
],
);
let flow =
Flow { id: "fl_sse".into(), stream_kind: Some(StreamKind::Sse), ..Default::default() };
let body = read_body(&db, &blobs, &flow, FlowBody::Response, 1 << 20).await.unwrap();
let expected = format!(
"{short}event: big\nid: 7\ndata: {}\ndata: {}\n\n",
"a".repeat(3000),
"b".repeat(3000)
);
assert_eq!(String::from_utf8(body.data).unwrap(), expected);
assert_eq!((body.truncated, body.decode_error, body.note), (false, None, None));
// The request is no stream, and reads from the blob store as any other.
assert!(!from_messages(&flow, FlowBody::Request));
let cut = read_body(&db, &blobs, &flow, FlowBody::Response, 10).await.unwrap();
assert_eq!((cut.data.as_slice(), cut.truncated), (&short.as_bytes()[..10], true));
// Ended by a failure or a cancel, it is cut short, however whole its events are.
let cancelled = Flow { status: Some(200), cancelled: true, ..flow.clone() };
assert!(
read_body(&db, &blobs, &cancelled, FlowBody::Response, 1 << 20)
.await
.unwrap()
.truncated
);
// With a Content-Encoding, the bytes are its record, whatever the encoding.
for encoding in ["gzip", "br"] {
let encoded = Flow {
response_headers: vec![crate::models::ProxyHeader {
name: "Content-Encoding".into(),
value: encoding.into(),
}],
..flow.clone()
};
assert!(!from_messages(&encoded, FlowBody::Response), "{encoding}");
}
}
/// A message cut at the capture limit declares more than it holds: the body ends with it,
/// so no reader takes the frames after it as its rest.
#[tokio::test]
async fn grpc_body_ends_at_a_cut_message() {
use yaak_proxy::{MessageDirection as D, MessageKind as K};
let (_db, blobs, _rx) = yaak_models::init_in_memory().unwrap();
let (_dir, db) = proxy_db();
let mut cut = stream_message(D::Server, K::GrpcMessage, 11, b"\x0a\x09Hel");
cut.truncated = true;
store_messages(
&db,
"fl_cut",
&[
stream_message(D::Server, K::GrpcMessage, 2, b"\x08\x01"),
cut,
stream_message(D::Server, K::GrpcMessage, 2, b"\x08\x02"),
],
);
let flow = Flow {
id: "fl_cut".into(),
stream_kind: Some(StreamKind::Grpc),
response_headers: vec![crate::models::ProxyHeader {
name: "content-type".into(),
value: "application/grpc".into(),
}],
..Default::default()
};
let body = read_body(&db, &blobs, &flow, FlowBody::Response, 1024).await.unwrap();
assert_eq!(body.data, b"\x00\x00\x00\x00\x02\x08\x01\x00\x00\x00\x00\x0b\x0a\x09Hel");
assert!(body.truncated);
}
#[tokio::test]
async fn grpc_web_text_body_is_its_frames_in_base64() {
use yaak_proxy::{MessageDirection as D, MessageKind as K};
let (_db, blobs, _rx) = yaak_models::init_in_memory().unwrap();
let (_dir, db) = proxy_db();
let trailers = K::GrpcTrailers { status: Some(0), message: None };
store_messages(
&db,
"fl_web",
&[
stream_message(D::Client, K::GrpcMessage, 2, b"\x08\x01"),
stream_message(D::Server, K::GrpcMessage, 2, b"\x08\x02"),
stream_message(D::Server, trailers, 16, b"grpc-status: 0\r\n"),
],
);
let header = |name: &str, value: &str| crate::models::ProxyHeader {
name: name.into(),
value: value.into(),
};
let flow = Flow {
id: "fl_web".into(),
stream_kind: Some(StreamKind::GrpcWeb),
request_headers: vec![header("content-type", "application/grpc-web-text")],
response_headers: vec![header("content-type", "application/grpc-web-text+proto")],
..Default::default()
};
let request = read_body(&db, &blobs, &flow, FlowBody::Request, 1024).await.unwrap();
assert_eq!(request.data, BASE64.encode(b"\x00\x00\x00\x00\x02\x08\x01").as_bytes());
let response = read_body(&db, &blobs, &flow, FlowBody::Response, 1024).await.unwrap();
let mut frames = b"\x00\x00\x00\x00\x02\x08\x02\x80\x00\x00\x00\x10".to_vec();
frames.extend_from_slice(b"grpc-status: 0\r\n");
assert_eq!(response.data, BASE64.encode(&frames).as_bytes());
// A trailers-only answer's status came in its headers, not a frame.
let trailers_only = Flow {
response_headers: vec![
header("content-type", "application/grpc-web"),
header("grpc-status", "0"),
],
..flow.clone()
};
let response =
read_body(&db, &blobs, &trailers_only, FlowBody::Response, 1024).await.unwrap();
assert_eq!(response.data, b"\x00\x00\x00\x00\x02\x08\x02");
// A gateway's error page in place of a gRPC answer is a body like any other.
let gateway = Flow { response_headers: vec![header("content-type", "text/html")], ..flow };
assert!(!from_messages(&gateway, FlowBody::Response));
assert!(from_messages(&gateway, FlowBody::Request));
}
}
+4 -3
View File
@@ -5,7 +5,7 @@
use crate::bodies::{self, DecodedBody};
use crate::ca::CaStatus;
use crate::control::{
self, ControlInfo, ControlStatus, ErrorBody, RecordingRequest, StartRequest,
self, ControlInfo, ControlStatus, ErrorBody, NOTE_HEADER, RecordingRequest, StartRequest,
SystemProxyRequest, TRUNCATED_HEADER,
};
use crate::db::ProxyQueryManager;
@@ -111,8 +111,9 @@ impl ControlClient {
let resp =
self.send(self.http.get(self.url(&format!("/flows/{}/{side}", encode(id))))).await?;
let truncated = resp.headers().get(TRUNCATED_HEADER).is_some_and(|v| v == "true");
let note = resp.headers().get(NOTE_HEADER).and_then(|v| v.to_str().ok()).map(String::from);
let data = resp.bytes().await.map_err(|e| e.to_string())?.to_vec();
Ok(DecodedBody { stored_size: data.len(), data, truncated, decode_error: None })
Ok(DecodedBody { note, ..DecodedBody::new(data, truncated) })
}
pub async fn har(&self, filter: &FlowFilter) -> Result<Har, String> {
@@ -225,7 +226,7 @@ impl OfflineStore {
pub async fn body(&self, id: &str, which: FlowBody) -> Result<DecodedBody, String> {
let flow = flows::get(&self.db, id)?;
bodies::read_body(&self.blobs, &flow, which, self.capture_body_limit).await
bodies::read_body(&self.db, &self.blobs, &flow, which, self.capture_body_limit).await
}
pub async fn har(&self, filter: &FlowFilter) -> Result<Har, String> {
+8 -2
View File
@@ -266,6 +266,8 @@ pub struct RemovedResponse {
/// 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";
/// Raw body headers: what to know about a body beyond its bytes, as that a WebSocket has none.
pub const NOTE_HEADER: &str = "x-yaak-note";
// -- Server --
@@ -544,7 +546,7 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
})?;
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 {
match grpc::decode(&ctx.db, &ctx.blobs, &ctx.grpc, &flow, seq, false).await {
Ok(decoded) => (Some(decoded), None),
Err(e) => (None, Some(e)),
}
@@ -639,11 +641,15 @@ fn found(ctx: &ProxyCtx, id: &str) -> Result<(), ApiError> {
async fn raw_body(ctx: &ProxyCtx, id: &str, which: FlowBody) -> Result<ControlResponse, ApiError> {
let flow = flows::find(&ctx.db, id)
.ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, format!("No flow {id}")))?;
let body = bodies::read_body(&ctx.blobs, &flow, which, ctx.capture_body_limit()?).await?;
let body =
bodies::read_body(&ctx.db, &ctx.blobs, &flow, which, ctx.capture_body_limit()?).await?;
let content_type =
find_header(flow.headers(which), "content-type").unwrap_or("application/octet-stream");
let mut resp = response(StatusCode::OK, content_type, body.data);
resp.headers_mut().insert(TRUNCATED_HEADER, body.truncated.to_string().parse().unwrap());
if let Some(note) = body.note.as_deref().and_then(|n| n.parse().ok()) {
resp.headers_mut().insert(NOTE_HEADER, note);
}
Ok(resp)
}
+10 -2
View File
@@ -254,6 +254,7 @@ mod tests {
stored_size: data.len(),
truncated: false,
decode_error: None,
note: None,
}
}
@@ -416,6 +417,7 @@ mod tests {
stored_size: 3,
truncated: false,
decode_error: None,
note: None,
};
let c = flow_to_request(&f, &data);
assert_eq!(c.request.body_type.as_deref(), Some("other"));
@@ -427,8 +429,13 @@ mod tests {
fn decoded_empty_body() {
let f = flow("POST", "https://x.test/", &[("Content-Encoding", "gzip")]);
// A gzip stream of nothing: stored bytes, but an empty body once decoded.
let data =
DecodedBody { data: Vec::new(), stored_size: 20, truncated: false, decode_error: None };
let data = DecodedBody {
data: Vec::new(),
stored_size: 20,
truncated: false,
decode_error: None,
note: None,
};
let c = flow_to_request(&f, &data);
assert!(c.request.headers.is_empty());
assert_eq!(c.dropped_headers[0].reason, DropReason::BodyDecoded);
@@ -450,6 +457,7 @@ mod tests {
stored_size: 4,
truncated: true,
decode_error: None,
note: None,
};
let c = flow_to_request(&f, &data);
assert_eq!(names(&c.request), vec!["Content-Type"]);
+4 -3
View File
@@ -715,18 +715,19 @@ pub async fn detail(
body_cap: usize,
) -> Result<FlowDetail, String> {
let flow = get(db, flow_id)?;
let request_body = preview(blobs, &flow, FlowBody::Request, body_cap).await?;
let response_body = preview(blobs, &flow, FlowBody::Response, body_cap).await?;
let request_body = preview(db, blobs, &flow, FlowBody::Request, body_cap).await?;
let response_body = preview(db, blobs, &flow, FlowBody::Response, body_cap).await?;
Ok(FlowDetail { flow, request_body, response_body })
}
async fn preview(
db: &ProxyQueryManager,
blobs: &BlobManager,
flow: &Flow,
which: FlowBody,
cap: usize,
) -> Result<Option<BodyPreview>, String> {
let body = bodies::read_body(blobs, flow, which, cap).await?;
let body = bodies::read_body(db, blobs, flow, which, cap).await?;
if body.data.is_empty() && !body.truncated {
return Ok(None);
}
+5 -1
View File
@@ -391,13 +391,14 @@ async fn find_schema(
}
}
/// Decodes a captured gRPC message.
/// Decodes a captured gRPC message, with its call's schema unless `schemaless_only`.
pub async fn decode(
db: &ProxyQueryManager,
blobs: &BlobManager,
state: &GrpcState,
flow: &Flow,
seq: i64,
schemaless_only: bool,
) -> Result<DecodedGrpcMessage, String> {
let message = messages::get(db, &flow.id, seq)?;
if message.kind != MessageKind::GrpcMessage {
@@ -407,6 +408,9 @@ pub async fn decode(
if message.compressed && message.error.is_some() {
return Err(message.error.unwrap_or_default());
}
if schemaless_only {
return Ok(schemaless(&payload, &message, None));
}
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())));
};
+9 -3
View File
@@ -152,8 +152,8 @@ pub async fn export(
) -> 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?;
let request = bodies::read_body(db, blobs, flow, FlowBody::Request, limit).await?;
let response = bodies::read_body(db, blobs, flow, FlowBody::Response, limit).await?;
let mut entry = entry(flow, &request, &response);
if flow.stream_kind == Some(StreamKind::Websocket) {
entry.web_socket_messages = Some(websocket_messages(db, blobs, flow)?);
@@ -323,7 +323,13 @@ mod tests {
}
fn body(data: &[u8], truncated: bool) -> DecodedBody {
DecodedBody { data: data.to_vec(), stored_size: data.len(), truncated, decode_error: None }
DecodedBody {
data: data.to_vec(),
stored_size: data.len(),
truncated,
decode_error: None,
note: None,
}
}
fn at(second: u32) -> chrono::NaiveDateTime {
+419 -15
View File
@@ -607,7 +607,8 @@ impl ProxyCtx {
) -> Result<SaveFlowResponse, String> {
let flow = flows::get(&self.db, flow_id)?;
let limit = self.capture_body_limit()?;
let body = bodies::read_body(&self.blobs, &flow, FlowBody::Request, limit).await?;
let body =
bodies::read_body(&self.db, &self.blobs, &flow, FlowBody::Request, limit).await?;
let saved = ClientDb::open(&self.client_data_dir)?.save(&flow, &body, req)?;
let flow = Flow { saved_request_id: Some(saved.request.id.clone()), ..flow };
@@ -986,6 +987,10 @@ pub struct GetFlowBodyResponse {
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub decode_error: Option<String>,
/// What to know about the body beyond its bytes, as that a WebSocket has none.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub note: Option<String>,
}
#[derive(Deserialize, TS)]
@@ -1121,6 +1126,10 @@ pub struct DecodeGrpcMessageRequest {
pub flow_id: String,
#[ts(type = "number")]
pub seq: i64,
/// Decode without a schema even when one is found.
#[serde(default)]
#[ts(optional, as = "Option<bool>")]
pub schemaless: bool,
}
#[derive(Deserialize, TS)]
@@ -1185,7 +1194,9 @@ async fn decode_grpc_message(
req: DecodeGrpcMessageRequest,
) -> Result<DecodedGrpcMessage, RpcError> {
let flow = find_flow(&ctx, &req.flow_id)?;
grpc::decode(&ctx.db, &ctx.blobs, &ctx.grpc, &flow, req.seq).await.map_err(rpc_error)
grpc::decode(&ctx.db, &ctx.blobs, &ctx.grpc, &flow, req.seq, req.schemaless)
.await
.map_err(rpc_error)
}
fn list_grpc_schemas(
@@ -1296,8 +1307,9 @@ async fn list_workspaces(
async fn preview_save(ctx: ProxyCtx, req: PreviewSaveRequest) -> Result<SavePreview, RpcError> {
let flow = find_flow(&ctx, &req.flow_id)?;
let limit = settings(&ctx)?.capture_body_limit;
let body =
bodies::read_body(&ctx.blobs, &flow, FlowBody::Request, limit).await.map_err(rpc_error)?;
let body = bodies::read_body(&ctx.db, &ctx.blobs, &flow, FlowBody::Request, limit)
.await
.map_err(rpc_error)?;
let conversion = convert::flow_to_request(&flow, &body);
let request = conversion.request;
let body = request.body_type.as_deref().map(|body_type| match body_type {
@@ -1372,13 +1384,15 @@ async fn get_flow_body(
) -> Result<GetFlowBodyResponse, RpcError> {
let flow = find_flow(&ctx, &req.flow_id)?;
let limit = settings(&ctx)?.capture_body_limit;
let body =
bodies::read_body_or_raw(&ctx.blobs, &flow, req.which, limit).await.map_err(rpc_error)?;
let body = bodies::read_body_or_raw(&ctx.db, &ctx.blobs, &flow, req.which, limit)
.await
.map_err(rpc_error)?;
Ok(GetFlowBodyResponse {
data: BASE64.encode(&body.data),
truncated: body.truncated,
stored_size: body.stored_size,
decode_error: body.decode_error,
note: body.note,
})
}
@@ -1390,8 +1404,13 @@ async fn save_flow_body(
) -> Result<SaveFlowBodyResponse, RpcError> {
let flow = find_flow(&ctx, &req.flow_id)?;
let limit = settings(&ctx)?.capture_body_limit;
let body =
bodies::read_body_or_raw(&ctx.blobs, &flow, req.which, limit).await.map_err(rpc_error)?;
let body = bodies::read_body_or_raw(&ctx.db, &ctx.blobs, &flow, req.which, limit)
.await
.map_err(rpc_error)?;
// Nothing to save; an empty file would say the body was empty.
if let Some(note) = body.note.filter(|_| body.data.is_empty()) {
return Err(rpc_error(note));
}
let saved = SaveFlowBodyResponse {
size: body.data.len(),
truncated: body.truncated,
@@ -1414,7 +1433,8 @@ async fn viewer_body(
which: FlowBody,
limit: usize,
) -> Result<bodies::DecodedBody, RpcError> {
let body = bodies::read_body(&ctx.blobs, flow, which, limit).await.map_err(rpc_error)?;
let body =
bodies::read_body(&ctx.db, &ctx.blobs, flow, which, limit).await.map_err(rpc_error)?;
match body.decode_error {
Some(e) => Err(rpc_error(e)),
None => Ok(body),
@@ -1567,6 +1587,22 @@ struct InFlight {
}
impl InFlight {
/// Stops writing the bodies its stream's messages carry, which are read back from them.
/// A request's bytes are kept while it uploads, as a call can end before its upload does,
/// with a message still partway in: they are dropped once the upload ends, or kept as its
/// record, cut, when the flow ends first.
fn drop_message_bodies(&mut self) {
if bodies::from_messages(&self.flow, FlowBody::Response) {
self.response_body = None;
}
}
/// Its bytes on the wire are its record, as for any body that isn't a stream's messages, an
/// encoded one included. Their cut at the capture limit is then the body's.
fn keeps_bytes(&self, which: FlowBody) -> bool {
!bodies::from_messages(&self.flow, which)
}
/// Something shown of the flow changed: one written while it streams is written again on
/// the stream flow interval, so it does not wait for a message to show it.
fn changed(&mut self) {
@@ -1681,6 +1717,22 @@ fn record_message(
f.flow.grpc_status = *status;
f.flow.grpc_message = message.clone();
}
// A body read back from its messages is cut where they are.
if message.truncated {
match message.direction {
yaak_proxy::MessageDirection::Client
if bodies::from_messages(&f.flow, FlowBody::Request) =>
{
f.flow.request_truncated = true
}
yaak_proxy::MessageDirection::Server
if bodies::from_messages(&f.flow, FlowBody::Response) =>
{
f.flow.response_truncated = true
}
_ => {}
}
}
let seq = f.next_seq;
f.next_seq += 1;
f.flow.message_count += 1;
@@ -1750,6 +1802,10 @@ impl FlowSink {
f.flow.grpc_service = Some(service.to_string());
f.flow.grpc_method = Some(method.to_string());
}
// Its messages are the record of the bodies they carry, which are not
// written again on their own. A gRPC response's body is known to be messages
// once its headers are, at its first chunk.
f.drop_message_bodies();
// Shown while it streams, rather than only once it ends.
self.write_stream_flow(f);
}
@@ -1773,7 +1829,9 @@ impl FlowSink {
ProxyEvent::RequestBodyChunk { id, len, data } => {
if let Some(f) = in_flight.get_mut(&id) {
f.flow.request_size += len as i64;
f.flow.request_truncated |= data.len() < len;
if f.keeps_bytes(FlowBody::Request) {
f.flow.request_truncated |= data.len() < len;
}
write_body_chunk(&mut f.request_body, &data);
f.changed();
}
@@ -1781,8 +1839,16 @@ impl FlowSink {
ProxyEvent::RequestBodyComplete { id, size, truncated } => {
if let Some(f) = in_flight.get_mut(&id) {
f.flow.request_size = size as i64;
f.flow.request_truncated = truncated;
finish_body(f.request_body.take());
if f.keeps_bytes(FlowBody::Request) {
f.flow.request_truncated = truncated;
finish_body(f.request_body.take());
} else if f.request_body.take().is_some() {
// The upload ended whole, its messages its record: its bytes go.
let body_id = Flow::body_id(&f.flow.id, FlowBody::Request);
if let Err(e) = blobs.with_tx(|b| b.delete_chunks(&body_id)) {
warn!("Failed to delete a stream's request bytes: {e}");
}
}
f.changed();
}
}
@@ -1805,7 +1871,10 @@ impl FlowSink {
ProxyEvent::ResponseBodyChunk { id, len, data } => {
if let Some(f) = in_flight.get_mut(&id) {
f.flow.response_size += len as i64;
f.flow.response_truncated |= data.len() < len;
f.drop_message_bodies();
if f.keeps_bytes(FlowBody::Response) {
f.flow.response_truncated |= data.len() < len;
}
write_body_chunk(&mut f.response_body, &data);
f.changed();
}
@@ -1820,7 +1889,9 @@ impl FlowSink {
} => {
if let Some(mut f) = in_flight.remove(&id) {
f.flow.response_size = size as i64;
f.flow.response_truncated = truncated;
if f.keeps_bytes(FlowBody::Response) {
f.flow.response_truncated = truncated;
}
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
f.flow.error = error;
f.flow.cancelled = cancelled;
@@ -1958,7 +2029,12 @@ impl FlowSink {
}
}
fn finish_flow(&self, f: InFlight) {
fn finish_flow(&self, mut f: InFlight) {
// Ended while its upload still went on: what came of it is kept, cut.
let upload_cut = bodies::from_messages(&f.flow, FlowBody::Request)
&& f.request_body.is_some()
&& f.flow.request_size > 0;
f.flow.request_truncated |= upload_cut;
finish_body(f.request_body);
finish_body(f.response_body);
let id = f.flow.id.clone();
@@ -2218,6 +2294,329 @@ mod tests {
}
}
/// A gRPC call's bodies are its messages: neither is written to the blob store, and each
/// reads back framed again, cut where a message was cut.
#[tokio::test(flavor = "multi_thread")]
async fn grpc_bodies_are_read_back_from_their_messages() {
use yaak_proxy::{MessageDirection as D, MessageKind as K};
let dir = tempfile::tempdir().unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let (tx, event_loop) = event_loop(&ctx);
let send = |event| tx.send(event).unwrap();
send(ProxyEvent::RequestStart {
id: 1,
started_at: SystemTime::now(),
method: "POST".into(),
url: "https://api.example.com/pkg.Greeter/SayHello".into(),
http_version: "HTTP/2.0".into(),
connection: 1,
client_addr: "127.0.0.1:1".parse().unwrap(),
});
send(ProxyEvent::RequestHeader {
id: 1,
name: "content-type".into(),
value: "application/grpc".into(),
});
send(ProxyEvent::StreamStart { id: 1, kind: yaak_proxy::StreamKind::Grpc });
let request = b"\x00\x00\x00\x00\x05\x0a\x03Ada";
send(ProxyEvent::RequestBodyChunk {
id: 1,
len: request.len(),
data: bytes::Bytes::from_static(request),
});
send(ws_message(1, D::Client, K::GrpcMessage, b"\x0a\x03Ada"));
send(ProxyEvent::RequestBodyComplete {
id: 1,
size: request.len() as u64,
truncated: false,
});
send(ProxyEvent::ResponseStart {
id: 1,
status: 200,
http_version: "HTTP/2.0".into(),
remote_addr: None,
elapsed_ms: 1,
});
send(ProxyEvent::ResponseHeader {
id: 1,
name: "content-type".into(),
value: "application/grpc+proto".into(),
});
// Over the capture limit on the wire: the body stored only the limit's worth before.
let response = b"\x00\x00\x00\x00\x0b\x0a\x09Hello Ada";
send(ProxyEvent::ResponseBodyChunk {
id: 1,
len: response.len(),
data: bytes::Bytes::from_static(&response[..4]),
});
let mut cut = ws_message(1, D::Server, K::GrpcMessage, b"\x0a\x09Hel");
if let ProxyEvent::Message { message, .. } = &mut cut {
message.truncated = true;
message.size = 11;
}
send(cut);
let trailers = K::GrpcTrailers { status: Some(0), message: None };
send(ws_message(1, D::Server, trailers, b"grpc-status: 0\r\n"));
send(ProxyEvent::ResponseBodyComplete {
id: 1,
size: response.len() as u64,
truncated: true,
elapsed_ms: 5,
error: None,
cancelled: false,
});
drop(tx);
event_loop.join().unwrap();
let flow = flows::list(&ctx.db, &Default::default()).unwrap().remove(0);
assert_eq!((flow.message_count, flow.grpc_status), (3, Some(0)));
assert_eq!((flow.request_size, flow.response_size), (10, 16), "sizes on the wire");
assert_eq!((flow.request_truncated, flow.response_truncated), (false, true));
let blobs = ctx.blobs.connect();
assert!(!blobs.body_exists(&Flow::body_id(&flow.id, FlowBody::Request)).unwrap());
assert!(!blobs.body_exists(&Flow::body_id(&flow.id, FlowBody::Response)).unwrap());
let read = |which| bodies::read_body(&ctx.db, &ctx.blobs, &flow, which, 1 << 20);
let request_body = read(FlowBody::Request).await.unwrap();
assert_eq!((request_body.data.as_slice(), request_body.truncated), (&request[..], false));
// HTTP/2 trailers are no part of the body.
let response_body = read(FlowBody::Response).await.unwrap();
// Framed with the length it was sent with, so it reads back as it was on the wire, cut.
assert_eq!(response_body.data, b"\x00\x00\x00\x00\x0b\x0a\x09Hel");
assert!(response_body.truncated);
let har = har::export(&ctx.db, &ctx.blobs, &[flow], 1 << 20).await.unwrap();
assert_eq!(har.log.entries[0].response.content.size, 10);
}
/// A gzipped event stream keeps its bytes as well as its events: they read back through the
/// body's decoder, so one that decodes reads as its events did, and one that doesn't keeps
/// its bytes and says why.
#[tokio::test(flavor = "multi_thread")]
async fn encoded_event_streams_keep_their_bytes() {
use std::io::Write;
use yaak_proxy::{MessageDirection as D, MessageKind as K};
let dir = tempfile::tempdir().unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let (tx, event_loop) = event_loop(&ctx);
let raw = "data: hi\n\n".to_string();
let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gzip.write_all(raw.as_bytes()).unwrap();
let gzip = bytes::Bytes::from(gzip.finish().unwrap());
let bodies = [
(1, "https://a.example.com/events", gzip),
(
2,
"https://b.example.com/events",
bytes::Bytes::from_static(b"\x1f\x8b not really gzip"),
),
];
for (id, url, data) in bodies.clone() {
tx.send(ProxyEvent::RequestStart {
id,
started_at: SystemTime::now(),
method: "GET".into(),
url: url.into(),
http_version: "HTTP/1.1".into(),
connection: id,
client_addr: "127.0.0.1:1".parse().unwrap(),
})
.unwrap();
tx.send(ProxyEvent::ResponseStart {
id,
status: 200,
http_version: "HTTP/1.1".into(),
remote_addr: None,
elapsed_ms: 1,
})
.unwrap();
for (name, value) in [
("content-type", "text/event-stream"),
("content-encoding", "gzip"),
] {
let (name, value) = (name.into(), value.into());
tx.send(ProxyEvent::ResponseHeader { id, name, value }).unwrap();
}
tx.send(ProxyEvent::StreamStart { id, kind: yaak_proxy::StreamKind::Sse }).unwrap();
tx.send(ProxyEvent::ResponseBodyChunk { id, len: data.len(), data }).unwrap();
}
// The first one's bytes decoded into an event; the second's never did.
let event = K::SseEvent { event: None, id: None, retry: None, raw: raw.clone() };
let mut message = ws_message(1, D::Server, event, b"hi");
if let ProxyEvent::Message { message, .. } = &mut message {
message.size = raw.len() as u64;
}
tx.send(message).unwrap();
for (id, _, data) in bodies.clone() {
tx.send(ProxyEvent::ResponseBodyComplete {
id,
size: data.len() as u64,
truncated: false,
elapsed_ms: 5,
error: None,
cancelled: false,
})
.unwrap();
}
drop(tx);
event_loop.join().unwrap();
let flows = flows::list(&ctx.db, &Default::default()).unwrap();
let flow = |host: &str| flows.iter().find(|f| f.url.contains(host)).unwrap().clone();
let (decoded, undecoded) = (flow("a.example"), flow("b.example"));
assert_eq!(decoded.message_count, 1);
let read =
|flow| bodies::read_body_or_raw(&ctx.db, &ctx.blobs, flow, FlowBody::Response, 1024);
let body = read(&decoded).await.unwrap();
assert_eq!((body.data.as_slice(), body.decode_error), (raw.as_bytes(), None));
let body = read(&undecoded).await.unwrap();
assert_eq!(body.data, b"\x1f\x8b not really gzip");
assert!(body.decode_error.is_some());
}
#[tokio::test(flavor = "multi_thread")]
async fn encoded_grpc_bodies_that_never_decode_keep_their_bytes_and_cut() {
use yaak_proxy::{MessageDirection as D, MessageKind as K};
let dir = tempfile::tempdir().unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let (tx, event_loop) = event_loop(&ctx);
let send = |event| tx.send(event).unwrap();
let header = |name: &str, value: &str| (name.to_string(), value.to_string());
send(ProxyEvent::RequestStart {
id: 1,
started_at: SystemTime::now(),
method: "POST".into(),
url: "https://api.example.com/pkg.Greeter/SayHello".into(),
http_version: "HTTP/2.0".into(),
connection: 1,
client_addr: "127.0.0.1:1".parse().unwrap(),
});
for (name, value) in [
header("content-type", "application/grpc"),
header("content-encoding", "gzip"),
] {
send(ProxyEvent::RequestHeader { id: 1, name, value });
}
send(ProxyEvent::StreamStart { id: 1, kind: yaak_proxy::StreamKind::Grpc });
// Cut at the capture limit: 4 of 30 bytes kept.
send(ProxyEvent::RequestBodyChunk {
id: 1,
len: 30,
data: bytes::Bytes::from_static(b"junk"),
});
send(ProxyEvent::RequestBodyComplete { id: 1, size: 30, truncated: true });
send(ProxyEvent::ResponseStart {
id: 1,
status: 200,
http_version: "HTTP/2.0".into(),
remote_addr: None,
elapsed_ms: 1,
});
for (name, value) in [
header("content-type", "application/grpc"),
header("content-encoding", "gzip"),
] {
send(ProxyEvent::ResponseHeader { id: 1, name, value });
}
send(ProxyEvent::ResponseBodyChunk {
id: 1,
len: 40,
data: bytes::Bytes::from_static(b"\x1f\x8bnope"),
});
// The status came in the HTTP/2 trailers, not from the body's bytes.
let trailers = K::GrpcTrailers { status: Some(0), message: None };
send(ws_message(1, D::Server, trailers, b"grpc-status: 0\r\n"));
send(ProxyEvent::ResponseBodyComplete {
id: 1,
size: 40,
truncated: true,
elapsed_ms: 5,
error: None,
cancelled: false,
});
drop(tx);
event_loop.join().unwrap();
let flow = flows::list(&ctx.db, &Default::default()).unwrap().remove(0);
assert_eq!((flow.request_truncated, flow.response_truncated), (true, true));
for (which, kept) in [
(FlowBody::Request, &b"junk"[..]),
(FlowBody::Response, b"\x1f\x8bnope"),
] {
// The bytes are kept, and read as a cut body is: what decoded of them, cut short.
assert_eq!(bodies::read_raw_body(&ctx.blobs, &flow.id, which).unwrap(), kept);
let body = bodies::read_body(&ctx.db, &ctx.blobs, &flow, which, 1024).await.unwrap();
assert!(body.truncated, "{which:?}");
}
}
/// A call that ends while its upload still goes on keeps what came of the upload, cut; one
/// whose upload ended whole keeps only its messages.
#[tokio::test(flavor = "multi_thread")]
async fn a_grpc_upload_outlived_by_its_call_keeps_its_bytes() {
use yaak_proxy::{MessageDirection as D, MessageKind as K};
let dir = tempfile::tempdir().unwrap();
let (events, _event_rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
let (tx, event_loop) = event_loop(&ctx);
let send = |event| tx.send(event).unwrap();
send(ProxyEvent::RequestStart {
id: 1,
started_at: SystemTime::now(),
method: "POST".into(),
url: "https://api.example.com/pkg.Uploader/Upload".into(),
http_version: "HTTP/2.0".into(),
connection: 1,
client_addr: "127.0.0.1:1".parse().unwrap(),
});
send(ProxyEvent::RequestHeader {
id: 1,
name: "content-type".into(),
value: "application/grpc".into(),
});
send(ProxyEvent::StreamStart { id: 1, kind: yaak_proxy::StreamKind::Grpc });
// One whole message, and the start of the next.
let uploaded = b"\x00\x00\x00\x00\x02\x08\x01\x00\x00\x00\x00\x0a\x0a\x08par";
send(ProxyEvent::RequestBodyChunk {
id: 1,
len: uploaded.len(),
data: bytes::Bytes::from_static(uploaded),
});
send(ws_message(1, D::Client, K::GrpcMessage, b"\x08\x01"));
send(ProxyEvent::ResponseStart {
id: 1,
status: 200,
http_version: "HTTP/2.0".into(),
remote_addr: None,
elapsed_ms: 1,
});
send(ProxyEvent::ResponseHeader {
id: 1,
name: "content-type".into(),
value: "application/grpc".into(),
});
// The server answers and ends the call before the upload is done.
send(ProxyEvent::ResponseBodyComplete {
id: 1,
size: 0,
truncated: false,
elapsed_ms: 5,
error: None,
cancelled: false,
});
drop(tx);
event_loop.join().unwrap();
let flow = flows::list(&ctx.db, &Default::default()).unwrap().remove(0);
assert!(flow.request_truncated);
let body = bodies::read_body(&ctx.db, &ctx.blobs, &flow, FlowBody::Request, 1 << 20)
.await
.unwrap();
assert_eq!((body.data.as_slice(), body.truncated), (&uploaded[..], true));
}
#[tokio::test(flavor = "multi_thread")]
async fn websocket_messages_are_stored_and_exported() {
use yaak_proxy::{MessageDirection as D, MessageKind as K};
@@ -2275,6 +2674,11 @@ mod tests {
(Some("receive"), Some(2))
);
assert_eq!(sent[1]["data"], BASE64.encode(&big));
// No body after the 101, and it says why.
let body = bodies::read_body(&ctx.db, &ctx.blobs, &flow, FlowBody::Response, 1 << 20)
.await
.unwrap();
assert_eq!((body.data.len(), body.note.as_deref()), (0, Some(bodies::WEBSOCKET_BODY_NOTE)));
let names: Vec<_> = event_rx.try_iter().map(|e| e.event).collect();
assert_eq!(names.iter().filter(|n| **n == "message_write").count(), 3, "{names:?}");
+6 -3
View File
@@ -16,7 +16,8 @@ pub struct ProxyHeader {
pub value: String,
}
/// One proxied request and its response. The bodies are in `blobs.sqlite`, not the row.
/// One proxied request and its response. The bodies are in `blobs.sqlite`, not the row; a
/// stream's are its messages, and read back from them (`bodies::from_messages`).
#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
@@ -48,9 +49,11 @@ pub struct Flow {
/// Bytes of the response body on the wire, captured or not.
#[ts(type = "number")]
pub response_size: i64,
/// Only the first `capture_body_limit` bytes of the body are stored.
/// Only the first `capture_body_limit` bytes of the body are stored. For a body that is a
/// stream's messages, a message was cut at the limit.
pub request_truncated: bool,
/// Only the first `capture_body_limit` bytes of the body are stored.
/// Only the first `capture_body_limit` bytes of the body are stored. For a body that is a
/// stream's messages, a message was cut at the limit.
pub response_truncated: bool,
/// Milliseconds from `started_at` to the response headers.
pub elapsed_headers_ms: Option<i32>,