fix(traffic/hookvm): account string->[]byte, strSlice, append, and regexp.Compile in memory budget

This commit is contained in:
BaaRai
2026-11-21 00:48:27 +01:00
parent 680227b1ea
commit db9e121f68
4 changed files with 97 additions and 2 deletions
+1 -1
View File
@@ -50,7 +50,7 @@ Hooks are parsed with Go's standard `go/parser` and must declare `package hook`.
package hook
func OnResponse(req *Request, resp *Response) error
```
In `OnResponse`, `req` is **read-only** and holds the request as sent to the target.
In `OnResponse`, `req` holds an isolated copy of the request as sent to the target: field assignments (`req.Method`, `req.Path`, `req.RawQuery`, `req.Body`, `req.Headers`) and mutator methods (`req.SetHeader`, `req.AddHeader`, `req.DelHeader`) fail with `forbidden_mutation`, while direct map/slice element writes (such as `req.Headers[k] = ...`, `delete(req.Headers, k)`, or `req.Body[0] = ...`) mutate only the VM copy and are discarded without affecting the wire exchange or trace.
### Allowed Syntax
+4 -1
View File
@@ -825,6 +825,7 @@ func (e *vm) callBuiltin(name string, args []any) any {
e.failf("append expects >=2 args")
}
if s, ok := args[0].([]byte); ok {
e.alloc(int64(len(s)))
out := append([]byte(nil), s...)
for _, a := range args[1:] {
if b, ok := a.([]byte); ok {
@@ -838,7 +839,7 @@ func (e *vm) callBuiltin(name string, args []any) any {
return out
}
if s, ok := args[0].([]any); ok {
e.alloc(int64(len(args)-1) * 16)
e.alloc(int64(len(s)+len(args)-1) * 16)
return append(append([]any(nil), s...), args[1:]...)
}
case "delete":
@@ -1121,6 +1122,7 @@ func (e *vm) bytes(v any) []byte {
return b
}
if s, ok := v.(string); ok {
e.alloc(int64(len(s)))
return []byte(s)
}
e.failf("expected []byte or string, got %T", v)
@@ -1131,6 +1133,7 @@ func (e *vm) strSlice(v any) []string {
return ss
}
if sa, ok := v.([]any); ok {
e.alloc(int64(len(sa)) * 16)
out := make([]string, len(sa))
for i, el := range sa {
out[i] = e.str(el)
+3
View File
@@ -14,6 +14,8 @@ import (
"strings"
)
const regexpCompileCost = 32 << 10
func (e *vm) checkRepeat(elemLen, cnt int64) int {
if cnt < 0 {
e.failf("Repeat: negative count")
@@ -203,6 +205,7 @@ func (e *vm) callPkg(pkg, fn string, args []any) any {
if len(pat) > DefaultMaxRegexBytes {
e.failf("regexp pattern exceeds %d bytes", DefaultMaxRegexBytes)
}
e.alloc(regexpCompileCost + int64(len(pat))*32)
re, err := regexp.Compile(pat)
if err != nil {
e.fail(err)
+89
View File
@@ -180,6 +180,27 @@ func OnResponse(req *Request, resp *Response) error {
t.Fatalf("err = %v, want ErrForbiddenMutation", err)
}
})
t.Run("response_phase_req_headers_index_only_mutates_vm_copy", func(t *testing.T) {
src := `package hook
func OnResponse(req *Request, resp *Response) error {
req.Headers["X-Vm-Only"] = []any{"1"}
resp.SetHeader("X-Seen", req.GetHeader("X-Vm-Only"))
return nil
}`
prog, err := Compile("response", src)
if err != nil {
t.Fatal(err)
}
vmReq := &Request{Headers: map[string][]string{"X-Orig": {"keep"}}}
resp := &Response{Status: 200, Headers: map[string][]string{}}
if err := prog.RunResponse(context.Background(), vmReq, resp, RunOptions{}); err != nil {
t.Fatalf("RunResponse: %v", err)
}
if len(resp.Headers["X-Seen"]) != 1 || resp.Headers["X-Seen"][0] != "1" {
t.Fatalf("expected VM-local mutation visible inside hook, got %v", resp.Headers)
}
})
}
func TestResourceBoundsMemoryStepTimeoutPanicAndRegexp(t *testing.T) {
@@ -218,6 +239,74 @@ func OnRequest(req *Request) error {
}
})
t.Run("bytes_contains_string_loop_stopped_by_memory_budget", func(t *testing.T) {
src := `package hook
import "bytes"
func OnRequest(req *Request) error {
s := string(req.Body)
for i := 0; i < 1000; i++ {
if bytes.Contains(s, "needle") {
return nil
}
}
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
req := &Request{Body: bytes.Repeat([]byte("A"), 1<<20)}
err = prog.RunRequest(context.Background(), req, RunOptions{})
if !errors.Is(err, ErrMemoryLimit) {
t.Fatalf("err = %v, want ErrMemoryLimit", err)
}
})
t.Run("regexp_compile_loop_stopped_by_memory_budget", func(t *testing.T) {
src := `package hook
import "regexp"
func OnRequest(req *Request) error {
for i := 0; i < 500; i++ {
_, err := regexp.MatchString("foo[0-9]+bar", "hello")
if err != nil {
return err
}
}
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
err = prog.RunRequest(context.Background(), &Request{}, RunOptions{})
if !errors.Is(err, ErrMemoryLimit) {
t.Fatalf("err = %v, want ErrMemoryLimit", err)
}
})
t.Run("strslice_join_loop_stopped_by_memory_budget", func(t *testing.T) {
src := `package hook
import "strings"
func OnRequest(req *Request) error {
items := make([]any, 1000)
for i := 0; i < 1000; i++ {
items[i] = ""
}
for i := 0; i < 1000; i++ {
_ = strings.Join(items, "")
}
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
err = prog.RunRequest(context.Background(), &Request{}, RunOptions{MaxMemory: 256 << 10})
if !errors.Is(err, ErrMemoryLimit) {
t.Fatalf("err = %v, want ErrMemoryLimit", err)
}
})
t.Run("infinite_loop_stopped_by_step_limit", func(t *testing.T) {
src := `package hook
func OnRequest(req *Request) error {