mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-03 21:44:10 +01:00
Capture WebSocket, SSE and gRPC (#814)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
08a98d5f82
commit
1129f7aa93
32 files changed
+5228
-100
No files matched your search
@@ -22,12 +22,13 @@ rusqlite = { version = "0.38", features = ["bundled", "chrono", "functions"] }
|
||||
sea-query = { version = "1.0", features = ["with-chrono", "attr"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["io-util", "macros", "net", "process", "rt-multi-thread"] }
|
||||
tokio = { workspace = true, features = ["io-util", "macros", "net", "process", "rt-multi-thread", "sync", "time"] }
|
||||
ts-rs = { workspace = true, features = ["chrono-impl"] }
|
||||
url = "2"
|
||||
yaak-common = { workspace = true }
|
||||
yaak-database = { workspace = true }
|
||||
yaak-filter = { workspace = true }
|
||||
yaak-grpc = { workspace = true }
|
||||
yaak-http = { workspace = true }
|
||||
yaak-lifecycle = { workspace = true }
|
||||
yaak-models = { workspace = true }
|
||||
@@ -71,9 +72,13 @@ plist = "1.7"
|
||||
base64 = "0.23.1"
|
||||
bytes = "1"
|
||||
flate2 = "1"
|
||||
futures-util = "0.3"
|
||||
http-body-util = "0.1"
|
||||
hyper = { version = "1", features = ["http1", "server"] }
|
||||
hyper-util = { version = "0.1", features = ["tokio"] }
|
||||
hyper = { version = "1", features = ["http1", "http2", "server"] }
|
||||
hyper-util = { version = "0.1", features = ["tokio", "server-auto"] }
|
||||
protoc-bin-vendored = "3"
|
||||
tonic = { version = "0.14.6", default-features = false }
|
||||
tonic-reflection = "0.14.6"
|
||||
reqwest = { workspace = true }
|
||||
tempfile = "3"
|
||||
tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "time"] }
|
||||
|
||||
+136
-1
@@ -65,10 +65,145 @@ clientBundleId: string | null,
|
||||
/**
|
||||
* Its app bundle's path, or its executable's outside an app.
|
||||
*/
|
||||
clientPath: string | null, };
|
||||
clientPath: string | null,
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
streamKind: StreamKind | null,
|
||||
/**
|
||||
* Messages recorded so far.
|
||||
*/
|
||||
messageCount: number,
|
||||
/**
|
||||
* A gRPC call's service, from its path: `package.Service`.
|
||||
*/
|
||||
grpcService: string | null,
|
||||
/**
|
||||
* A gRPC call's method, from its path.
|
||||
*/
|
||||
grpcMethod: string | null,
|
||||
/**
|
||||
* A gRPC call's status, from its trailers. Not 0 is a failed call.
|
||||
*/
|
||||
grpcStatus: number | null,
|
||||
/**
|
||||
* A gRPC call's `grpc-message`, decoded.
|
||||
*/
|
||||
grpcMessage: string | null, };
|
||||
|
||||
export type FlowBody = "request" | "response";
|
||||
|
||||
/**
|
||||
* One message of a streaming flow. Its payload is fetched on its own.
|
||||
*/
|
||||
export type FlowMessage = { id: string, flowId: string,
|
||||
/**
|
||||
* Its place in the flow, from 0, in the order messages passed the proxy.
|
||||
*/
|
||||
seq: number, direction: MessageDirection, kind: MessageKind,
|
||||
/**
|
||||
* When it had passed the proxy whole.
|
||||
*/
|
||||
timestamp: string,
|
||||
/**
|
||||
* Bytes it took on the wire: the frames' payloads, the event's lines, the gRPC message
|
||||
* without its prefix.
|
||||
*/
|
||||
size: number,
|
||||
/**
|
||||
* Bytes of payload stored: unmasked, reassembled, inflated or decompressed, and cut at the
|
||||
* capture limit.
|
||||
*/
|
||||
storedSize: number,
|
||||
/**
|
||||
* The stored payload is cut short at the capture limit.
|
||||
*/
|
||||
truncated: boolean,
|
||||
/**
|
||||
* It was compressed on the wire (permessage-deflate, gRPC's compressed flag); the payload is
|
||||
* stored decompressed unless `error` says otherwise.
|
||||
*/
|
||||
compressed: boolean,
|
||||
/**
|
||||
* Why the payload could not be decoded or stored.
|
||||
*/
|
||||
error: string | null, meta: MessageMeta,
|
||||
/**
|
||||
* The payload's start as text, when it is text.
|
||||
*/
|
||||
preview: string | null, };
|
||||
|
||||
/**
|
||||
* Descriptors for decoding the gRPC calls to hosts that match `hostPattern`.
|
||||
*/
|
||||
export type GrpcSchema = { id: string, createdAt: string, updatedAt: string,
|
||||
/**
|
||||
* A host (`api.example.com`), a host and port (`localhost:50051`), any subdomain of one
|
||||
* (`*.example.com`), or every host (`*`).
|
||||
*/
|
||||
hostPattern: string, source: GrpcSchemaSource,
|
||||
/**
|
||||
* The `.proto` files and include directories compiled, for a `files` schema.
|
||||
*/
|
||||
protoPaths: Array<string>,
|
||||
/**
|
||||
* The services the descriptors define, by full name.
|
||||
*/
|
||||
services: Array<string>, };
|
||||
|
||||
/**
|
||||
* Where a schema's descriptors came from.
|
||||
*/
|
||||
export type GrpcSchemaSource = "files" | "reflection";
|
||||
|
||||
export type MessageDirection = "client" | "server";
|
||||
|
||||
export type MessageKind = "websocket_text" | "websocket_binary" | "websocket_ping" | "websocket_pong" | "websocket_close" | "sse_event" | "grpc_message" | "grpc_trailers";
|
||||
|
||||
/**
|
||||
* What a kind of message carries beside its payload. Fields that do not apply are left out.
|
||||
*/
|
||||
export type MessageMeta = {
|
||||
/**
|
||||
* A WebSocket close frame's status code.
|
||||
*/
|
||||
closeCode?: number,
|
||||
/**
|
||||
* A WebSocket close frame's reason.
|
||||
*/
|
||||
closeReason?: string,
|
||||
/**
|
||||
* An SSE event's `event` field.
|
||||
*/
|
||||
event?: string,
|
||||
/**
|
||||
* An SSE event's `id` field.
|
||||
*/
|
||||
eventId?: string,
|
||||
/**
|
||||
* An SSE event's `retry` field, in milliseconds.
|
||||
*/
|
||||
retry?: number,
|
||||
/**
|
||||
* An SSE event's lines as they came, comments included, up to 4 KB.
|
||||
*/
|
||||
raw?: string,
|
||||
/**
|
||||
* gRPC trailers' `grpc-status`.
|
||||
*/
|
||||
grpcStatus?: number,
|
||||
/**
|
||||
* gRPC trailers' `grpc-message`, decoded.
|
||||
*/
|
||||
grpcMessage?: string, };
|
||||
|
||||
export type ModelPayload = { model: Flow, change: ModelChangeEvent, };
|
||||
|
||||
export type ProxyHeader = { name: string, value: string, };
|
||||
|
||||
/**
|
||||
* The streaming protocol a flow carries.
|
||||
*/
|
||||
export type StreamKind = "websocket" | "sse" | "grpc" | "grpc_web";
|
||||
+88
-4
@@ -1,10 +1,20 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Flow, FlowBody, ModelPayload } from "./gen_models";
|
||||
import type { Flow, FlowBody, FlowMessage, GrpcSchema, ModelPayload } from "./gen_models";
|
||||
|
||||
export type ActionInvocation = { "scope": "global", action: GlobalAction, };
|
||||
|
||||
export type ActionMetadata = { label: string, defaultHotkey: string | null, };
|
||||
|
||||
export type AddGrpcSchemaRequest = {
|
||||
/**
|
||||
* `api.example.com`, `localhost:50051`, `*.example.com` or `*`.
|
||||
*/
|
||||
hostPattern: string,
|
||||
/**
|
||||
* `.proto` files, and directories they import from.
|
||||
*/
|
||||
protoPaths: Array<string>, };
|
||||
|
||||
export type AppIconRequest = {
|
||||
/**
|
||||
* A flow's `clientPath`.
|
||||
@@ -44,6 +54,31 @@ bundleId: string | null,
|
||||
*/
|
||||
path: string, };
|
||||
|
||||
export type DecodeGrpcMessageRequest = { flowId: string, seq: number, };
|
||||
|
||||
/**
|
||||
* A captured gRPC message as JSON.
|
||||
*/
|
||||
export type 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).
|
||||
*/
|
||||
json: string,
|
||||
/**
|
||||
* The message type decoded with: `package.HelloReply`. None when schemaless.
|
||||
*/
|
||||
messageType: string | null,
|
||||
/**
|
||||
* The schema decoded with. None when schemaless.
|
||||
*/
|
||||
schema: GrpcSchema | null,
|
||||
/**
|
||||
* Why it decoded schemaless, or what to know about the decode.
|
||||
*/
|
||||
note: string | null, };
|
||||
|
||||
export type DropReason = "hop_by_hop" | "set_by_sending" | "body_decoded";
|
||||
|
||||
export type DroppedHeader = { name: string, value: string, reason: DropReason, };
|
||||
@@ -100,7 +135,8 @@ app?: Array<string>,
|
||||
*/
|
||||
method?: 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.
|
||||
*/
|
||||
status?: string,
|
||||
/**
|
||||
@@ -149,6 +185,18 @@ storedSize: number,
|
||||
*/
|
||||
decodeError?: string, };
|
||||
|
||||
export type GetMessagePayloadRequest = { flowId: string, seq: number, };
|
||||
|
||||
export type GetMessagePayloadResponse = {
|
||||
/**
|
||||
* The payload as stored (unmasked, inflated, decompressed), in base64.
|
||||
*/
|
||||
data: string,
|
||||
/**
|
||||
* It is cut at the capture limit.
|
||||
*/
|
||||
truncated: boolean, };
|
||||
|
||||
export type GetProxyStateRequest = Record<string, never>;
|
||||
|
||||
export type GetProxyStateResponse = { state: ProxyState,
|
||||
@@ -214,6 +262,28 @@ total: number,
|
||||
*/
|
||||
matching: number | null, };
|
||||
|
||||
export type ListGrpcSchemasRequest = Record<string, never>;
|
||||
|
||||
export type ListMessagesRequest = { flowId: string,
|
||||
/**
|
||||
* Only messages after this `seq`, for following a stream as it grows.
|
||||
*/
|
||||
afterSeq?: number,
|
||||
/**
|
||||
* At most this many, the first after `afterSeq`.
|
||||
*/
|
||||
limit?: number, };
|
||||
|
||||
export type ListMessagesResponse = {
|
||||
/**
|
||||
* In order, by `seq`.
|
||||
*/
|
||||
messages: Array<FlowMessage>,
|
||||
/**
|
||||
* Messages the flow has in all.
|
||||
*/
|
||||
total: number, };
|
||||
|
||||
export type ListWorkspacesRequest = Record<string, never>;
|
||||
|
||||
export type ListWorkspacesResponse = {
|
||||
@@ -222,6 +292,11 @@ export type ListWorkspacesResponse = {
|
||||
*/
|
||||
yaakFound: boolean, workspaces: Array<WorkspaceSummary>, };
|
||||
|
||||
/**
|
||||
* A message of a streaming flow was recorded.
|
||||
*/
|
||||
export type MessagePayload = { message: FlowMessage, };
|
||||
|
||||
export type OtherOwner = { owner: Owner, pid: number, startedAt: string,
|
||||
/**
|
||||
* The engine's port while it runs.
|
||||
@@ -241,9 +316,18 @@ export type ProxyState = "running" | "stopped";
|
||||
|
||||
export type ProxyStatePayload = { state: ProxyState, };
|
||||
|
||||
export type RpcEventSchema = { flows_cleared: FlowsClearedPayload, model_write: ModelPayload, proxy_state_changed: ProxyStatePayload, };
|
||||
export type ReflectGrpcHostRequest = {
|
||||
/**
|
||||
* `host` or `host:port`, over TLS on 443 unless a port is given, or either after
|
||||
* `http://` to ask without TLS.
|
||||
*/
|
||||
host: string, };
|
||||
|
||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], format_body: [FormatBodyRequest, string], list_actions: [ListActionsRequest, ListActionsResponse], list_flows: [FlowFilter, ListFlowsResponse], set_recording: [SetRecordingRequest, boolean], set_system_proxy_at_launch: [SetSystemProxyAtLaunchRequest, boolean], set_http_version: [SetHttpVersionRequest, HttpVersion], app_icon: [AppIconRequest, string | null], ca_status: [CaStatusRequest, CaStatus], ca_trust: [CaTrustRequest, CaStatus], clear_flows: [ClearFlowsRequest, number], export_har: [ExportHarRequest, number], filter_body: [FilterBodyRequest, FilterBodyResponse], get_flow_body: [GetFlowBodyRequest, GetFlowBodyResponse], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], helper_register: [HelperRegisterRequest, SystemProxyStatus], helper_unregister: [HelperUnregisterRequest, SystemProxyStatus], list_workspaces: [ListWorkspacesRequest, ListWorkspacesResponse], preview_save: [PreviewSaveRequest, SavePreview], save_flow: [SaveFlowToYaakRequest, SavedFlow], save_flow_body: [SaveFlowBodyRequest, SaveFlowBodyResponse], system_proxy_set: [SystemProxySetRequest, SystemProxyStatus], system_proxy_status: [SystemProxyStatusRequest, SystemProxyStatus], take_over: [TakeOverRequest, boolean], };
|
||||
export type RemoveGrpcSchemaRequest = { id: string, };
|
||||
|
||||
export type RpcEventSchema = { flows_cleared: FlowsClearedPayload, message_write: MessagePayload, model_write: ModelPayload, proxy_state_changed: ProxyStatePayload, };
|
||||
|
||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], format_body: [FormatBodyRequest, string], get_message_payload: [GetMessagePayloadRequest, GetMessagePayloadResponse], list_actions: [ListActionsRequest, ListActionsResponse], list_flows: [FlowFilter, ListFlowsResponse], list_grpc_schemas: [ListGrpcSchemasRequest, Array<GrpcSchema>], list_messages: [ListMessagesRequest, ListMessagesResponse], remove_grpc_schema: [RemoveGrpcSchemaRequest, boolean], set_recording: [SetRecordingRequest, boolean], set_system_proxy_at_launch: [SetSystemProxyAtLaunchRequest, boolean], set_http_version: [SetHttpVersionRequest, HttpVersion], add_grpc_schema: [AddGrpcSchemaRequest, GrpcSchema], app_icon: [AppIconRequest, string | null], ca_status: [CaStatusRequest, CaStatus], ca_trust: [CaTrustRequest, CaStatus], clear_flows: [ClearFlowsRequest, number], decode_grpc_message: [DecodeGrpcMessageRequest, DecodedGrpcMessage], export_har: [ExportHarRequest, number], filter_body: [FilterBodyRequest, FilterBodyResponse], get_flow_body: [GetFlowBodyRequest, GetFlowBodyResponse], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], helper_register: [HelperRegisterRequest, SystemProxyStatus], helper_unregister: [HelperUnregisterRequest, SystemProxyStatus], list_workspaces: [ListWorkspacesRequest, ListWorkspacesResponse], preview_save: [PreviewSaveRequest, SavePreview], reflect_grpc_host: [ReflectGrpcHostRequest, GrpcSchema], save_flow: [SaveFlowToYaakRequest, SavedFlow], save_flow_body: [SaveFlowBodyRequest, SaveFlowBodyResponse], system_proxy_set: [SystemProxySetRequest, SystemProxyStatus], system_proxy_status: [SystemProxyStatusRequest, SystemProxyStatus], take_over: [TakeOverRequest, boolean], };
|
||||
|
||||
export type SaveFlowBodyRequest = { flowId: string, which: FlowBody,
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
-- Streaming flows: WebSocket, server-sent events, gRPC and gRPC-Web.
|
||||
ALTER TABLE flows ADD COLUMN stream_kind TEXT;
|
||||
ALTER TABLE flows ADD COLUMN message_count INTEGER NOT NULL DEFAULT 0;
|
||||
-- A gRPC call's service and method, from its path, and its status, from its trailers.
|
||||
ALTER TABLE flows ADD COLUMN grpc_service TEXT;
|
||||
ALTER TABLE flows ADD COLUMN grpc_method TEXT;
|
||||
ALTER TABLE flows ADD COLUMN grpc_status INTEGER;
|
||||
ALTER TABLE flows ADD COLUMN grpc_message TEXT;
|
||||
|
||||
-- The messages of streaming flows, in the order they passed. A payload over a few KB is in
|
||||
-- blobs.sqlite, under `<flow id>.msg.<message id>`, and `data` is NULL.
|
||||
CREATE TABLE flow_messages
|
||||
(
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
flow_id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
direction TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
timestamp DATETIME NOT NULL,
|
||||
size INTEGER NOT NULL DEFAULT 0,
|
||||
stored_size INTEGER NOT NULL DEFAULT 0,
|
||||
truncated BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
compressed BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
error TEXT,
|
||||
meta TEXT NOT NULL DEFAULT '{}',
|
||||
preview TEXT,
|
||||
data BLOB
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX idx_flow_messages_flow_id_seq ON flow_messages (flow_id, seq);
|
||||
|
||||
-- Where gRPC messages are decoded from: protos attached to a host pattern, or a server's
|
||||
-- reflection, with the descriptors compiled from them.
|
||||
CREATE TABLE grpc_schemas
|
||||
(
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
host_pattern TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
proto_paths TEXT NOT NULL DEFAULT '[]',
|
||||
services TEXT NOT NULL DEFAULT '[]',
|
||||
descriptor BLOB NOT NULL
|
||||
);
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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" {
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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())
|
||||
}
|
||||
@@ -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")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
//! Streaming flows through a running engine: server-sent events and gRPC-Web over plain
|
||||
//! HTTP, stored as messages while they stream, and gRPC messages decoded with and without a
|
||||
//! schema.
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use http_body_util::combinators::UnsyncBoxBody;
|
||||
use http_body_util::{BodyExt, Full, StreamBody};
|
||||
use hyper::body::{Frame, Incoming};
|
||||
use hyper::service::service_fn;
|
||||
use hyper::{Request, Response};
|
||||
use hyper_util::rt::{TokioExecutor, TokioIo};
|
||||
use hyper_util::server::conn::auto;
|
||||
use serde_json::{Value, json};
|
||||
use tokio::net::TcpListener;
|
||||
use yaak_proxy_lib::models::Flow;
|
||||
use yaak_proxy_lib::settings::ProxySettings;
|
||||
use yaak_proxy_lib::{GrpcConfig, ProxyCtx};
|
||||
use yaak_rpc::RpcEventEmitter;
|
||||
|
||||
type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||
type TestBody = UnsyncBoxBody<Bytes, BoxError>;
|
||||
|
||||
const PROTO: &str = r#"
|
||||
syntax = "proto3";
|
||||
package pkg;
|
||||
service Greeter {
|
||||
rpc SayHello (HelloRequest) returns (HelloReply);
|
||||
}
|
||||
message HelloRequest { string name = 1; }
|
||||
message HelloReply { string message = 1; int32 count = 2; }
|
||||
"#;
|
||||
|
||||
/// The longest a test here may run: one that hangs fails with a message instead of holding CI
|
||||
/// until its job is cancelled.
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
async fn within<T>(test: impl Future<Output = T>) -> T {
|
||||
match tokio::time::timeout(TEST_TIMEOUT, test).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => panic!("the test did not finish within {TEST_TIMEOUT:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn full(data: impl Into<Bytes>) -> TestBody {
|
||||
Full::new(data.into()).map_err(|never| match never {}).boxed_unsync()
|
||||
}
|
||||
|
||||
fn grpc_frame(flag: u8, payload: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![flag];
|
||||
out.extend((payload.len() as u32).to_be_bytes());
|
||||
out.extend(payload);
|
||||
out
|
||||
}
|
||||
|
||||
/// A protobuf message with a string in field 1, and a varint in field 2 when given.
|
||||
fn proto(text: &str, count: Option<u8>) -> Vec<u8> {
|
||||
let mut out = vec![0x0a, text.len() as u8];
|
||||
out.extend(text.as_bytes());
|
||||
if let Some(count) = count {
|
||||
out.extend([0x10, count]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn protoc() -> GrpcConfig {
|
||||
GrpcConfig {
|
||||
protoc_bin_path: protoc_bin_vendored::protoc_bin_path().unwrap(),
|
||||
protoc_include_dir: protoc_bin_vendored::include_path().unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn proto_file(dir: &Path) -> String {
|
||||
let path = dir.join("greeter.proto");
|
||||
std::fs::write(&path, PROTO).unwrap();
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
type ReflectionFuture = std::pin::Pin<Box<dyn Future<Output = Response<tonic::body::Body>> + Send>>;
|
||||
/// A gRPC reflection service, its type erased.
|
||||
type Reflection =
|
||||
std::sync::Arc<dyn Fn(Request<tonic::body::Body>) -> ReflectionFuture + Send + Sync>;
|
||||
|
||||
fn reflection_service<S>(service: S) -> Reflection
|
||||
where
|
||||
S: tonic::codegen::Service<
|
||||
Request<tonic::body::Body>,
|
||||
Response = Response<tonic::body::Body>,
|
||||
Error = Infallible,
|
||||
> + Clone
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
S::Future: Send,
|
||||
{
|
||||
std::sync::Arc::new(move |req| {
|
||||
let mut service = service.clone();
|
||||
Box::pin(async move {
|
||||
std::future::poll_fn(|cx| service.poll_ready(cx)).await.unwrap();
|
||||
service.call(req).await.unwrap()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Serves the upstream's routes, and gRPC reflection for `pkg.Greeter` over HTTP/2 when given
|
||||
/// one.
|
||||
async fn route(
|
||||
req: Request<Incoming>,
|
||||
reflection: Option<Reflection>,
|
||||
) -> Result<Response<TestBody>, Infallible> {
|
||||
let path = req.uri().path().to_string();
|
||||
if path.starts_with("/grpc.reflection.v1.ServerReflection/") {
|
||||
let Some(reflection) = reflection else {
|
||||
return Ok(Response::builder().status(404).body(full("")).unwrap());
|
||||
};
|
||||
let resp = reflection(req.map(tonic::body::Body::new)).await;
|
||||
return Ok(resp.map(|b| b.map_err(|e| Box::new(e) as BoxError).boxed_unsync()));
|
||||
}
|
||||
Ok(match path.as_str() {
|
||||
// Two events a while apart, so the first is stored while the stream is open.
|
||||
"/events" => {
|
||||
let frames = futures_util::stream::unfold(0, |i| async move {
|
||||
let chunk = match i {
|
||||
0 => "event: tick\nid: 1\ndata: first\n\n",
|
||||
1 => {
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
"data: second\n\n"
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some((Ok::<_, BoxError>(Frame::data(Bytes::from(chunk))), i + 1))
|
||||
});
|
||||
Response::builder()
|
||||
.header("content-type", "text/event-stream")
|
||||
.body(StreamBody::new(frames).boxed_unsync())
|
||||
.unwrap()
|
||||
}
|
||||
"/pkg.Greeter/SayHello" => {
|
||||
let body = req.into_body().collect().await.unwrap().to_bytes();
|
||||
let name = String::from_utf8_lossy(&body[7..]).into_owned();
|
||||
let mut out = grpc_frame(0, &proto(&format!("Hello {name}"), Some(3)));
|
||||
out.extend(grpc_frame(0x80, b"grpc-status: 0\r\n"));
|
||||
Response::builder()
|
||||
.header("content-type", "application/grpc-web+proto")
|
||||
.body(full(out))
|
||||
.unwrap()
|
||||
}
|
||||
_ => Response::builder()
|
||||
.header("content-type", "application/grpc-web+proto")
|
||||
.body(full(grpc_frame(0x80, b"grpc-status: 12\r\ngrpc-message: not%20here\r\n")))
|
||||
.unwrap(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn spawn_upstream(reflection: Option<Reflection>) -> SocketAddr {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let (tcp, _) = listener.accept().await.unwrap();
|
||||
let reflection = reflection.clone();
|
||||
tokio::spawn(async move {
|
||||
let svc = service_fn(move |req| route(req, reflection.clone()));
|
||||
let _ = auto::Builder::new(TokioExecutor::new())
|
||||
.serve_connection(TokioIo::new(tcp), svc)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
});
|
||||
addr
|
||||
}
|
||||
|
||||
fn start(dir: &Path) -> (ProxyCtx, std::sync::mpsc::Receiver<yaak_rpc::RpcEvent>) {
|
||||
let settings = ProxySettings {
|
||||
port: 0,
|
||||
capture_body_limit: 1024 * 1024,
|
||||
system_proxy_at_launch: false,
|
||||
..Default::default()
|
||||
};
|
||||
settings.save(&dir.join("settings.json")).unwrap();
|
||||
let (events, event_rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir, events).unwrap().with_protoc(protoc());
|
||||
ctx.start().unwrap();
|
||||
(ctx, event_rx)
|
||||
}
|
||||
|
||||
fn client(ctx: &ProxyCtx) -> reqwest::Client {
|
||||
let proxy = format!("http://127.0.0.1:{}", ctx.port().unwrap());
|
||||
reqwest::Client::builder().proxy(reqwest::Proxy::all(proxy).unwrap()).build().unwrap()
|
||||
}
|
||||
|
||||
async fn rpc(ctx: &ProxyCtx, cmd: &str, payload: Value) -> Result<Value, String> {
|
||||
yaak_proxy_lib::build_router().dispatch(cmd, payload, ctx).await.map_err(|e| e.message)
|
||||
}
|
||||
|
||||
/// Waits until `check` holds for the flow of `url`, as stored.
|
||||
async fn wait_for(ctx: &ProxyCtx, url: &str, check: impl Fn(&Flow) -> bool) -> Flow {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let flows = ctx.db.with_conn(|db| db.find_all::<Flow>().unwrap());
|
||||
if let Some(flow) = flows.into_iter().find(|f| f.url == url && check(f)) {
|
||||
return flow;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no flow for {url} as expected");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn server_sent_events_are_stored_while_the_stream_is_open() {
|
||||
within(async {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (ctx, event_rx) = start(dir.path());
|
||||
let upstream = spawn_upstream(None).await;
|
||||
let url = format!("http://{upstream}/events");
|
||||
let reading = tokio::spawn({
|
||||
let client = client(&ctx);
|
||||
let url = url.clone();
|
||||
async move { client.get(&url).send().await.unwrap().text().await.unwrap() }
|
||||
});
|
||||
|
||||
// The flow is in the database with its first event while the second is still to come.
|
||||
let open = wait_for(&ctx, &url, |f| f.message_count == 1).await;
|
||||
assert_eq!(open.stream_kind.map(|k| k.as_str()), Some("sse"));
|
||||
assert_eq!(open.elapsed_ms, None, "still streaming");
|
||||
let listed = rpc(&ctx, "list_messages", json!({ "flowId": open.id })).await.unwrap();
|
||||
assert_eq!(listed["total"], 1);
|
||||
let first = &listed["messages"][0];
|
||||
assert_eq!(
|
||||
(first["kind"].as_str(), first["direction"].as_str()),
|
||||
(Some("sse_event"), Some("server"))
|
||||
);
|
||||
assert_eq!(first["preview"], "first");
|
||||
assert_eq!(
|
||||
first["meta"],
|
||||
json!({ "event": "tick", "eventId": "1", "raw": "event: tick\nid: 1\ndata: first\n\n" })
|
||||
);
|
||||
|
||||
assert_eq!(reading.await.unwrap(), "event: tick\nid: 1\ndata: first\n\ndata: second\n\n");
|
||||
let ended = wait_for(&ctx, &url, |f| f.elapsed_ms.is_some()).await;
|
||||
assert_eq!((ended.message_count, ended.error), (2, None));
|
||||
let after =
|
||||
rpc(&ctx, "list_messages", json!({ "flowId": ended.id, "afterSeq": 0 })).await.unwrap();
|
||||
assert_eq!(after["messages"].as_array().unwrap().len(), 1);
|
||||
let payload = rpc(&ctx, "get_message_payload", json!({ "flowId": ended.id, "seq": 1 }))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(payload["data"], "c2Vjb25k", "\"second\" in base64");
|
||||
|
||||
// The app heard of the open flow, of each message, and of the end.
|
||||
let events: Vec<_> = event_rx.try_iter().map(|e| e.event).collect();
|
||||
let writes = |name: &str| events.iter().filter(|e| **e == name).count();
|
||||
assert_eq!(writes("message_write"), 2, "{events:?}");
|
||||
assert!(writes("model_write") >= 2, "{events:?}");
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn grpc_web_calls_are_stored_and_decoded() {
|
||||
within(async {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (ctx, _event_rx) = start(dir.path());
|
||||
let upstream = spawn_upstream(None).await;
|
||||
let client = client(&ctx);
|
||||
|
||||
let url = format!("http://{upstream}/pkg.Greeter/SayHello");
|
||||
let body = client
|
||||
.post(&url)
|
||||
.header("content-type", "application/grpc-web+proto")
|
||||
.body(grpc_frame(0, &proto("Ada", None)))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.bytes()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(body.starts_with(&grpc_frame(0, &proto("Hello Ada", Some(3)))));
|
||||
let flow = wait_for(&ctx, &url, |f| f.elapsed_ms.is_some()).await;
|
||||
assert_eq!(flow.stream_kind.map(|k| k.as_str()), Some("grpc_web"));
|
||||
assert_eq!(
|
||||
(flow.grpc_service.as_deref(), flow.grpc_method.as_deref()),
|
||||
(Some("pkg.Greeter"), Some("SayHello"))
|
||||
);
|
||||
assert_eq!((flow.grpc_status, flow.message_count), (Some(0), 3));
|
||||
|
||||
let failing = format!("http://{upstream}/pkg.Greeter/Missing");
|
||||
client
|
||||
.post(&failing)
|
||||
.header("content-type", "application/grpc-web+proto")
|
||||
.body(grpc_frame(0, &proto("Bo", None)))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let failed = wait_for(&ctx, &failing, |f| f.elapsed_ms.is_some()).await;
|
||||
assert_eq!(
|
||||
(failed.grpc_status, failed.grpc_message.as_deref()),
|
||||
(Some(12), Some("not here"))
|
||||
);
|
||||
let errors = rpc(&ctx, "list_flows", json!({ "status": "error" })).await.unwrap();
|
||||
let ids: Vec<_> =
|
||||
errors["flows"].as_array().unwrap().iter().map(|f| f["id"].clone()).collect();
|
||||
assert_eq!(ids, vec![json!(failed.id)], "a non-zero status is a failed call");
|
||||
|
||||
// No schema, and reflection against the server fails: decoded by wire type alone.
|
||||
let decode = json!({ "flowId": flow.id, "seq": 1 });
|
||||
let schemaless = rpc(&ctx, "decode_grpc_message", decode.clone()).await.unwrap();
|
||||
assert_eq!(schemaless["messageType"], Value::Null);
|
||||
assert!(schemaless["note"].as_str().unwrap().contains("reflection failed"), "{schemaless}");
|
||||
let fields: Value = serde_json::from_str(schemaless["json"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(fields[0]["string"], "Hello Ada");
|
||||
assert_eq!(fields[1], json!({ "field": 2, "wireType": "varint", "value": 3 }));
|
||||
|
||||
// With the proto attached to the host, by name.
|
||||
let protos = tempfile::tempdir().unwrap();
|
||||
let added = rpc(
|
||||
&ctx,
|
||||
"add_grpc_schema",
|
||||
json!({ "hostPattern": "127.0.0.1", "protoPaths": [proto_file(protos.path())] }),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(added["services"], json!(["pkg.Greeter"]));
|
||||
assert_eq!(added["source"], "files");
|
||||
let decoded = rpc(&ctx, "decode_grpc_message", decode.clone()).await.unwrap();
|
||||
assert_eq!(decoded["messageType"], "pkg.HelloReply");
|
||||
let message: Value = serde_json::from_str(decoded["json"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(message, json!({ "message": "Hello Ada", "count": 3 }));
|
||||
let request = json!({ "flowId": flow.id, "seq": 0 });
|
||||
let decoded = rpc(&ctx, "decode_grpc_message", request).await.unwrap();
|
||||
assert_eq!(decoded["messageType"], "pkg.HelloRequest");
|
||||
let trailers = json!({ "flowId": flow.id, "seq": 2 });
|
||||
assert!(
|
||||
rpc(&ctx, "decode_grpc_message", trailers).await.is_err(),
|
||||
"trailers are no message"
|
||||
);
|
||||
|
||||
// The control API returns the same, and lists the messages.
|
||||
ctx.serve_control_api().unwrap();
|
||||
let info = ctx.control_info().unwrap();
|
||||
let api = reqwest::Client::new();
|
||||
let get = |path: String| {
|
||||
api.get(format!("{}{path}", info.base_url())).bearer_auth(&info.token).send()
|
||||
};
|
||||
let listed: Value = get(format!("/flows/{}/messages?after=0&limit=1", flow.id))
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(listed["total"].as_i64(), listed["messages"][0]["seq"].as_i64()),
|
||||
(Some(3), Some(1))
|
||||
);
|
||||
let detail: Value =
|
||||
get(format!("/flows/{}/messages/1", flow.id)).await.unwrap().json().await.unwrap();
|
||||
assert_eq!(detail["decoded"]["messageType"], "pkg.HelloReply");
|
||||
assert_eq!(detail["payload"]["encoding"], "utf8");
|
||||
let schemas: Value = get("/grpc-schemas".into()).await.unwrap().json().await.unwrap();
|
||||
assert_eq!(schemas.as_array().unwrap().len(), 1);
|
||||
|
||||
let removed = rpc(&ctx, "remove_grpc_schema", json!({ "id": added["id"] })).await.unwrap();
|
||||
assert_eq!(removed, true);
|
||||
let after = rpc(&ctx, "decode_grpc_message", decode).await.unwrap();
|
||||
assert_eq!(after["messageType"], Value::Null);
|
||||
|
||||
// Clearing removes the messages with their flows.
|
||||
rpc(&ctx, "clear_flows", json!({})).await.unwrap();
|
||||
assert!(rpc(&ctx, "list_messages", json!({ "flowId": flow.id })).await.is_err());
|
||||
let left: i64 = ctx.db.with_conn(|c| {
|
||||
c.conn()
|
||||
.resolve()
|
||||
.query_row("SELECT COUNT(*) FROM flow_messages", [], |r| r.get(0))
|
||||
.unwrap()
|
||||
});
|
||||
assert_eq!(left, 0);
|
||||
ctx.stop_control_api();
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn grpc_schemas_come_from_the_servers_reflection() {
|
||||
within(async {
|
||||
let protos = tempfile::tempdir().unwrap();
|
||||
let pool =
|
||||
yaak_grpc::fill_pool_from_files(&protoc(), &vec![proto_file(protos.path()).into()])
|
||||
.await
|
||||
.unwrap();
|
||||
let descriptors = pool.encode_to_vec();
|
||||
let reflection = tonic_reflection::server::Builder::configure()
|
||||
.register_encoded_file_descriptor_set(&descriptors)
|
||||
.build_v1()
|
||||
.unwrap();
|
||||
let upstream = spawn_upstream(Some(reflection_service(reflection))).await;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (ctx, _event_rx) = start(dir.path());
|
||||
// Plain HTTP, so reflection is asked without TLS, as the call was made.
|
||||
let url = format!("http://{upstream}/pkg.Greeter/SayHello");
|
||||
client(&ctx)
|
||||
.post(&url)
|
||||
.header("content-type", "application/grpc-web+proto")
|
||||
.body(grpc_frame(0, &proto("Cy", None)))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let flow = wait_for(&ctx, &url, |f| f.elapsed_ms.is_some()).await;
|
||||
|
||||
// Nothing attached: the server is asked once, and its answer kept for the host. Two
|
||||
// decodes at once both wait for that answer.
|
||||
let request = json!({ "flowId": flow.id, "seq": 1 });
|
||||
let (decoded, alongside) = tokio::join!(
|
||||
rpc(&ctx, "decode_grpc_message", request.clone()),
|
||||
rpc(&ctx, "decode_grpc_message", request)
|
||||
);
|
||||
let (decoded, alongside) = (decoded.unwrap(), alongside.unwrap());
|
||||
assert_eq!(decoded["messageType"], "pkg.HelloReply", "{decoded}");
|
||||
assert_eq!(alongside["messageType"], "pkg.HelloReply", "{alongside}");
|
||||
assert_eq!(decoded["schema"]["source"], "reflection");
|
||||
assert_eq!(decoded["schema"]["hostPattern"], format!("127.0.0.1:{}", upstream.port()));
|
||||
let schemas = rpc(&ctx, "list_grpc_schemas", json!({})).await.unwrap();
|
||||
assert_eq!(schemas.as_array().unwrap().len(), 1);
|
||||
|
||||
// Asked again on demand, it replaces the host's earlier answer.
|
||||
let host = format!("http://127.0.0.1:{}", upstream.port());
|
||||
let again = rpc(&ctx, "reflect_grpc_host", json!({ "host": host })).await.unwrap();
|
||||
assert_eq!(again["services"], json!(["pkg.Greeter"]));
|
||||
let schemas = rpc(&ctx, "list_grpc_schemas", json!({})).await.unwrap();
|
||||
assert_eq!(schemas.as_array().unwrap().len(), 1);
|
||||
})
|
||||
.await
|
||||
}
|
||||
Reference in new issue
Block a user