device_actions_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. // device_actions_test.go — issue #439: reserva DHCP + bloqueo de dispositivo.
  2. // Todo con fakes (SSHRunner scripteable + routers en DB temporal); NINGÚN
  3. // router real se toca. Cubre create/update/idempotencia/conflicto, fallos SSH,
  4. // rollback ante fallo de reload, gate admin y validación.
  5. package httpapi_test
  6. import (
  7. "encoding/json"
  8. "errors"
  9. "io"
  10. "net/http"
  11. "net/http/httptest"
  12. "strings"
  13. "sync"
  14. "testing"
  15. "time"
  16. "github.com/gnacho/netpulse/server-go/internal/adapters"
  17. "github.com/gnacho/netpulse/server-go/internal/auth"
  18. "github.com/gnacho/netpulse/server-go/internal/config"
  19. "github.com/gnacho/netpulse/server-go/internal/db"
  20. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  21. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  22. "github.com/gnacho/netpulse/server-go/internal/sse"
  23. )
  24. const (
  25. devMAC = "aa:bb:cc:dd:ee:ff"
  26. otherMAC = "11:22:33:44:55:66"
  27. )
  28. // --- fake SSHRunner (por subcadena, en orden) ---
  29. type sshRule struct {
  30. host string // opcional: si no vacío, la regla solo aplica a ese host SSH
  31. contains string
  32. out string
  33. err error
  34. }
  35. type scriptedSSH struct {
  36. mu sync.Mutex
  37. cmds []string
  38. hosts []string
  39. rules []sshRule
  40. }
  41. func (f *scriptedSSH) Run(host, cmd string, _ time.Duration) (string, error) {
  42. f.mu.Lock()
  43. defer f.mu.Unlock()
  44. f.cmds = append(f.cmds, cmd)
  45. f.hosts = append(f.hosts, host)
  46. for _, r := range f.rules {
  47. // Desde #605 el pool entrega "host:puerto_ssh"; la regla puede estar
  48. // escrita con el host pelado, así que consideramos ambos equivalentes
  49. // cuando el puerto es el por defecto (22).
  50. if r.host != "" && r.host != host && r.host+":22" != host {
  51. continue
  52. }
  53. if strings.Contains(cmd, r.contains) {
  54. return r.out, r.err
  55. }
  56. }
  57. return "", nil
  58. }
  59. func (f *scriptedSSH) saw(substr string) bool {
  60. f.mu.Lock()
  61. defer f.mu.Unlock()
  62. for _, c := range f.cmds {
  63. if strings.Contains(c, substr) {
  64. return true
  65. }
  66. }
  67. return false
  68. }
  69. // sawHost es como saw pero acotado a un host SSH concreto (issue #537: la
  70. // reserva debe escribirse en el router que sirve DHCP, no siempre en el
  71. // gateway).
  72. //
  73. // Desde el issue #605 el pool recibe siempre "host:puerto" (SSHAddr), así que
  74. // un router SSH por defecto llega como "192.168.1.2:22". Comparar solo el host
  75. // para que los tests escritos con el host "pelado" sigan validando.
  76. func (f *scriptedSSH) sawHost(host, substr string) bool {
  77. f.mu.Lock()
  78. defer f.mu.Unlock()
  79. for i, c := range f.cmds {
  80. if i >= len(f.hosts) {
  81. continue
  82. }
  83. seen := f.hosts[i]
  84. if seen != host && seen != host+":22" {
  85. continue
  86. }
  87. if strings.Contains(c, substr) {
  88. return true
  89. }
  90. }
  91. return false
  92. }
  93. func (f *scriptedSSH) count(substr string) int {
  94. f.mu.Lock()
  95. defer f.mu.Unlock()
  96. n := 0
  97. for _, c := range f.cmds {
  98. if strings.Contains(c, substr) {
  99. n++
  100. }
  101. }
  102. return n
  103. }
  104. // --- fixtures uci show ---
  105. const dhcpEmpty = `dhcp.@dnsmasq[0]=dnsmasq
  106. dhcp.@dnsmasq[0].server='127.0.0.1#5353'
  107. dhcp.lan=dhcp
  108. dhcp.lan.interface='lan'
  109. dhcp.lan.start='100'
  110. dhcp.lan.limit='150'
  111. `
  112. const dhcpOtherHost = dhcpEmpty + `dhcp.@host[0]=host
  113. dhcp.@host[0].name='tv-salon'
  114. dhcp.@host[0].mac='11:22:33:44:55:66'
  115. dhcp.@host[0].ip='192.168.1.50'
  116. `
  117. const dhcpDevHost = dhcpEmpty + `dhcp.np_host_aabbccddeeff=host
  118. dhcp.np_host_aabbccddeeff.name='tv-salon'
  119. dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'
  120. dhcp.np_host_aabbccddeeff.ip='192.168.1.60'
  121. `
  122. const fwEmpty = `firewall.@defaults[0]=defaults
  123. firewall.@defaults[0].input='ACCEPT'
  124. firewall.lan=zone
  125. firewall.lan.name='lan'
  126. firewall.lan.network='lan'
  127. firewall.@rule[0]=rule
  128. firewall.@rule[0].name='Allow-DHCP'
  129. firewall.@rule[0].src_mac='00:00:00:00:00:00'
  130. firewall.@rule[0].target='ACCEPT'
  131. `
  132. const fwBlocked = fwEmpty + `firewall.np_block_aabbccddeeff=rule
  133. firewall.np_block_aabbccddeeff.name='np-block-aabbccddeeff'
  134. firewall.np_block_aabbccddeeff.src='lan'
  135. firewall.np_block_aabbccddeeff.dest='*'
  136. firewall.np_block_aabbccddeeff.target='DROP'
  137. firewall.np_block_aabbccddeeff.src_mac='aa:bb:cc:dd:ee:ff'
  138. `
  139. // --- servidor de test ---
  140. type deviceActionsTestServer struct {
  141. *httptest.Server
  142. db *db.DB
  143. ssh *scriptedSSH
  144. gwID string
  145. apID string
  146. cookie string
  147. }
  148. func makeDeviceActionsTestServer(t *testing.T, ssh *scriptedSSH, adapterOpt ...adapters.Snapshotter) *deviceActionsTestServer {
  149. t.Helper()
  150. dataDir := t.TempDir()
  151. cfg, err := config.Load(map[string]string{
  152. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  153. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  154. }, dataDir)
  155. if err != nil {
  156. t.Fatalf("config: %v", err)
  157. }
  158. d, err := db.Open(dataDir)
  159. if err != nil {
  160. t.Fatalf("db: %v", err)
  161. }
  162. secret, err := auth.EnsureSessionSecret(d, cfg)
  163. if err != nil {
  164. t.Fatalf("secret: %v", err)
  165. }
  166. if err := auth.EnsureUsers(d, cfg); err != nil {
  167. t.Fatalf("users: %v", err)
  168. }
  169. gw, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
  170. Name: "gateway", Host: "192.168.1.1", Type: "openwrt", IsGateway: true,
  171. })
  172. if err != nil {
  173. t.Fatalf("AddRouter gateway: %v", err)
  174. }
  175. ap, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
  176. Name: "patio", Host: "192.168.1.2", Type: "openwrt",
  177. })
  178. if err != nil {
  179. t.Fatalf("AddRouter patio: %v", err)
  180. }
  181. agents := adapters.NewAgentRegistry(0)
  182. hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
  183. var runner httpapi.SSHRunner
  184. if ssh != nil {
  185. runner = ssh
  186. }
  187. adapter := adapters.Snapshotter(adapters.NewDemo())
  188. if len(adapterOpt) > 0 && adapterOpt[0] != nil {
  189. adapter = adapterOpt[0]
  190. }
  191. handler := httpapi.NewHandler(httpapi.Deps{
  192. Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
  193. Agents: agents, Pool: runner, Started: time.Now(),
  194. })
  195. srv := httptest.NewServer(handler)
  196. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  197. if status != 204 {
  198. t.Fatalf("login: %d", status)
  199. }
  200. ts := &deviceActionsTestServer{Server: srv, db: d, ssh: ssh, gwID: gw.ID, apID: ap.ID, cookie: cookie}
  201. t.Cleanup(func() {
  202. srv.Close()
  203. d.Close()
  204. })
  205. return ts
  206. }
  207. func deviceReq(t *testing.T, method, base, path, cookie, body string) *http.Response {
  208. t.Helper()
  209. var rdr io.Reader
  210. if body != "" {
  211. rdr = strings.NewReader(body)
  212. }
  213. req, _ := http.NewRequest(method, base+path, rdr)
  214. if body != "" {
  215. req.Header.Set("Content-Type", "application/json")
  216. }
  217. if cookie != "" {
  218. req.Header.Set("Cookie", "session="+cookie)
  219. }
  220. res, err := http.DefaultClient.Do(req)
  221. if err != nil {
  222. t.Fatalf("%s %s: %v", method, path, err)
  223. }
  224. return res
  225. }
  226. func decodeBody(t *testing.T, res *http.Response) map[string]any {
  227. t.Helper()
  228. defer res.Body.Close()
  229. var m map[string]any
  230. if err := json.NewDecoder(res.Body).Decode(&m); err != nil {
  231. t.Fatalf("decode response: %v", err)
  232. }
  233. return m
  234. }
  235. // newSSH crea el fake con el `uci show` scripteado (dhcp + firewall) y reglas
  236. // extra (fallos). Por defecto todo tiene éxito.
  237. func newSSH(dhcp, fw string, extra ...sshRule) *scriptedSSH {
  238. // Los fallos (extra) van PRIMERO para que ganen sobre las salidas por
  239. // defecto cuando comparten subcadena (p. ej. "uci show dhcp").
  240. rules := append([]sshRule{}, extra...)
  241. rules = append(rules,
  242. sshRule{contains: "uci show dhcp", out: dhcp},
  243. sshRule{contains: "uci show firewall", out: fw},
  244. )
  245. return &scriptedSSH{rules: rules}
  246. }
  247. // --- Reserva DHCP ---
  248. func TestReservationCreate(t *testing.T) {
  249. ssh := newSSH(dhcpEmpty, fwEmpty)
  250. ts := makeDeviceActionsTestServer(t, ssh)
  251. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  252. `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
  253. if res.StatusCode != 200 {
  254. t.Fatalf("PUT reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
  255. }
  256. res.Body.Close()
  257. if !ssh.saw("uci set dhcp.np_host_aabbccddeeff=host") {
  258. t.Error("falta la creación de la sección host")
  259. }
  260. if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'") {
  261. t.Error("falta la mac en la sección host")
  262. }
  263. if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.ip='192.168.1.60'") {
  264. t.Error("falta la ip en la sección host")
  265. }
  266. if !ssh.saw("uci commit dhcp") {
  267. t.Error("falta uci commit dhcp")
  268. }
  269. if !ssh.saw("/etc/init.d/dnsmasq restart") {
  270. t.Error("falta el reinicio de dnsmasq")
  271. }
  272. }
  273. func TestReservationUpdate(t *testing.T) {
  274. ssh := newSSH(dhcpDevHost, fwEmpty)
  275. ts := makeDeviceActionsTestServer(t, ssh)
  276. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  277. `{"ip":"192.168.1.70"}`)
  278. if res.StatusCode != 200 {
  279. t.Fatalf("PUT reservation: %d", res.StatusCode)
  280. }
  281. res.Body.Close()
  282. if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.ip='192.168.1.70'") {
  283. t.Error("falta la actualización de ip en la sección existente")
  284. }
  285. }
  286. func TestReservationIdempotent(t *testing.T) {
  287. ssh := newSSH(dhcpDevHost, fwEmpty)
  288. ts := makeDeviceActionsTestServer(t, ssh)
  289. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  290. `{"ip":"192.168.1.60"}`)
  291. if res.StatusCode != 200 {
  292. t.Fatalf("PUT reservation idempotente: %d", res.StatusCode)
  293. }
  294. res.Body.Close()
  295. // La misma IP no debe generar conflicto (es la propia MAC).
  296. if ssh.saw("uci add") {
  297. t.Error("no debe añadir secciones nuevas en update idempotente")
  298. }
  299. }
  300. func TestReservationConflict(t *testing.T) {
  301. ssh := newSSH(dhcpOtherHost, fwEmpty)
  302. ts := makeDeviceActionsTestServer(t, ssh)
  303. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  304. `{"ip":"192.168.1.50"}`)
  305. if res.StatusCode != 409 {
  306. t.Fatalf("conflicto: got %d want 409", res.StatusCode)
  307. }
  308. body := decodeBody(t, res)
  309. if body["error"] != "ip_conflict" {
  310. t.Errorf("error code: %v", body["error"])
  311. }
  312. if ssh.saw("uci commit dhcp") {
  313. t.Error("no debe escribir nada en conflicto")
  314. }
  315. }
  316. func TestReservationGet(t *testing.T) {
  317. ssh := newSSH(dhcpDevHost, fwEmpty)
  318. ts := makeDeviceActionsTestServer(t, ssh)
  319. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  320. if res.StatusCode != 200 {
  321. t.Fatalf("GET reservation: %d", res.StatusCode)
  322. }
  323. body := decodeBody(t, res)
  324. if body["reserved"] != true || body["ip"] != "192.168.1.60" {
  325. t.Errorf("reserved payload: %v", body)
  326. }
  327. }
  328. func TestReservationGetNotReserved(t *testing.T) {
  329. ssh := newSSH(dhcpEmpty, fwEmpty)
  330. ts := makeDeviceActionsTestServer(t, ssh)
  331. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  332. body := decodeBody(t, res)
  333. if body["reserved"] != false {
  334. t.Errorf("reserved debería ser false: %v", body)
  335. }
  336. }
  337. func TestReservationNoGateway(t *testing.T) {
  338. ssh := newSSH(dhcpEmpty, fwEmpty)
  339. ts := makeDeviceActionsTestServer(t, ssh)
  340. if !routerstore.RemoveRouter(ts.db.DB, ts.gwID) {
  341. t.Fatal("no se pudo quitar el gateway")
  342. }
  343. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  344. if res.StatusCode != 400 {
  345. t.Fatalf("sin gateway: got %d want 400", res.StatusCode)
  346. }
  347. body := decodeBody(t, res)
  348. if body["error"] != "no_gateway" {
  349. t.Errorf("error code: %v", body["error"])
  350. }
  351. }
  352. func TestReservationSSHReadFailure(t *testing.T) {
  353. ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "uci show dhcp", err: errors.New("ssh down")})
  354. ts := makeDeviceActionsTestServer(t, ssh)
  355. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  356. if res.StatusCode != 500 {
  357. t.Fatalf("ssh read failure: got %d want 500", res.StatusCode)
  358. }
  359. body := decodeBody(t, res)
  360. if body["error"] != "ssh_error" {
  361. t.Errorf("error code: %v", body["error"])
  362. }
  363. }
  364. func TestReservationApplyFailure(t *testing.T) {
  365. ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "uci commit dhcp", err: errors.New("commit fail")})
  366. ts := makeDeviceActionsTestServer(t, ssh)
  367. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  368. `{"ip":"192.168.1.60"}`)
  369. if res.StatusCode != 500 {
  370. t.Fatalf("apply failure: got %d want 500", res.StatusCode)
  371. }
  372. body := decodeBody(t, res)
  373. if body["error"] != "apply_error" {
  374. t.Errorf("error code: %v", body["error"])
  375. }
  376. if ssh.saw("/etc/init.d/dnsmasq restart") {
  377. t.Error("no debe reiniciar dnsmasq si el commit falló")
  378. }
  379. }
  380. func TestReservationReloadFailureRollsBack(t *testing.T) {
  381. ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "restart", err: errors.New("reload fail")})
  382. ts := makeDeviceActionsTestServer(t, ssh)
  383. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  384. `{"ip":"192.168.1.60"}`)
  385. if res.StatusCode != 500 {
  386. t.Fatalf("reload failure: got %d want 500", res.StatusCode)
  387. }
  388. res.Body.Close()
  389. if !ssh.saw("uci delete dhcp.np_host_aabbccddeeff") {
  390. t.Error("falta el rollback (borrado de la sección recién creada)")
  391. }
  392. }
  393. func TestReservationDelete(t *testing.T) {
  394. ssh := newSSH(dhcpDevHost, fwEmpty)
  395. ts := makeDeviceActionsTestServer(t, ssh)
  396. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  397. if res.StatusCode != 200 {
  398. t.Fatalf("DELETE reservation: %d", res.StatusCode)
  399. }
  400. res.Body.Close()
  401. if !ssh.saw("uci delete dhcp.np_host_aabbccddeeff") {
  402. t.Error("falta el borrado de la sección host")
  403. }
  404. if !ssh.saw("/etc/init.d/dnsmasq restart") {
  405. t.Error("falta el reinicio de dnsmasq")
  406. }
  407. }
  408. func TestReservationDeleteNotFound(t *testing.T) {
  409. ssh := newSSH(dhcpEmpty, fwEmpty)
  410. ts := makeDeviceActionsTestServer(t, ssh)
  411. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  412. if res.StatusCode != 404 {
  413. t.Fatalf("DELETE not reserved: got %d want 404", res.StatusCode)
  414. }
  415. body := decodeBody(t, res)
  416. if body["error"] != "not_reserved" {
  417. t.Errorf("error code: %v", body["error"])
  418. }
  419. }
  420. // --- Bloqueo ---
  421. func TestBlockAdd(t *testing.T) {
  422. ssh := newSSH(dhcpEmpty, fwEmpty)
  423. ts := makeDeviceActionsTestServer(t, ssh)
  424. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  425. `{"router":"`+ts.apID+`"}`)
  426. if res.StatusCode != 200 {
  427. t.Fatalf("PUT block: %d", res.StatusCode)
  428. }
  429. res.Body.Close()
  430. if !ssh.saw("uci set firewall.np_block_aabbccddeeff=rule") {
  431. t.Error("falta la sección rule nombrada")
  432. }
  433. if !ssh.saw("uci set firewall.np_block_aabbccddeeff.src_mac='aa:bb:cc:dd:ee:ff'") {
  434. t.Error("falta src_mac")
  435. }
  436. if !ssh.saw("uci set firewall.np_block_aabbccddeeff.target='DROP'") {
  437. t.Error("falta target DROP")
  438. }
  439. if !ssh.saw("/etc/init.d/firewall restart") {
  440. t.Error("falta el reinicio del firewall")
  441. }
  442. }
  443. func TestBlockIdempotent(t *testing.T) {
  444. ssh := newSSH(dhcpEmpty, fwBlocked)
  445. ts := makeDeviceActionsTestServer(t, ssh)
  446. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  447. `{"router":"`+ts.apID+`"}`)
  448. if res.StatusCode != 200 {
  449. t.Fatalf("PUT block ya bloqueado: %d", res.StatusCode)
  450. }
  451. body := decodeBody(t, res)
  452. if body["already"] != true {
  453. t.Errorf("already: %v", body["already"])
  454. }
  455. if ssh.saw("uci commit firewall") {
  456. t.Error("no debe reescribir si ya está bloqueado")
  457. }
  458. }
  459. func TestBlockGet(t *testing.T) {
  460. ssh := newSSH(dhcpEmpty, fwBlocked)
  461. ts := makeDeviceActionsTestServer(t, ssh)
  462. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/block?router="+ts.apID, ts.cookie, "")
  463. body := decodeBody(t, res)
  464. if body["blocked"] != true {
  465. t.Errorf("blocked debería ser true: %v", body)
  466. }
  467. }
  468. func TestBlockRemove(t *testing.T) {
  469. ssh := newSSH(dhcpEmpty, fwBlocked)
  470. ts := makeDeviceActionsTestServer(t, ssh)
  471. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  472. `{"router":"`+ts.apID+`"}`)
  473. if res.StatusCode != 200 {
  474. t.Fatalf("DELETE block: %d", res.StatusCode)
  475. }
  476. res.Body.Close()
  477. if !ssh.saw("uci delete firewall.np_block_aabbccddeeff") {
  478. t.Error("falta el borrado de la regla")
  479. }
  480. if !ssh.saw("/etc/init.d/firewall restart") {
  481. t.Error("falta el reinicio del firewall")
  482. }
  483. }
  484. func TestBlockUnblockIdempotent(t *testing.T) {
  485. ssh := newSSH(dhcpEmpty, fwEmpty)
  486. ts := makeDeviceActionsTestServer(t, ssh)
  487. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  488. `{"router":"`+ts.apID+`"}`)
  489. if res.StatusCode != 200 {
  490. t.Fatalf("DELETE block no bloqueado: %d", res.StatusCode)
  491. }
  492. body := decodeBody(t, res)
  493. if body["already"] != true {
  494. t.Errorf("already: %v", body["already"])
  495. }
  496. }
  497. func TestBlockReloadFailureRollsBack(t *testing.T) {
  498. ssh := newSSH(dhcpEmpty, fwBlocked, sshRule{contains: "restart", err: errors.New("reload fail")})
  499. ts := makeDeviceActionsTestServer(t, ssh)
  500. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  501. `{"router":"`+ts.apID+`"}`)
  502. if res.StatusCode != 500 {
  503. t.Fatalf("reload failure: got %d want 500", res.StatusCode)
  504. }
  505. res.Body.Close()
  506. if !ssh.saw("uci set firewall.np_block_aabbccddeeff=rule") {
  507. t.Error("falta el rollback (re-crear la regla)")
  508. }
  509. }
  510. // --- Validación y gate admin ---
  511. func TestReservationInvalidMAC(t *testing.T) {
  512. ssh := newSSH(dhcpEmpty, fwEmpty)
  513. ts := makeDeviceActionsTestServer(t, ssh)
  514. res := deviceReq(t, "GET", ts.URL, "/api/devices/aa:bb:cc:dd:ee/reservation", ts.cookie, "")
  515. if res.StatusCode != 400 {
  516. t.Fatalf("mac inválida: got %d want 400", res.StatusCode)
  517. }
  518. body := decodeBody(t, res)
  519. if body["error"] != "invalid_mac" {
  520. t.Errorf("error code: %v", body["error"])
  521. }
  522. }
  523. func TestReservationInvalidIP(t *testing.T) {
  524. ssh := newSSH(dhcpEmpty, fwEmpty)
  525. ts := makeDeviceActionsTestServer(t, ssh)
  526. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  527. `{"ip":"no-es-ip"}`)
  528. if res.StatusCode != 400 {
  529. t.Fatalf("ip inválida: got %d want 400", res.StatusCode)
  530. }
  531. body := decodeBody(t, res)
  532. if body["error"] != "invalid_ip" {
  533. t.Errorf("error code: %v", body["error"])
  534. }
  535. }
  536. func TestBlockMissingRouter(t *testing.T) {
  537. ssh := newSSH(dhcpEmpty, fwEmpty)
  538. ts := makeDeviceActionsTestServer(t, ssh)
  539. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie, `{}`)
  540. if res.StatusCode != 400 {
  541. t.Fatalf("router ausente: got %d want 400", res.StatusCode)
  542. }
  543. body := decodeBody(t, res)
  544. if body["error"] != "missing_router" {
  545. t.Errorf("error code: %v", body["error"])
  546. }
  547. }
  548. func TestBlockUnknownRouter(t *testing.T) {
  549. ssh := newSSH(dhcpEmpty, fwEmpty)
  550. ts := makeDeviceActionsTestServer(t, ssh)
  551. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  552. `{"router":"no-existe"}`)
  553. if res.StatusCode != 400 {
  554. t.Fatalf("router desconocido: got %d want 400", res.StatusCode)
  555. }
  556. body := decodeBody(t, res)
  557. if body["error"] != "no_router" {
  558. t.Errorf("error code: %v", body["error"])
  559. }
  560. }
  561. func TestDeviceActionsAdminOnly(t *testing.T) {
  562. ssh := newSSH(dhcpEmpty, fwEmpty)
  563. ts := makeDeviceActionsTestServer(t, ssh)
  564. // Sin sesión → 401 (requireAuth global).
  565. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", "", "")
  566. if res.StatusCode != 401 {
  567. t.Errorf("sin sesión: got %d want 401", res.StatusCode)
  568. }
  569. res.Body.Close()
  570. // Rol user → 403 (RequireAdmin).
  571. _, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  572. userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewer", "clave12345", "user")
  573. for _, rt := range []struct{ method, path string }{
  574. {"GET", "/api/devices/" + devMAC + "/reservation"},
  575. {"PUT", "/api/devices/" + devMAC + "/reservation"},
  576. {"GET", "/api/devices/" + devMAC + "/block?router=" + ts.apID},
  577. {"PUT", "/api/devices/" + devMAC + "/block"},
  578. } {
  579. if got := do(t, rt.method, ts.URL, rt.path, userCookie).StatusCode; got != 403 {
  580. t.Errorf("%s %s como user: got %d want 403", rt.method, rt.path, got)
  581. }
  582. }
  583. }
  584. // --- #537: la reserva DHCP va al router que sirve el lease, no siempre al
  585. // gateway global ---
  586. // leaseAwareAdapter envuelve un adapter de test (Demo) añadiéndole la
  587. // resolución de "qué router reportó el lease de la MAC" (RouterServingDHCP).
  588. // sirve: MAC → router ID (el router que concede DHCP a esa MAC).
  589. type leaseAwareAdapter struct {
  590. adapters.Snapshotter
  591. sirve map[string]string
  592. }
  593. func (a *leaseAwareAdapter) RouterServingDHCP(mac string) string {
  594. return a.sirve[strings.ToUpper(mac)]
  595. }
  596. // El AP "patio" (192.168.1.2) es quien reporta el lease de devMAC: su host
  597. // tiene dhcpDevHost (la reserva ya existe ahí). El gateway (192.168.1.1) NO la
  598. // tiene. Con esto, la reserva debe escribirse/leerse en 192.168.1.2.
  599. func TestReservationTargetsServingRouter(t *testing.T) {
  600. ssh := &scriptedSSH{rules: []sshRule{
  601. {host: "192.168.1.2", contains: "uci show dhcp", out: dhcpDevHost},
  602. {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
  603. }}
  604. adapter := &leaseAwareAdapter{
  605. Snapshotter: adapters.NewDemo(),
  606. sirve: map[string]string{strings.ToUpper(devMAC): "patio"},
  607. }
  608. // "patio" es el Name del router creado con host 192.168.1.2 en el helper;
  609. // el helper guarda apID. Construimos el server y después recuperamos el
  610. // ID real del AP para el mapa (por si el helper genera IDs distintos).
  611. ts := makeDeviceActionsTestServer(t, ssh, adapter)
  612. adapter.sirve[strings.ToUpper(devMAC)] = ts.apID
  613. // GET: debe leer el uci show dhcp del AP (192.168.1.2), donde está la
  614. // reserva → reserved=true.
  615. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  616. if res.StatusCode != 200 {
  617. t.Fatalf("GET reservation: %d", res.StatusCode)
  618. }
  619. body := decodeBody(t, res)
  620. if body["reserved"] != true || body["ip"] != "192.168.1.60" {
  621. t.Errorf("reserved payload (desde el router que sirve DHCP): %v", body)
  622. }
  623. if !ssh.sawHost("192.168.1.2", "uci show dhcp") {
  624. t.Fatalf("GET no consultó el router que sirve DHCP: %v", ssh.hosts)
  625. }
  626. }
  627. // PUT: al crear la reserva de un dispositivo cuyo lease lo sirve el AP, el
  628. // write debe ir al AP (192.168.1.2), NO al gateway (192.168.1.1).
  629. func TestReservationPutTargetsServingRouter(t *testing.T) {
  630. ssh := &scriptedSSH{rules: []sshRule{
  631. {host: "192.168.1.2", contains: "uci show dhcp", out: dhcpEmpty},
  632. {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
  633. }}
  634. adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
  635. ts := makeDeviceActionsTestServer(t, ssh, adapter)
  636. adapter.sirve = map[string]string{strings.ToUpper(devMAC): ts.apID}
  637. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  638. `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
  639. if res.StatusCode != 200 {
  640. t.Fatalf("PUT reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
  641. }
  642. res.Body.Close()
  643. if !ssh.sawHost("192.168.1.2", "uci set dhcp.np_host_aabbccddeeff=host") {
  644. t.Error("la reserva debe escribirse en el router que sirve DHCP (192.168.1.2)")
  645. }
  646. if ssh.sawHost("192.168.1.1", "uci set dhcp.") {
  647. t.Error("la reserva NO debe escribirse en el gateway (192.168.1.1)")
  648. }
  649. if !ssh.sawHost("192.168.1.2", "/etc/init.d/dnsmasq restart") {
  650. t.Error("dnsmasq debe reiniciarse en el router que sirve DHCP")
  651. }
  652. }
  653. // DELETE: si la reserva está en el router que sirve DHCP (no en el gateway),
  654. // se borra de ahí.
  655. func TestReservationDeleteTargetsServingRouter(t *testing.T) {
  656. ssh := &scriptedSSH{rules: []sshRule{
  657. {host: "192.168.1.2", contains: "uci show dhcp", out: dhcpDevHost},
  658. {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
  659. }}
  660. adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
  661. ts := makeDeviceActionsTestServer(t, ssh, adapter)
  662. adapter.sirve = map[string]string{strings.ToUpper(devMAC): ts.apID}
  663. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  664. if res.StatusCode != 200 {
  665. t.Fatalf("DELETE reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
  666. }
  667. res.Body.Close()
  668. if !ssh.sawHost("192.168.1.2", "uci delete dhcp.np_host_aabbccddeeff") {
  669. t.Error("el borrado debe ir al router que sirve DHCP (192.168.1.2)")
  670. }
  671. if ssh.sawHost("192.168.1.1", "uci delete dhcp.") {
  672. t.Error("el borrado NO debe ir al gateway (192.168.1.1)")
  673. }
  674. }
  675. // Sin resolver (adapter por defecto, demo): la reserva sigue cayendo al
  676. // gateway (red gestionada clásica) - compatibilidad con el comportamiento
  677. // previo.
  678. func TestReservationFallsBackToGatewayWithoutResolver(t *testing.T) {
  679. ssh := &scriptedSSH{rules: []sshRule{
  680. {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
  681. {host: "192.168.1.2", contains: "uci show dhcp", out: dhcpEmpty},
  682. }}
  683. ts := makeDeviceActionsTestServer(t, ssh) // demo: sin RouterServingDHCP
  684. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  685. `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
  686. if res.StatusCode != 200 {
  687. t.Fatalf("PUT reservation: %d", res.StatusCode)
  688. }
  689. res.Body.Close()
  690. if !ssh.sawHost("192.168.1.1", "uci set dhcp.np_host_aabbccddeeff=host") {
  691. t.Error("sin resolver, la reserva debe ir al gateway (192.168.1.1)")
  692. }
  693. }
  694. // El resolver apunta a un router agent-only (sin SSH): no se puede escribir
  695. // ahí → cae al gateway (hostOfRouter devuelve vacío para agent-only).
  696. func TestReservationSkipsAgentOnlyServingRouter(t *testing.T) {
  697. ssh := &scriptedSSH{rules: []sshRule{
  698. {host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
  699. }}
  700. adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
  701. ts := makeDeviceActionsTestServer(t, ssh, adapter)
  702. // Creamos un router agent-only con host y apuntamos el resolver ahí.
  703. agentOnly, err := routerstore.AddRouter(ts.db.DB, routerstore.AddInput{
  704. Name: "sw-ao", Host: "192.168.1.9", Type: "openwrt", AgentOnly: true,
  705. })
  706. if err != nil {
  707. t.Fatalf("AddRouter agent-only: %v", err)
  708. }
  709. adapter.sirve = map[string]string{strings.ToUpper(devMAC): agentOnly.ID}
  710. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  711. `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
  712. if res.StatusCode != 200 {
  713. t.Fatalf("PUT reservation: %d", res.StatusCode)
  714. }
  715. res.Body.Close()
  716. if !ssh.sawHost("192.168.1.1", "uci set dhcp.np_host_aabbccddeeff=host") {
  717. t.Error("router agent-only sin SSH → la reserva debe caer al gateway")
  718. }
  719. if ssh.sawHost("192.168.1.9", "uci set dhcp.") {
  720. t.Error("no debe intentar escribir en el router agent-only")
  721. }
  722. }