feat(traffic): filter stream messages by direction

GET /api/traffic/stream and the traffic_messages tool take an optional
direction (c2s or s2c) to list one side of a WebSocket or SSE
conversation. total and offset apply to the filtered list, seq stays the
position in the whole stream, and the meta limit marker is kept in a
filtered page so dropped messages are never hidden. Any other value is
rejected (400 / tool error).

Part of #379 (traffic inspection: filter by direction).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
unknown
2026-11-19 22:37:23 +01:00
co-authored by Claude Opus 5.5
parent 0255f6af2c
commit d22e9e0e58
6 changed files with 234 additions and 12 deletions
+1
View File
@@ -26,6 +26,7 @@ All notable changes to this project are documented in this file. The format is b
- **Capture-proxy rewrite rules, storage and API**: `GET`, `POST`, `PUT` and `DELETE /api/traffic/rewrite-rules` and `POST /api/traffic/rewrite-rules/{id}/toggle` manage rules that match a request or a response (method, host, URL, headers, body, status) and describe a rewrite (method, path and query, headers, body, status). Rules are validated on save, limited to 100 of which 50 enabled, created disabled, and stored in the new table `traffic_rewrite_rules` (migration `0005_traffic_rewrite_rules.sql`) with `matchers` and `actions` encrypted at rest. The value of an action marked `sensitive` is never returned, and an update sent without it keeps the stored one. The server compiles the enabled rules at startup and after every change and hands the snapshot to the proxy. The proxy applies them from the next entry. See `docs/traffic-rewrite-rules.md`.
- **Capture-proxy rewrite rules applied**: the capture proxy applies enabled rules to each HTTP request before it is sent to the target and to each response before it reaches the client. Each action that ran is recorded in the new table `exchange_rewrites` in the same transaction as the exchange, `traffic_get` shows a `REWRITTEN` line, and `traffic_search` never finds a value a rule wrote. SSE status and headers are rewritten at the start of the stream. **WebSocket handshakes are not rewritten**: the capture library runs its hook after the upgrade, so the status and headers cannot be changed, and frames pass unchanged. **Responses of 5 MiB or more** are forwarded unchanged and not recorded in full, because the library does not call the response hook for them. Snapshots of original requests are capped at 1024 entries and 64 MiB. Replays go through the proxy, so the rules apply to them. Archives, a per-replay rule toggle, the web UI and the proof flag come later.
- **Bulk finding status** (#298): select findings in the findings table and apply one disposition to all of them, up to 500 per call, in one transaction; each row still goes through the single-decision notification semantics and the change is mirrored onto its exploration node (#289).
- **Stream message direction filter** (#379): `GET /api/traffic/stream` and the `traffic_messages` agent tool take an optional `direction` (`c2s` or `s2c`) that lists only one side of a WebSocket or SSE conversation. `total` and `offset` apply to the filtered list, each row keeps its `seq` in the whole stream, and the `meta` row (messages dropped past the recorder limits) stays in a filtered page. Any other value is a 400 (API) or a tool error.
- **Traffic replay** (#266): replay a recorded request from the traffic detail with its method, URL, headers and stored body; replay is disabled when only the body preview is loaded.
- **Finding proof strength in reports** (#268): the Markdown report and the export show each finding's proof strength next to its verification status.
- **Opt-in Keenable web search backend** (#295): the search tool gains Keenable alongside Brave and Tavily; the key is stored encrypted and can be cleared independently.
+8 -2
View File
@@ -3676,7 +3676,8 @@ func (s *Server) getTrafficExchange(w http.ResponseWriter, r *http.Request) {
}
// getTrafficStream returns one page of a WebSocket/SSE exchange's messages in
// order (limit 1..200, default 50).
// order (limit 1..200, default 50). direction=c2s or s2c keeps one side of the
// conversation (plus the meta limit marker); any other non-empty value is a 400.
func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) {
tr := s.m.Traffic()
if tr == nil {
@@ -3691,7 +3692,12 @@ func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) {
}
offset, _ := strconv.Atoi(q.Get("offset"))
limit, _ := strconv.Atoi(q.Get("limit"))
msgs, total, err := tr.StreamMessages(id, offset, limit)
direction := strings.ToLower(strings.TrimSpace(q.Get("direction")))
msgs, total, err := tr.StreamMessagesByDirection(id, direction, offset, limit)
if errors.Is(err, traffic.ErrBadStreamDirection) {
writeErr(w, 400, err.Error())
return
}
if err != nil {
writeErr(w, 500, err.Error())
return
+63
View File
@@ -2,6 +2,7 @@ package server
import (
"encoding/json"
"fmt"
"testing"
)
@@ -87,3 +88,65 @@ VALUES('1-0001',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'we
t.Fatalf("exchange = %d %s", w.Code, w.Body)
}
}
func TestTrafficStreamRouteDirection(t *testing.T) {
s, request := ingestServer(t)
db := s.m.Traffic().DB()
if _, err := db.Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
VALUES('1-0002',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'websocket',0,0,'')`); err != nil {
t.Fatal(err)
}
// seq 1 c2s, 2 s2c, 3 c2s, 4 s2c, 5 meta.
for i, dir := range []string{"c2s", "s2c", "c2s", "s2c", "meta"} {
kind := 1
if dir == "meta" {
kind = 0
}
if _, err := db.Exec(`INSERT INTO stream_messages(exchange_id,seq,ts,direction,kind,size,payload) VALUES('1-0002',?,1,?,?,1,'x')`, i+1, dir, kind); err != nil {
t.Fatal(err)
}
}
type page struct {
Items []struct {
Seq int64 `json:"seq"`
Direction string `json:"direction"`
} `json:"items"`
Total int `json:"total"`
}
get := func(query string) page {
t.Helper()
w := request("GET", "/api/traffic/stream?exchange=1-0002"+query, "")
if w.Code != 200 {
t.Fatalf("GET %s = %d %s", query, w.Code, w.Body)
}
var p page
if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil {
t.Fatal(err)
}
return p
}
seqs := func(p page) []int64 {
out := []int64{}
for _, it := range p.Items {
out = append(out, it.Seq)
}
return out
}
if p := get(""); p.Total != 5 || len(p.Items) != 5 {
t.Fatalf("unfiltered = %+v", p)
}
if p := get("&direction=c2s"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[1 3 5]" {
t.Fatalf("c2s = total %d seqs %v, want 3 and [1 3 5]", p.Total, seqs(p))
}
if p := get("&direction=S2C"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[2 4 5]" {
t.Fatalf("S2C = total %d seqs %v, want 3 and [2 4 5]", p.Total, seqs(p))
}
if p := get("&direction=s2c&offset=1&limit=1"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[4]" {
t.Fatalf("s2c offset=1 limit=1 = total %d seqs %v, want 3 and [4]", p.Total, seqs(p))
}
if w := request("GET", "/api/traffic/stream?exchange=1-0002&direction=meta", ""); w.Code != 400 {
t.Fatalf("direction=meta = %d %s, want 400", w.Code, w.Body)
}
}
+34 -2
View File
@@ -528,6 +528,37 @@ type StreamMessage struct {
// most streamPreview (4 KiB); a longer one lives in the blob store and the row
// carries its hash for the rest (traffic_blob, GET /api/traffic/blob).
func (t *Traffic) StreamMessages(exchangeID string, offset, limit int) ([]StreamMessage, int, error) {
return t.StreamMessagesByDirection(exchangeID, "", offset, limit)
}
// ErrBadStreamDirection is returned by StreamMessagesByDirection for a
// direction other than "", "c2s" or "s2c".
var ErrBadStreamDirection = errors.New(`direction must be "c2s", "s2c" or empty`)
// streamDirectionFilter returns the SQL condition (after exchange_id=?) and its
// argument for a direction filter. A filtered page keeps the 'meta' limit
// marker, so a reader never misses that messages were dropped.
func streamDirectionFilter(direction string) (cond string, args []any, err error) {
switch direction {
case "":
return "", nil, nil
case "c2s", "s2c":
return ` AND direction IN (?, 'meta')`, []any{direction}, nil
default:
return "", nil, ErrBadStreamDirection
}
}
// StreamMessagesByDirection is StreamMessages restricted to one direction:
// "c2s" (client to server), "s2c" (server to client), or "" for both. total
// counts only the matching rows, so offset pages through the filtered list.
// The 'meta' row (messages dropped past the recorder's limits) is kept in a
// filtered page. Seq stays the message's position in the whole stream.
func (t *Traffic) StreamMessagesByDirection(exchangeID, direction string, offset, limit int) ([]StreamMessage, int, error) {
cond, dirArgs, err := streamDirectionFilter(direction)
if err != nil {
return nil, 0, err
}
if limit <= 0 {
limit = 50
}
@@ -538,11 +569,12 @@ func (t *Traffic) StreamMessages(exchangeID string, offset, limit int) ([]Stream
offset = 0
}
var total int
if err := t.db.QueryRow(`SELECT COUNT(*) FROM stream_messages WHERE exchange_id=?`, exchangeID).Scan(&total); err != nil {
args := append([]any{exchangeID}, dirArgs...)
if err := t.db.QueryRow(`SELECT COUNT(*) FROM stream_messages WHERE exchange_id=?`+cond, args...).Scan(&total); err != nil {
return nil, 0, err
}
rows, err := t.db.Query(`SELECT seq,ts,direction,kind,event,event_id,retry,size,payload,payload_blob,truncated
FROM stream_messages WHERE exchange_id=? ORDER BY seq LIMIT ? OFFSET ?`, exchangeID, limit, offset)
FROM stream_messages WHERE exchange_id=?`+cond+` ORDER BY seq LIMIT ? OFFSET ?`, append(args, limit, offset)...)
if err != nil {
return nil, 0, err
}
+114
View File
@@ -0,0 +1,114 @@
package traffic
import (
"errors"
"strings"
"testing"
"github.com/gorilla/websocket"
)
// directionStream records c2s "q0","q1",... and s2c "a0","a1",... interleaved
// (q0 a0 q1 a1 ...) on one WebSocket exchange and returns its id.
func directionStream(t *testing.T, pairs int) (*Traffic, string) {
t.Helper()
tr, s, f := unitStream(t, "direction.test")
for i := 0; i < pairs; i++ {
addWS(f, true, websocket.TextMessage, []byte("q"+string(rune('0'+i))))
addWS(f, false, websocket.TextMessage, []byte("a"+string(rune('0'+i))))
}
s.WebSocketMessage(f)
s.WebSocketEnd(f)
return tr, onlyExchange(t, tr)
}
func TestStreamMessagesByDirection(t *testing.T) {
tr, id := directionStream(t, 3)
all, total, err := tr.StreamMessagesByDirection(id, "", 0, 50)
if err != nil || total != 6 || len(all) != 6 {
t.Fatalf("unfiltered: %d of %d, err %v; want 6 of 6", len(all), total, err)
}
for _, tc := range []struct {
dir string
payloads []string
seqs []int64
}{
{"c2s", []string{"q0", "q1", "q2"}, []int64{1, 3, 5}},
{"s2c", []string{"a0", "a1", "a2"}, []int64{2, 4, 6}},
} {
msgs, total, err := tr.StreamMessagesByDirection(id, tc.dir, 0, 50)
if err != nil || total != 3 || len(msgs) != 3 {
t.Fatalf("%s: %d of %d, err %v; want 3 of 3", tc.dir, len(msgs), total, err)
}
for i, m := range msgs {
// Seq stays the position in the whole stream, so a filtered row
// can be matched against the unfiltered conversation.
if m.Direction != tc.dir || m.Payload != tc.payloads[i] || m.Seq != tc.seqs[i] {
t.Fatalf("%s message %d = %+v, want payload %q seq %d", tc.dir, i, m, tc.payloads[i], tc.seqs[i])
}
}
// offset and total apply to the filtered list.
page, total, err := tr.StreamMessagesByDirection(id, tc.dir, 1, 1)
if err != nil || total != 3 || len(page) != 1 || page[0].Payload != tc.payloads[1] {
t.Fatalf("%s offset=1 limit=1: %+v total %d err %v; want %q", tc.dir, page, total, err, tc.payloads[1])
}
}
// StreamMessages is the unfiltered form.
if msgs, total, err := tr.StreamMessages(id, 0, 50); err != nil || total != 6 || len(msgs) != 6 {
t.Fatalf("StreamMessages: %d of %d, err %v", len(msgs), total, err)
}
}
func TestStreamMessagesByDirectionRejectsUnknown(t *testing.T) {
tr, id := directionStream(t, 1)
for _, dir := range []string{"meta", "both", "C2S", "c2s' OR 1=1 --"} {
if _, _, err := tr.StreamMessagesByDirection(id, dir, 0, 50); !errors.Is(err, ErrBadStreamDirection) {
t.Fatalf("direction %q: err %v, want ErrBadStreamDirection", dir, err)
}
}
}
// A filtered page keeps the meta row, so dropped messages are never hidden.
func TestStreamMessagesByDirectionKeepsMetaRow(t *testing.T) {
tr, s, f := unitStream(t, "direction-meta.test")
for i := 0; i < maxStreamMessages+4; i++ {
addWS(f, i%2 == 0, websocket.TextMessage, []byte("m"))
}
s.WebSocketMessage(f)
s.WebSocketEnd(f)
id := onlyExchange(t, tr)
_, total, err := tr.StreamMessagesByDirection(id, "s2c", 0, 1)
if err != nil || total != maxStreamMessages/2+1 {
t.Fatalf("s2c total %d err %v, want %d messages and the meta row", total, err, maxStreamMessages/2+1)
}
last, _, err := tr.StreamMessagesByDirection(id, "s2c", total-1, 1)
if err != nil || len(last) != 1 || last[0].Type != "meta" {
t.Fatalf("last s2c row %+v err %v, want the meta row", last, err)
}
}
func TestTrafficMessagesToolDirection(t *testing.T) {
tr, id := directionStream(t, 2)
out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":"s2c"}`)
if !strings.HasPrefix(out, "[messages 1-2 of 2]") || !strings.Contains(out, `"a0"`) || !strings.Contains(out, `"a1"`) || strings.Contains(out, `"q0"`) {
t.Fatalf("s2c output:\n%s", out)
}
out = toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":" C2S "}`)
if !strings.HasPrefix(out, "[messages 1-2 of 2]") || !strings.Contains(out, `"q1"`) || strings.Contains(out, `"a1"`) {
t.Fatalf("c2s output (case and spaces normalized):\n%s", out)
}
if out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`"}`); !strings.HasPrefix(out, "[messages 1-4 of 4]") {
t.Fatalf("no direction output:\n%s", out)
}
if out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":"sideways"}`); !strings.Contains(out, "direction must be") {
t.Fatalf("bad direction output:\n%s", out)
}
if out := toolText(t, tr, "traffic_messages", `{"id":"nope","direction":"c2s"}`); !strings.Contains(out, "No c2s stream messages") {
t.Fatalf("empty filtered output:\n%s", out)
}
}
+14 -8
View File
@@ -2353,13 +2353,14 @@ func (t *Traffic) Tools() []actool.CoreTool {
messages := actool.Build(actool.Spec{
Name: "traffic_messages",
Description: "List the messages of one captured WebSocket or SSE (Server-Sent Events) record in order: direction (c2s client→server, s2c server→client), type (text/binary/event, or meta when the recorder dropped messages past its limits), size and a preview of at most 1KB (binary as hex). A payload stored as a blob carries its hash; read the rest with traffic_blob. Returns 20 messages by default, at most 50; use offset to page.",
Description: "List the messages of one captured WebSocket or SSE (Server-Sent Events) record in order: direction (c2s client→server, s2c server→client), type (text/binary/event, or meta when the recorder dropped messages past its limits), size and a preview of at most 1KB (binary as hex). A payload stored as a blob carries its hash; read the rest with traffic_blob. Set direction to c2s or s2c to list only one side of the conversation (the meta row is kept). Returns 20 messages by default, at most 50; use offset to page.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"id": map[string]any{"type": "string", "description": "the record id from traffic_search (a WebSocket status-101 or SSE record)"},
"offset": map[string]any{"type": "integer", "description": "number of messages to skip, default 0"},
"limit": map[string]any{"type": "integer", "description": "messages to return, default 20, max 50"},
"id": map[string]any{"type": "string", "description": "the record id from traffic_search (a WebSocket status-101 or SSE record)"},
"direction": map[string]any{"type": "string", "enum": []any{"c2s", "s2c"}, "description": "only messages in this direction: c2s (client→server) or s2c (server→client); omit for both"},
"offset": map[string]any{"type": "integer", "description": "number of messages to skip within the (filtered) list, default 0"},
"limit": map[string]any{"type": "integer", "description": "messages to return, default 20, max 50"},
},
"required": []any{"id"},
},
@@ -2367,9 +2368,10 @@ func (t *Traffic) Tools() []actool.CoreTool {
Permissions: allow,
Run: func(_ context.Context, in json.RawMessage, _ *actool.ToolContext) (actool.Result, error) {
var a struct {
ID string
Offset int
Limit int
ID string
Direction string
Offset int
Limit int
}
_ = json.Unmarshal(in, &a)
if strings.TrimSpace(a.ID) == "" {
@@ -2384,11 +2386,15 @@ func (t *Traffic) Tools() []actool.CoreTool {
if a.Offset < 0 {
a.Offset = 0
}
msgs, total, err := t.StreamMessages(a.ID, a.Offset, a.Limit)
a.Direction = strings.ToLower(strings.TrimSpace(a.Direction))
msgs, total, err := t.StreamMessagesByDirection(a.ID, a.Direction, a.Offset, a.Limit)
if err != nil {
return actool.Errorf(err.Error()), nil
}
if total == 0 {
if a.Direction != "" {
return actool.Text(fmt.Sprintf("No %s stream messages recorded for this id (not a WebSocket/SSE record, or no message was sent in that direction).", a.Direction)), nil
}
return actool.Text("No stream messages recorded for this id (not a WebSocket/SSE record, or no message was exchanged)."), nil
}
type liteMsg struct {