474 lines
17 KiB
Go
474 lines
17 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func managedCLIFixture(t *testing.T) (managedDeps, map[string]string, *int) {
|
|
t.Helper()
|
|
root := t.TempDir()
|
|
env := map[string]string{
|
|
"ZAPRET_AUTOTUNE_TARGET_ROLE": "managed-test", "ZAPRET_AUTOTUNE_TARGET_ID": managedTargetID,
|
|
"ZAPRET_AUTOTUNE_TARGET_DIR": managedTargetDirectory, "ZAPRET_CONFIG": managedTargetConfig,
|
|
"SOCKS_PORT": "11080", "ZAPRET_AUTOTUNE_SOCKS_PROXY": "socks5://127.0.0.1:11080",
|
|
}
|
|
calls := new(int)
|
|
d := managedDeps{
|
|
lookup: func(key string) (string, bool) { value, ok := env[key]; return value, ok },
|
|
script: filepath.Join(root, "zapret2"), directory: filepath.Join(root, "target"),
|
|
verifyRuntime: func(dir string) error {
|
|
if dir != managedTargetDirectory {
|
|
return errors.New("wrong runtime directory")
|
|
}
|
|
return nil
|
|
},
|
|
verifySOCKS: func(port int) error {
|
|
if port != 11080 {
|
|
return errors.New("wrong ss-local port")
|
|
}
|
|
return nil
|
|
},
|
|
run: func(path string, args ...string) error {
|
|
*calls++
|
|
if path != filepath.Join(root, "zapret2") || !reflect.DeepEqual(args, []string{"restart"}) {
|
|
t.Fatalf("unexpected executable/argv: %q %q", path, args)
|
|
}
|
|
return nil
|
|
},
|
|
player: func(_ context.Context, args []string, stdout, _ io.Writer) error {
|
|
if !strings.Contains(strings.Join(args, "|"), "--noproxy||--proxy|socks5://127.0.0.1:11080|") {
|
|
t.Fatalf("unsafe health argv: %q", args)
|
|
}
|
|
_, err := io.WriteString(stdout, `{"playabilityStatus":{"status":"OK"}}`)
|
|
return err
|
|
},
|
|
openDB: func() (*sql.DB, error) { t.Fatal("unexpected DB access"); return nil, nil },
|
|
}
|
|
if err := os.WriteFile(d.script, []byte("not executed"), 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Mkdir(d.directory, 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return d, env, calls
|
|
}
|
|
|
|
func callManaged(t *testing.T, d managedDeps, args ...string) (int, string, string) {
|
|
t.Helper()
|
|
var out, diagnostic bytes.Buffer
|
|
code := managedCLI(args, &out, &diagnostic, d)
|
|
return code, out.String(), diagnostic.String()
|
|
}
|
|
|
|
func initManagedCLI(t *testing.T, d managedDeps) {
|
|
t.Helper()
|
|
if code, _, diagnostic := callManaged(t, d, "init"); code != 0 {
|
|
t.Fatalf("init: %d %s", code, diagnostic)
|
|
}
|
|
b, err := os.ReadFile(filepath.Join(d.directory, "config"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertManagedFirewallConfig(t, string(b), "0")
|
|
if !strings.Contains(string(b), "\nNFQWS2_OPT=''\n") {
|
|
t.Fatal("baseline strategy is not disabled")
|
|
}
|
|
}
|
|
|
|
func TestManagedCLIArguments(t *testing.T) {
|
|
for _, args := range [][]string{nil, {"unknown"}, {"init", "--dir", "/etc"}, {"status", "extra"}, {"apply"}, {"apply", "--frontend-candidate", "1", "--frontend-candidate", "2"}, {"apply", "--frontend-candidate", "1", "--googlevideo-candidate", "1"}, {"apply", "--frontend-candidate", "-1", "--googlevideo-candidate", "2"}, {"apply", "--frontend-candidate", "1;id", "--googlevideo-candidate", "2"}, {"apply", "--frontend-candidate", "9223372036854775808", "--googlevideo-candidate", "2"}, {"apply", "--frontend-candidate", "0", "--googlevideo-candidate", "2"}} {
|
|
d, _, calls := managedCLIFixture(t)
|
|
if code, _, _ := callManaged(t, d, args...); code != 2 || *calls != 0 {
|
|
t.Fatalf("accepted %q", args)
|
|
}
|
|
}
|
|
command, ids, err := managedArguments([]string{"apply", "--googlevideo-candidate", "2", "--frontend-candidate", "1"})
|
|
if err != nil || command != "apply" || !reflect.DeepEqual(ids, []int64{1, 2}) {
|
|
t.Fatalf("%s %v %v", command, ids, err)
|
|
}
|
|
// Exercise the actual top-level dispatch without a runner or network call.
|
|
t.Setenv("ZAPRET_AUTOTUNE_TARGET_ROLE", "old-container")
|
|
var out, diagnostic bytes.Buffer
|
|
if code := run([]string{"managed", "status"}, &out, &diagnostic); code != 2 || !strings.Contains(diagnostic.String(), "TARGET_ROLE") {
|
|
t.Fatalf("dispatch: %d %s", code, diagnostic.String())
|
|
}
|
|
}
|
|
|
|
func TestManagedProductionRestartExecutable(t *testing.T) {
|
|
d := managedDependencies(nil)
|
|
if d.script != "/opt/zapret2/init.d/sysv/zapret2" {
|
|
t.Fatalf("unexpected production restart executable: %q", d.script)
|
|
}
|
|
}
|
|
|
|
func TestManagedCLIRoleAndDirectoryGuards(t *testing.T) {
|
|
for _, role := range []string{"", "dev", "managed-test ", "old-container"} {
|
|
d, env, _ := managedCLIFixture(t)
|
|
env["ZAPRET_AUTOTUNE_TARGET_ROLE"] = role
|
|
if code, _, _ := callManaged(t, d, "init"); code != 2 {
|
|
t.Fatalf("accepted role %q", role)
|
|
}
|
|
if entries, err := os.ReadDir(d.directory); err != nil || len(entries) != 0 {
|
|
t.Fatal("guard wrote target directory")
|
|
}
|
|
}
|
|
for _, path := range []string{"", "relative", "/", "/tmp/../etc"} {
|
|
d, env, _ := managedCLIFixture(t)
|
|
env["ZAPRET_AUTOTUNE_TARGET_DIR"] = path
|
|
if code, _, _ := callManaged(t, d, "init"); code == 0 {
|
|
t.Fatalf("accepted path %q", path)
|
|
}
|
|
}
|
|
for _, mode := range []string{"symlink", "public", "ancestor"} {
|
|
d, env, _ := managedCLIFixture(t)
|
|
dir := d.directory
|
|
var err error
|
|
if mode == "public" {
|
|
err = os.Chmod(dir, 0755)
|
|
} else {
|
|
if err := os.Remove(dir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
err = os.Symlink(t.TempDir(), dir)
|
|
if mode == "ancestor" {
|
|
env["ZAPRET_AUTOTUNE_TARGET_DIR"] = filepath.Join(dir, "nested")
|
|
}
|
|
}
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, _, _ := callManaged(t, d, "init"); code == 0 {
|
|
t.Fatalf("accepted %s", mode)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestManagedCLIInitNonOverwrite(t *testing.T) {
|
|
d, _, calls := managedCLIFixture(t)
|
|
dir := d.directory
|
|
path := filepath.Join(dir, "config")
|
|
secret := "EXISTING_SECRET='do not overwrite'\n"
|
|
if err := os.WriteFile(path, []byte(secret), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, _, _ := callManaged(t, d, "init"); code == 0 {
|
|
t.Fatal("adopted non-baseline config")
|
|
}
|
|
b, err := os.ReadFile(path)
|
|
if err != nil || string(b) != secret || *calls != 0 {
|
|
t.Fatalf("config=%q err=%v", b, err)
|
|
}
|
|
if err := os.WriteFile(path, []byte(managedBaseline), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
initManagedCLI(t, d)
|
|
if code, _, _ := callManaged(t, d, "init"); code == 0 {
|
|
t.Fatal("reinitialized identity")
|
|
}
|
|
if code, out, diagnostic := callManaged(t, d, "status"); code != 0 || !strings.Contains(out, "generation=0") || !strings.Contains(out, "none (disabled)") {
|
|
t.Fatalf("status %d %s %s", code, out, diagnostic)
|
|
}
|
|
if *calls != 0 {
|
|
t.Fatal("init/status reloaded")
|
|
}
|
|
}
|
|
|
|
func TestManagedCLIApplyAndRollback(t *testing.T) {
|
|
for _, mode := range []string{"success", "health", "reload", "unqualified", "wrong-group", "missing-id", "missing-script", "wrong-binding", "bad-proxy", "missing-marker", "drift"} {
|
|
t.Run(mode, func(t *testing.T) {
|
|
d, env, calls := managedCLIFixture(t)
|
|
initManagedCLI(t, d)
|
|
db := testStore(t)
|
|
front := managedCandidateFixture(t, db, "frontend", "youtube.com", "--lua-desync=fake", mode != "unqualified")
|
|
ggc := managedCandidateFixture(t, db, "googlevideo", "rr1.googlevideo.com", "--lua-desync=multisplit", true)
|
|
d.openDB = func() (*sql.DB, error) { return db, nil }
|
|
config := filepath.Join(d.directory, "config")
|
|
fixedRestart := d.run
|
|
d.run = func(path string, args ...string) error {
|
|
if err := fixedRestart(path, args...); err != nil {
|
|
return err
|
|
}
|
|
b, err := os.ReadFile(config)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if *calls == 1 {
|
|
assertManagedFirewallConfig(t, string(b), "1")
|
|
} else if string(b) != managedBaseline {
|
|
t.Fatalf("rollback restart did not load disabled baseline: %s", b)
|
|
}
|
|
return nil
|
|
}
|
|
switch mode {
|
|
case "health":
|
|
d.player = func(_ context.Context, _ []string, stdout, _ io.Writer) error {
|
|
_, err := io.WriteString(stdout, `{"playabilityStatus":{"status":"ERROR","secret":"do-not-print"}}`)
|
|
return err
|
|
}
|
|
case "reload":
|
|
fixed := d.run
|
|
d.run = func(path string, args ...string) error {
|
|
if err := fixed(path, args...); err != nil {
|
|
return err
|
|
}
|
|
if *calls == 1 {
|
|
return errors.New("reload failed")
|
|
}
|
|
return nil
|
|
}
|
|
case "wrong-group":
|
|
front, ggc = ggc, front
|
|
case "missing-id":
|
|
front = 999999
|
|
case "missing-script":
|
|
if err := os.Remove(d.script); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
case "wrong-binding":
|
|
env["ZAPRET_CONFIG"] = "/opt/zapret2/config"
|
|
case "bad-proxy":
|
|
env["ZAPRET_AUTOTUNE_SOCKS_PROXY"] = "socks5://192.0.2.1:1080"
|
|
case "missing-marker":
|
|
if err := os.Remove(filepath.Join(d.directory, managedMarkerName)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
case "drift":
|
|
if err := os.WriteFile(config, []byte("EXTERNAL_SECRET=private\n"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
code, out, diagnostic := callManaged(t, d, "apply", "--frontend-candidate", fmt.Sprint(front), "--googlevideo-candidate", fmt.Sprint(ggc))
|
|
if (mode == "success") != (code == 0) {
|
|
t.Fatalf("apply: %d %s %s", code, out, diagnostic)
|
|
}
|
|
if strings.Contains(out+diagnostic, "do-not-print") || strings.Contains(out+diagnostic, "EXTERNAL_SECRET") {
|
|
t.Fatal("leaked config/response")
|
|
}
|
|
b, err := os.ReadFile(config)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
wantCalls := 0
|
|
if mode == "success" {
|
|
wantCalls = 1
|
|
assertManagedFirewallConfig(t, string(b), "1")
|
|
if !strings.Contains(string(b), "--hostlist-domains=^rr1.googlevideo.com") {
|
|
t.Fatalf("wrong applied scope: %s", b)
|
|
}
|
|
d.openDB = func() (*sql.DB, error) { return openHistoryStore(databasePath()) }
|
|
code, out, diagnostic = callManaged(t, d, "status")
|
|
if code != 0 || !strings.Contains(out, "generation=1") || !strings.Contains(out, "groups=frontend,googlevideo") || strings.Contains(out, "lua-desync") || strings.Contains(out, "rr1") {
|
|
t.Fatalf("status: %d %s %s", code, out, diagnostic)
|
|
}
|
|
} else if mode == "drift" {
|
|
if string(b) != "EXTERNAL_SECRET=private\n" {
|
|
t.Fatal("drift overwritten")
|
|
}
|
|
} else {
|
|
if string(b) != managedBaseline {
|
|
t.Fatalf("baseline not restored: %s", b)
|
|
}
|
|
if mode == "health" || mode == "reload" {
|
|
wantCalls = 2
|
|
}
|
|
}
|
|
if *calls != wantCalls {
|
|
t.Fatalf("reloads=%d want=%d", *calls, wantCalls)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestManagedCLIIdentityAndStatusRedaction(t *testing.T) {
|
|
for _, mode := range []string{"identity", "symlink", "hardlink", "journal", "drift"} {
|
|
t.Run(mode, func(t *testing.T) {
|
|
d, _, calls := managedCLIFixture(t)
|
|
initManagedCLI(t, d)
|
|
dir := d.directory
|
|
path := filepath.Join(dir, managedMarkerName)
|
|
switch mode {
|
|
case "identity":
|
|
if err := os.WriteFile(path, []byte(`{"Role":"dev","Directory":"secret"}`), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
case "symlink", "hardlink":
|
|
outside := filepath.Join(t.TempDir(), "outside")
|
|
if err := os.Rename(path, outside); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var err error
|
|
if mode == "symlink" {
|
|
err = os.Symlink(outside, path)
|
|
} else {
|
|
err = os.Link(outside, path)
|
|
}
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if mode == "hardlink" {
|
|
if err := os.Link(outside, outside+"-second"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
case "journal":
|
|
if err := os.Remove(filepath.Join(dir, managedJournalName)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
case "drift":
|
|
if err := os.WriteFile(filepath.Join(dir, "config"), []byte("PASSWORD=secret\n"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
code, out, diagnostic := callManaged(t, d, "status")
|
|
if code == 0 || strings.Contains(out+diagnostic, "secret") || *calls != 0 {
|
|
t.Fatalf("status: %d %s %s", code, out, diagnostic)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestManagedCLIFreshTargetContract(t *testing.T) {
|
|
for _, mode := range []string{"wrong-id", "missing-id", "old-env", "other-directory", "old-config", "other-config", "non-mountpoint", "missing-base-runtime", "wrong-port", "other-loopback", "wrong-process", "missing-proxy", "missing-port"} {
|
|
for _, command := range []string{"init", "reconcile", "status", "apply"} {
|
|
t.Run(mode+"/"+command, func(t *testing.T) {
|
|
d, env, calls := managedCLIFixture(t)
|
|
if command != "init" {
|
|
initManagedCLI(t, d)
|
|
}
|
|
switch mode {
|
|
case "wrong-id":
|
|
env["ZAPRET_AUTOTUNE_TARGET_ID"] = "another-target"
|
|
case "missing-id":
|
|
delete(env, "ZAPRET_AUTOTUNE_TARGET_ID")
|
|
case "old-env":
|
|
// A role and a self-created directory/identity alone cannot pass.
|
|
delete(env, "ZAPRET_AUTOTUNE_TARGET_ID")
|
|
delete(env, "ZAPRET_CONFIG")
|
|
delete(env, "SOCKS_PORT")
|
|
case "other-directory":
|
|
env["ZAPRET_AUTOTUNE_TARGET_DIR"] = d.directory
|
|
case "old-config":
|
|
env["ZAPRET_CONFIG"] = "/opt/zapret2/config"
|
|
case "other-config":
|
|
env["ZAPRET_CONFIG"] = "/etc/config"
|
|
case "non-mountpoint", "missing-base-runtime":
|
|
d.verifyRuntime = func(string) error { return errors.New(mode) }
|
|
case "wrong-port":
|
|
env["SOCKS_PORT"] = "1080"
|
|
case "other-loopback":
|
|
env["ZAPRET_AUTOTUNE_SOCKS_PROXY"] = "socks5://127.0.0.1:1080"
|
|
case "wrong-process":
|
|
d.verifySOCKS = func(int) error { return errors.New("listener belongs to another process") }
|
|
case "missing-proxy":
|
|
delete(env, "ZAPRET_AUTOTUNE_SOCKS_PROXY")
|
|
case "missing-port":
|
|
delete(env, "SOCKS_PORT")
|
|
}
|
|
args := []string{command}
|
|
if command == "apply" {
|
|
args = append(args, "--frontend-candidate", "1", "--googlevideo-candidate", "2")
|
|
}
|
|
if code, _, _ := callManaged(t, d, args...); code == 0 || *calls != 0 {
|
|
t.Fatal("unsafe target contract accepted or reloaded")
|
|
}
|
|
if command == "reconcile" {
|
|
if _, err := os.Lstat(filepath.Join(d.directory, "candidates.db")); !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatal("runtime guard opened database", err)
|
|
}
|
|
}
|
|
if command == "init" {
|
|
entries, err := os.ReadDir(d.directory)
|
|
if err != nil || len(entries) != 0 {
|
|
t.Fatal("refused init modified target")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestManagedCLIStagedProfiles(t *testing.T) {
|
|
for _, group := range []string{"frontend", "googlevideo"} {
|
|
t.Run(group, func(t *testing.T) {
|
|
d, _, calls := managedCLIFixture(t)
|
|
initManagedCLI(t, d)
|
|
db := testStore(t)
|
|
front := managedCandidateFixture(t, db, "frontend", "youtube.com", "--lua-desync=fake", true)
|
|
ggc := managedCandidateFixture(t, db, "googlevideo", "rr1.googlevideo.com", "--lua-desync=fake", true)
|
|
id, missing := front, "googlevideo"
|
|
if group == "googlevideo" {
|
|
id, missing = ggc, "frontend"
|
|
}
|
|
d.openDB = func() (*sql.DB, error) { return openHistoryStore(databasePath()) }
|
|
if code, out, diagnostic := callManaged(t, d, "apply", "--"+group+"-candidate", fmt.Sprint(id)); code != 0 {
|
|
t.Fatalf("single group apply: %d %s %s", code, out, diagnostic)
|
|
}
|
|
if code, out, diagnostic := callManaged(t, d, "status"); code != 0 || !strings.Contains(out, "groups="+group+" ") || !strings.Contains(out, "unresolved_groups="+missing) || !strings.Contains(out, "NOT CHECKED") {
|
|
t.Fatalf("partial status: %d %s %s", code, out, diagnostic)
|
|
}
|
|
code, out, diagnostic := callManaged(t, d, "active-ids")
|
|
var state struct {
|
|
IDs []int64 `json:"active_candidate_ids"`
|
|
Missing []string `json:"unresolved_groups"`
|
|
}
|
|
if code != 0 || json.Unmarshal([]byte(out), &state) != nil || !reflect.DeepEqual(state.IDs, []int64{id}) || !reflect.DeepEqual(state.Missing, []string{missing}) || *calls != 1 {
|
|
t.Fatalf("active IDs: %d %s %s", code, out, diagnostic)
|
|
}
|
|
if _, err := db.Exec("DELETE FROM candidate_evidence WHERE candidate_id = ?", id); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, out, diagnostic := callManaged(t, d, "status"); code != 0 || !strings.Contains(out, "groups=unknown ") || !strings.Contains(out, "active_candidate_ids=[] ") || !strings.Contains(out, "unresolved_groups=frontend,googlevideo") {
|
|
t.Fatalf("invalid DB status: %d %s %s", code, out, diagnostic)
|
|
}
|
|
if code, out, diagnostic := callManaged(t, d, "active-ids"); code == 0 || out != "" || !strings.Contains(diagnostic, "active candidate IDs unresolved") || *calls != 1 {
|
|
t.Fatalf("invalid DB IDs trusted: %d %s %s", code, out, diagnostic)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestManagedCLILegacyIDsUnresolved(t *testing.T) {
|
|
d, _, calls := managedCLIFixture(t)
|
|
initManagedCLI(t, d)
|
|
m := &managedTransaction{Dir: d.directory, Name: "config", Reload: func() error { return nil }, Health: func() (string, error) { return "OK", nil }}
|
|
j, err := m.load()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
j.Version = 1
|
|
if err := m.journal(j); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, out, diagnostic := callManaged(t, d, "status"); code != 0 || !strings.Contains(out, "groups=unknown") || !strings.Contains(out, "unresolved_groups=frontend,googlevideo") {
|
|
t.Fatalf("legacy status: %d %s %s", code, out, diagnostic)
|
|
}
|
|
if code, out, _ := callManaged(t, d, "active-ids"); code == 0 || out != "" || *calls != 0 {
|
|
t.Fatal("legacy IDs inferred")
|
|
}
|
|
}
|
|
|
|
func TestManagedMountpoint(t *testing.T) {
|
|
for _, path := range []string{"/", filepath.Dir(managedTargetDirectory), managedTargetDirectory + "-other"} {
|
|
if managedMountpoint("1 2 0:3 / "+path+" rw - tmpfs tmpfs rw\n", managedTargetDirectory) {
|
|
t.Fatal("accepted another mount")
|
|
}
|
|
}
|
|
if !managedMountpoint("1 2 0:3 / "+managedTargetDirectory+" rw - ext4 /dev/test rw\n", managedTargetDirectory) {
|
|
t.Fatal("dedicated mount rejected")
|
|
}
|
|
if err := verifyManagedRuntime("/opt/zapret2"); err == nil {
|
|
t.Fatal("production verifier accepted arbitrary directory")
|
|
}
|
|
}
|