diff options
Diffstat (limited to 'internal/rules/rules.go')
| -rw-r--r-- | internal/rules/rules.go | 43 |
1 files changed, 39 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) |