High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: a cut PostData carries no truncated signal, so a clipped request… (PIN-114)
Luigi Agostiec717a7a9df3
diff --git a/docs/endpoints.md b/docs/endpoints.mdindex 0c3ed0d5..62107a42 100644--- a/docs/endpoints.md+++ b/docs/endpoints.md@@ -620,8 +620,9 @@ Response body behavior for network detail/export:Request body (`postData`) behavior:- `postData` holds the request body as the page sent it, decoded. Chrome delivers it base64-encoded and split into chunks; PinchTab decodes and joins it, so no base64 decoding is needed by the caller-- it is capped at 64 KiB of decoded body, cut on a character boundary-- it is omitted when the body is not text — a binary part in a multipart upload, for example — because the field carries no encoding marker+- it is capped at 64 KiB of decoded body, cut on a character boundary, and a cut body is marked `postDataTruncated=true` — without it a clipped request body reads as the body the client sent+- it is omitted when the body is not text — a binary part in a multipart upload, for example — because the field carries no encoding marker. An omitted body says why: `postDataSkipped=true` with `postDataSkipReason` ("request body entry is not base64", "request body is not valid UTF-8"), so an absent `postData` is never mistaken for a request sent without one+- `postDataTruncated` and `postDataSkipped` are different answers and never both set: truncated means cut but usable, skipped means there is no body to read. A request that simply had no body carries neither flag- HAR export puts the same decoded value in `request.postData.text`, and omits the block entirely when there is no publishable bodyNetwork export query parameters:diff --git a/internal/bridge/network_test.go b/internal/bridge/network_test.goindex c0c08c54..6c4f3653 100644--- a/internal/bridge/network_test.go+++ b/internal/bridge/network_test.go@@ -98,6 +98,12 @@ func TestNetworkBuffer_TruncatesOversizedFields(t *testing.T) {if len(entry.PostData) > testMaxNetworkPostDataBytes {t.Fatalf("PostData length = %d, want <= %d", len(entry.PostData), testMaxNetworkPostDataBytes)}+ if !entry.PostDataTruncated {+ t.Error("a request body cut by the buffer reports no truncation, so a reader of the entry sees a clipped body as complete")+ }+ if entry.PostDataSkipped {+ t.Errorf("a cut body must not also report skipped: %q", entry.PostDataSkipReason)+ }totalHeaderBytes := 0for key, value := range entry.RequestHeaders {totalHeaderBytes += len(key) + len(value)diff --git a/internal/bridge/observe/network.go b/internal/bridge/observe/network.goindex ab39d9e9..483e31d3 100644--- a/internal/bridge/observe/network.go+++ b/internal/bridge/observe/network.go@@ -132,25 +132,7 @@ func (nm *NetworkMonitor) StartCaptureWithSize(tabCtx context.Context, tabID strchromedp.ListenTarget(listenerCtx, func(ev interface{}) {switch e := ev.(type) {case *network.EventRequestWillBeSent:- headers := make(map[string]string)- if e.Request.Headers != nil {- for k, v := range e.Request.Headers {- if s, ok := v.(string); ok {- headers[k] = s- }- }- }- postData := decodePostData(e.Request.PostDataEntries)- entry := NetworkEntry{- RequestID: string(e.RequestID),- URL: e.Request.URL,- Method: e.Request.Method,- ResourceType: e.Type.String(),- RequestHeaders: headers,- PostData: postData,- StartTime: time.Now(),- }- buf.Add(entry)+ buf.Add(requestEntryFromEvent(e))buf.MarkRequestStart(string(e.RequestID))case *network.EventResponseReceived:@@ -292,14 +274,15 @@ func skipRetainedBody(buf *NetworkBuffer, requestID, reason string) {const (retentionLimitScope = "retention limit"retentionBudgetScope = "retention budget"+ postDataLimitScope = "request body limit")-// clampRetainedBody applies a byte budget to a retained response body. One rule:-// a retained body is a byte-exact prefix of the response, or there is no retained-// body. Text is cut on a rune boundary with the suffix-free helper — the display+// clampRetainedBody applies a byte budget to a retained payload — a response body,+// or the request body in PostData. One rule: a retained payload is a byte-exact+// prefix of what crossed the wire, or there is no retained payload. Text is cut on a rune boundary with the suffix-free helper — the display// variant appends "..." inside the budget, and a machine-read body must not carry-// characters the response never contained when bodyTruncated already says it was-// cut. A base64 body cannot be cut at all (the encoding's length and padding make+// characters the payload never contained when the truncated flag already says it+// was cut. A base64 body cannot be cut at all (the encoding's length and padding make// a fragment undecodable in whole, not only at the tail), and a budget smaller// than the body's first character leaves no whole rune to keep; both are dropped// with a reason rather than returned corrupt or returned empty-but-retained.@@ -437,11 +420,12 @@ func GetResponseBody(ctx context.Context, requestID string) (string, bool, error// in a field named after the request body, and base64(a)+base64(b) is not base64(a+b) once an// entry's length is not a multiple of three, so any multi-entry body arrives corrupt.//-// Anything that cannot be published as the text it claims to be publishes nothing: an entry-// that is not base64, or a body that is not valid UTF-8 once decoded, such as a file part in-// a multipart POST. The alternative is mojibake or a blob in a field with no encoding signal.-// The reason for the absence has nowhere to ride yet — the signal is PIN-114's.-func decodePostData(entries []*network.PostDataEntry) string {+// Anything that cannot be published as the text it claims to be publishes nothing, and says+// why: an entry that is not base64, or a body that is not valid UTF-8 once decoded, such as a+// file part in a multipart POST. The alternative is mojibake, or a blob in a field with no+// encoding signal, or — worse — an empty string that reads as a request sent with no body.+// The second return is that reason, empty when there is nothing to explain.+func decodePostData(entries []*network.PostDataEntry) (string, string) {var decoded []bytefor _, entry := range entries {if entry == nil {@@ -449,14 +433,40 @@ func decodePostData(entries []*network.PostDataEntry) string {}chunk, err := base64.StdEncoding.DecodeString(entry.Bytes)if err != nil {- return ""+ return "", "request body entry is not base64"}decoded = append(decoded, chunk...)}if !utf8.Valid(decoded) {- return ""+ return "", "request body is not valid UTF-8"+ }+ return string(decoded), ""+}++// requestEntryFromEvent builds the entry a started request is recorded as. It is the one+// place a refused request body turns into a stated reason on the entry, so an absent+// postData is never mistaken for a request sent without one.+func requestEntryFromEvent(e *network.EventRequestWillBeSent) NetworkEntry {+ headers := make(map[string]string)+ if e.Request.Headers != nil {+ for k, v := range e.Request.Headers {+ if s, ok := v.(string); ok {+ headers[k] = s+ }+ }+ }+ postData, postDataSkipReason := decodePostData(e.Request.PostDataEntries)+ return NetworkEntry{+ RequestID: string(e.RequestID),+ URL: e.Request.URL,+ Method: e.Request.Method,+ ResourceType: e.Type.String(),+ RequestHeaders: headers,+ PostData: postData,+ PostDataSkipped: postDataSkipReason != "",+ PostDataSkipReason: postDataSkipReason,+ StartTime: time.Now(),}- return string(decoded)}func normalizeNetworkEntry(entry NetworkEntry) NetworkEntry {@@ -466,9 +476,21 @@ func normalizeNetworkEntry(entry NetworkEntry) NetworkEntry {entry.StatusText = sanitize.TruncateUTF8Bytes(entry.StatusText, maxNetworkStatusTextBytes)entry.MimeType = sanitize.TruncateUTF8Bytes(entry.MimeType, maxNetworkMimeTypeBytes)entry.Error = sanitize.TruncateUTF8Bytes(entry.Error, maxNetworkErrorBytes)- // The budget measures the decoded body, which is what PostData now holds, so the- // constant describes the request content rather than its encoded length.- entry.PostData = sanitize.PrefixUTF8Bytes(entry.PostData, maxNetworkPostDataBytes)+ // The request body is clamped by the one owner of that rule, so it inherits the+ // prefix-or-nothing policy the response body already states. The budget measures the+ // decoded body, which is what PostData holds, so the constant describes the request+ // content rather than its encoded length. Flags are only ever set here, never cleared:+ // an entry is re-normalised on every update, and a second pass sees a value already+ // within budget.+ clampedPostData, postDataTruncated, postDataDropReason := clampRetainedBody(entry.PostData, false, maxNetworkPostDataBytes, postDataLimitScope)+ entry.PostData = clampedPostData+ if postDataTruncated {+ entry.PostDataTruncated = true+ }+ if postDataDropReason != "" {+ entry.PostDataSkipped = true+ entry.PostDataSkipReason = postDataDropReason+ }entry.RequestHeaders = normalizeNetworkHeaders(entry.RequestHeaders)entry.ResponseHeaders = normalizeNetworkHeaders(entry.ResponseHeaders)return entrydiff --git a/internal/bridge/observe/network_body_clamp_test.go b/internal/bridge/observe/network_body_clamp_test.goindex cc44b09d..1621be5f 100644--- a/internal/bridge/observe/network_body_clamp_test.go+++ b/internal/bridge/observe/network_body_clamp_test.go@@ -267,8 +267,11 @@ func TestBodyClampsAndDisplayFieldsUseTheirOwnHelper(t *testing.T) {if strings.Contains(clamp, "sanitize.TruncateUTF8Bytes(") {t.Error("clampRetainedBody reaches the ellipsis variant again: the retained body would carry characters the response never sent")}- if !strings.Contains(src, "entry.PostData = sanitize.PrefixUTF8Bytes(") {- t.Error("PostData no longer cuts with the suffix-free helper")+ if !strings.Contains(src, "clampRetainedBody(entry.PostData,") {+ t.Error("PostData no longer goes through clampRetainedBody: a second clamp beside it drifts, and PostData loses the drop-with-reason cases the response body already handles")+ }+ if strings.Contains(src, "entry.PostData = sanitize.") {+ t.Error("PostData cuts with a sanitize helper directly again, bypassing the one payload clamp")}displayFields := []string{"entry.URL", "entry.Method", "entry.ResourceType", "entry.StatusText", "entry.MimeType", "entry.Error"}@@ -287,7 +290,7 @@ func TestBodyClampsAndDisplayFieldsUseTheirOwnHelper(t *testing.T) {// The checks above ask whether each site this test KNOWS about picked the right// helper, which cannot see a site it does not know about — and an unlisted field// taking the ellipsis by default is how the defect this file exists for arrived.- accounted := len(displayFields) + len(headerClamps) + 2 // the two body clamps: the retained body and PostData+ accounted := len(displayFields) + len(headerClamps) + 1 // the one payload clamp, which both the retained body and PostData go throughif sites := strings.Count(src, "sanitize.TruncateUTF8Bytes(") + strings.Count(src, "sanitize.PrefixUTF8Bytes("); sites != accounted {t.Errorf("network.go cuts a field at %d sites but this test classifies %d — a new field is picking a truncation policy nobody reviewed. Add it above: the ellipsis variant if a human reads it, the suffix-free one if it is machine-read and a marker would be fabricated content",sites, accounted)diff --git a/internal/bridge/observe/network_buffer.go b/internal/bridge/observe/network_buffer.goindex 23886bde..c47deb05 100644--- a/internal/bridge/observe/network_buffer.go+++ b/internal/bridge/observe/network_buffer.go@@ -37,6 +37,10 @@ type NetworkEntry struct {BodySkipReason string `json:"bodySkipReason,omitempty"`BodyTruncated bool `json:"bodyTruncated,omitempty"`BodyError string `json:"bodyError,omitempty"`++ PostDataTruncated bool `json:"postDataTruncated,omitempty"`+ PostDataSkipped bool `json:"postDataSkipped,omitempty"`+ PostDataSkipReason string `json:"postDataSkipReason,omitempty"`}type NetworkBuffer struct {diff --git a/internal/bridge/observe/network_postdata_test.go b/internal/bridge/observe/network_postdata_test.goindex ed04d101..9fd5690f 100644--- a/internal/bridge/observe/network_postdata_test.go+++ b/internal/bridge/observe/network_postdata_test.go@@ -9,6 +9,14 @@ import ("github.com/chromedp/cdproto/network")+// harPostData keeps the HAR fixtures reading the decoded value the entry would carry,+// without the reason those tests do not assert.+func harPostData(t *testing.T, entries []*network.PostDataEntry) string {+ t.Helper()+ decoded, _ := decodePostData(entries)+ return decoded+}+func postDataEntries(chunks ...string) []*network.PostDataEntry {entries := make([]*network.PostDataEntry, 0, len(chunks))for _, chunk := range chunks {@@ -23,7 +31,7 @@ func postDataEntries(chunks ...string) []*network.PostDataEntry {func TestPostDataIsTheBodyThePageSentNotBase64(t *testing.T) {const body = `{"hi":"there — 🎯"}`- got := decodePostData(postDataEntries(body))+ got, _ := decodePostData(postDataEntries(body))if got != body {t.Errorf("postData = %q, want the body byte for byte", got)@@ -47,7 +55,7 @@ func TestPostDataJoinsMultipleEntriesOnDecodedBytes(t *testing.T) {t.Run(tc.name, func(t *testing.T) {want := tc.first + tc.second- got := decodePostData(postDataEntries(tc.first, tc.second))+ got, _ := decodePostData(postDataEntries(tc.first, tc.second))if got != want {t.Errorf("postData = %q, want %q — the entries were joined before decoding", got, want)@@ -68,32 +76,40 @@ func TestPostDataJoinsMultipleEntriesOnDecodedBytes(t *testing.T) {// signal that says why it is absent.func TestPostDataPublishesNothingRatherThanSomethingItCannotDescribe(t *testing.T) {for _, tc := range []struct {- name string- entries []*network.PostDataEntry+ name string+ entries []*network.PostDataEntry+ wantReason string}{{- name: "not base64 at all",- entries: []*network.PostDataEntry{{Bytes: "not base64!!"}},+ name: "not base64 at all",+ entries: []*network.PostDataEntry{{Bytes: "not base64!!"}},+ wantReason: "request body entry is not base64",},{- name: "one bad entry among good ones",- entries: append(postDataEntries("good"), &network.PostDataEntry{Bytes: "@@@"}),+ name: "one bad entry among good ones",+ entries: append(postDataEntries("good"), &network.PostDataEntry{Bytes: "@@@"}),+ wantReason: "request body entry is not base64",},{- name: "decodes to bytes that are not valid UTF-8",- entries: []*network.PostDataEntry{{Bytes: base64.StdEncoding.EncodeToString([]byte{0xff, 0xfe, 0x00, 0x80})}},+ name: "decodes to bytes that are not valid UTF-8",+ entries: []*network.PostDataEntry{{Bytes: base64.StdEncoding.EncodeToString([]byte{0xff, 0xfe, 0x00, 0x80})}},+ wantReason: "request body is not valid UTF-8",},{- name: "valid UTF-8 chunks that are invalid once joined",- entries: []*network.PostDataEntry{{Bytes: base64.StdEncoding.EncodeToString([]byte("é")[:1])}},+ name: "valid UTF-8 chunks that are invalid once joined",+ entries: []*network.PostDataEntry{{Bytes: base64.StdEncoding.EncodeToString([]byte("é")[:1])}},+ wantReason: "request body is not valid UTF-8",},} {t.Run(tc.name, func(t *testing.T) {- got := decodePostData(tc.entries)+ got, reason := decodePostData(tc.entries)if got != "" {t.Errorf("postData = %q, want it absent: the field carries no encoding signal, so this is either mojibake or a blob claiming to be text", got)}+ if reason != tc.wantReason {+ t.Errorf("skip reason = %q, want %q: an absent body with no reason reads as a request sent without one", reason, tc.wantReason)+ }})}}@@ -109,9 +125,13 @@ func TestPostDataIsAbsentWhenTheRequestHasNoBody(t *testing.T) {{name: "empty entry", entries: postDataEntries("")},} {t.Run(tc.name, func(t *testing.T) {- if got := decodePostData(tc.entries); got != "" {+ got, reason := decodePostData(tc.entries)+ if got != "" {t.Errorf("postData = %q, want empty", got)}+ if reason != "" {+ t.Errorf("skip reason = %q, want none: a request with no body was not refused", reason)+ }})}}@@ -131,7 +151,8 @@ func TestPostDataCapMeasuresTheDecodedBodyAndCutsOnARuneBoundary(t *testing.T) {t.Fatal("fixture must straddle the limit with a multi-byte rune")}- entry := normalizeNetworkEntry(NetworkEntry{PostData: decodePostData(postDataEntries(body))})+ decoded, _ := decodePostData(postDataEntries(body))+ entry := normalizeNetworkEntry(NetworkEntry{PostData: decoded})if len(entry.PostData) > maxNetworkPostDataBytes {t.Errorf("postData is %d bytes, over the %d-byte cap on the decoded body", len(entry.PostData), maxNetworkPostDataBytes)@@ -156,7 +177,7 @@ func TestHARPostDataTextHoldsTheDecodedBody(t *testing.T) {entry := NetworkEntry{URL: "https://example.test/sink",Method: "POST",- PostData: decodePostData(postDataEntries(body)),+ PostData: harPostData(t, postDataEntries(body)),RequestHeaders: map[string]string{"Content-Type": "application/json"},}@@ -179,7 +200,7 @@ func TestHAROmitsPostDataWhenTheBodyCouldNotBePublished(t *testing.T) {entry := NetworkEntry{URL: "https://example.test/upload",Method: "POST",- PostData: decodePostData([]*network.PostDataEntry{{Bytes: base64.StdEncoding.EncodeToString([]byte{0xff, 0xfe})}}),+ PostData: harPostData(t, []*network.PostDataEntry{{Bytes: base64.StdEncoding.EncodeToString([]byte{0xff, 0xfe})}}),}if e := NetworkEntryToExport(entry, "", false); e.Request.PostData != nil {@@ -196,7 +217,138 @@ func TestPostDataUnderTheDecodedCapIsNotCut(t *testing.T) {t.Fatalf("fixture encodes to %d bytes, which is under the cap too — it cannot tell the two measurements apart", len(encoded))}- if got := normalizeNetworkEntry(NetworkEntry{PostData: decodePostData(postDataEntries(body))}).PostData; got != body {+ decodedUnderCap, _ := decodePostData(postDataEntries(body))+ if got := normalizeNetworkEntry(NetworkEntry{PostData: decodedUnderCap}).PostData; got != body {t.Errorf("postData is %d bytes, want the whole %d-byte body: the cap is measuring the encoded length", len(got), len(body))}}++// A cut request body that carries no signal is indistinguishable from the body the client+// actually sent — the whole point of the flag. Truncated (cut but usable) and skipped+// (absent, with a reason) are different answers and must never both be set.+func TestPostDataOverTheCapIsFlaggedTruncatedNotSkipped(t *testing.T) {+ body := strings.Repeat("a", maxNetworkPostDataBytes) + "tail"++ decoded, _ := decodePostData(postDataEntries(body))+ entry := normalizeNetworkEntry(NetworkEntry{PostData: decoded})++ if !entry.PostDataTruncated {+ t.Error("a request body cut at the cap reports no truncation, so a clipped payload reads as complete")+ }+ if entry.PostDataSkipped || entry.PostDataSkipReason != "" {+ t.Errorf("a cut body must not also report skipped: skipped=%v reason=%q", entry.PostDataSkipped, entry.PostDataSkipReason)+ }+ if entry.PostData != body[:len(entry.PostData)] {+ t.Error("postData is not a byte-exact prefix of the body the page sent")+ }+}++func TestPostDataUnderTheCapCarriesNoSignal(t *testing.T) {+ const body = `{"hi":"there — 🎯"}`++ decoded, _ := decodePostData(postDataEntries(body))+ entry := normalizeNetworkEntry(NetworkEntry{PostData: decoded})++ if entry.PostData != body {+ t.Fatalf("postData = %q, want the whole body", entry.PostData)+ }+ if entry.PostDataTruncated || entry.PostDataSkipped || entry.PostDataSkipReason != "" {+ t.Errorf("an untouched body carries a signal: %+v", entry)+ }+}++// Entries are re-normalised on every update, and the second pass sees a value already+// within budget. The flag has to survive that or the signal disappears the moment the+// response arrives.+func TestPostDataTruncationSurvivesRenormalisation(t *testing.T) {+ body := strings.Repeat("a", maxNetworkPostDataBytes) + "tail"++ decoded, _ := decodePostData(postDataEntries(body))+ once := normalizeNetworkEntry(NetworkEntry{PostData: decoded})+ twice := normalizeNetworkEntry(once)++ if !twice.PostDataTruncated {+ t.Error("the truncated flag was cleared by a second normalise, so an entry updated after its response reads as complete")+ }+ if twice.PostData != once.PostData {+ t.Errorf("second normalise changed the body: %d bytes then %d", len(once.PostData), len(twice.PostData))+ }+}++// The refusal reason has to reach the ENTRY, not just decodePostData's return: this is the+// wiring an absent postData depends on to say why it is absent.+func TestRequestEntryCarriesTheRefusalReasonForAnUnpublishableBody(t *testing.T) {+ for _, tc := range []struct {+ name string+ entries []*network.PostDataEntry+ wantReason string+ }{+ {+ name: "binary file part",+ entries: []*network.PostDataEntry{{Bytes: base64.StdEncoding.EncodeToString([]byte{0xff, 0xfe, 0x00, 0x80})}},+ wantReason: "request body is not valid UTF-8",+ },+ {+ name: "entry that is not base64",+ entries: []*network.PostDataEntry{{Bytes: "not base64!!"}},+ wantReason: "request body entry is not base64",+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ entry := requestEntryFromEvent(&network.EventRequestWillBeSent{+ RequestID: "req-1",+ Type: network.ResourceTypeXHR,+ Request: &network.Request{URL: "https://example.test/upload", Method: "POST", PostDataEntries: tc.entries},+ })++ if entry.PostData != "" {+ t.Fatalf("postData = %q, want it absent", entry.PostData)+ }+ if !entry.PostDataSkipped {+ t.Error("an absent body reports no skip, so it reads as a request sent with no body at all")+ }+ if entry.PostDataSkipReason != tc.wantReason {+ t.Errorf("skip reason = %q, want %q", entry.PostDataSkipReason, tc.wantReason)+ }+ if entry.PostDataTruncated {+ t.Error("a body that was never published cannot also be truncated")+ }+ })+ }+}++func TestRequestEntryFlagsNothingForAnOrdinaryBody(t *testing.T) {+ const body = `{"ok":true}`++ entry := requestEntryFromEvent(&network.EventRequestWillBeSent{+ RequestID: "req-2",+ Type: network.ResourceTypeXHR,+ Request: &network.Request{URL: "https://example.test/api", Method: "POST", PostDataEntries: postDataEntries(body)},+ })++ if entry.PostData != body {+ t.Fatalf("postData = %q, want %q", entry.PostData, body)+ }+ if entry.PostDataSkipped || entry.PostDataSkipReason != "" || entry.PostDataTruncated {+ t.Errorf("a publishable body carries a signal: %+v", entry)+ }+}++// The sub-rune budget cannot arise through normalizeNetworkEntry — the cap is a constant far+// larger than any rune — so the case is pinned where it lives, on the shared clamp, with the+// scope name this call site passes. That name is what an operator reads in the reason.+func TestTheRequestBodyScopeNamesItselfInTheDropReason(t *testing.T) {+ for limit := 1; limit < 4; limit++ {+ clamped, truncated, reason := clampRetainedBody("🎯 body", false, limit, postDataLimitScope)++ if clamped != "" || truncated {+ t.Errorf("limit=%d: kept %q (truncated=%v) of a body whose first character does not fit", limit, clamped, truncated)+ }+ if reason != postDataLimitScope+" is smaller than the body's first character" {+ t.Errorf("limit=%d: reason = %q, which does not name the request body budget", limit, reason)+ }+ }+ if clamped, truncated, reason := clampRetainedBody("🎯 body", false, 4, postDataLimitScope); clamped != "🎯" || !truncated || reason != "" {+ t.Fatalf("limit=4: got (%q, %v, %q), want the first character alone as a truncated prefix — the drops above must be the budget, not a dead branch", clamped, truncated, reason)+ }+}