| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894 |
- // device_actions_test.go — issue #439: reserva DHCP + bloqueo de dispositivo.
- // Todo con fakes (SSHRunner scripteable + routers en DB temporal); NINGÚN
- // router real se toca. Cubre create/update/idempotencia/conflicto, fallos SSH,
- // rollback ante fallo de reload, gate admin y validación.
- package httpapi_test
- import (
- "encoding/json"
- "errors"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- "sync"
- "testing"
- "time"
- "github.com/gnacho/netpulse/server-go/internal/adapters"
- "github.com/gnacho/netpulse/server-go/internal/auth"
- "github.com/gnacho/netpulse/server-go/internal/config"
- "github.com/gnacho/netpulse/server-go/internal/db"
- "github.com/gnacho/netpulse/server-go/internal/httpapi"
- "github.com/gnacho/netpulse/server-go/internal/routerstore"
- "github.com/gnacho/netpulse/server-go/internal/sse"
- )
- const (
- devMAC = "aa:bb:cc:dd:ee:ff"
- otherMAC = "11:22:33:44:55:66"
- )
- // --- fake SSHRunner (por subcadena, en orden) ---
- type sshRule struct {
- host string // opcional: si no vacío, la regla solo aplica a ese host SSH
- contains string
- out string
- err error
- }
- type scriptedSSH struct {
- mu sync.Mutex
- cmds []string
- hosts []string
- rules []sshRule
- }
- func (f *scriptedSSH) Run(host, cmd string, _ time.Duration) (string, error) {
- f.mu.Lock()
- defer f.mu.Unlock()
- f.cmds = append(f.cmds, cmd)
- f.hosts = append(f.hosts, host)
- for _, r := range f.rules {
- // Desde #605 el pool entrega "host:puerto_ssh"; la regla puede estar
- // escrita con el host pelado, así que consideramos ambos equivalentes
- // cuando el puerto es el por defecto (22).
- if r.host != "" && r.host != host && r.host+":22" != host {
- continue
- }
- if strings.Contains(cmd, r.contains) {
- return r.out, r.err
- }
- }
- return "", nil
- }
- func (f *scriptedSSH) saw(substr string) bool {
- f.mu.Lock()
- defer f.mu.Unlock()
- for _, c := range f.cmds {
- if strings.Contains(c, substr) {
- return true
- }
- }
- return false
- }
- // cmdsSnapshot copia los comandos vistos (para mensajes de fallo).
- func (f *scriptedSSH) cmdsSnapshot() []string {
- f.mu.Lock()
- defer f.mu.Unlock()
- out := make([]string, len(f.cmds))
- copy(out, f.cmds)
- return out
- }
- // sawHost es como saw pero acotado a un host SSH concreto (issue #537: la
- // reserva debe escribirse en el router que sirve DHCP, no siempre en el
- // gateway).
- //
- // Desde el issue #605 el pool recibe siempre "host:puerto" (SSHAddr), así que
- // un router SSH por defecto llega como "192.168.1.2:22". Comparar solo el host
- // para que los tests escritos con el host "pelado" sigan validando.
- func (f *scriptedSSH) sawHost(host, substr string) bool {
- f.mu.Lock()
- defer f.mu.Unlock()
- for i, c := range f.cmds {
- if i >= len(f.hosts) {
- continue
- }
- seen := f.hosts[i]
- if seen != host && seen != host+":22" {
- continue
- }
- if strings.Contains(c, substr) {
- return true
- }
- }
- return false
- }
- func (f *scriptedSSH) count(substr string) int {
- f.mu.Lock()
- defer f.mu.Unlock()
- n := 0
- for _, c := range f.cmds {
- if strings.Contains(c, substr) {
- n++
- }
- }
- return n
- }
- // --- fixtures uci show ---
- const dhcpEmpty = `dhcp.@dnsmasq[0]=dnsmasq
- dhcp.@dnsmasq[0].server='127.0.0.1#5353'
- dhcp.lan=dhcp
- dhcp.lan.interface='lan'
- dhcp.lan.start='100'
- dhcp.lan.limit='150'
- `
- const dhcpOtherHost = dhcpEmpty + `dhcp.@host[0]=host
- dhcp.@host[0].name='tv-salon'
- dhcp.@host[0].mac='11:22:33:44:55:66'
- dhcp.@host[0].ip='192.168.1.50'
- `
- const dhcpDevHost = dhcpEmpty + `dhcp.np_host_aabbccddeeff=host
- dhcp.np_host_aabbccddeeff.name='tv-salon'
- dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'
- dhcp.np_host_aabbccddeeff.ip='192.168.1.60'
- `
- const fwEmpty = `firewall.@defaults[0]=defaults
- firewall.@defaults[0].input='ACCEPT'
- firewall.lan=zone
- firewall.lan.name='lan'
- firewall.lan.network='lan'
- firewall.@rule[0]=rule
- firewall.@rule[0].name='Allow-DHCP'
- firewall.@rule[0].src_mac='00:00:00:00:00:00'
- firewall.@rule[0].target='ACCEPT'
- `
- const fwBlocked = fwEmpty + `firewall.np_block_aabbccddeeff=rule
- firewall.np_block_aabbccddeeff.name='np-block-aabbccddeeff'
- firewall.np_block_aabbccddeeff.src='lan'
- firewall.np_block_aabbccddeeff.dest='*'
- firewall.np_block_aabbccddeeff.target='DROP'
- firewall.np_block_aabbccddeeff.src_mac='aa:bb:cc:dd:ee:ff'
- `
- // --- servidor de test ---
- type deviceActionsTestServer struct {
- *httptest.Server
- db *db.DB
- ssh *scriptedSSH
- gwID string
- apID string
- cookie string
- }
- func makeDeviceActionsTestServer(t *testing.T, ssh *scriptedSSH, adapterOpt ...adapters.Snapshotter) *deviceActionsTestServer {
- t.Helper()
- dataDir := t.TempDir()
- cfg, err := config.Load(map[string]string{
- "AUTH_USER": "admin", "AUTH_PASS": "test123456",
- "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
- }, dataDir)
- if err != nil {
- t.Fatalf("config: %v", err)
- }
- d, err := db.Open(dataDir)
- if err != nil {
- t.Fatalf("db: %v", err)
- }
- secret, err := auth.EnsureSessionSecret(d, cfg)
- if err != nil {
- t.Fatalf("secret: %v", err)
- }
- if err := auth.EnsureUsers(d, cfg); err != nil {
- t.Fatalf("users: %v", err)
- }
- gw, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
- Name: "gateway", Host: "192.168.1.1", Type: "openwrt", IsGateway: true,
- })
- if err != nil {
- t.Fatalf("AddRouter gateway: %v", err)
- }
- ap, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
- Name: "patio", Host: "192.168.1.2", Type: "openwrt",
- })
- if err != nil {
- t.Fatalf("AddRouter patio: %v", err)
- }
- agents := adapters.NewAgentRegistry(0)
- hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
- var runner httpapi.SSHRunner
- if ssh != nil {
- runner = ssh
- }
- adapter := adapters.Snapshotter(adapters.NewDemo())
- if len(adapterOpt) > 0 && adapterOpt[0] != nil {
- adapter = adapterOpt[0]
- }
- handler := httpapi.NewHandler(httpapi.Deps{
- Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
- Agents: agents, Pool: runner, Started: time.Now(),
- })
- srv := httptest.NewServer(handler)
- status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
- if status != 204 {
- t.Fatalf("login: %d", status)
- }
- ts := &deviceActionsTestServer{Server: srv, db: d, ssh: ssh, gwID: gw.ID, apID: ap.ID, cookie: cookie}
- t.Cleanup(func() {
- srv.Close()
- d.Close()
- })
- return ts
- }
- func deviceReq(t *testing.T, method, base, path, cookie, body string) *http.Response {
- t.Helper()
- var rdr io.Reader
- if body != "" {
- rdr = strings.NewReader(body)
- }
- req, _ := http.NewRequest(method, base+path, rdr)
- if body != "" {
- req.Header.Set("Content-Type", "application/json")
- }
- if cookie != "" {
- req.Header.Set("Cookie", "session="+cookie)
- }
- res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("%s %s: %v", method, path, err)
- }
- return res
- }
- func decodeBody(t *testing.T, res *http.Response) map[string]any {
- t.Helper()
- defer res.Body.Close()
- var m map[string]any
- if err := json.NewDecoder(res.Body).Decode(&m); err != nil {
- t.Fatalf("decode response: %v", err)
- }
- return m
- }
- // newSSH crea el fake con el `uci show` scripteado (dhcp + firewall) y reglas
- // extra (fallos). Por defecto todo tiene éxito.
- func newSSH(dhcp, fw string, extra ...sshRule) *scriptedSSH {
- // Los fallos (extra) van PRIMERO para que ganen sobre las salidas por
- // defecto cuando comparten subcadena (p. ej. "uci show dhcp").
- rules := append([]sshRule{}, extra...)
- rules = append(rules,
- sshRule{contains: "uci show dhcp", out: dhcp},
- sshRule{contains: "uci show firewall", out: fw},
- )
- return &scriptedSSH{rules: rules}
- }
- // --- Reserva DHCP ---
- func TestReservationCreate(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
- }
- res.Body.Close()
- if !ssh.saw("uci set dhcp.np_host_aabbccddeeff=host") {
- t.Error("falta la creación de la sección host")
- }
- if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'") {
- t.Error("falta la mac en la sección host")
- }
- if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.ip='192.168.1.60'") {
- t.Error("falta la ip en la sección host")
- }
- if !ssh.saw("uci commit dhcp") {
- t.Error("falta uci commit dhcp")
- }
- if !ssh.saw("/etc/init.d/dnsmasq restart") {
- t.Error("falta el reinicio de dnsmasq")
- }
- }
- func TestReservationUpdate(t *testing.T) {
- ssh := newSSH(dhcpDevHost, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.70"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT reservation: %d", res.StatusCode)
- }
- res.Body.Close()
- if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.ip='192.168.1.70'") {
- t.Error("falta la actualización de ip en la sección existente")
- }
- }
- func TestReservationIdempotent(t *testing.T) {
- ssh := newSSH(dhcpDevHost, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT reservation idempotente: %d", res.StatusCode)
- }
- res.Body.Close()
- // La misma IP no debe generar conflicto (es la propia MAC).
- if ssh.saw("uci add") {
- t.Error("no debe añadir secciones nuevas en update idempotente")
- }
- }
- func TestReservationConflict(t *testing.T) {
- ssh := newSSH(dhcpOtherHost, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.50"}`)
- if res.StatusCode != 409 {
- t.Fatalf("conflicto: got %d want 409", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "ip_conflict" {
- t.Errorf("error code: %v", body["error"])
- }
- if ssh.saw("uci commit dhcp") {
- t.Error("no debe escribir nada en conflicto")
- }
- }
- func TestReservationGet(t *testing.T) {
- ssh := newSSH(dhcpDevHost, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- if res.StatusCode != 200 {
- t.Fatalf("GET reservation: %d", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["reserved"] != true || body["ip"] != "192.168.1.60" {
- t.Errorf("reserved payload: %v", body)
- }
- }
- func TestReservationGetNotReserved(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- body := decodeBody(t, res)
- if body["reserved"] != false {
- t.Errorf("reserved debería ser false: %v", body)
- }
- }
- func TestReservationNoGateway(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- if !routerstore.RemoveRouter(ts.db.DB, ts.gwID) {
- t.Fatal("no se pudo quitar el gateway")
- }
- res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- if res.StatusCode != 400 {
- t.Fatalf("sin gateway: got %d want 400", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "no_gateway" {
- t.Errorf("error code: %v", body["error"])
- }
- }
- func TestReservationSSHReadFailure(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "uci show dhcp", err: errors.New("ssh down")})
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- if res.StatusCode != 500 {
- t.Fatalf("ssh read failure: got %d want 500", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "ssh_error" {
- t.Errorf("error code: %v", body["error"])
- }
- }
- func TestReservationApplyFailure(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "uci commit dhcp", err: errors.New("commit fail")})
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60"}`)
- if res.StatusCode != 500 {
- t.Fatalf("apply failure: got %d want 500", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "apply_error" {
- t.Errorf("error code: %v", body["error"])
- }
- if ssh.saw("/etc/init.d/dnsmasq restart") {
- t.Error("no debe reiniciar dnsmasq si el commit falló")
- }
- }
- func TestReservationReloadFailureRollsBack(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "restart", err: errors.New("reload fail")})
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60"}`)
- if res.StatusCode != 500 {
- t.Fatalf("reload failure: got %d want 500", res.StatusCode)
- }
- res.Body.Close()
- if !ssh.saw("uci delete dhcp.np_host_aabbccddeeff") {
- t.Error("falta el rollback (borrado de la sección recién creada)")
- }
- }
- func TestReservationDelete(t *testing.T) {
- ssh := newSSH(dhcpDevHost, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- if res.StatusCode != 200 {
- t.Fatalf("DELETE reservation: %d", res.StatusCode)
- }
- res.Body.Close()
- if !ssh.saw("uci delete dhcp.np_host_aabbccddeeff") {
- t.Error("falta el borrado de la sección host")
- }
- if !ssh.saw("/etc/init.d/dnsmasq restart") {
- t.Error("falta el reinicio de dnsmasq")
- }
- }
- func TestReservationDeleteNotFound(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- if res.StatusCode != 404 {
- t.Fatalf("DELETE not reserved: got %d want 404", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "not_reserved" {
- t.Errorf("error code: %v", body["error"])
- }
- }
- // --- Bloqueo ---
- func TestBlockAdd(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
- `{"router":"`+ts.apID+`"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT block: %d", res.StatusCode)
- }
- res.Body.Close()
- if !ssh.saw("uci set firewall.np_block_aabbccddeeff=rule") {
- t.Error("falta la sección rule nombrada")
- }
- if !ssh.saw("uci set firewall.np_block_aabbccddeeff.src_mac='aa:bb:cc:dd:ee:ff'") {
- t.Error("falta src_mac")
- }
- if !ssh.saw("uci set firewall.np_block_aabbccddeeff.target='DROP'") {
- t.Error("falta target DROP")
- }
- if !ssh.saw("/etc/init.d/firewall restart") {
- t.Error("falta el reinicio del firewall")
- }
- }
- func TestBlockIdempotent(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwBlocked)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
- `{"router":"`+ts.apID+`"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT block ya bloqueado: %d", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["already"] != true {
- t.Errorf("already: %v", body["already"])
- }
- if ssh.saw("uci commit firewall") {
- t.Error("no debe reescribir si ya está bloqueado")
- }
- }
- func TestBlockGet(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwBlocked)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/block?router="+ts.apID, ts.cookie, "")
- body := decodeBody(t, res)
- if body["blocked"] != true {
- t.Errorf("blocked debería ser true: %v", body)
- }
- }
- func TestBlockRemove(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwBlocked)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
- `{"router":"`+ts.apID+`"}`)
- if res.StatusCode != 200 {
- t.Fatalf("DELETE block: %d", res.StatusCode)
- }
- res.Body.Close()
- if !ssh.saw("uci delete firewall.np_block_aabbccddeeff") {
- t.Error("falta el borrado de la regla")
- }
- if !ssh.saw("/etc/init.d/firewall restart") {
- t.Error("falta el reinicio del firewall")
- }
- }
- func TestBlockUnblockIdempotent(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
- `{"router":"`+ts.apID+`"}`)
- if res.StatusCode != 200 {
- t.Fatalf("DELETE block no bloqueado: %d", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["already"] != true {
- t.Errorf("already: %v", body["already"])
- }
- }
- func TestBlockReloadFailureRollsBack(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwBlocked, sshRule{contains: "restart", err: errors.New("reload fail")})
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
- `{"router":"`+ts.apID+`"}`)
- if res.StatusCode != 500 {
- t.Fatalf("reload failure: got %d want 500", res.StatusCode)
- }
- res.Body.Close()
- if !ssh.saw("uci set firewall.np_block_aabbccddeeff=rule") {
- t.Error("falta el rollback (re-crear la regla)")
- }
- }
- // --- Validación y gate admin ---
- func TestReservationInvalidMAC(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "GET", ts.URL, "/api/devices/aa:bb:cc:dd:ee/reservation", ts.cookie, "")
- if res.StatusCode != 400 {
- t.Fatalf("mac inválida: got %d want 400", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "invalid_mac" {
- t.Errorf("error code: %v", body["error"])
- }
- }
- func TestReservationInvalidIP(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"no-es-ip"}`)
- if res.StatusCode != 400 {
- t.Fatalf("ip inválida: got %d want 400", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "invalid_ip" {
- t.Errorf("error code: %v", body["error"])
- }
- }
- // --- #693: hostname de la reserva sin superficie de inyección ---
- // El PoC del issue (hostname con comilla simple que rompe el quoting del
- // comando uci) debe rechazarse con 400 SIN llegar a abrir sesión SSH.
- func TestReservationHostnameInjectionRejected(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60","hostname":"x'; touch /tmp/netpulse_poc; echo '"}`)
- if res.StatusCode != 400 {
- t.Fatalf("hostname inyectable: got %d want 400 (body %v)", res.StatusCode, decodeBody(t, res))
- }
- body := decodeBody(t, res)
- if body["error"] != "invalid_hostname" {
- t.Errorf("error code: %v", body["error"])
- }
- if ssh.saw("uci") || ssh.saw("touch") {
- t.Error("el payload malicioso no debe generar NINGÚN comando SSH")
- }
- }
- // Hostnames válidos (DNS) pasan; el resto (espacios, sustituciones, unicode)
- // se rechaza con 400 invalid_hostname.
- func TestReservationHostnameValidation(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- valid := []string{"tv-salon", "nas.lan", "a"}
- for _, h := range valid {
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60","hostname":"`+h+`"}`)
- if res.StatusCode != 200 {
- t.Errorf("hostname válido %q: got %d want 200 (body %v)", h, res.StatusCode, decodeBody(t, res))
- }
- res.Body.Close()
- }
- invalid := []string{"tv salon", "x$(id)", "x`id`", "pc_1", "télé"}
- for _, h := range invalid {
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60","hostname":"`+h+`"}`)
- if res.StatusCode != 400 {
- t.Errorf("hostname inválido %q: got %d want 400", h, res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "invalid_hostname" {
- t.Errorf("hostname inválido %q: error code %v", h, body["error"])
- }
- }
- }
- // Defensa en profundidad: el rollback del DELETE re-interpola valores LEÍDOS
- // del router (name de la sección host). Si el router devolviera un name hostil,
- // el comando de rollback debe llevarlo escapado, no crudo (#693).
- func TestReservationDeleteRollbackEscapesHostileName(t *testing.T) {
- const dhcpHostile = dhcpEmpty + `dhcp.np_host_aabbccddeeff=host
- dhcp.np_host_aabbccddeeff.name='tv'; ping -c1 evil.example; echo '
- dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'
- dhcp.np_host_aabbccddeeff.ip='192.168.1.60'
- `
- ssh := newSSH(dhcpHostile, fwEmpty, sshRule{contains: "restart", err: errors.New("reload fail")})
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- if res.StatusCode != 500 {
- t.Fatalf("DELETE con reload fallido: got %d want 500", res.StatusCode)
- }
- res.Body.Close()
- // El rollback re-crea la sección: el name hostil debe viajar escapado.
- if !ssh.saw(`name='tv'\''; ping`) {
- t.Errorf("el rollback debe escapar la comilla simple del name leído del router; cmds: %v", ssh.cmdsSnapshot())
- }
- if ssh.saw(`name='tv'; ping`) {
- t.Error("el name hostil llegó SIN escapar al comando SSH")
- }
- }
- func TestBlockMissingRouter(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie, `{}`)
- if res.StatusCode != 400 {
- t.Fatalf("router ausente: got %d want 400", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "missing_router" {
- t.Errorf("error code: %v", body["error"])
- }
- }
- func TestBlockUnknownRouter(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
- `{"router":"no-existe"}`)
- if res.StatusCode != 400 {
- t.Fatalf("router desconocido: got %d want 400", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["error"] != "no_router" {
- t.Errorf("error code: %v", body["error"])
- }
- }
- func TestDeviceActionsAdminOnly(t *testing.T) {
- ssh := newSSH(dhcpEmpty, fwEmpty)
- ts := makeDeviceActionsTestServer(t, ssh)
- // Sin sesión → 401 (requireAuth global).
- res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", "", "")
- if res.StatusCode != 401 {
- t.Errorf("sin sesión: got %d want 401", res.StatusCode)
- }
- res.Body.Close()
- // Rol user → 403 (RequireAdmin).
- _, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
- userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewer", "clave12345", "user")
- for _, rt := range []struct{ method, path string }{
- {"GET", "/api/devices/" + devMAC + "/reservation"},
- {"PUT", "/api/devices/" + devMAC + "/reservation"},
- {"GET", "/api/devices/" + devMAC + "/block?router=" + ts.apID},
- {"PUT", "/api/devices/" + devMAC + "/block"},
- } {
- if got := do(t, rt.method, ts.URL, rt.path, userCookie).StatusCode; got != 403 {
- t.Errorf("%s %s como user: got %d want 403", rt.method, rt.path, got)
- }
- }
- }
- // --- #537: la reserva DHCP va al router que sirve el lease, no siempre al
- // gateway global ---
- // leaseAwareAdapter envuelve un adapter de test (Demo) añadiéndole la
- // resolución de "qué router reportó el lease de la MAC" (RouterServingDHCP).
- // sirve: MAC → router ID (el router que concede DHCP a esa MAC).
- type leaseAwareAdapter struct {
- adapters.Snapshotter
- sirve map[string]string
- }
- func (a *leaseAwareAdapter) RouterServingDHCP(mac string) string {
- return a.sirve[strings.ToUpper(mac)]
- }
- // El AP "patio" (192.168.1.2) es quien reporta el lease de devMAC: su host
- // tiene dhcpDevHost (la reserva ya existe ahí). El gateway (192.168.1.1) NO la
- // tiene. Con esto, la reserva debe escribirse/leerse en 192.168.1.2.
- func TestReservationTargetsServingRouter(t *testing.T) {
- ssh := &scriptedSSH{rules: []sshRule{
- {host: "192.168.1.2", contains: "uci show dhcp", out: dhcpDevHost},
- {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
- }}
- adapter := &leaseAwareAdapter{
- Snapshotter: adapters.NewDemo(),
- sirve: map[string]string{strings.ToUpper(devMAC): "patio"},
- }
- // "patio" es el Name del router creado con host 192.168.1.2 en el helper;
- // el helper guarda apID. Construimos el server y después recuperamos el
- // ID real del AP para el mapa (por si el helper genera IDs distintos).
- ts := makeDeviceActionsTestServer(t, ssh, adapter)
- adapter.sirve[strings.ToUpper(devMAC)] = ts.apID
- // GET: debe leer el uci show dhcp del AP (192.168.1.2), donde está la
- // reserva → reserved=true.
- res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- if res.StatusCode != 200 {
- t.Fatalf("GET reservation: %d", res.StatusCode)
- }
- body := decodeBody(t, res)
- if body["reserved"] != true || body["ip"] != "192.168.1.60" {
- t.Errorf("reserved payload (desde el router que sirve DHCP): %v", body)
- }
- if !ssh.sawHost("192.168.1.2", "uci show dhcp") {
- t.Fatalf("GET no consultó el router que sirve DHCP: %v", ssh.hosts)
- }
- }
- // PUT: al crear la reserva de un dispositivo cuyo lease lo sirve el AP, el
- // write debe ir al AP (192.168.1.2), NO al gateway (192.168.1.1).
- func TestReservationPutTargetsServingRouter(t *testing.T) {
- ssh := &scriptedSSH{rules: []sshRule{
- {host: "192.168.1.2", contains: "uci show dhcp", out: dhcpEmpty},
- {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
- }}
- adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
- ts := makeDeviceActionsTestServer(t, ssh, adapter)
- adapter.sirve = map[string]string{strings.ToUpper(devMAC): ts.apID}
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
- }
- res.Body.Close()
- if !ssh.sawHost("192.168.1.2", "uci set dhcp.np_host_aabbccddeeff=host") {
- t.Error("la reserva debe escribirse en el router que sirve DHCP (192.168.1.2)")
- }
- if ssh.sawHost("192.168.1.1", "uci set dhcp.") {
- t.Error("la reserva NO debe escribirse en el gateway (192.168.1.1)")
- }
- if !ssh.sawHost("192.168.1.2", "/etc/init.d/dnsmasq restart") {
- t.Error("dnsmasq debe reiniciarse en el router que sirve DHCP")
- }
- }
- // DELETE: si la reserva está en el router que sirve DHCP (no en el gateway),
- // se borra de ahí.
- func TestReservationDeleteTargetsServingRouter(t *testing.T) {
- ssh := &scriptedSSH{rules: []sshRule{
- {host: "192.168.1.2", contains: "uci show dhcp", out: dhcpDevHost},
- {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
- }}
- adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
- ts := makeDeviceActionsTestServer(t, ssh, adapter)
- adapter.sirve = map[string]string{strings.ToUpper(devMAC): ts.apID}
- res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
- if res.StatusCode != 200 {
- t.Fatalf("DELETE reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
- }
- res.Body.Close()
- if !ssh.sawHost("192.168.1.2", "uci delete dhcp.np_host_aabbccddeeff") {
- t.Error("el borrado debe ir al router que sirve DHCP (192.168.1.2)")
- }
- if ssh.sawHost("192.168.1.1", "uci delete dhcp.") {
- t.Error("el borrado NO debe ir al gateway (192.168.1.1)")
- }
- }
- // Sin resolver (adapter por defecto, demo): la reserva sigue cayendo al
- // gateway (red gestionada clásica) - compatibilidad con el comportamiento
- // previo.
- func TestReservationFallsBackToGatewayWithoutResolver(t *testing.T) {
- ssh := &scriptedSSH{rules: []sshRule{
- {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
- {host: "192.168.1.2", contains: "uci show dhcp", out: dhcpEmpty},
- }}
- ts := makeDeviceActionsTestServer(t, ssh) // demo: sin RouterServingDHCP
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT reservation: %d", res.StatusCode)
- }
- res.Body.Close()
- if !ssh.sawHost("192.168.1.1", "uci set dhcp.np_host_aabbccddeeff=host") {
- t.Error("sin resolver, la reserva debe ir al gateway (192.168.1.1)")
- }
- }
- // El resolver apunta a un router agent-only (sin SSH): no se puede escribir
- // ahí → cae al gateway (hostOfRouter devuelve vacío para agent-only).
- func TestReservationSkipsAgentOnlyServingRouter(t *testing.T) {
- ssh := &scriptedSSH{rules: []sshRule{
- {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
- }}
- adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
- ts := makeDeviceActionsTestServer(t, ssh, adapter)
- // Creamos un router agent-only con host y apuntamos el resolver ahí.
- agentOnly, err := routerstore.AddRouter(ts.db.DB, routerstore.AddInput{
- Name: "sw-ao", Host: "192.168.1.9", Type: "openwrt", AgentOnly: true,
- })
- if err != nil {
- t.Fatalf("AddRouter agent-only: %v", err)
- }
- adapter.sirve = map[string]string{strings.ToUpper(devMAC): agentOnly.ID}
- res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
- `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
- if res.StatusCode != 200 {
- t.Fatalf("PUT reservation: %d", res.StatusCode)
- }
- res.Body.Close()
- if !ssh.sawHost("192.168.1.1", "uci set dhcp.np_host_aabbccddeeff=host") {
- t.Error("router agent-only sin SSH → la reserva debe caer al gateway")
- }
- if ssh.sawHost("192.168.1.9", "uci set dhcp.") {
- t.Error("no debe intentar escribir en el router agent-only")
- }
- }
|