feat(traffic/hookvm): add deterministic resource-bounded Go-subset VM and sandbox tests

This commit is contained in:
BaaRai
2026-11-21 00:48:27 +01:00
parent f45d75bda5
commit 95d6d98307
4 changed files with 1996 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+265
View File
@@ -0,0 +1,265 @@
package hookvm
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"net/url"
"regexp"
"strconv"
"strings"
)
func (e *vm) checkRepeat(elemLen, cnt int64) int {
if cnt < 0 {
e.failf("Repeat: negative count")
}
if cnt > 0 && elemLen > e.memLimit/cnt {
e.fail(ErrMemoryLimit)
}
e.alloc(elemLen * cnt)
return int(cnt)
}
func (e *vm) callPkg(pkg, fn string, args []any) any {
need := func(n int) {
if len(args) != n {
e.failf("%s.%s expects %d arg(s)", pkg, fn, n)
}
}
switch pkg {
case "strings":
switch fn {
case "Contains", "HasPrefix", "HasSuffix", "Index", "TrimPrefix", "TrimSuffix", "Split", "Join", "Repeat":
need(2)
switch fn {
case "Contains":
return strings.Contains(e.str(args[0]), e.str(args[1]))
case "HasPrefix":
return strings.HasPrefix(e.str(args[0]), e.str(args[1]))
case "HasSuffix":
return strings.HasSuffix(e.str(args[0]), e.str(args[1]))
case "Index":
return int64(strings.Index(e.str(args[0]), e.str(args[1])))
case "TrimPrefix":
return strings.TrimPrefix(e.str(args[0]), e.str(args[1]))
case "TrimSuffix":
return strings.TrimSuffix(e.str(args[0]), e.str(args[1]))
case "Split":
a, sep := e.str(args[0]), e.str(args[1])
parts := strings.Split(a, sep)
e.alloc(int64(len(a)) + int64(len(parts))*16)
out := make([]any, len(parts))
for i, p := range parts {
out[i] = p
}
return out
case "Join":
ss, sep := e.strSlice(args[0]), e.str(args[1])
var est int64
for _, p := range ss {
est += int64(len(p) + len(sep))
}
e.alloc(est)
return strings.Join(ss, sep)
case "Repeat":
s := e.str(args[0])
return strings.Repeat(s, e.checkRepeat(int64(len(s)), e.int(args[1])))
}
case "ToLower", "ToUpper", "TrimSpace":
need(1)
s := e.str(args[0])
if fn == "TrimSpace" {
return strings.TrimSpace(s)
}
e.alloc(int64(len(s)))
if fn == "ToLower" {
return strings.ToLower(s)
}
return strings.ToUpper(s)
case "ReplaceAll":
need(3)
out := strings.ReplaceAll(e.str(args[0]), e.str(args[1]), e.str(args[2]))
e.alloc(int64(len(out)))
return out
}
case "bytes":
switch fn {
case "Contains", "HasPrefix", "HasSuffix", "Equal", "Index", "Repeat":
need(2)
switch fn {
case "Contains":
return bytes.Contains(e.bytes(args[0]), e.bytes(args[1]))
case "HasPrefix":
return bytes.HasPrefix(e.bytes(args[0]), e.bytes(args[1]))
case "HasSuffix":
return bytes.HasSuffix(e.bytes(args[0]), e.bytes(args[1]))
case "Equal":
return bytes.Equal(e.bytes(args[0]), e.bytes(args[1]))
case "Index":
return int64(bytes.Index(e.bytes(args[0]), e.bytes(args[1])))
case "Repeat":
b := e.bytes(args[0])
return bytes.Repeat(b, e.checkRepeat(int64(len(b)), e.int(args[1])))
}
case "TrimSpace", "ToLower", "ToUpper":
need(1)
b := e.bytes(args[0])
e.alloc(int64(len(b)))
if fn == "TrimSpace" {
return append([]byte(nil), bytes.TrimSpace(b)...)
}
if fn == "ToLower" {
return bytes.ToLower(b)
}
return bytes.ToUpper(b)
case "ReplaceAll":
need(3)
out := bytes.ReplaceAll(e.bytes(args[0]), e.bytes(args[1]), e.bytes(args[2]))
e.alloc(int64(len(out)))
return out
}
case "encoding/json":
need(1)
if fn == "Marshal" {
raw, err := json.Marshal(args[0])
if err == nil {
e.alloc(int64(len(raw)))
}
return multiVal{raw, err}
}
if fn == "Decode" {
b := e.bytes(args[0])
e.alloc(int64(len(b)) * 4)
var dst any
return multiVal{dst, json.Unmarshal(b, &dst)}
}
case "encoding/base64":
need(1)
enc := base64.StdEncoding
if strings.HasPrefix(fn, "URL") {
enc = base64.RawURLEncoding
}
if strings.HasSuffix(fn, "EncodeToString") {
b := e.bytes(args[0])
e.alloc(int64(enc.EncodedLen(len(b))))
return enc.EncodeToString(b)
}
if strings.HasSuffix(fn, "DecodeString") {
s := e.str(args[0])
e.alloc(int64(len(s)))
b, err := enc.DecodeString(s)
return multiVal{b, err}
}
case "encoding/hex":
need(1)
if fn == "EncodeToString" {
b := e.bytes(args[0])
e.alloc(int64(len(b) * 2))
return hex.EncodeToString(b)
}
if fn == "DecodeString" {
s := e.str(args[0])
e.alloc(int64(len(s)))
b, err := hex.DecodeString(s)
return multiVal{b, err}
}
case "net/url":
need(1)
switch fn {
case "QueryEscape":
out := url.QueryEscape(e.str(args[0]))
e.alloc(int64(len(out)))
return out
case "QueryUnescape":
out, err := url.QueryUnescape(e.str(args[0]))
if err == nil {
e.alloc(int64(len(out)))
}
return multiVal{out, err}
case "ParseQuery":
s := e.str(args[0])
e.alloc(int64(len(s)) * 2)
v, err := url.ParseQuery(s)
return multiVal{map[string][]string(v), err}
case "EncodeQuery":
m, ok := args[0].(map[string][]string)
if !ok {
e.failf("url.EncodeQuery expects map[string][]string")
}
out := url.Values(m).Encode()
e.alloc(int64(len(out)))
return out
}
case "regexp":
if len(args) < 2 {
e.failf("regexp.%s expects at least 2 args", fn)
}
pat, s := e.str(args[0]), e.str(args[1])
if len(pat) > DefaultMaxRegexBytes {
e.failf("regexp pattern exceeds %d bytes", DefaultMaxRegexBytes)
}
re, err := regexp.Compile(pat)
if err != nil {
e.fail(err)
}
switch fn {
case "MatchString":
need(2)
return multiVal{re.MatchString(s), nil}
case "FindString":
need(2)
return re.FindString(s)
case "ReplaceAllString":
need(3)
out := re.ReplaceAllString(s, e.str(args[2]))
e.alloc(int64(len(out)))
return out
}
case "crypto/sha256":
need(1)
sum := sha256.Sum256(e.bytes(args[0]))
if fn == "Sum256" {
return append([]byte(nil), sum[:]...)
}
if fn == "Sum256Hex" {
return hex.EncodeToString(sum[:])
}
case "crypto/hmac":
need(2)
m := hmac.New(sha256.New, e.bytes(args[0]))
m.Write(e.bytes(args[1]))
sum := m.Sum(nil)
if fn == "SHA256" {
return sum
}
if fn == "SHA256Hex" {
return hex.EncodeToString(sum)
}
case "strconv":
need(1)
switch fn {
case "Atoi":
n, err := strconv.Atoi(e.str(args[0]))
return multiVal{int64(n), err}
case "Itoa":
return strconv.FormatInt(e.int(args[0]), 10)
case "ParseBool":
b, err := strconv.ParseBool(e.str(args[0]))
return multiVal{b, err}
case "FormatBool":
return strconv.FormatBool(e.bool(args[0]))
}
case "errors":
if fn == "New" {
need(1)
return errors.New(e.str(args[0]))
}
}
e.failf("unsupported stdlib call %s.%s", pkg, fn)
return nil
}
+227
View File
@@ -0,0 +1,227 @@
// Package hookvm implements a small, deterministic, resource-bounded Go-subset
// evaluator built on Go's standard library go/parser and go/ast packages.
// Zero external dependencies; no filesystem, network, subprocess, environment,
// wall-clock, randomness, goroutine, channel, pointer, or global-state access.
package hookvm
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"strings"
)
const (
MaxSourceBytes = 64 * 1024
DefaultMaxSteps = 100_000
DefaultMaxMemory = 4 * 1024 * 1024
DefaultMaxRegexBytes = 1024
MaxCallDepth = 32
)
var (
ErrStepLimit = errors.New("hook exceeded step limit")
ErrTimeout = errors.New("hook timed out")
ErrMemoryLimit = errors.New("hook exceeded memory limit")
ErrForbiddenMutation = errors.New("hook attempted forbidden mutation")
ErrCallDepth = errors.New("hook exceeded call depth limit")
)
// AllowedImports is the closed set of pure, deterministic virtual packages.
var AllowedImports = map[string]bool{
"strings": true, "bytes": true, "encoding/json": true, "encoding/base64": true,
"encoding/hex": true, "net/url": true, "regexp": true, "crypto/sha256": true,
"crypto/hmac": true, "strconv": true, "errors": true,
}
var allowedBuiltins = map[string]bool{
"len": true, "cap": true, "append": true, "make": true, "delete": true,
"string": true, "int": true, "int64": true, "float64": true, "byte": true, "panic": true,
}
// Program is a validated AST ready for concurrent read-only execution.
type Program struct {
phase string
imports map[string]string
funcs map[string]*ast.FuncDecl
consts map[string]any
entry *ast.FuncDecl
}
// Compile parses and statically validates a Go-subset tampering hook for phase
// ("request" or "response").
func Compile(phase, source string) (*Program, error) {
if phase != "request" && phase != "response" {
return nil, fmt.Errorf("invalid hook phase %q", phase)
}
if len(source) == 0 || len(source) > MaxSourceBytes {
return nil, fmt.Errorf("hook source length must be 1..%d bytes", MaxSourceBytes)
}
file, err := parser.ParseFile(token.NewFileSet(), "hook.go", source, 0)
if err != nil {
return nil, fmt.Errorf("parse hook: %w", err)
}
if file.Name == nil || file.Name.Name != "hook" {
return nil, errors.New("hook must declare 'package hook'")
}
prog := &Program{
phase: phase, imports: map[string]string{},
funcs: map[string]*ast.FuncDecl{}, consts: map[string]any{},
}
for _, imp := range file.Imports {
path := strings.Trim(imp.Path.Value, `"`)
if !AllowedImports[path] {
return nil, fmt.Errorf("forbidden import %q", path)
}
alias := path[strings.LastIndexByte(path, '/')+1:]
if imp.Name != nil {
if imp.Name.Name == "." || imp.Name.Name == "_" {
return nil, fmt.Errorf("dot/blank import %q is not allowed", path)
}
alias = imp.Name.Name
}
prog.imports[alias] = path
}
for _, decl := range file.Decls {
switch d := decl.(type) {
case *ast.GenDecl:
switch d.Tok {
case token.IMPORT:
case token.CONST:
if err := collectConsts(d, prog.consts); err != nil {
return nil, err
}
case token.VAR:
return nil, errors.New("package-level variables are forbidden (hooks must be stateless)")
case token.TYPE:
return nil, errors.New("custom package-level types are not supported in hooks")
default:
return nil, fmt.Errorf("unsupported declaration %s", d.Tok)
}
case *ast.FuncDecl:
if d.Recv != nil {
return nil, errors.New("custom receiver methods are not supported in hooks")
}
name := d.Name.Name
if name == "init" {
return nil, errors.New("init() is forbidden in hooks")
}
if _, dup := prog.funcs[name]; dup || d.Body == nil {
return nil, fmt.Errorf("invalid or duplicate function %q", name)
}
if err := validateBlock(d.Body); err != nil {
return nil, fmt.Errorf("function %s: %w", name, err)
}
prog.funcs[name] = d
default:
return nil, fmt.Errorf("unsupported top-level declaration %T", decl)
}
}
entryName, wantParams := "OnRequest", 1
if phase == "response" {
entryName, wantParams = "OnResponse", 2
}
entry := prog.funcs[entryName]
if entry == nil {
return nil, fmt.Errorf("phase %q requires function %s", phase, entryName)
}
if countFields(entry.Type.Params) != wantParams || countFields(entry.Type.Results) != 1 {
return nil, fmt.Errorf("%s must accept %d parameter(s) and return error", entryName, wantParams)
}
prog.entry = entry
return prog, nil
}
func countFields(fl *ast.FieldList) int {
if fl == nil {
return 0
}
n := 0
for _, f := range fl.List {
n += max(1, len(f.Names))
}
return n
}
func collectConsts(d *ast.GenDecl, out map[string]any) error {
for _, spec := range d.Specs {
vs, ok := spec.(*ast.ValueSpec)
if !ok || len(vs.Names) != len(vs.Values) {
return errors.New("const declarations must have explicit values")
}
for i, name := range vs.Names {
v, err := evalConstExpr(vs.Values[i])
if err != nil {
return fmt.Errorf("const %s: %w", name.Name, err)
}
out[name.Name] = v
}
}
return nil
}
func evalConstExpr(e ast.Expr) (any, error) {
switch x := e.(type) {
case *ast.BasicLit:
return parseBasicLit(x)
case *ast.Ident:
if x.Name == "true" || x.Name == "false" {
return x.Name == "true", nil
}
case *ast.UnaryExpr:
if x.Op == token.SUB {
if v, err := evalConstExpr(x.X); err == nil {
if n, ok := v.(int64); ok {
return -n, nil
}
if f, ok := v.(float64); ok {
return -f, nil
}
}
}
}
return nil, fmt.Errorf("unsupported const expression %T", e)
}
func validateBlock(body *ast.BlockStmt) error {
var firstErr error
ast.Inspect(body, func(n ast.Node) bool {
if firstErr != nil || n == nil {
return false
}
switch x := n.(type) {
case *ast.GoStmt:
firstErr = errors.New("goroutines ('go') are forbidden in hooks")
case *ast.SendStmt, *ast.ChanType, *ast.SelectStmt:
firstErr = errors.New("channels and select are forbidden in hooks")
case *ast.DeferStmt:
firstErr = errors.New("defer is forbidden in hooks")
case *ast.SwitchStmt, *ast.TypeSwitchStmt:
firstErr = errors.New("switch is not supported in hooks; use if / else if")
case *ast.FuncLit:
firstErr = errors.New("anonymous function literals are not supported in hooks")
case *ast.UnaryExpr:
if x.Op == token.AND {
firstErr = errors.New("address-of (&) is not supported in hooks")
}
case *ast.BranchStmt:
if x.Tok == token.GOTO {
firstErr = errors.New("goto is forbidden in hooks")
}
case *ast.CallExpr:
if id, ok := x.Fun.(*ast.Ident); ok {
switch id.Name {
case "recover", "print", "println", "close", "complex", "real", "imag", "new":
firstErr = fmt.Errorf("builtin %q is forbidden in hooks", id.Name)
}
}
}
return firstErr == nil
})
return firstErr
}
+345
View File
@@ -0,0 +1,345 @@
package hookvm
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"strings"
"testing"
"time"
)
func TestCompileRejectsForbiddenConstructsAndImports(t *testing.T) {
cases := []struct {
name string
phase string
src string
}{
{"import_os", "request", `package hook; import "os"; func OnRequest(req *Request) error { _ = os.Getenv("HOME"); return nil }`},
{"import_io_fs", "request", `package hook; import "io/fs"; func OnRequest(req *Request) error { return nil }`},
{"import_net", "request", `package hook; import "net"; func OnRequest(req *Request) error { return nil }`},
{"import_net_http", "request", `package hook; import "net/http"; func OnRequest(req *Request) error { return nil }`},
{"import_os_exec", "request", `package hook; import "os/exec"; func OnRequest(req *Request) error { return nil }`},
{"import_syscall", "request", `package hook; import "syscall"; func OnRequest(req *Request) error { return nil }`},
{"import_unsafe", "request", `package hook; import "unsafe"; func OnRequest(req *Request) error { return nil }`},
{"import_reflect", "request", `package hook; import "reflect"; func OnRequest(req *Request) error { return nil }`},
{"import_time", "request", `package hook; import "time"; func OnRequest(req *Request) error { _ = time.Now(); return nil }`},
{"import_math_rand", "request", `package hook; import "math/rand"; func OnRequest(req *Request) error { _ = rand.Int(); return nil }`},
{"import_crypto_rand", "request", `package hook; import "crypto/rand"; func OnRequest(req *Request) error { return nil }`},
{"import_fmt_disallowed", "request", `package hook; import "fmt"; func OnRequest(req *Request) error { return nil }`},
{"import_sort_disallowed", "request", `package hook; import "sort"; func OnRequest(req *Request) error { return nil }`},
{"dot_import", "request", `package hook; import . "strings"; func OnRequest(req *Request) error { return nil }`},
{"blank_import", "request", `package hook; import _ "strings"; func OnRequest(req *Request) error { return nil }`},
{"goroutine", "request", `package hook; func f(){}; func OnRequest(req *Request) error { go f(); return nil }`},
{"channel_type", "request", `package hook; func OnRequest(req *Request) error { var c chan int; _ = c; return nil }`},
{"select_stmt", "request", `package hook; func OnRequest(req *Request) error { select {}; return nil }`},
{"defer_stmt", "request", `package hook; func f(){}; func OnRequest(req *Request) error { defer f(); return nil }`},
{"goto_stmt", "request", `package hook; func OnRequest(req *Request) error { goto end; end: return nil }`},
{"init_func", "request", `package hook; func init() {}; func OnRequest(req *Request) error { return nil }`},
{"mutable_global", "request", `package hook; var counter = 0; func OnRequest(req *Request) error { counter++; return nil }`},
{"switch_stmt", "request", `package hook; func OnRequest(req *Request) error { switch req.Method { case "GET": }; return nil }`},
{"address_of", "request", `package hook; func OnRequest(req *Request) error { x := 1; _ = &x; return nil }`},
{"func_lit", "request", `package hook; func OnRequest(req *Request) error { f := func() {}; _ = f; return nil }`},
{"builtin_recover", "request", `package hook; func OnRequest(req *Request) error { _ = recover(); return nil }`},
{"builtin_print", "request", `package hook; func OnRequest(req *Request) error { print("x"); return nil }`},
{"builtin_println", "request", `package hook; func OnRequest(req *Request) error { println("x"); return nil }`},
{"wrong_package", "request", `package main; func OnRequest(req *Request) error { return nil }`},
{"missing_entry", "request", `package hook; func Helper() error { return nil }`},
{"wrong_arity_response", "response", `package hook; func OnResponse(resp *Response) error { return nil }`},
{"oversized_source", "request", "package hook\nfunc OnRequest(req *Request) error { return nil }\n//" + strings.Repeat("a", MaxSourceBytes)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if _, err := Compile(tc.phase, tc.src); err == nil {
t.Fatalf("expected Compile(%s) to reject %s", tc.phase, tc.name)
}
})
}
}
func TestRequestAndResponseTransformationsAndHelpers(t *testing.T) {
src := `package hook
import (
"crypto/hmac"
"encoding/base64"
"encoding/json"
"net/url"
"strings"
)
const secretKey = "k-123"
func sign(data []byte) string {
return hmac.SHA256Hex([]byte(secretKey), data)
}
func OnRequest(req *Request) error {
req.SetHeader("X-Tampered", "yes")
req.DelHeader("X-Remove")
if strings.HasPrefix(req.Path, "/v1/") {
req.Path = strings.ReplaceAll(req.Path, "/v1/", "/v2/")
}
q, err := url.ParseQuery(req.RawQuery)
if err != nil {
return err
}
q["debug"] = []any{"1"}
req.RawQuery = url.EncodeQuery(q)
val, err := json.Decode(req.Body)
if err != nil {
return err
}
obj, ok := val.(map[string]any)
if !ok {
return nil
}
obj["role"] = "admin"
out, err := json.Marshal(obj)
if err != nil {
return err
}
req.Body = out
req.SetHeader("X-Sig", sign(out))
req.SetHeader("X-B64", base64.EncodeToString([]byte(req.Host)))
return nil
}
`
prog, err := Compile("request", src)
if err != nil {
t.Fatalf("Compile: %v", err)
}
req := &Request{
Scheme: "https",
Host: "api.example.test",
Port: "443",
Method: "POST",
Path: "/v1/users",
RawQuery: "a=2",
Headers: map[string][]string{"X-Remove": {"bye"}},
Body: []byte(`{"role":"user","id":7}`),
}
if err := prog.RunRequest(context.Background(), req, RunOptions{}); err != nil {
t.Fatalf("RunRequest: %v", err)
}
if req.Path != "/v2/users" {
t.Fatalf("Path = %q, want /v2/users", req.Path)
}
if req.RawQuery != "a=2&debug=1" {
t.Fatalf("RawQuery = %q, want a=2&debug=1", req.RawQuery)
}
if got := req.Headers["X-Tampered"]; len(got) != 1 || got[0] != "yes" {
t.Fatalf("X-Tampered = %v", got)
}
if _, exists := req.Headers["X-Remove"]; exists {
t.Fatal("X-Remove was not deleted")
}
if !bytes.Contains(req.Body, []byte(`"role":"admin"`)) {
t.Fatalf("Body = %s", req.Body)
}
if len(req.Headers["X-Sig"]) != 1 || len(req.Headers["X-Sig"][0]) != 64 {
t.Fatalf("X-Sig = %v", req.Headers["X-Sig"])
}
}
func TestForbiddenHostSchemePortAndReadOnlyRequest(t *testing.T) {
for _, field := range []string{"Host", "Scheme", "Port"} {
t.Run("mutate_"+field, func(t *testing.T) {
src := `package hook
func OnRequest(req *Request) error {
req.` + field + ` = "evil.example.test"
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatalf("Compile: %v", err)
}
req := &Request{Scheme: "https", Host: "good.example.test", Port: "443"}
err = prog.RunRequest(context.Background(), req, RunOptions{})
if !errors.Is(err, ErrForbiddenMutation) {
t.Fatalf("err = %v, want ErrForbiddenMutation", err)
}
})
}
t.Run("mutate_request_in_response_phase", func(t *testing.T) {
src := `package hook
func OnResponse(req *Request, resp *Response) error {
req.SetHeader("X-Bad", "1")
return nil
}`
prog, err := Compile("response", src)
if err != nil {
t.Fatal(err)
}
err = prog.RunResponse(context.Background(), &Request{}, &Response{Status: 200}, RunOptions{})
if !errors.Is(err, ErrForbiddenMutation) {
t.Fatalf("err = %v, want ErrForbiddenMutation", err)
}
})
}
func TestResourceBoundsMemoryStepTimeoutPanicAndRegexp(t *testing.T) {
t.Run("make_100MiB_stopped_by_memory_budget", func(t *testing.T) {
src := `package hook
func OnRequest(req *Request) error {
b := make([]byte, 100*1024*1024)
_ = b
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
err = prog.RunRequest(context.Background(), &Request{}, RunOptions{MaxMemory: 1 << 20})
if !errors.Is(err, ErrMemoryLimit) {
t.Fatalf("err = %v, want ErrMemoryLimit", err)
}
})
t.Run("strings_repeat_stopped_by_memory_budget", func(t *testing.T) {
src := `package hook
import "strings"
func OnRequest(req *Request) error {
s := strings.Repeat("A", 10*1024*1024)
_ = s
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
err = prog.RunRequest(context.Background(), &Request{}, RunOptions{MaxMemory: 1 << 20})
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 {
for {
}
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
err = prog.RunRequest(context.Background(), &Request{}, RunOptions{MaxSteps: 500})
if !errors.Is(err, ErrStepLimit) {
t.Fatalf("err = %v, want ErrStepLimit", err)
}
})
t.Run("infinite_loop_stopped_by_context_timeout", func(t *testing.T) {
src := `package hook
func OnRequest(req *Request) error {
i := 0
for {
i++
}
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
err = prog.RunRequest(ctx, &Request{}, RunOptions{MaxSteps: 100_000_000})
if !errors.Is(err, ErrTimeout) {
t.Fatalf("err = %v, want ErrTimeout", err)
}
})
t.Run("panic_recovered_as_panic_error", func(t *testing.T) {
src := `package hook
func OnRequest(req *Request) error {
panic("boom")
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
err = prog.RunRequest(context.Background(), &Request{}, RunOptions{})
var pe *PanicError
if !errors.As(err, &pe) || pe.Value != "boom" {
t.Fatalf("err = %v, want PanicError(boom)", err)
}
})
t.Run("regexp_pattern_bounded", func(t *testing.T) {
src := `package hook
import (
"regexp"
"strings"
)
func OnRequest(req *Request) error {
pat := strings.Repeat("a", 2048)
_, err := regexp.MatchString(pat, "aaa")
return err
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
if err := prog.RunRequest(context.Background(), &Request{}, RunOptions{}); err == nil || !strings.Contains(err.Error(), "exceeds") {
t.Fatalf("expected regexp size limit error, got %v", err)
}
})
}
func TestDeterminismAndSortedMapIteration(t *testing.T) {
src := `package hook
import "encoding/json"
func OnRequest(req *Request) error {
v, err := json.Decode(req.Body)
if err != nil {
return err
}
m, _ := v.(map[string]any)
joined := ""
for k, val := range m {
s, _ := val.(string)
joined += k + "=" + s + ";"
}
req.SetHeader("X-Order", joined)
out, err := json.Marshal(m)
if err != nil {
return err
}
req.Body = out
return nil
}`
prog, err := Compile("request", src)
if err != nil {
t.Fatal(err)
}
inputBody := []byte(`{"z":"last","a":"first","m":"mid","b":"second","k":"fifth"}`)
var firstHeader, firstHash string
for run := 0; run < 20; run++ {
req := &Request{
Scheme: "https", Host: "example.test", Port: "443",
Method: "POST", Path: "/api",
Body: append([]byte(nil), inputBody...),
}
if err := prog.RunRequest(context.Background(), req, RunOptions{}); err != nil {
t.Fatalf("run %d: %v", run, err)
}
h := req.Headers["X-Order"][0]
sum := sha256.Sum256(req.Body)
bodyHash := hex.EncodeToString(sum[:])
if run == 0 {
firstHeader, firstHash = h, bodyHash
if firstHeader != "a=first;b=second;k=fifth;m=mid;z=last;" {
t.Fatalf("unsorted map iteration: %q", firstHeader)
}
} else if h != firstHeader || bodyHash != firstHash {
t.Fatalf("run %d diverged: (%q, %s) != (%q, %s)", run, h, bodyHash, firstHeader, firstHash)
}
}
}