diff options
| author | srdusr <[email protected]> | 2026-06-09 15:46:00 +0200 |
|---|---|---|
| committer | srdusr <[email protected]> | 2026-06-09 15:46:00 +0200 |
| commit | a2362fc08c31b23fb971279f8b160555123ad2f6 (patch) | |
| tree | 6e7adf22167987f685d122f77f56b31a2ce988b2 /internal/rules | |
| parent | 9028f8175bda63d6a85e5a2dee2b4039020317a4 (diff) | |
| download | mitmux-a2362fc08c31b23fb971279f8b160555123ad2f6.tar.gz mitmux-a2362fc08c31b23fb971279f8b160555123ad2f6.zip | |
Body match-and-replace rules
Extends match-and-replace rules to request/response bodies, not just
headers. A body rule materializes the body into memory (bounded by
the same maxCaptureBytes cap as history capture) instead of streaming
it straight through - the opposite of the normal path, so it's only
paid when a body rule is actually configured. A body over the cap
passes through byte-exact and unmodified rather than being partially
rewritten.
Response Content-Length is recomputed explicitly when a rule changes
body length: unlike http.Request.Write, http.ResponseWriter doesn't
derive it from resp.ContentLength on its own, so a stale header would
otherwise corrupt response framing for the client.
The history audit trail still shows the original, pre-rule bytes on
both legs; only the wire traffic reflects the rewrite. Verified live
against a real daemon: origin receives the rewritten request body,
client receives the rewritten response body with correct
Content-Length, and history keeps the unmodified bytes.
Adds a Part selector (header/body) to the Rules add/edit form and
table in the TUI.
Diffstat (limited to 'internal/rules')
| -rw-r--r-- | internal/rules/rules.go | 43 | ||||
| -rw-r--r-- | internal/rules/rules_test.go | 93 |
2 files changed, 132 insertions, 4 deletions
diff --git a/internal/rules/rules.go b/internal/rules/rules.go index 1f50ec4..e0547db 100644 --- a/internal/rules/rules.go +++ b/internal/rules/rules.go @@ -1,7 +1,6 @@ // Package rules implements match-and-replace: user-defined rules that -// rewrite request/response headers as they pass through the proxy. -// Deliberately headers-only for now - see ApplyHeaders for why bodies -// are a separate, harder problem (noted as a follow-up in PLAN.md). +// rewrite request/response headers or bodies as they pass through the +// proxy. See ApplyHeaders and ApplyBody for how each part is handled. package rules import ( @@ -19,7 +18,7 @@ type Rule struct { Enabled bool Name string Scope string // "request" or "response" - Part string // "header" (only part supported so far) + Part string // "header" or "body" Match string Replace string IsRegex bool @@ -75,6 +74,42 @@ func ApplyHeaders(h http.Header, rs []Rule) http.Header { return http.Header(mh) } +// HasBodyRules reports whether any of rs (already filtered to enabled +// rules for one scope, as returned by store.EnabledRules) is a body +// rule - used to decide whether materializing a request/response body +// at all is worth it. Most traffic has no body rule configured and +// should keep streaming through unbuffered, which is what makes exact +// capture of arbitrarily large bodies possible in the first place. +func HasBodyRules(rs []Rule) bool { + for _, r := range rs { + if r.Enabled && r.Part == "body" { + return true + } + } + return false +} + +// ApplyBody rewrites body by running every enabled rule with +// Part=="body" over it, in Position order - literal substring replace +// by default, or regex if the rule's Regex toggle is on. Unlike +// ApplyHeaders, this operates directly on raw bytes with no reparse/ +// validation step: body content isn't a fixed format the way a header +// block is, so there's nothing to parse back and confirm is still +// well-formed. A rule that doesn't match anything is simply a no-op, +// same as ApplyHeaders. +func ApplyBody(body []byte, rs []Rule) []byte { + text := string(body) + for _, r := range sortedByPosition(rs) { + if !r.Enabled || r.Part != "body" { + continue + } + if next, ok := apply(text, r); ok { + text = next + } + } + return []byte(text) +} + func sortedByPosition(rs []Rule) []Rule { out := make([]Rule, len(rs)) copy(out, rs) diff --git a/internal/rules/rules_test.go b/internal/rules/rules_test.go new file mode 100644 index 0000000..3368607 --- /dev/null +++ b/internal/rules/rules_test.go @@ -0,0 +1,93 @@ +package rules + +import ( + "net/http" + "testing" +) + +func TestHasBodyRules(t *testing.T) { + tests := []struct { + name string + rs []Rule + want bool + }{ + {"empty", nil, false}, + {"header rule only", []Rule{{Enabled: true, Part: "header"}}, false}, + {"body rule enabled", []Rule{{Enabled: true, Part: "body"}}, true}, + {"body rule disabled", []Rule{{Enabled: false, Part: "body"}}, false}, + {"mixed, one enabled body rule", []Rule{ + {Enabled: true, Part: "header"}, + {Enabled: true, Part: "body"}, + }, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := HasBodyRules(tt.rs); got != tt.want { + t.Errorf("HasBodyRules(%+v) = %v, want %v", tt.rs, got, tt.want) + } + }) + } +} + +func TestApplyBodyLiteral(t *testing.T) { + body := []byte(`{"admin":false,"user":"bob"}`) + rs := []Rule{{Enabled: true, Part: "body", Match: `"admin":false`, Replace: `"admin":true`}} + got := ApplyBody(body, rs) + want := `{"admin":true,"user":"bob"}` + if string(got) != want { + t.Errorf("ApplyBody = %q, want %q", got, want) + } +} + +func TestApplyBodyRegex(t *testing.T) { + body := []byte(`user_id=12345&session=abc`) + rs := []Rule{{Enabled: true, Part: "body", Match: `user_id=\d+`, Replace: "user_id=1", IsRegex: true}} + got := ApplyBody(body, rs) + want := `user_id=1&session=abc` + if string(got) != want { + t.Errorf("ApplyBody = %q, want %q", got, want) + } +} + +func TestApplyBodySkipsDisabledAndHeaderRules(t *testing.T) { + body := []byte("hello world") + rs := []Rule{ + {Enabled: false, Part: "body", Match: "hello", Replace: "bye"}, + {Enabled: true, Part: "header", Match: "world", Replace: "planet"}, + } + got := ApplyBody(body, rs) + if string(got) != "hello world" { + t.Errorf("ApplyBody = %q, want unchanged %q", got, "hello world") + } +} + +func TestApplyBodyRespectsPositionOrder(t *testing.T) { + body := []byte("aaa") + rs := []Rule{ + {Enabled: true, Part: "body", Match: "a", Replace: "b", Position: 1}, + {Enabled: true, Part: "body", Match: "b", Replace: "c", Position: 0}, + } + // Position 0 runs first: "aaa" -[b->c, no match]-> "aaa" -[a->b]-> "bbb" + got := ApplyBody(body, rs) + if string(got) != "bbb" { + t.Errorf("ApplyBody = %q, want %q", got, "bbb") + } +} + +func TestApplyHeadersAddsRemovesHeader(t *testing.T) { + h := http.Header{"Host": []string{"example.com"}} + rs := []Rule{{Enabled: true, Part: "header", Match: "Host: example.com", Replace: "Host: example.com\r\nX-Injected: 1"}} + got := ApplyHeaders(h, rs) + if got.Get("X-Injected") != "1" { + t.Errorf("expected X-Injected header to be added, got %+v", got) + } +} + +func TestApplyHeadersInvalidRegexLeavesUnchanged(t *testing.T) { + h := http.Header{"Host": []string{"example.com"}} + rs := []Rule{{Enabled: true, Part: "header", Match: "(unclosed", Replace: "x", IsRegex: true}} + got := ApplyHeaders(h, rs) + if got.Get("Host") != "example.com" { + t.Errorf("expected headers unchanged on invalid regex, got %+v", got) + } +} |