| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896 |
- package executor
- import (
- "net"
- "os"
- "strconv"
- "strings"
- "testing"
- "time"
- )
- // fakeRunner registra los comandos ejecutados y devuelve respuestas canned.
- type fakeRunner struct {
- calls []string
- inputs []string
- responses map[string]int // prefix → exitCode (0 si no está)
- outputs map[string]string // prefix → stdout cuando exitCode es 0
- }
- func (f *fakeRunner) RunInput(input, name string, args ...string) (string, int) {
- f.inputs = append(f.inputs, input)
- return f.Run(name, args...)
- }
- func newFakeRunner() *fakeRunner {
- return &fakeRunner{responses: map[string]int{}, outputs: map[string]string{}}
- }
- func (f *fakeRunner) Run(name string, args ...string) (string, int) {
- cmd := name + " " + strings.Join(args, " ")
- f.calls = append(f.calls, cmd)
- // Buscar respuesta por prefix.
- for prefix, code := range f.responses {
- if strings.HasPrefix(cmd, prefix) {
- if code == 0 {
- if out, ok := f.outputs[prefix]; ok {
- return out, 0
- }
- return "ok", 0
- }
- return "", code
- }
- }
- // Respuestas por defecto con stdout custom (p. ej. uci get value=1).
- for prefix, out := range f.outputs {
- if strings.HasPrefix(cmd, prefix) {
- return out, 0
- }
- }
- return "ok", 0 // default success
- }
- func TestValidateRejectsUnknownKind(t *testing.T) {
- err := Validate(Op{Kind: "rm_rf", Args: map[string]string{}})
- if err == nil {
- t.Fatal("unknown kind should be rejected")
- }
- }
- func TestValidateRejectsShellMetachars(t *testing.T) {
- err := Validate(Op{
- Kind: "uci_set",
- Args: map[string]string{
- "config": "dhcp",
- "section": "@dnsmasq[0]",
- "option": "server",
- "value": "1.1.1.1; rm -rf /", // shell injection
- },
- })
- if err == nil {
- t.Fatal("shell metachars in value should be rejected")
- }
- }
- func TestValidateAcceptsValidOp(t *testing.T) {
- err := Validate(Op{
- Kind: "uci_set",
- Args: map[string]string{
- "config": "dhcp",
- "section": "@dnsmasq[0]",
- "option": "server",
- "value": "1.1.1.1",
- },
- })
- if err != nil {
- t.Fatalf("valid op rejected: %v", err)
- }
- }
- func TestValidateRejectsMissingArg(t *testing.T) {
- err := Validate(Op{
- Kind: "uci_set",
- Args: map[string]string{"config": "dhcp", "section": "foo", "option": "bar"},
- // missing "value"
- })
- if err == nil {
- t.Fatal("missing arg should be rejected")
- }
- }
- func TestValidateServiceAction(t *testing.T) {
- // Acciones válidas (start/stop añadidos en Fase 17.1 para módulos que
- // escuchan en puerto, p. ej. parar AdGuard antes de reconfigurarlo).
- for _, action := range []string{"restart", "reload", "enable", "disable", "start", "stop"} {
- if err := Validate(Op{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": action}}); err != nil {
- t.Fatalf("action %q should be accepted: %v", action, err)
- }
- }
- // Acción inválida
- if err := Validate(Op{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart;;rm"}}); err == nil {
- t.Fatal("action with shell metachars should be rejected")
- }
- }
- // --- Fase 17.2: uci_add + secciones @[-1] ---
- func TestValidateUciAdd(t *testing.T) {
- valid := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface"}}
- if err := Validate(valid); err != nil {
- t.Fatalf("uci_add válido rechazado: %v", err)
- }
- // type con shell metachars → rechazado
- bad := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface; rm -rf /"}}
- if err := Validate(bad); err == nil {
- t.Fatal("uci_add type con metachars debería rechazarse")
- }
- // config inválido
- bad2 := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless;", "type": "wifi-iface"}}
- if err := Validate(bad2); err == nil {
- t.Fatal("uci_add config inválido debería rechazarse")
- }
- // uci_delete_section válido (sección nombrada y @referencia)
- del := Op{Kind: "uci_delete_section", Args: map[string]string{"config": "network", "section": "guest"}}
- if err := Validate(del); err != nil {
- t.Fatalf("uci_delete_section válido rechazado: %v", err)
- }
- del2 := Op{Kind: "uci_delete_section", Args: map[string]string{"config": "firewall", "section": "@zone[2]"}}
- if err := Validate(del2); err != nil {
- t.Fatalf("uci_delete_section @referencia rechazado: %v", err)
- }
- }
- func TestValidateSectionLastIndex(t *testing.T) {
- // @wifi-iface[-1] (última sección) válido para uci_set tras uci_add
- op := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "ssid", "value": "NetPulse-Guest"}}
- if err := Validate(op); err != nil {
- t.Fatalf("@wifi-iface[-1] debería aceptarse: %v", err)
- }
- // índice numérico sigue válido
- op2 := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[0]", "option": "ssid", "value": "Main"}}
- if err := Validate(op2); err != nil {
- t.Fatalf("@wifi-iface[0] debería aceptarse: %v", err)
- }
- // negativo distinto de -1 → rechazado
- op3 := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-2]", "option": "ssid", "value": "X"}}
- if err := Validate(op3); err == nil {
- t.Fatal("@wifi-iface[-2] debería rechazarse (solo -1)")
- }
- }
- // TestValidateSectionWithDigits (17.4): las secciones UCI de interfaces reales
- // llevan dígitos (eth1, wlan0, br-lan) — el nombre de sección debe aceptarlos.
- func TestValidateSectionWithDigits(t *testing.T) {
- for _, sec := range []string{"eth1", "wlan0", "br-lan", "wan6"} {
- op := Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": sec, "option": "enabled", "value": "1"}}
- if err := Validate(op); err != nil {
- t.Errorf("section %q debería aceptarse (interfaz UCI): %v", sec, err)
- }
- }
- // @tipo[-1] con tipo que lleva dígito
- op := Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": "@queue[-1]", "option": "interface", "value": "eth1"}}
- if err := Validate(op); err != nil {
- t.Errorf("@queue[-1] debería aceptarse: %v", err)
- }
- }
- // --- Fase 17.1: validación de los nuevos Kinds ---
- func TestValidateDownloadURLAllowlist(t *testing.T) {
- // URL oficial válida
- valid := Op{Kind: "download", Args: map[string]string{
- "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
- "dest": "/tmp/AdGuardHome.tar.gz",
- "sha256": strings.Repeat("a", 64),
- }}
- if err := Validate(valid); err != nil {
- t.Fatalf("valid download URL rejected: %v", err)
- }
- missingSum := Op{Kind: "download", Args: map[string]string{
- "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
- "dest": "/tmp/AdGuardHome.tar.gz",
- }}
- if err := Validate(missingSum); err == nil {
- t.Fatal("download without sha256 should be rejected")
- }
- badSum := Op{Kind: "download", Args: map[string]string{
- "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
- "dest": "/tmp/AdGuardHome.tar.gz",
- "sha256": "no-es-un-sha",
- }}
- if err := Validate(badSum); err == nil {
- t.Fatal("download with malformed sha256 should be rejected")
- }
- // URL maliciosa (dominio distinto) → rechazo
- bad := Op{Kind: "download", Args: map[string]string{
- "url": "https://evil.example.com/AdGuardHome.tar.gz",
- "dest": "/tmp/x.tar.gz",
- }}
- if err := Validate(bad); err == nil {
- t.Fatal("non-allowlisted download URL should be rejected")
- }
- // URL oficial pero path fuera de allowlist (otro repo) → rechazo
- bad2 := Op{Kind: "download", Args: map[string]string{
- "url": "https://github.com/evil/repo/releases/download/v1.0/payload",
- "dest": "/tmp/x.tar.gz",
- }}
- if err := Validate(bad2); err == nil {
- t.Fatal("non-AdguardTeam github path should be rejected")
- }
- }
- func TestValidateDawnCheck(t *testing.T) {
- if err := Validate(Op{Kind: "dawn_check", Args: map[string]string{}}); err != nil {
- t.Fatalf("dawn_check debería validar: %v", err)
- }
- }
- func TestValidateUsteerCheck(t *testing.T) {
- if err := Validate(Op{Kind: "usteer_check", Args: map[string]string{}}); err != nil {
- t.Fatalf("usteer_check debería validar: %v", err)
- }
- }
- func TestValidateRemoveKinds(t *testing.T) {
- for _, k := range []string{"apk_remove", "opkg_remove"} {
- if err := Validate(Op{Kind: k, Args: map[string]string{"package": "luci-app-usteer"}}); err != nil {
- t.Errorf("%s con package con guion debería validar: %v", k, err)
- }
- if err := Validate(Op{Kind: k, Args: map[string]string{"package": "dawn"}}); err != nil {
- t.Errorf("%s debería validar: %v", k, err)
- }
- if err := Validate(Op{Kind: k, Args: map[string]string{}}); err == nil {
- t.Errorf("%s sin package debería fallar", k)
- }
- if err := Validate(Op{Kind: k, Args: map[string]string{"package": "bad;rm -rf /"}}); err == nil {
- t.Errorf("%s con package inválido debería fallar", k)
- }
- }
- }
- func TestValidateWifiReload(t *testing.T) {
- if err := Validate(Op{Kind: "wifi_reload", Args: map[string]string{}}); err != nil {
- t.Fatalf("wifi_reload debería validar: %v", err)
- }
- }
- func TestValidateFilePathAllowlist(t *testing.T) {
- for _, p := range []string{"/etc/AdGuardHome.yaml", "/tmp/agh.tar.gz", "/usr/bin/AdGuardHome", "/usr/lib/AdGuardHome/dns"} {
- if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err != nil {
- t.Errorf("path %q should be accepted: %v", p, err)
- }
- }
- for _, p := range []string{"/etc/passwd;rm", "/etc/../etc/shadow", "/root/.ssh/id_rsa", "/var/log/x", "/home/nacho/x"} {
- if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err == nil {
- t.Errorf("path %q should be rejected", p)
- }
- }
- }
- func TestValidateChmodMode(t *testing.T) {
- for _, m := range []string{"755", "644", "600", "0755", "1777"} {
- if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err != nil {
- t.Errorf("mode %q should be accepted: %v", m, err)
- }
- }
- for _, m := range []string{"999", "rwxr-xr-x", "755;rm", "abc"} {
- if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err == nil {
- t.Errorf("mode %q should be rejected", m)
- }
- }
- }
- func TestValidateApkInstall(t *testing.T) {
- if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home"}}); err != nil {
- t.Fatalf("valid apk_install rejected: %v", err)
- }
- if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home;rm"}}); err == nil {
- t.Fatal("apk_install with shell metachars should be rejected")
- }
- }
- func TestValidateExtractTarball(t *testing.T) {
- if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/tmp/agh"}}); err != nil {
- t.Fatalf("valid extract_tarball rejected: %v", err)
- }
- // dest fuera de allowlist
- if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/home/nacho"}}); err == nil {
- t.Fatal("extract_tarball dest outside allowlist should be rejected")
- }
- }
- func TestValidateMv(t *testing.T) {
- if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/agh-x/AdGuardHome", "dest": "/usr/bin/AdGuardHome"}}); err != nil {
- t.Fatalf("valid mv rejected: %v", err)
- }
- // dest fuera de allowlist
- if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/x", "dest": "/etc/passwd;rm"}}); err == nil {
- t.Fatal("mv with malicious dest should be rejected")
- }
- // src con traversal
- if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/../etc/shadow", "dest": "/tmp/x"}}); err == nil {
- t.Fatal("mv src with traversal should be rejected")
- }
- }
- // TestWriteFileCreatesParentDir: write_file debe crear /etc/AdGuardHome/ si
- // no existe (MkdirAll del dir padre).
- func TestWriteFileCreatesParentDir(t *testing.T) {
- parent := "/tmp/netpulse-mkdir-test-" + t.Name()
- defer os.RemoveAll(parent)
- path := parent + "/AdGuardHome/AdGuardHome.yaml"
- spec := allowlist["write_file"]
- if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code != 0 {
- t.Fatalf("write_file exec failed: exit %d", code)
- }
- if _, err := os.ReadFile(path); err != nil {
- t.Fatalf("file not written (dir padre no creado?): %v", err)
- }
- }
- // TestWriteFileExec verifica el exec de write_file escribe el contenido real.
- // Usa un tmpdir (no fakeRunner) porque exec usa os.WriteFile directamente.
- func TestWriteFileExec(t *testing.T) {
- // Invoco exec directamente con un path /tmp real y limpio después.
- // El path debe casar con reFilePath (^/tmp/...).
- path := "/tmp/netpulse-exec-test-" + t.Name()
- defer os.Remove(path)
- content := "bind_port: 3000\n"
- b64 := "YmluZF9wb3J0OiAzMDAwCg==" // base64 de content
- spec := allowlist["write_file"]
- if spec.exec == nil {
- t.Fatal("write_file has no exec")
- }
- if code := spec.exec(nil, map[string]string{"path": path, "content_b64": b64}); code != 0 {
- t.Fatalf("write_file exec failed: exit %d", code)
- }
- data, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("file not written: %v", err)
- }
- if string(data) != content {
- t.Fatalf("content mismatch: got %q want %q", data, content)
- }
- }
- // TestWriteFileRejectsTraversal: path con .. debe ser rechazado por exec
- // (defense in depth: aunque el regex lo pille, exec lo revalida).
- func TestWriteFileRejectsTraversal(t *testing.T) {
- spec := allowlist["write_file"]
- // "/tmp/../../../etc/x" no casa el regex → Validate lo rechaza.
- // Pero comprobemos exec con un path que SÍ casa el regex pero tiene ..:
- // filepath.Clean("/tmp/a/../b") = "/tmp/b" (válido). Para forzar el
- // rechazo en exec, pasamos un path que Clean cambie (no debería casar
- // el regex, pero si alguien lo bypassa, exec lo para).
- // Como no podemos bypassar el regex desde Validate, este test documenta
- // la defensa: si path != Clean(path), exit 1.
- path := "/tmp/a/./b"
- if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code == 0 {
- t.Fatal("exec should reject path where Clean(path) != path")
- }
- }
- // TestApplyPlanConDownloadWriteChmod: plan que mezcla los nuevos Kinds con
- // los existentes, verificando que Apply despacha exec vs build correctamente.
- func TestApplyPlanConDownloadWriteChmod(t *testing.T) {
- fr := newFakeRunner()
- // download/extract/chmod via fakeRunner (build path). write_file via exec
- // (escribe de verdad en /tmp). service via fakeRunner.
- tmpFile := "/tmp/netpulse-plan-test-" + t.Name()
- defer os.Remove(tmpFile)
- sha := strings.Repeat("b", 64)
- fr.outputs["sha256sum"] = sha + " " + tmpFile
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "download", Args: map[string]string{
- "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
- "dest": tmpFile,
- "sha256": sha,
- }, Desc: "Download AdGuard tarball"},
- {Kind: "write_file", Args: map[string]string{
- "path": "/tmp/netpulse-plan-test-cfg.yaml",
- "content_b64": "YmluZF9wb3J0OiAzMDAwCg==",
- }, Desc: "Write AdGuard config"},
- {Kind: "chmod", Args: map[string]string{"mode": "755", "path": tmpFile}, Desc: "Make executable"},
- {Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "start"}, Desc: "Start AdGuard"},
- }
- defer os.Remove("/tmp/netpulse-plan-test-cfg.yaml")
- res := e.Apply(ops)
- if res.Status != "applied" {
- t.Fatalf("expected applied, got %s: %s", res.Status, res.Error)
- }
- // Verifica que los comandos build se ejecutaron (download, chmod, service).
- got := strings.Join(fr.calls, "\n")
- for _, want := range []string{"uclient-fetch https:", "chmod 755", "/etc/init.d/adguardhome start"} {
- if !strings.Contains(got, want) {
- t.Errorf("missing call %q in:\n%s", want, got)
- }
- }
- // Y que write_file escribió el fichero config.
- if _, err := os.ReadFile("/tmp/netpulse-plan-test-cfg.yaml"); err != nil {
- t.Errorf("config file not written: %v", err)
- }
- }
- func TestApplyDownloadChecksumMismatch(t *testing.T) {
- fr := newFakeRunner()
- fr.outputs["sha256sum"] = strings.Repeat("c", 64) + " /tmp/netpulse-plan-test-download"
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- res := e.Apply([]Op{{
- Kind: "download",
- Args: map[string]string{
- "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
- "dest": "/tmp/netpulse-plan-test-download",
- "sha256": strings.Repeat("d", 64),
- },
- Desc: "Download with wrong digest",
- }})
- if res.Status != "failed" {
- t.Fatalf("expected failed, got %s", res.Status)
- }
- }
- func TestUnsafeTarNames(t *testing.T) {
- for _, name := range []string{"../etc/passwd", "/etc/passwd", `a\..\b`, "a/../../b"} {
- if !unsafeTarNames(name) {
- t.Errorf("unsafe name accepted: %q", name)
- }
- }
- for _, name := range []string{"AdGuardHome/AdGuardHome", "dir/file", ""} {
- if unsafeTarNames(name) {
- t.Errorf("safe name rejected: %q", name)
- }
- }
- }
- func TestUnsafeTarTypes(t *testing.T) {
- for _, line := range []string{"lrwxrwxrwx 0 0 0 0 Jan 1 00:00 link", "hrw-r--r-- 0 0 0 0 Jan 1 00:00 hard", "brw-r--r-- 0 0 0 0 Jan 1 00:00 dev"} {
- if !unsafeTarTypes(line) {
- t.Errorf("unsafe tar type accepted: %q", line)
- }
- }
- for _, line := range []string{"-rw-r--r-- 0 0 0 0 Jan 1 00:00 file", "drwxr-xr-x 0 0 0 0 Jan 1 00:00 dir"} {
- if unsafeTarTypes(line) {
- t.Errorf("safe tar type rejected: %q", line)
- }
- }
- }
- func TestApplyExtractRejectsUnsafeTarNames(t *testing.T) {
- fr := newFakeRunner()
- fr.outputs["tar -tzf"] = "../escape\n"
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- res := e.Apply([]Op{{
- Kind: "extract_tarball",
- Args: map[string]string{"src": "/tmp/netpulse-extract-test.tar.gz", "dest": "/tmp/netpulse-extract-test"},
- Desc: "Extract unsafe tarball",
- }})
- if res.Status != "failed" {
- t.Fatalf("expected failed, got %s", res.Status)
- }
- if strings.Contains(strings.Join(fr.calls, "\n"), "tar -xzf") {
- t.Fatal("unsafe tarball must not be extracted")
- }
- }
- func TestApplyExtractRejectsUnsafeTarTypes(t *testing.T) {
- fr := newFakeRunner()
- fr.outputs["tar -tzf"] = "ok\n"
- fr.outputs["tar -tvzf"] = "lrwxrwxrwx 0 0 0 0 Jan 1 00:00 link\n"
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- res := e.Apply([]Op{{
- Kind: "extract_tarball",
- Args: map[string]string{"src": "/tmp/netpulse-extract-test.tar.gz", "dest": "/tmp/netpulse-extract-test"},
- Desc: "Extract symlink tarball",
- }})
- if res.Status != "failed" {
- t.Fatalf("expected failed, got %s", res.Status)
- }
- if strings.Contains(strings.Join(fr.calls, "\n"), "tar -xzf") {
- t.Fatal("tarball with symlink must not be extracted")
- }
- }
- func TestApplySuccess(t *testing.T) {
- fr := newFakeRunner()
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS upstream"},
- {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit dhcp"},
- }
- res := e.Apply(ops)
- if res.Status != "applied" {
- t.Fatalf("expected applied, got %s (error=%s)", res.Status, res.Error)
- }
- if res.Snapshot != "dhcp" {
- t.Fatalf("snapshot should list dhcp, got %q", res.Snapshot)
- }
- // Verificar que se hizo snapshot (uci export dhcp) antes de ejecutar
- foundSnap := false
- for _, c := range fr.calls {
- if strings.Contains(c, "uci export dhcp") {
- foundSnap = true
- break
- }
- }
- if !foundSnap {
- t.Fatal("should have done uci export for snapshot")
- }
- // Verificar commit
- foundCommit := false
- for _, c := range fr.calls {
- if c == "uci commit dhcp" {
- foundCommit = true
- break
- }
- }
- if !foundCommit {
- t.Fatal("should have committed dhcp")
- }
- }
- func TestApplyFailingOpReverts(t *testing.T) {
- fr := newFakeRunner()
- // Hacer que el segundo op (commit) falle
- fr.responses["uci commit dhcp"] = 1
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS"},
- {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
- }
- res := e.Apply(ops)
- if res.Status != "failed" {
- t.Fatalf("expected failed, got %s", res.Status)
- }
- // Verificar que se hizo revert de los staged changes
- foundRevert := false
- for _, c := range fr.calls {
- if strings.Contains(c, "uci revert dhcp") {
- foundRevert = true
- break
- }
- }
- if !foundRevert {
- t.Fatal("should have reverted staged changes on failure")
- }
- }
- func TestApplyHealthcheckFailRollsBack(t *testing.T) {
- fr := newFakeRunner()
- snap := "config dhcp 'lan'\n\toption dns '8.8.8.8'\n\tlist domain '$(reboot)'"
- fr.outputs["uci export"] = snap
- // Hacer que el ping falle (healthcheck)
- fr.responses["ping"] = 1
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "8.8.8.8"}, Desc: "Change DNS"},
- {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
- }
- res := e.Apply(ops)
- if res.Status != "rolled_back" {
- t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
- }
- if res.Error != "healthcheck_failed" {
- t.Fatalf("error should be healthcheck_failed, got %s", res.Error)
- }
- // Verificar que se restauró el snapshot (uci import)
- foundImport := false
- for _, c := range fr.calls {
- if strings.Contains(c, "uci import") {
- foundImport = true
- break
- }
- }
- if !foundImport {
- t.Fatal("should have imported snapshot on rollback")
- }
- if len(fr.inputs) == 0 || fr.inputs[0] != snap {
- t.Fatalf("snapshot should reach uci import via stdin, got %q", fr.inputs)
- }
- }
- // TestValidateWgCheck (10.3): el healthcheck del túnel valida interface y
- // rechaza metachars shell.
- func TestValidateWgCheck(t *testing.T) {
- if err := Validate(Op{Kind: "wg_check", Args: map[string]string{"interface": "wg0"}}); err != nil {
- t.Fatalf("valid wg_check rejected: %v", err)
- }
- if err := Validate(Op{Kind: "wg_check", Args: map[string]string{"interface": "wg0; rm -rf /"}}); err == nil {
- t.Fatal("wg_check with shell metachars should be rejected")
- }
- if err := Validate(Op{Kind: "wg_check", Args: map[string]string{}}); err == nil {
- t.Fatal("wg_check missing interface should be rejected")
- }
- }
- // TestApplyWgCheckFailRollsBack (10.3): si `wg show wg0` falla tras el apply,
- // el executor restaura los snapshots y relanza la red (rollback real), en vez
- // de devolver un simple "failed".
- func TestApplyWgCheckFailRollsBack(t *testing.T) {
- fr := newFakeRunner()
- fr.responses["wg show wg0"] = 1 // el túnel no levantó tras el reload
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": "wg0", "type": "interface"}, Desc: "Create interface"},
- {Kind: "uci_set", Args: map[string]string{"config": "network", "section": "wg0", "option": "proto", "value": "wireguard"}, Desc: "Set proto"},
- {Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit"},
- {Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network"},
- {Kind: "wg_check", Args: map[string]string{"interface": "wg0"}, Desc: "Check tunnel up"},
- }
- res := e.Apply(ops)
- if res.Status != "rolled_back" {
- t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
- }
- if res.Error != "wg_check_failed" {
- t.Fatalf("error should be wg_check_failed, got %s", res.Error)
- }
- got := strings.Join(fr.calls, "\n")
- if !strings.Contains(got, "uci import") {
- t.Error("should have restored the snapshot (uci import) on wg_check failure")
- }
- if !strings.Contains(got, "/etc/init.d/network reload") {
- t.Error("should have reloaded network after restoring the snapshot")
- }
- }
- func TestAffectedConfigsDedup(t *testing.T) {
- ops := []Op{
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s1", "option": "o1", "value": "v1"}},
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s2", "option": "o2", "value": "v2"}},
- {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
- {Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart"}},
- }
- cfgs := affectedConfigs(ops)
- if len(cfgs) != 1 || cfgs[0] != "dhcp" {
- t.Fatalf("expected [dhcp], got %v", cfgs)
- }
- }
- func TestMarshalUnmarshalOps(t *testing.T) {
- ops := []Op{
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s", "option": "o", "value": "1.2.3.4"}, Desc: "test"},
- }
- data, err := MarshalOps(ops)
- if err != nil {
- t.Fatal(err)
- }
- got, err := UnmarshalOps(data)
- if err != nil {
- t.Fatal(err)
- }
- if len(got) != 1 || got[0].Kind != "uci_set" || got[0].Args["value"] != "1.2.3.4" {
- t.Fatalf("roundtrip failed: %+v", got)
- }
- }
- // TestValidateTcpCheck: args host/port validados por regex.
- func TestValidateTcpCheck(t *testing.T) {
- cases := []struct {
- name, host, port string
- ok bool
- }{
- {"ipv4", "127.0.0.1", "3000", true},
- {"localhost", "localhost", "53", true},
- {"lan-ip", "192.168.1.1", "80", true},
- {"port-zero", "127.0.0.1", "0", false},
- {"port-too-high", "127.0.0.1", "65536", false},
- {"port-leading-zero", "127.0.0.1", "03000", false},
- {"host-space", "127.0.0.1 ", "3000", false},
- {"host-shell-chars", "127.0.0.1; rm -rf /", "3000", false},
- {"missing-port", "127.0.0.1", "", false},
- }
- for _, c := range cases {
- op := Op{Kind: "tcp_check", Args: map[string]string{"host": c.host, "port": c.port}}
- err := Validate(op)
- if (err == nil) != c.ok {
- t.Errorf("%s: esperaba ok=%v, got err=%v", c.name, c.ok, err)
- }
- }
- }
- // TestTcpCheckExecOpenThenClosed: el exec de tcp_check devuelve 0 si el
- // puerto está abierto y 1 si está cerrado (healthcheck real de servicio).
- func TestTcpCheckExecOpenThenClosed(t *testing.T) {
- // Acortar el budget para que el caso "cerrado" no tarde 10 s en el test.
- prev := tcpCheckBudget
- tcpCheckBudget = 300 * time.Millisecond
- defer func() { tcpCheckBudget = prev }()
- ln, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("no pude abrir listener: %v", err)
- }
- port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
- spec, ok := allowlist["tcp_check"]
- if !ok {
- t.Fatal("tcp_check no está en allowlist")
- }
- // Puerto abierto → 0
- if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 0 {
- t.Errorf("puerto abierto: esperaba 0, got %d", rc)
- }
- // Cerrar el listener → puerto cerrado → 1 (tras exhausting el budget corto)
- ln.Close()
- if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 1 {
- t.Errorf("puerto cerrado: esperaba 1, got %d", rc)
- }
- }
- // --- Fase 18: ownership UCI ---
- func TestValidateOwnershipMode(t *testing.T) {
- if err := Validate(Op{Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}}); err != nil {
- t.Fatalf("ownership_mode enforce=true debería validar: %v", err)
- }
- if err := Validate(Op{Kind: "ownership_mode", Args: map[string]string{"enforce": "false"}}); err != nil {
- t.Fatalf("ownership_mode enforce=false debería validar: %v", err)
- }
- if err := Validate(Op{Kind: "ownership_mode", Args: map[string]string{"enforce": "yes"}}); err == nil {
- t.Fatal("ownership_mode enforce=yes debería rechazarse")
- }
- if err := Validate(Op{Kind: "ownership_mode", Args: map[string]string{}}); err == nil {
- t.Fatal("ownership_mode sin enforce debería rechazarse")
- }
- }
- func TestValidateUciSetManaged(t *testing.T) {
- if err := Validate(Op{Kind: "uci_set_managed", Args: map[string]string{"config": "wireless", "section": "guest"}}); err != nil {
- t.Fatalf("uci_set_managed válido rechazado: %v", err)
- }
- if err := Validate(Op{Kind: "uci_set_managed", Args: map[string]string{"config": "wireless", "section": "bad;rm"}}); err == nil {
- t.Fatal("uci_set_managed con section malicioso debería rechazarse")
- }
- if err := Validate(Op{Kind: "uci_set_managed", Args: map[string]string{"config": "wireless"}}); err == nil {
- t.Fatal("uci_set_managed sin section debería rechazarse")
- }
- }
- func TestApplyOwnershipBlocksUnmanaged(t *testing.T) {
- fr := newFakeRunner()
- // La sección dhcp.@dnsmasq[0] existe pero no está gestionada.
- fr.responses["uci show dhcp.@dnsmasq[0]"] = 0
- fr.responses["uci get dhcp.@dnsmasq[0].np_managed"] = 1
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}},
- {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
- }
- res := e.Apply(ops)
- if res.Status != "failed" {
- t.Fatalf("esperaba failed, got %s", res.Status)
- }
- if !strings.Contains(res.Error, "section_not_managed") {
- t.Fatalf("error debería ser section_not_managed, got %q", res.Error)
- }
- }
- func TestApplyOwnershipAllowsManaged(t *testing.T) {
- fr := newFakeRunner()
- fr.responses["uci show dhcp.@dnsmasq[0]"] = 0
- fr.responses["uci get dhcp.@dnsmasq[0].np_managed"] = 0
- fr.outputs["uci get dhcp.@dnsmasq[0].np_managed"] = "1"
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}},
- {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
- }
- res := e.Apply(ops)
- if res.Status != "applied" {
- t.Fatalf("esperaba applied, got %s (error=%s)", res.Status, res.Error)
- }
- }
- func TestApplyOwnershipUciAddMarksManaged(t *testing.T) {
- fr := newFakeRunner()
- // uci add wireless wifi-iface devuelve el nombre de la sección creada;
- // fakeRunner devuelve "ok" por defecto, que usamos como nombre.
- fr.outputs["uci get wireless.@wifi-iface[-1].np_managed"] = "1"
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
- {Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface"}, Desc: "Add guest iface"},
- {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "ssid", "value": "NetPulse-Guest"}},
- {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}},
- }
- res := e.Apply(ops)
- if res.Status != "applied" {
- t.Fatalf("esperaba applied, got %s (error=%s)", res.Status, res.Error)
- }
- got := strings.Join(fr.calls, "\n")
- if !strings.Contains(got, "uci add wireless wifi-iface") {
- t.Error("falta uci add wireless wifi-iface")
- }
- if !strings.Contains(got, "uci set wireless.ok.np_managed=1") {
- t.Errorf("falta uci set wireless.ok.np_managed=1 tras uci_add. Calls:\n%s", got)
- }
- }
- func TestApplyOwnershipUciSetNamedMarksManaged(t *testing.T) {
- fr := newFakeRunner()
- // La sección network.guest no existe todavía.
- fr.responses["uci show network.guest"] = 1
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
- {Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": "guest", "type": "interface"}},
- {Kind: "uci_commit", Args: map[string]string{"config": "network"}},
- }
- res := e.Apply(ops)
- if res.Status != "applied" {
- t.Fatalf("esperaba applied, got %s (error=%s)", res.Status, res.Error)
- }
- got := strings.Join(fr.calls, "\n")
- if !strings.Contains(got, "uci set network.guest=interface") {
- t.Error("falta uci set network.guest=interface")
- }
- if !strings.Contains(got, "uci set network.guest.np_managed=1") {
- t.Errorf("falta uci set network.guest.np_managed=1. Calls:\n%s", got)
- }
- }
- func TestApplyOwnershipUciSetManagedTakeover(t *testing.T) {
- fr := newFakeRunner()
- // Sección existente no gestionada; uci_set_managed debe poder marcarla.
- fr.responses["uci set wireless.guest.np_managed=1"] = 0
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
- {Kind: "uci_set_managed", Args: map[string]string{"config": "wireless", "section": "guest"}},
- {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}},
- }
- res := e.Apply(ops)
- if res.Status != "applied" {
- t.Fatalf("esperaba applied, got %s (error=%s)", res.Status, res.Error)
- }
- }
- func TestApplyOwnershipDisabled(t *testing.T) {
- fr := newFakeRunner()
- // Con enforce=false no debe importar si la sección está gestionada.
- fr.responses["uci show dhcp.@dnsmasq[0]"] = 0
- fr.responses["uci get dhcp.@dnsmasq[0].np_managed"] = 1
- e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
- ops := []Op{
- {Kind: "ownership_mode", Args: map[string]string{"enforce": "false"}},
- {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}},
- {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
- }
- res := e.Apply(ops)
- if res.Status != "applied" {
- t.Fatalf("esperaba applied con ownership desactivado, got %s (error=%s)", res.Status, res.Error)
- }
- }
|