Files
zapret-autotune/cmd/zapret-autotune/render_test.go
T
2026-10-09 20:59:51 +03:00

183 lines
7.5 KiB
Go

package main
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func passing(group string) candidate {
return candidate{group, []string{group + ".example.com"}, "--lua-desync=fake:blob=tls_clienthello", 1, 1, 3, 3, 10, 100}
}
func encodeCandidates(t *testing.T, candidates ...candidate) string {
t.Helper()
data, err := json.Marshal(candidates)
if err != nil {
t.Fatal(err)
}
return string(data)
}
func TestRenderSelection(t *testing.T) {
base := passing("frontend")
tests := []struct {
name string
change func(*candidate)
wins bool
}{
{"higher speed", func(c *candidate) { c.MedianSpeed++; c.MedianLatency++ }, true},
{"lower speed", func(c *candidate) { c.MedianSpeed-- }, false},
{"lower latency", func(c *candidate) { c.MedianLatency-- }, true},
{"higher latency", func(c *candidate) { c.MedianLatency++ }, false},
{"more stages", func(c *candidate) { c.Args = "--lua-desync=fake --lua-desync=multisplit" }, false},
{"lexical args", func(c *candidate) { c.Args = "--lua-desync=aaa" }, true},
{"domain tie", func(c *candidate) { c.Domains = []string{"aaa.example.com"} }, true},
{"partial success", func(c *candidate) { c.SuccessRate = .99; c.MedianSpeed++ }, false},
{"partial coverage", func(c *candidate) { c.Coverage = .99; c.MedianSpeed++ }, false},
{"incomplete passes", func(c *candidate) { c.PassesOK--; c.MedianSpeed++ }, false},
{"no passes", func(c *candidate) { c.PassesTotal = 0; c.PassesOK = 0; c.MedianSpeed++ }, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
other := passing("frontend")
other.Domains = []string{"other.example.com"}
tt.change(&other)
want := base
if tt.wins {
want = other
}
video := passing("googlevideo")
expected, err := renderResults(strings.NewReader(encodeCandidates(t, want, video)))
if err != nil {
t.Fatal(err)
}
for _, candidates := range [][]candidate{{base, other, video}, {video, other, base}} {
got, err := renderResults(strings.NewReader(encodeCandidates(t, candidates...)))
if err != nil || got != expected {
t.Fatalf("got %q, %v; want %q", got, err, expected)
}
}
})
}
}
func TestRenderValidation(t *testing.T) {
tests := []struct {
name string
change func(*candidate)
}{
{"unknown group", func(c *candidate) { c.Group = "other" }},
{"no domains", func(c *candidate) { c.Domains = nil }},
{"negative speed", func(c *candidate) { c.MedianSpeed = -1 }},
{"negative latency", func(c *candidate) { c.MedianLatency = -1 }},
{"success over one", func(c *candidate) { c.SuccessRate = 2 }},
{"coverage negative", func(c *candidate) { c.Coverage = -1 }},
{"negative passes", func(c *candidate) { c.PassesOK = -1 }},
{"impossible passes", func(c *candidate) { c.PassesOK = 4 }},
}
for _, domain := range []string{"https://example.com", "*.example.com", "a;b.com", "a$b.com", "a b.com", "a_b.com", "-a.com", "a-.com", "a..com", "a.com.", strings.Repeat("a", 64) + ".com", strings.Repeat("a.", 127) + "com"} {
domain := domain
tests = append(tests, struct {
name string
change func(*candidate)
}{"domain " + domain, func(c *candidate) { c.Domains = []string{domain} }})
}
for _, args := range []string{"", "--new", "--filter-tcp=80", "--lua-desync=", "--lua-desync=123", "--lua-desync=fake extra", "--lua-desync=fake\n", "--lua-desync=fake\r", "--lua-desync=fake\t", "--lua-desync='fake'", "--lua-desync=\"fake\"", "--lua-desync=`fake`", "--lua-desync=$fake", "--lua-desync=fake;", "--lua-desync=fake\\", "--lua-desync=fake|cat", "--lua-desync=fake&", "--lua-desync=fake>file"} {
args := args
tests = append(tests, struct {
name string
change func(*candidate)
}{"args " + args, func(c *candidate) { c.Args = args }})
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
bad := passing("frontend")
tt.change(&bad)
got, err := renderResults(strings.NewReader(encodeCandidates(t, bad, passing("frontend"), passing("googlevideo"))))
if err == nil || got != "" {
t.Fatalf("untrusted candidate accepted: %q, %v", got, err)
}
})
}
}
func TestRenderJSON(t *testing.T) {
valid := encodeCandidates(t, passing("frontend"), passing("googlevideo"))
for _, input := range []string{"", "[", "{}", "null", "[]", "[null]", valid + " {}", valid + " garbage", strings.Replace(valid, `"group":"frontend",`, "", 1), strings.Replace(valid, `"coverage":1`, `"coverage":null`, 1), strings.Replace(valid, `"coverage":1`, `"coverage":1,"unknown":true`, 1), strings.Replace(valid, `"coverage":1`, `"coverage":"1"`, 1), strings.Replace(valid, `"coverage":1`, `"coverage":1e999`, 1)} {
if got, err := renderResults(strings.NewReader(input)); err == nil || got != "" {
t.Errorf("accepted invalid JSON %q: %q, %v", input, got, err)
}
}
for _, group := range []string{"frontend", "googlevideo"} {
if got, err := renderResults(strings.NewReader(encodeCandidates(t, passing(group)))); err == nil || got != "" {
t.Errorf("accepted only %s: %q, %v", group, got, err)
}
}
}
func TestStrategyOptionGrammar(t *testing.T) {
for _, args := range []string{
"--payload=tls_client_hello --lua-desync=hostfakesplit:disorder_after:tcp_md5:repeats=1",
"--in-range=-s1 --lua-desync=oob:urp=midsld",
"--out-range=s1-s10 --lua-init=@/opt/zapret2/lua/zapret-lib.lua --lua-desync=multisplit:pos=1,midsld",
} {
c := passing("frontend")
c.Args = args
if err := c.validate(); err != nil || c.Args != args {
t.Fatalf("valid args changed/rejected: %q, %v", c.Args, err)
}
}
for _, args := range []string{
"nfqws2 --lua-desync=oob", "--payload=nope", "--payload=", "--in-range=xyz", "--out-range=s1--s2",
"--lua-desync=oob:", "--lua-desync=oob::urp=midsld", "--lua-desync=oob:urp=", "--lua-desync=oob:1bad=x",
"--lua-init=os.execute=bad", "--lua-init=@/tmp/x.lua", "--lua-init=@/opt/zapret2/lua/../x.lua",
"--lua-init=@/opt/zapret2/lua/x.lua;id", "--payload='tls_client_hello'", "--in-range=$(id)",
} {
c := passing("frontend")
c.Args = args
if err := c.validate(); err == nil {
t.Fatalf("invalid args accepted: %q", args)
}
}
}
func TestRenderCLI(t *testing.T) {
front := passing("frontend")
front.Domains = []string{"Z.Example.com", "a.example.com"}
front.Args = " --lua-desync=fake:blob=tls_clienthello --lua-desync=multisplit:pos=1 "
path := filepath.Join(t.TempDir(), "results.json")
if err := os.WriteFile(path, []byte(encodeCandidates(t, front, passing("googlevideo"))+"\n "), 0600); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
if code := run([]string{"render", path}, &stdout, &stderr); code != 0 || stderr.Len() != 0 {
t.Fatalf("code %d, stderr %q", code, stderr.String())
}
want := "NFQWS2_OPT='--filter-tcp=443 --filter-l7=tls --hostlist-domains=a.example.com,z.example.com " + front.Args + " --new --filter-tcp=443 --filter-l7=tls --hostlist-domains=googlevideo.example.com --lua-desync=fake:blob=tls_clienthello'\n"
if stdout.String() != want {
t.Fatalf("got %q, want %q", stdout.String(), want)
}
if run([]string{"render", path}, failingWriter{}, &stderr) != 1 {
t.Error("write failure must fail")
}
stdout.Reset()
if run([]string{"render", path + ".missing"}, &stdout, &stderr) != 1 || stdout.Len() != 0 {
t.Error("missing file must fail without output")
}
if err := os.WriteFile(path, []byte("[]"), 0600); err != nil {
t.Fatal(err)
}
if run([]string{"render", path}, &stdout, &stderr) != 1 || stdout.Len() != 0 {
t.Error("no candidates must fail without output")
}
for _, args := range [][]string{{"render"}, {"render", path, "extra"}} {
if run(args, &stdout, &stderr) != 2 {
t.Error("wrong arity must return usage error")
}
}
}