Preserve configured proxy DNS semantics while reusing strict URL and loopback validation. Cover proxy forwarding, legacy socks5, and unsafe endpoints with offline tests; document the managed DoH boundary. Co-authored-by: GPT-6 <gpt-6@openai.com>
211 lines
9.0 KiB
Go
211 lines
9.0 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func configLookup(values map[string]string) func(string) (string, bool) {
|
|
return func(key string) (string, bool) {
|
|
value, ok := values[key]
|
|
return value, ok
|
|
}
|
|
}
|
|
|
|
func TestHealthConfigDefaultsAndOverrides(t *testing.T) {
|
|
cfg, err := parseHealthConfig(configLookup(nil))
|
|
want := healthConfig{SOCKSProxy: "socks5://127.0.0.1:11080", VideoID: "dQw4w9WgXcQ", HealthInterval: 5 * time.Minute, FailureThreshold: 3, RecoveryCooldown: 30 * time.Minute}
|
|
if err != nil || !reflect.DeepEqual(cfg, want) {
|
|
t.Fatalf("defaults = %+v, %v; want %+v", cfg, err, want)
|
|
}
|
|
values := map[string]string{
|
|
"ZAPRET_AUTOTUNE_SOCKS_PROXY": "socks5://[::1]:12080",
|
|
"ZAPRET_AUTOTUNE_VIDEO_ID": "abcdefghijk",
|
|
"ZAPRET_AUTOTUNE_HEALTH_INTERVAL": "90s",
|
|
"ZAPRET_AUTOTUNE_FAILURE_THRESHOLD": "5",
|
|
"ZAPRET_AUTOTUNE_RECOVERY_COOLDOWN": "1h",
|
|
}
|
|
cfg, err = parseHealthConfig(configLookup(values))
|
|
want = healthConfig{SOCKSProxy: "socks5://[::1]:12080", VideoID: "abcdefghijk", HealthInterval: 90 * time.Second, FailureThreshold: 5, RecoveryCooldown: time.Hour}
|
|
if err != nil || !reflect.DeepEqual(cfg, want) {
|
|
t.Fatalf("overrides = %+v, %v; want %+v", cfg, err, want)
|
|
}
|
|
for _, proxy := range []string{"socks5://localhost:1", "socks5://LOCALHOST:65535", "socks5://127.0.0.2:11080", "socks5://[::1]:11080", "socks5h://localhost:1", "socks5h://LOCALHOST:65535", "socks5h://127.0.0.2:11080", "socks5h://[::1]:11080"} {
|
|
if cfg, err := parseHealthConfig(configLookup(map[string]string{"ZAPRET_AUTOTUNE_SOCKS_PROXY": proxy})); err != nil || cfg.SOCKSProxy != proxy {
|
|
t.Errorf("valid loopback rejected: %s: %v", proxy, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestHealthConfigRejectsInvalid(t *testing.T) {
|
|
invalid := map[string][]string{
|
|
"ZAPRET_AUTOTUNE_SOCKS_PROXY": {
|
|
"", "http://127.0.0.1:11080", "https://127.0.0.1:11080", "socks4://127.0.0.1:11080",
|
|
"socks5://192.168.1.1:11080", "socks5://0.0.0.0:11080", "socks5://[::]:11080",
|
|
"socks5://proxy.example:11080", "socks5://localhost.evil:11080",
|
|
"socks5://user:SECRET@localhost:11080", "socks5://localhost", "socks5://localhost:0",
|
|
"socks5://localhost:65536", "socks5://localhost:bad", "socks5://localhost:11080/path",
|
|
"socks5://localhost:11080?SECRET", "socks5://localhost:11080#SECRET", " socks5://localhost:11080",
|
|
"socks5://@localhost:11080", "socks5://SECRET@localhost:11080", "socks5://localhost:11080?", "socks5://localhost:11080#",
|
|
"socks5://localhost:11080\x00", "socks5://localhost:11080\x1f", "socks5://localhost:11080\x7f",
|
|
},
|
|
"ZAPRET_AUTOTUNE_VIDEO_ID": {"", "short", "dQw4w9WgXc!"},
|
|
"ZAPRET_AUTOTUNE_HEALTH_INTERVAL": {"", "0", "-5m", "5", "SECRET", "999999999999999999999h"},
|
|
"ZAPRET_AUTOTUNE_RECOVERY_COOLDOWN": {"", "0s", "-30m", "SECRET"},
|
|
"ZAPRET_AUTOTUNE_FAILURE_THRESHOLD": {"", "0", "-3", "1.5", "SECRET", "999999999999999999999"},
|
|
}
|
|
for key, values := range invalid {
|
|
if key == "ZAPRET_AUTOTUNE_SOCKS_PROXY" {
|
|
for _, value := range values {
|
|
if strings.HasPrefix(value, "socks5://") {
|
|
values = append(values, strings.Replace(value, "socks5://", "socks5h://", 1))
|
|
}
|
|
}
|
|
}
|
|
for _, value := range values {
|
|
if _, err := parseHealthConfig(configLookup(map[string]string{key: value})); err == nil || !strings.Contains(err.Error(), key) || strings.Contains(err.Error(), "SECRET") {
|
|
t.Errorf("%s=%q: expected sanitized config error, got %v", key, value, err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestPlayerHealth(t *testing.T) {
|
|
for _, body := range []string{
|
|
`{"playabilityStatus":{"status":"OK"}}`,
|
|
`{"playabilityStatus":{"status":"OK"},"streamingData":{"serverAbrStreamingUrl":"invalid"}}`,
|
|
} {
|
|
if err := playerHealth([]byte(body)); err != nil {
|
|
t.Errorf("OK must not require a streaming URL: %v", err)
|
|
}
|
|
}
|
|
for _, body := range []string{
|
|
`{"playabilityStatus":{"status":"LOGIN_REQUIRED","reason":"SECRET"}}`,
|
|
`{"playabilityStatus":{"status":"UNPLAYABLE"}}`, `{"playabilityStatus":{"status":"ok"}}`,
|
|
`{}`, `null`, `{"playabilityStatus":null}`, `{"playabilityStatus":{}}`,
|
|
`{"playabilityStatus":{"status":null}}`, `{"playabilityStatus":{"status":42}}`,
|
|
`{"playabilityStatus":"OK"}`, `not JSON SECRET`, `{"playabilityStatus":{"status":"OK"}} trailing`,
|
|
strings.Repeat(" ", playerResponseLimit+1),
|
|
} {
|
|
if err := playerHealth([]byte(body)); err == nil || strings.Contains(err.Error(), "SECRET") {
|
|
t.Errorf("invalid/non-OK response accepted or leaked: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func setHealthEnvironment(t *testing.T) {
|
|
t.Helper()
|
|
for key, value := range map[string]string{
|
|
"ZAPRET_AUTOTUNE_SOCKS_PROXY": "socks5://127.0.0.1:11080",
|
|
"ZAPRET_AUTOTUNE_VIDEO_ID": "dQw4w9WgXcQ",
|
|
"ZAPRET_AUTOTUNE_HEALTH_INTERVAL": "5m",
|
|
"ZAPRET_AUTOTUNE_FAILURE_THRESHOLD": "3",
|
|
"ZAPRET_AUTOTUNE_RECOVERY_COOLDOWN": "30m",
|
|
} {
|
|
t.Setenv(key, value)
|
|
}
|
|
}
|
|
|
|
func TestRunHealthYoutube(t *testing.T) {
|
|
for _, proxy := range []string{"socks5://[::1]:12080", "socks5h://[::1]:12080", "socks5h://127.0.0.1:11082"} {
|
|
t.Run(proxy, func(t *testing.T) {
|
|
setHealthEnvironment(t)
|
|
t.Setenv("ZAPRET_AUTOTUNE_SOCKS_PROXY", proxy)
|
|
t.Setenv("ZAPRET_AUTOTUNE_VIDEO_ID", "abcdefghijk")
|
|
for _, key := range []string{"ALL_PROXY", "HTTPS_PROXY", "https_proxy", "all_proxy"} {
|
|
t.Setenv(key, "http://untrusted.example:8080")
|
|
}
|
|
t.Setenv("NO_PROXY", "*")
|
|
var stdout, stderr bytes.Buffer
|
|
calls := 0
|
|
runner := func(ctx context.Context, args []string, out, diagnostics io.Writer) error {
|
|
calls++
|
|
deadline, ok := ctx.Deadline()
|
|
if !ok || time.Until(deadline) <= 0 || time.Until(deadline) > 35*time.Second {
|
|
t.Error("request must have bounded deadline")
|
|
}
|
|
prefix := []string{"--disable", "--silent", "--show-error", "--fail", "--max-time", "30", "--noproxy", "", "--proxy", proxy, "--user-agent", playerUserAgent, "--json"}
|
|
if len(args) != len(prefix)+2 || !reflect.DeepEqual(args[:len(prefix)], prefix) || args[len(args)-1] != playerURL {
|
|
t.Fatalf("unexpected proxy/API arguments: %q", args)
|
|
}
|
|
var payload struct {
|
|
VideoID string `json:"videoId"`
|
|
}
|
|
if err := json.Unmarshal([]byte(args[len(prefix)]), &payload); err != nil || payload.VideoID != "abcdefghijk" {
|
|
t.Fatalf("unexpected video payload: %+v %v", payload, err)
|
|
}
|
|
io.WriteString(diagnostics, "SECRET")
|
|
_, err := io.WriteString(out, `{"playabilityStatus":{"status":"OK"}}`)
|
|
return err
|
|
}
|
|
if code := runWithPlayer([]string{"health", "youtube"}, &stdout, &stderr, runner); code != 0 || calls != 1 || stderr.Len() != 0 || !strings.Contains(stdout.String(), "Player API: OK (not a playback check)") {
|
|
t.Fatalf("code=%d calls=%d stdout=%q stderr=%q", code, calls, &stdout, &stderr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestHealthYoutubeFailures(t *testing.T) {
|
|
setHealthEnvironment(t)
|
|
for _, mode := range []string{"blocked", "missing", "invalid", "runner", "stdout limit", "stderr limit", "write result"} {
|
|
t.Run(mode, func(t *testing.T) {
|
|
var stdout, stderr bytes.Buffer
|
|
calls := 0
|
|
runner := func(_ context.Context, _ []string, out, diagnostics io.Writer) error {
|
|
calls++
|
|
io.WriteString(diagnostics, "SECRET")
|
|
switch mode {
|
|
case "blocked":
|
|
io.WriteString(out, `{"playabilityStatus":{"status":"UNPLAYABLE","reason":"SECRET"}}`)
|
|
case "missing":
|
|
io.WriteString(out, `{}`)
|
|
case "invalid":
|
|
io.WriteString(out, `SECRET`)
|
|
case "runner":
|
|
return errors.New("SECRET")
|
|
case "stdout limit":
|
|
out.Write(bytes.Repeat([]byte("S"), playerResponseLimit+1))
|
|
case "stderr limit":
|
|
diagnostics.Write(bytes.Repeat([]byte("S"), (64<<10)+1))
|
|
default:
|
|
io.WriteString(out, `{"playabilityStatus":{"status":"OK"}}`)
|
|
}
|
|
return nil
|
|
}
|
|
var dest io.Writer = &stdout
|
|
if mode == "write result" {
|
|
dest = failingWriter{}
|
|
}
|
|
if code := runWithPlayer([]string{"health", "youtube"}, dest, &stderr, runner); code != 1 || calls != 1 || stdout.Len() != 0 || stderr.Len() == 0 || strings.Contains(stderr.String(), "SECRET") {
|
|
t.Fatalf("code=%d calls=%d stdout=%q stderr=%q", code, calls, &stdout, &stderr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestHealthDispatchAndConfigFailWithoutRequest(t *testing.T) {
|
|
setHealthEnvironment(t)
|
|
runner := func(context.Context, []string, io.Writer, io.Writer) error {
|
|
t.Fatal("invalid command/config must not request or fall back")
|
|
return nil
|
|
}
|
|
for _, args := range [][]string{{"health"}, {"health", "other"}, {"health", "youtube", "extra"}, {"health", "youtube", "--proxy", "socks5://localhost:1080"}} {
|
|
var stdout, stderr bytes.Buffer
|
|
if code := runWithPlayer(args, &stdout, &stderr, runner); code != 2 || stdout.Len() != 0 || !strings.Contains(stderr.String(), usage) {
|
|
t.Fatalf("args=%q code=%d stdout=%q stderr=%q", args, code, &stdout, &stderr)
|
|
}
|
|
}
|
|
t.Setenv("ZAPRET_AUTOTUNE_SOCKS_PROXY", "socks5://remote.example:11080")
|
|
var stdout, stderr bytes.Buffer
|
|
if code := runWithPlayer([]string{"health", "youtube"}, &stdout, &stderr, runner); code != 2 || stdout.Len() != 0 || !strings.Contains(stderr.String(), "ZAPRET_AUTOTUNE_SOCKS_PROXY") {
|
|
t.Fatalf("invalid config: code=%d stdout=%q stderr=%q", code, &stdout, &stderr)
|
|
}
|
|
}
|