| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439 |
- // device_overrides_test.go — issue #797: nombre visible y tipo de dispositivo
- // como overrides persistidos (además del icono existente, #437).
- package httpapi
- import (
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
- "github.com/gnacho/netpulse/server-go/internal/db"
- )
- func newOverrideTestServer(t *testing.T) *server {
- t.Helper()
- dataDir := t.TempDir()
- d, err := db.Open(dataDir)
- if err != nil {
- t.Fatalf("db: %v", err)
- }
- t.Cleanup(func() { _ = d.Close() })
- return &server{db: d}
- }
- func doOverridePut(t *testing.T, s *server, mac, body string) *httptest.ResponseRecorder {
- t.Helper()
- req := httptest.NewRequest("PUT", "/api/devices/"+mac+"/override", strings.NewReader(body))
- req.SetPathValue("mac", mac)
- rec := httptest.NewRecorder()
- s.handleDeviceOverridePut(rec, req)
- return rec
- }
- func doOverrideGet(t *testing.T, s *server, mac string) map[string]any {
- t.Helper()
- req := httptest.NewRequest("GET", "/api/devices/"+mac+"/override", nil)
- req.SetPathValue("mac", mac)
- rec := httptest.NewRecorder()
- s.handleDeviceOverrideGet(rec, req)
- var out map[string]any
- if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
- t.Fatalf("get decode: %v", err)
- }
- return out
- }
- func TestDeviceOverrideNameTypeRoundtrip(t *testing.T) {
- s := newOverrideTestServer(t)
- mac := "aa:bb:cc:dd:ee:ff"
- rec := doOverridePut(t, s, mac, `{"icon":"tv","name":"TV Salón","type":"tv","notifyOffline":true}`)
- if rec.Code != 200 {
- t.Fatalf("put: %d %s", rec.Code, rec.Body.String())
- }
- got := doOverrideGet(t, s, mac)
- if got["icon"] != "tv" || got["name"] != "TV Salón" || got["type"] != "tv" || got["notifyOffline"] != true {
- t.Errorf("roundtrip incompleto: %+v", got)
- }
- }
- func TestDeviceOverrideNotifyOffline(t *testing.T) {
- s := newOverrideTestServer(t)
- mac := "AA:BB:CC:DD:EE:FF"
- // Marcar opt-in: persiste el flag aunque icon/name/type queden vacíos.
- if rec := doOverridePut(t, s, mac, `{"notifyOffline":true}`); rec.Code != 200 {
- t.Fatalf("notifyOffline true: %d", rec.Code)
- }
- if got := doOverrideGet(t, s, mac); got["notifyOffline"] != true {
- t.Errorf("notifyOffline no persistió: %+v", got)
- }
- // Apagar el flag con el resto vacío: la fila se borra (cero estado).
- if rec := doOverridePut(t, s, mac, `{"notifyOffline":false}`); rec.Code != 200 {
- t.Fatalf("notifyOffline false: %d", rec.Code)
- }
- var n int
- if err := s.db.QueryRow("SELECT COUNT(*) FROM device_overrides WHERE mac = ?", mac).Scan(&n); err != nil {
- t.Fatalf("count: %v", err)
- }
- if n != 0 {
- t.Errorf("la fila debió borrarse con notifyOffline=false y sin más campos, quedaron %d", n)
- }
- // El flag se conserva ante un put parcial que no lo envía (cliente antiguo).
- doOverridePut(t, s, mac, `{"name":"TV","notifyOffline":true}`)
- if rec := doOverridePut(t, s, mac, `{"icon":"tv"}`); rec.Code != 200 {
- t.Fatalf("put parcial: %d", rec.Code)
- }
- if got := doOverrideGet(t, s, mac); got["notifyOffline"] != true {
- t.Errorf("el put parcial pisó notifyOffline: %+v", got)
- }
- // Tipo inválido (string en un bool): el decode falla y devuelve 400.
- if rec := doOverridePut(t, s, mac, `{"notifyOffline":"yes"}`); rec.Code != 400 {
- t.Errorf("notifyOffline no booleano debió dar 400, dio %d", rec.Code)
- }
- }
- func TestDeviceOverridePartialPutPreservesOthers(t *testing.T) {
- s := newOverrideTestServer(t)
- mac := "aa:bb:cc:dd:ee:ff"
- doOverridePut(t, s, mac, `{"icon":"tv","name":"TV Salón","type":"tv"}`)
- // Cliente antiguo que solo envía icon (#772): name/type no se tocan.
- rec := doOverridePut(t, s, mac, `{"icon":"speaker"}`)
- if rec.Code != 200 {
- t.Fatalf("put parcial: %d", rec.Code)
- }
- got := doOverrideGet(t, s, mac)
- if got["icon"] != "speaker" || got["name"] != "TV Salón" || got["type"] != "tv" {
- t.Errorf("el put parcial pisó otros campos: %+v", got)
- }
- // Limpiar solo el nombre.
- doOverridePut(t, s, mac, `{"name":""}`)
- got = doOverrideGet(t, s, mac)
- if got["name"] != "" || got["icon"] != "speaker" || got["type"] != "tv" {
- t.Errorf("limpiar name no funcionó: %+v", got)
- }
- }
- func TestDeviceOverrideClearAllDeletesRow(t *testing.T) {
- s := newOverrideTestServer(t)
- mac := "AA:BB:CC:DD:EE:FF"
- doOverridePut(t, s, mac, `{"icon":"tv","name":"TV","type":"tv"}`)
- rec := doOverridePut(t, s, mac, `{"icon":"","name":"","type":""}`)
- if rec.Code != 200 {
- t.Fatalf("clear: %d", rec.Code)
- }
- var n int
- if err := s.db.QueryRow("SELECT COUNT(*) FROM device_overrides WHERE mac = ?", mac).Scan(&n); err != nil {
- t.Fatalf("count: %v", err)
- }
- if n != 0 {
- t.Errorf("la fila debió borrarse con los tres campos vacíos")
- }
- }
- func TestDeviceOverrideValidation(t *testing.T) {
- s := newOverrideTestServer(t)
- mac := "aa:bb:cc:dd:ee:ff"
- if rec := doOverridePut(t, s, mac, `{"type":"router-magico"}`); rec.Code != 400 {
- t.Errorf("tipo inválido debió dar 400, dio %d", rec.Code)
- }
- if rec := doOverridePut(t, s, mac, `{"icon":"icono-falso"}`); rec.Code != 400 {
- t.Errorf("icon inválido debió dar 400, dio %d", rec.Code)
- }
- if rec := doOverridePut(t, s, "not-a-mac", `{"name":"x"}`); rec.Code != 400 {
- t.Errorf("mac inválida debió dar 400, dio %d", rec.Code)
- }
- // Nombre con salto de línea: rechazado.
- if rec := doOverridePut(t, s, mac, `{"name":"a\nb"}`); rec.Code != 400 {
- t.Errorf("name con newline debió dar 400, dio %d", rec.Code)
- }
- // Tipo válido del clasificador: aceptado.
- if rec := doOverridePut(t, s, mac, `{"type":"movil"}`); rec.Code != 200 {
- t.Errorf("tipo válil debió dar 200, dio %d", rec.Code)
- }
- }
- // Iconos de domótica: uno por categoría del selector debe aceptarse y
- // persistirse, para que la whitelist del server siga a ICON_OVERRIDES.
- func TestDeviceOverrideSmartHomeIcons(t *testing.T) {
- s := newOverrideTestServer(t)
- mac := "aa:bb:cc:dd:ee:ff"
- for _, icon := range []string{
- "refrigerator", "toilet", "plug-zap", "lamp-ceiling", "lock-keyhole",
- "paw-print", "projector", "hard-drive", "blinds",
- } {
- rec := doOverridePut(t, s, mac, `{"icon":"`+icon+`"}`)
- if rec.Code != 200 {
- t.Errorf("icon %q debió dar 200, dio %d %s", icon, rec.Code, rec.Body.String())
- continue
- }
- if got := doOverrideGet(t, s, mac); got["icon"] != icon {
- t.Errorf("icon %q no persistió: %+v", icon, got)
- }
- }
- if rec := doOverridePut(t, s, mac, `{"icon":"icono-falso"}`); rec.Code != 400 {
- t.Errorf("icon inválido debió dar 400, dio %d", rec.Code)
- }
- }
- // #1145: DELETE /api/devices/{mac} borra la fila del registro y 404 si no
- // existe. El handler requiere admin (el test llama al handler directamente
- // con PathValue, como el resto de tests de handlers con PathValue).
- func TestDeviceDelete(t *testing.T) {
- s := panelTestServer(t)
- if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('AA:BB:CC:DD:EE:FF', 1, 2, 'watch')"); err != nil {
- t.Fatalf("seed: %v", err)
- }
- r := httptest.NewRequest(http.MethodDelete, "/api/devices/aa-bb-cc-dd-ee-ff", nil)
- r.SetPathValue("mac", "aa-bb-cc-dd-ee-ff")
- rec := httptest.NewRecorder()
- s.handleDeviceDelete(rec, r)
- if rec.Code != http.StatusNoContent {
- t.Fatalf("status = %d, want 204", rec.Code)
- }
- var n int
- if err := s.db.QueryRow("SELECT COUNT(*) FROM device_seen WHERE mac = 'AA:BB:CC:DD:EE:FF'").Scan(&n); err != nil {
- t.Fatal(err)
- }
- if n != 0 {
- t.Fatalf("rows = %d, want 0 (borrado)", n)
- }
- // MAC desconocida: 404.
- rec = httptest.NewRecorder()
- r = httptest.NewRequest(http.MethodDelete, "/api/devices/11-22-33-44-55-66", nil)
- r.SetPathValue("mac", "11-22-33-44-55-66")
- s.handleDeviceDelete(rec, r)
- if rec.Code != http.StatusNotFound {
- t.Fatalf("status = %d, want 404", rec.Code)
- }
- }
- // #1151: link con validaciones (self 400, ok 200, ya enlazada 409, target
- // alias 409) y unlink (204 / 404).
- func TestDeviceLinkPutDelete(t *testing.T) {
- s := panelTestServer(t)
- do := func(method, mac, body string) *httptest.ResponseRecorder {
- r := httptest.NewRequest(method, "/api/devices/"+mac+"/link", strings.NewReader(body))
- r.SetPathValue("mac", mac)
- if body != "" {
- r.Header.Set("Content-Type", "application/json")
- }
- rec := httptest.NewRecorder()
- if method == http.MethodPut {
- s.handleDeviceLinkPut(rec, r)
- } else {
- s.handleDeviceLinkDelete(rec, r)
- }
- return rec
- }
- // self-link: 400
- if rec := do(http.MethodPut, "AA:AA:AA:00:00:01", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusBadRequest {
- t.Fatalf("self link = %d, want 400", rec.Code)
- }
- // ok: 200
- if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusOK {
- t.Fatalf("link = %d, want 200", rec.Code)
- }
- // ya enlazada: 409
- if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:09"}`); rec.Code != http.StatusConflict {
- t.Fatalf("relink = %d, want 409", rec.Code)
- }
- // target es a su vez alias: 409
- if rec := do(http.MethodPut, "AA:AA:AA:00:00:03", `{"target":"AA:AA:AA:00:00:02"}`); rec.Code != http.StatusConflict {
- t.Fatalf("target alias = %d, want 409", rec.Code)
- }
- // unlink: 204 y 404
- if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNoContent {
- t.Fatalf("unlink = %d, want 204", rec.Code)
- }
- if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNotFound {
- t.Fatalf("unlink de nuevo = %d, want 404", rec.Code)
- }
- }
- // TestDeviceLinkPutRejectsInvalidMAC verifica que PUT /api/devices/{mac}/link
- // rechaza MACs inválidas en el path o en target con 400 invalid_mac.
- func TestDeviceLinkPutRejectsInvalidMAC(t *testing.T) {
- s := newOverrideTestServer(t)
- t.Run("path con MAC inválida", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodPut, "/api/devices/no-es-mac/link", strings.NewReader(`{"target":"02:00:00:00:00:01"}`))
- req.SetPathValue("mac", "no-es-mac")
- rec := httptest.NewRecorder()
- s.handleDeviceLinkPut(rec, req)
- if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "invalid_mac") {
- t.Fatalf("esperaba 400 invalid_mac, obtuve %d: %s", rec.Code, rec.Body.String())
- }
- })
- t.Run("target con MAC inválida", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodPut, "/api/devices/02:00:00:00:00:01/link", strings.NewReader(`{"target":"basura"}`))
- req.SetPathValue("mac", "02:00:00:00:00:01")
- rec := httptest.NewRecorder()
- s.handleDeviceLinkPut(rec, req)
- if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "invalid_mac") {
- t.Fatalf("esperaba 400 invalid_mac, obtuve %d: %s", rec.Code, rec.Body.String())
- }
- })
- }
- // TestDeviceLinkDeleteLegacyNonMAC garantiza que DELETE /api/devices/{mac}/link
- // sigue siendo permisivo para poder retirar filas heredadas no-MAC.
- func TestDeviceLinkDeleteLegacyNonMAC(t *testing.T) {
- s := newOverrideTestServer(t)
- if _, err := s.db.Exec("INSERT INTO device_links (mac, canonical) VALUES (?, ?)", "LEGACY:ALIAS", "02:00:00:00:00:01"); err != nil {
- t.Fatalf("sembrar device_links: %v", err)
- }
- del := func(raw string) int {
- req := httptest.NewRequest(http.MethodDelete, "/api/devices/x/link", nil)
- req.SetPathValue("mac", raw)
- rec := httptest.NewRecorder()
- s.handleDeviceLinkDelete(rec, req)
- return rec.Code
- }
- if code := del("no-existe"); code != http.StatusNotFound {
- t.Fatalf("clave desconocida: esperaba 404, obtuve %d", code)
- }
- if code := del("legacy-alias"); code != http.StatusNoContent {
- t.Fatalf("fila heredada: esperaba 204, obtuve %d", code)
- }
- }
- // TestDeviceDeleteLegacyNonMAC garantiza que DELETE /api/devices/{mac} sigue
- // borrando filas heredadas no-MAC de device_seen con 204.
- func TestDeviceDeleteLegacyNonMAC(t *testing.T) {
- s := panelTestServer(t)
- if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('legacy-non-mac', 1, 2, 'legacy')"); err != nil {
- t.Fatalf("sembrar device_seen: %v", err)
- }
- r := httptest.NewRequest(http.MethodDelete, "/api/devices/legacy-non-mac", nil)
- r.SetPathValue("mac", "legacy-non-mac")
- rec := httptest.NewRecorder()
- s.handleDeviceDelete(rec, r)
- if rec.Code != http.StatusNoContent {
- t.Fatalf("esperaba 204, obtuve %d (%s)", rec.Code, rec.Body.String())
- }
- var n int
- if err := s.db.QueryRow("SELECT COUNT(*) FROM device_seen WHERE mac = 'legacy-non-mac'").Scan(&n); err != nil {
- t.Fatal(err)
- }
- if n != 0 {
- t.Fatalf("filas restantes = %d, esperaba 0", n)
- }
- }
- // TestDeviceDeleteLegacyNonMACNoGarbageTombstone verifica que borrar una fila
- // heredada no-MAC de device_seen no inserta una lápida basura en deleted_clients.
- func TestDeviceDeleteLegacyNonMACNoGarbageTombstone(t *testing.T) {
- s := panelTestServer(t)
- if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('legacy-non-mac', 1, 2, 'legacy')"); err != nil {
- t.Fatalf("sembrar device_seen: %v", err)
- }
- r := httptest.NewRequest(http.MethodDelete, "/api/devices/legacy-non-mac", nil)
- r.SetPathValue("mac", "legacy-non-mac")
- rec := httptest.NewRecorder()
- s.handleDeviceDelete(rec, r)
- if rec.Code != http.StatusNoContent {
- t.Fatalf("esperaba 204, obtuve %d (%s)", rec.Code, rec.Body.String())
- }
- var tombs int
- if err := s.db.QueryRow("SELECT COUNT(*) FROM deleted_clients").Scan(&tombs); err != nil {
- t.Fatal(err)
- }
- if tombs != 0 {
- t.Fatalf("no debía guardarse lápida para clave no-MAC, obtuve %d filas en deleted_clients", tombs)
- }
- }
- // #2163: la fuente de nombre elegida por cliente se guarda, se devuelve y se
- // valida contra el contrato. "auto" la limpia sin borrar el resto.
- func TestDeviceOverrideNameSource(t *testing.T) {
- s := newOverrideTestServer(t)
- mac := "aa:bb:cc:dd:ee:01"
- rec := doOverridePut(t, s, mac, `{"nameSource":"mdns"}`)
- if rec.Code != http.StatusOK {
- t.Fatalf("put nameSource: %d %s", rec.Code, rec.Body.String())
- }
- if got := doOverrideGet(t, s, mac); got["nameSource"] != "mdns" {
- t.Fatalf("nameSource no persistió: %+v", got)
- }
- // Un nombre manual y la fuente conviven: el nombre sigue mandando.
- if rec := doOverridePut(t, s, mac, `{"name":"NAS"}`); rec.Code != http.StatusOK {
- t.Fatalf("put name: %d", rec.Code)
- }
- got := doOverrideGet(t, s, mac)
- if got["name"] != "NAS" || got["nameSource"] != "mdns" {
- t.Fatalf("la fuente se perdió al guardar el nombre: %+v", got)
- }
- // Fuera del contrato: 400.
- if rec := doOverridePut(t, s, mac, `{"nameSource":"telepatia"}`); rec.Code != http.StatusBadRequest {
- t.Fatalf("fuente inválida: %d, want 400", rec.Code)
- }
- // "auto" limpia la elección y conserva el nombre manual.
- if rec := doOverridePut(t, s, mac, `{"nameSource":"auto"}`); rec.Code != http.StatusOK {
- t.Fatalf("put auto: %d", rec.Code)
- }
- got = doOverrideGet(t, s, mac)
- if got["nameSource"] != "" || got["name"] != "NAS" {
- t.Fatalf("auto debe limpiar solo la fuente: %+v", got)
- }
- }
- // #2163: la preferencia global de fuentes se guarda en orden, se valida y se
- // devuelve tal cual. Lista vacía = automática.
- func TestSettingsNameOrderRoundtrip(t *testing.T) {
- s := newOverrideTestServer(t)
- put := func(body string) *httptest.ResponseRecorder {
- req := httptest.NewRequest("PUT", "/api/settings/nameorder", strings.NewReader(body))
- req.Header.Set("Content-Type", "application/json")
- rec := httptest.NewRecorder()
- s.handleSettingsNameOrderPut(rec, req)
- return rec
- }
- get := func() map[string]any {
- req := httptest.NewRequest("GET", "/api/settings/nameorder", nil)
- rec := httptest.NewRecorder()
- s.handleSettingsNameOrderGet(rec, req)
- var out map[string]any
- if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
- t.Fatalf("get decode: %v", err)
- }
- return out
- }
- if rec := put(`{"sources":["mdns","dhcp"]}`); rec.Code != http.StatusOK {
- t.Fatalf("put: %d %s", rec.Code, rec.Body.String())
- }
- got := get()["sources"].([]any)
- if len(got) != 2 || got[0] != "mdns" || got[1] != "dhcp" {
- t.Fatalf("orden guardado = %v", got)
- }
- // Las fuentes fijadas no se pueden reordenar y lo repetido es un error.
- for _, bad := range []string{`{"sources":["manual"]}`, `{"sources":["dhcp","dhcp"]}`, `{"sources":["telepatia"]}`} {
- if rec := put(bad); rec.Code != http.StatusBadRequest {
- t.Fatalf("%s: %d, want 400", bad, rec.Code)
- }
- }
- // Vaciar vuelve a la precedencia automática.
- if rec := put(`{"sources":[]}`); rec.Code != http.StatusOK {
- t.Fatalf("put vacío: %d", rec.Code)
- }
- if got := get()["sources"].([]any); len(got) != 0 {
- t.Fatalf("tras vaciar, sources = %v", got)
- }
- }
|