feat(health): add managed SOCKS probe configuration
Co-authored-by: GPT-6 <gpt-6@openai.com>
This commit is contained in:
1 parent
69077fb708
commit
5c540ce03b
7 files changed
+392
-24
No files matched your search
+4
-3
@@ -4,11 +4,12 @@
|
|||||||
|
|
||||||
## Готово
|
## Готово
|
||||||
|
|
||||||
|
- Добавлен одноразовый `health youtube`: bounded Player API-запрос только через явно заданный loopback SOCKS (`ZAPRET_AUTOTUNE_SOCKS_PROXY`, default `socks5://127.0.0.1:11080`), без ambient proxy/direct fallback. Health требует только `playabilityStatus.status=OK`, не streaming URL и не playback. Config валидирует video ID (default `dQw4w9WgXcQ`) и будущую policy: interval `5m`, failure threshold `3`, cooldown `30m`. Добавлены injectable unit-тесты config/health/CLI; проверки этого increment отложены оркестратору, тесты/build/network здесь не запускались. Autonomous monitor/apply/rollback не добавлены, контейнеры не изменены.
|
||||||
- Завершён удалённый ручной GGC scan для `rr16---sn-n8v7znsz.googlevideo.com`: TLS 1.2 — 1 525 рабочих стратегий, TLS 1.3 — 800. Shortlist check нашёл 20 проходящих вариантов; точная объединённая стратегия `--lua-init=fake_default_tls=tls_mod(fake_default_tls,'rnd') --payload=tls_client_hello --lua-desync=multidisorder:pos=2,midsld:seqovl=1:seqovl_pattern=fake_default_tls --in-range=-s1 --lua-desync=oob:urp=midsld` прошла по 3/3 для TLS 1.2 и TLS 1.3. Результат относится только к указанному hostname; не означает playback/SABR и не применялся.
|
- Завершён удалённый ручной GGC scan для `rr16---sn-n8v7znsz.googlevideo.com`: TLS 1.2 — 1 525 рабочих стратегий, TLS 1.3 — 800. Shortlist check нашёл 20 проходящих вариантов; точная объединённая стратегия `--lua-init=fake_default_tls=tls_mod(fake_default_tls,'rnd') --payload=tls_client_hello --lua-desync=multidisorder:pos=2,midsld:seqovl=1:seqovl_pattern=fake_default_tls --in-range=-s1 --lua-desync=oob:urp=midsld` прошла по 3/3 для TLS 1.2 и TLS 1.3. Результат относится только к указанному hostname; не означает playback/SABR и не применялся.
|
||||||
- Добавлена proposal-only команда `recover googlevideo --video-id ID --proxy socks5://HOST:PORT`: discovery одного свежего exact host → qualified schema-v3 сценарии newest-first → combined TLS1.2/1.3 3/3 точных сохранённых args. Первый успешный сценарий сохраняется новым immutable candidate/run и выдаётся как NOT ACTIVE без scan. Только отсутствие eligible candidates или валидные non-pass результаты разрешают обычный scan на уже найденном host; infrastructure/malformed-report ошибки fail closed. Apply/monitor и удалённый scan не затронуты.
|
- Добавлена proposal-only команда `recover googlevideo --video-id ID --proxy socks5://HOST:PORT`: discovery одного свежего exact host → qualified schema-v3 сценарии newest-first → combined TLS1.2/1.3 3/3 точных сохранённых args. Первый успешный сценарий сохраняется новым immutable candidate/run и выдаётся как NOT ACTIVE без scan. Только отсутствие eligible candidates или валидные non-pass результаты разрешают обычный scan на уже найденном host; infrastructure/malformed-report ошибки fail closed. Apply/monitor и удалённый scan не затронуты.
|
||||||
- Unit-тесты recovery порядка, fresh-host scope, short-circuit, fallback и fail-closed ошибок прошли; локальные `go test ./...`, `go build` и `git diff --check` успешны.
|
- Unit-тесты recovery порядка, fresh-host scope, short-circuit, fallback и fail-closed ошибок прошли; локальные `go test ./...`, `go build` и `git diff --check` успешны.
|
||||||
|
|
||||||
- CLI на Go: `tune youtube`, `tune googlevideo --video-id ID --proxy socks5://HOST:PORT`, `recover googlevideo --video-id ID --proxy socks5://HOST:PORT`, `discover youtube`, `status`, `history`, `strategies youtube`, `render`. `check youtube` пока намеренно отказывает; `apply`, `rollback` и мониторинг не реализованы.
|
- CLI на Go: `tune youtube`, `tune googlevideo --video-id ID --proxy socks5://HOST:PORT`, `recover googlevideo --video-id ID --proxy socks5://HOST:PORT`, `discover youtube`, `health youtube`, `status`, `history`, `strategies youtube`, `render`. `check youtube` пока намеренно отказывает; `apply`, `rollback` и мониторинг не реализованы.
|
||||||
- Proposal-only GGC pipeline: Android 21.02.35 discovery через явный proxy → scan TLS1.2/1.3 только одного найденного hostname → data-transfer shortlist (`--take 10 --passes 3`) → проверка точной комбинации 3/3 на обоих TLS → один инертный профиль с exact-host фильтром. Ранжирование по blockcheckw, не Selectel. SQLite v3 атомарно сохраняет googlevideo candidate и оба endpoint×TLS evidence; отдельный additive journal сохраняет failed runs. `history` и `strategies youtube` показывают точный endpoint/group; `status` пока относится только к frontend journal.
|
- Proposal-only GGC pipeline: Android 21.02.35 discovery через явный proxy → scan TLS1.2/1.3 только одного найденного hostname → data-transfer shortlist (`--take 10 --passes 3`) → проверка точной комбинации 3/3 на обоих TLS → один инертный профиль с exact-host фильтром. Ранжирование по blockcheckw, не Selectel. SQLite v3 атомарно сохраняет googlevideo candidate и оба endpoint×TLS evidence; отдельный additive journal сохраняет failed runs. `history` и `strategies youtube` показывают точный endpoint/group; `status` пока относится только к frontend journal.
|
||||||
- Добавлены injectable unit-тесты GGC success/order/scope/filter/persistence, обязательных флагов, discovery failure, неполной/неуспешной combined проверки и fail-closed DB. После исправления exact-host фильтра `go test ./...`, `go build` и `git diff --check` прошли локально. Полный новый `tune googlevideo` ещё не прогонялся удалённо.
|
- Добавлены injectable unit-тесты GGC success/order/scope/filter/persistence, обязательных флагов, discovery failure, неполной/неуспешной combined проверки и fail-closed DB. После исправления exact-host фильтра `go test ./...`, `go build` и `git diff --check` прошли локально. Полный новый `tune googlevideo` ещё не прогонялся удалённо.
|
||||||
- `tune youtube` сканирует frontend `youtube.com`, проверяет shortlist через `blockcheckw` и выдаёт один TLS-профиль только после совместной проверки TLS 1.2 и 1.3 по 3/3. Это предложение конфигурации, оно ничего не применяет.
|
- `tune youtube` сканирует frontend `youtube.com`, проверяет shortlist через `blockcheckw` и выдаёт один TLS-профиль только после совместной проверки TLS 1.2 и 1.3 по 3/3. Это предложение конфигурации, оно ничего не применяет.
|
||||||
@@ -32,13 +33,13 @@
|
|||||||
## Не готово
|
## Не готово
|
||||||
|
|
||||||
- Проверка реального YouTube video-transfer/SABR. Прямой GET `serverAbrStreamingUrl` возвращает `sabr.malformed_config`; hostname discovery и `blockcheckw` data-transfer checks не равны проверке воспроизведения видео.
|
- Проверка реального YouTube video-transfer/SABR. Прямой GET `serverAbrStreamingUrl` возвращает `sabr.malformed_config`; hostname discovery и `blockcheckw` data-transfer checks не равны проверке воспроизведения видео.
|
||||||
- Управляемое применение конфигурации, проверка после применения, rollback, активный профиль и health-check сервиса. Пользователь подтвердил целевую модель: новый отдельный prod-like контейнер в тестовой среде; существующий контейнер не трогать. Health policy должна настраиваться переменными (предложенные defaults: Player API каждые 5 минут, 3 последовательные ошибки, cooldown 30 минут). Перед реализацией/запуском контроллера пройти deployment/route/rollback gates из `Architecture.md`.
|
- Управляемое применение конфигурации, проверка после применения, rollback, активный профиль и автономный health monitor сервиса. Одноразовый Player API health и config policy уже есть, но interval/threshold/cooldown пока не запускают автоматизацию. Пользователь подтвердил целевую модель: новый отдельный prod-like zapret2-ss контейнер только в тестовой среде; существующий контейнер не трогать. Target должен иметь стабильный настраиваемый loopback SOCKS endpoint для same-host Xray; Xray config вне scope, пользователь настроит отдельно. Перед реализацией/запуском контроллера пройти deployment/route/rollback gates из `Architecture.md`.
|
||||||
- Полный сервис из требований: YAML-конфигурация сервисов, endpoint-история/покрытие, daemon/периодический мониторинг, API/метрики и multi-service режим.
|
- Полный сервис из требований: YAML-конфигурация сервисов, endpoint-история/покрытие, daemon/периодический мониторинг, API/метрики и multi-service режим.
|
||||||
|
|
||||||
## Открытые ограничения и следующие шаги
|
## Открытые ограничения и следующие шаги
|
||||||
|
|
||||||
1. Проверить новый `tune googlevideo` и `recover googlevideo` end-to-end на удалённом сервере; отдельно решить, как импортировать или переиспользовать уже полученные scan результаты без повторного перебора.
|
1. Проверить новый `tune googlevideo` и `recover googlevideo` end-to-end на удалённом сервере; отдельно решить, как импортировать или переиспользовать уже полученные scan результаты без повторного перебора.
|
||||||
2. Подготовить воспроизводимое описание отдельного prod-like target с закреплённым image digest, собственной bridge-сетью, независимой конфигурацией/секретами и только loopback-портами. До запуска проверить формат baseline-конфига и правила NFQUEUE внутри container network namespace; текущие mounts, сеть, порты и конфиг не переиспользовать.
|
2. Подготовить воспроизводимое описание отдельного prod-like target с закреплённым image digest, собственной bridge-сетью, независимой конфигурацией/секретами и только loopback-портами. До запуска проверить формат baseline-конфига и правила NFQUEUE внутри container network namespace; текущие mounts, сеть, порты и конфиг не переиспользовать.
|
||||||
3. Реализовать ограниченный apply helper с backup, проверкой активной конфигурации, post-apply probe и автоматическим rollback; затем добавить настраиваемые health interval/failure threshold/cooldown и monitor recovery.
|
3. Реализовать ограниченный apply helper с backup, проверкой активной конфигурации, post-apply probe и автоматическим rollback; затем подключить уже настраиваемые health interval/failure threshold/cooldown к monitor recovery.
|
||||||
4. До включения автоматического apply доказать safety gates из `Architecture.md`: изоляцию target, эквивалентность сетевого пути, версионирование, atomic activation/rollback и crash recovery.
|
4. До включения автоматического apply доказать safety gates из `Architecture.md`: изоляцию target, эквивалентность сетевого пути, версионирование, atomic activation/rollback и crash recovery.
|
||||||
5. Отдельно определить реальную video/SABR-проверку и traffic budget; не считать Selectel speedtest или blockcheck TLS тест заменой YouTube playback.
|
5. Отдельно определить реальную video/SABR-проверку и traffic budget; не считать Selectel speedtest или blockcheck TLS тест заменой YouTube playback.
|
||||||
@@ -2,6 +2,45 @@
|
|||||||
|
|
||||||
Go CLI for scanning and checking YouTube TLS bypass strategies with `blockcheckw`.
|
Go CLI for scanning and checking YouTube TLS bypass strategies with `blockcheckw`.
|
||||||
|
|
||||||
|
## One-shot Player API health
|
||||||
|
|
||||||
|
```sh
|
||||||
|
zapret-autotune health youtube
|
||||||
|
```
|
||||||
|
|
||||||
|
This makes one bounded Android Player API request through the explicitly
|
||||||
|
configured **loopback SOCKS5** endpoint. Healthy means only
|
||||||
|
`playabilityStatus.status == "OK"`; no streaming URL is required and no media is
|
||||||
|
fetched. **API health is not playback health.** Non-OK/missing status, malformed
|
||||||
|
responses and request failures return exit 1; invalid config returns exit 2.
|
||||||
|
Curl configuration and proxy bypasses are disabled; ambient proxy settings are
|
||||||
|
not used and there is no direct fallback. The request times out after 30 seconds
|
||||||
|
(35-second process deadline), with a 1 MiB response limit and sanitized errors.
|
||||||
|
|
||||||
|
| Environment variable | Default |
|
||||||
|
| --- | --- |
|
||||||
|
| `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` |
|
||||||
|
|
||||||
|
Configuration is parsed once per health invocation. The proxy must use `socks5`
|
||||||
|
with a loopback IP or `localhost`, port 1–65535, and no credentials/path/query.
|
||||||
|
Video IDs must be 11 characters; durations and the failure threshold must be
|
||||||
|
positive. Explicit empty values are invalid. Interval, consecutive-failure
|
||||||
|
threshold and cooldown are validated future recovery policy settings only:
|
||||||
|
**there is no scheduler, autonomous monitoring or recovery yet**.
|
||||||
|
|
||||||
|
The future managed target is a **brand-new prod-like zapret2-ss container in the
|
||||||
|
test environment only**, not the existing container. Its stable configurable
|
||||||
|
SOCKS endpoint must be loopback-accessible to this probe and same-host Xray.
|
||||||
|
This increment does not create or change any container, persist health, apply
|
||||||
|
configuration, restart services or roll back anything. Xray configuration is
|
||||||
|
out of scope and will be configured separately by the user. Run this command in
|
||||||
|
the host network context where that loopback endpoint is reachable; Docker
|
||||||
|
`localhost` otherwise refers to the CLI container itself.
|
||||||
|
|
||||||
## Exact cache-host proposal
|
## Exact cache-host proposal
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type healthConfig struct {
|
||||||
|
SOCKSProxy string
|
||||||
|
VideoID string
|
||||||
|
HealthInterval time.Duration
|
||||||
|
FailureThreshold int
|
||||||
|
RecoveryCooldown time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseHealthConfig(lookup func(string) (string, bool)) (healthConfig, error) {
|
||||||
|
value := func(key, fallback string) string {
|
||||||
|
if v, ok := lookup(key); ok {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
cfg := healthConfig{
|
||||||
|
SOCKSProxy: value("ZAPRET_AUTOTUNE_SOCKS_PROXY", "socks5://127.0.0.1:11080"),
|
||||||
|
VideoID: value("ZAPRET_AUTOTUNE_VIDEO_ID", "dQw4w9WgXcQ"),
|
||||||
|
}
|
||||||
|
if !validLoopbackSOCKS(cfg.SOCKSProxy) {
|
||||||
|
return healthConfig{}, fmt.Errorf("ZAPRET_AUTOTUNE_SOCKS_PROXY requires socks5://LOOPBACK:PORT without credentials")
|
||||||
|
}
|
||||||
|
if !videoIDPattern.MatchString(cfg.VideoID) {
|
||||||
|
return healthConfig{}, fmt.Errorf("ZAPRET_AUTOTUNE_VIDEO_ID requires an 11-character video ID")
|
||||||
|
}
|
||||||
|
for _, setting := range []struct {
|
||||||
|
key string
|
||||||
|
fallback string
|
||||||
|
dest *time.Duration
|
||||||
|
}{
|
||||||
|
{"ZAPRET_AUTOTUNE_HEALTH_INTERVAL", "5m", &cfg.HealthInterval},
|
||||||
|
{"ZAPRET_AUTOTUNE_RECOVERY_COOLDOWN", "30m", &cfg.RecoveryCooldown},
|
||||||
|
} {
|
||||||
|
duration, err := time.ParseDuration(value(setting.key, setting.fallback))
|
||||||
|
if err != nil || duration <= 0 {
|
||||||
|
return healthConfig{}, fmt.Errorf("%s requires a positive duration", setting.key)
|
||||||
|
}
|
||||||
|
*setting.dest = duration
|
||||||
|
}
|
||||||
|
threshold, err := strconv.Atoi(value("ZAPRET_AUTOTUNE_FAILURE_THRESHOLD", "3"))
|
||||||
|
if err != nil || threshold <= 0 {
|
||||||
|
return healthConfig{}, fmt.Errorf("ZAPRET_AUTOTUNE_FAILURE_THRESHOLD requires a positive integer")
|
||||||
|
}
|
||||||
|
cfg.FailureThreshold = threshold
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validLoopbackSOCKS(raw string) bool {
|
||||||
|
if !validDiscoveryProxy(raw) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
host := u.Hostname()
|
||||||
|
return strings.EqualFold(host, "localhost") || net.ParseIP(host).IsLoopback()
|
||||||
|
}
|
||||||
@@ -120,26 +120,12 @@ func discoverYoutube(args []string, stdout, stderr io.Writer, runner playerRunne
|
|||||||
fmt.Fprintln(stderr, "error: discover youtube", err)
|
fmt.Fprintln(stderr, "error: discover youtube", err)
|
||||||
return 2
|
return 2
|
||||||
}
|
}
|
||||||
payload, _ := json.Marshal(map[string]interface{}{
|
body, err := requestPlayer(videoID, proxy, runner)
|
||||||
"videoId": videoID,
|
if err != nil {
|
||||||
"context": map[string]interface{}{"client": map[string]interface{}{
|
fmt.Fprintln(stderr, "error:", err)
|
||||||
"clientName": "ANDROID", "clientVersion": "21.02.35", "androidSdkVersion": 30,
|
|
||||||
"userAgent": playerUserAgent, "osName": "Android", "osVersion": "11",
|
|
||||||
}},
|
|
||||||
})
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
var body bytes.Buffer
|
|
||||||
output := &playerBoundedWriter{dst: &body, limit: playerResponseLimit}
|
|
||||||
diagnostics := &playerBoundedWriter{dst: io.Discard, limit: 64 << 10}
|
|
||||||
// Disable curlrc and NO_PROXY bypasses: the explicit proxy must be used.
|
|
||||||
err = runner(ctx, []string{"--disable", "--silent", "--show-error", "--fail", "--max-time", "30",
|
|
||||||
"--noproxy", "", "--proxy", proxy, "--user-agent", playerUserAgent, "--json", string(payload), playerURL}, output, diagnostics)
|
|
||||||
if err != nil || output.exceeded || diagnostics.exceeded {
|
|
||||||
fmt.Fprintln(stderr, "error: player request failed or exceeded output limit")
|
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
host, err := playerHostname(body.Bytes())
|
host, err := playerHostname(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintln(stderr, "error:", err)
|
fmt.Fprintln(stderr, "error:", err)
|
||||||
return 1
|
return 1
|
||||||
@@ -154,3 +140,25 @@ func discoverYoutube(args []string, stdout, stderr io.Writer, runner playerRunne
|
|||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func requestPlayer(videoID, proxy string, runner playerRunner) ([]byte, error) {
|
||||||
|
payload, _ := json.Marshal(map[string]interface{}{
|
||||||
|
"videoId": videoID,
|
||||||
|
"context": map[string]interface{}{"client": map[string]interface{}{
|
||||||
|
"clientName": "ANDROID", "clientVersion": "21.02.35", "androidSdkVersion": 30,
|
||||||
|
"userAgent": playerUserAgent, "osName": "Android", "osVersion": "11",
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
var body bytes.Buffer
|
||||||
|
output := &playerBoundedWriter{dst: &body, limit: playerResponseLimit}
|
||||||
|
diagnostics := &playerBoundedWriter{dst: io.Discard, limit: 64 << 10}
|
||||||
|
// Disable curlrc and NO_PROXY bypasses: the explicit proxy must be used.
|
||||||
|
err := runner(ctx, []string{"--disable", "--silent", "--show-error", "--fail", "--max-time", "30",
|
||||||
|
"--noproxy", "", "--proxy", proxy, "--user-agent", playerUserAgent, "--json", string(payload), playerURL}, output, diagnostics)
|
||||||
|
if err != nil || output.exceeded || diagnostics.exceeded {
|
||||||
|
return nil, errors.New("player request failed or exceeded output limit")
|
||||||
|
}
|
||||||
|
return body.Bytes(), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
// API health is deliberately independent of streaming URLs and playback.
|
||||||
|
func playerHealth(body []byte) error {
|
||||||
|
var response struct {
|
||||||
|
PlayabilityStatus struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
} `json:"playabilityStatus"`
|
||||||
|
}
|
||||||
|
if len(body) > playerResponseLimit || json.Unmarshal(body, &response) != nil {
|
||||||
|
return errors.New("invalid player response")
|
||||||
|
}
|
||||||
|
if response.PlayabilityStatus.Status != "OK" {
|
||||||
|
return errors.New("player API is unhealthy: missing or non-OK playability status")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func healthYoutube(stdout, stderr io.Writer, runner playerRunner) int {
|
||||||
|
cfg, err := parseHealthConfig(os.LookupEnv)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(stderr, "error:", err)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
body, err := requestPlayer(cfg.VideoID, cfg.SOCKSProxy, runner)
|
||||||
|
if err == nil {
|
||||||
|
err = playerHealth(body)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(stderr, "error:", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if _, err := fmt.Fprintln(stdout, "YouTube Player API: OK (not a playback check)"); err != nil {
|
||||||
|
fmt.Fprintln(stderr, "error: cannot write health result")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
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{"socks5://127.0.0.1:11080", "dQw4w9WgXcQ", 5 * time.Minute, 3, 30 * time.Minute}
|
||||||
|
if err != nil || 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{"socks5://[::1]:12080", "abcdefghijk", 90 * time.Second, 5, time.Hour}
|
||||||
|
if err != nil || 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"} {
|
||||||
|
if _, err := parseHealthConfig(configLookup(map[string]string{"ZAPRET_AUTOTUNE_SOCKS_PROXY": proxy})); err != nil {
|
||||||
|
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", "socks5h://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",
|
||||||
|
},
|
||||||
|
"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 {
|
||||||
|
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) {
|
||||||
|
setHealthEnvironment(t)
|
||||||
|
t.Setenv("ZAPRET_AUTOTUNE_SOCKS_PROXY", "socks5://[::1]:12080")
|
||||||
|
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", "socks5://[::1]:12080", "--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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ Commands:
|
|||||||
strategies youtube List recorded proposals by group (not active)
|
strategies youtube List recorded proposals by group (not active)
|
||||||
discover youtube --video-id ID --proxy socks5://HOST:PORT
|
discover youtube --video-id ID --proxy socks5://HOST:PORT
|
||||||
Discover cache hostname only (no media-transfer check)
|
Discover cache hostname only (no media-transfer check)
|
||||||
|
health youtube One-shot Player API health through configured loopback SOCKS
|
||||||
check youtube Refuse checks until probe URLs/video IDs are configured and agreed
|
check youtube Refuse checks until probe URLs/video IDs are configured and agreed
|
||||||
tune youtube Test youtube.com frontend only; print options without applying
|
tune youtube Test youtube.com frontend only; print options without applying
|
||||||
tune googlevideo --video-id ID --proxy socks5://HOST:PORT
|
tune googlevideo --video-id ID --proxy socks5://HOST:PORT
|
||||||
@@ -28,11 +29,18 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func run(args []string, stdout, stderr io.Writer) int {
|
func run(args []string, stdout, stderr io.Writer) int {
|
||||||
|
return runWithPlayer(args, stdout, stderr, runPlayerCurl)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runWithPlayer(args []string, stdout, stderr io.Writer, player playerRunner) int {
|
||||||
|
if len(args) == 2 && args[0] == "health" && args[1] == "youtube" {
|
||||||
|
return healthYoutube(stdout, stderr, player)
|
||||||
|
}
|
||||||
if len(args) >= 2 && args[0] == "recover" && args[1] == "googlevideo" {
|
if len(args) >= 2 && args[0] == "recover" && args[1] == "googlevideo" {
|
||||||
return recoverGooglevideo(args[2:], stdout, stderr, runPlayerCurl, runBlockcheck, runCombinedBlockcheckForHost)
|
return recoverGooglevideo(args[2:], stdout, stderr, player, runBlockcheck, runCombinedBlockcheckForHost)
|
||||||
}
|
}
|
||||||
if len(args) >= 2 && args[0] == "tune" && args[1] == "googlevideo" {
|
if len(args) >= 2 && args[0] == "tune" && args[1] == "googlevideo" {
|
||||||
return tuneGooglevideo(args[2:], stdout, stderr, runPlayerCurl, runBlockcheck, runCombinedBlockcheckForHost)
|
return tuneGooglevideo(args[2:], stdout, stderr, player, runBlockcheck, runCombinedBlockcheckForHost)
|
||||||
}
|
}
|
||||||
if len(args) > 0 && args[0] == "history" {
|
if len(args) > 0 && args[0] == "history" {
|
||||||
return history(args[1:], stdout, stderr)
|
return history(args[1:], stdout, stderr)
|
||||||
@@ -74,7 +82,7 @@ func run(args []string, stdout, stderr io.Writer) int {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(args) >= 2 && args[0] == "discover" && args[1] == "youtube" {
|
if len(args) >= 2 && args[0] == "discover" && args[1] == "youtube" {
|
||||||
return discoverYoutube(args[2:], stdout, stderr, runPlayerCurl)
|
return discoverYoutube(args[2:], stdout, stderr, player)
|
||||||
}
|
}
|
||||||
if len(args) == 2 && args[0] == "check" && args[1] == "youtube" {
|
if len(args) == 2 && args[0] == "check" && args[1] == "youtube" {
|
||||||
fmt.Fprintln(stderr, "error: check youtube is unavailable: YouTube probe URLs/video IDs have not been configured or agreed. No network requests were made; production health was not checked.")
|
fmt.Fprintln(stderr, "error: check youtube is unavailable: YouTube probe URLs/video IDs have not been configured or agreed. No network requests were made; production health was not checked.")
|
||||||
|
|||||||
Reference in new issue
Block a user