device_actions_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. contains string
  31. out string
  32. err error
  33. }
  34. type scriptedSSH struct {
  35. mu sync.Mutex
  36. cmds []string
  37. rules []sshRule
  38. }
  39. func (f *scriptedSSH) Run(_host, cmd string, _ time.Duration) (string, error) {
  40. f.mu.Lock()
  41. defer f.mu.Unlock()
  42. f.cmds = append(f.cmds, cmd)
  43. for _, r := range f.rules {
  44. if strings.Contains(cmd, r.contains) {
  45. return r.out, r.err
  46. }
  47. }
  48. return "", nil
  49. }
  50. func (f *scriptedSSH) saw(substr string) bool {
  51. f.mu.Lock()
  52. defer f.mu.Unlock()
  53. for _, c := range f.cmds {
  54. if strings.Contains(c, substr) {
  55. return true
  56. }
  57. }
  58. return false
  59. }
  60. func (f *scriptedSSH) count(substr string) int {
  61. f.mu.Lock()
  62. defer f.mu.Unlock()
  63. n := 0
  64. for _, c := range f.cmds {
  65. if strings.Contains(c, substr) {
  66. n++
  67. }
  68. }
  69. return n
  70. }
  71. // --- fixtures uci show ---
  72. const dhcpEmpty = `dhcp.@dnsmasq[0]=dnsmasq
  73. dhcp.@dnsmasq[0].server='127.0.0.1#5353'
  74. dhcp.lan=dhcp
  75. dhcp.lan.interface='lan'
  76. dhcp.lan.start='100'
  77. dhcp.lan.limit='150'
  78. `
  79. const dhcpOtherHost = dhcpEmpty + `dhcp.@host[0]=host
  80. dhcp.@host[0].name='tv-salon'
  81. dhcp.@host[0].mac='11:22:33:44:55:66'
  82. dhcp.@host[0].ip='192.168.1.50'
  83. `
  84. const dhcpDevHost = dhcpEmpty + `dhcp.np_host_aabbccddeeff=host
  85. dhcp.np_host_aabbccddeeff.name='tv-salon'
  86. dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'
  87. dhcp.np_host_aabbccddeeff.ip='192.168.1.60'
  88. `
  89. const fwEmpty = `firewall.@defaults[0]=defaults
  90. firewall.@defaults[0].input='ACCEPT'
  91. firewall.lan=zone
  92. firewall.lan.name='lan'
  93. firewall.lan.network='lan'
  94. firewall.@rule[0]=rule
  95. firewall.@rule[0].name='Allow-DHCP'
  96. firewall.@rule[0].src_mac='00:00:00:00:00:00'
  97. firewall.@rule[0].target='ACCEPT'
  98. `
  99. const fwBlocked = fwEmpty + `firewall.np_block_aabbccddeeff=rule
  100. firewall.np_block_aabbccddeeff.name='np-block-aabbccddeeff'
  101. firewall.np_block_aabbccddeeff.src='lan'
  102. firewall.np_block_aabbccddeeff.dest='*'
  103. firewall.np_block_aabbccddeeff.target='DROP'
  104. firewall.np_block_aabbccddeeff.src_mac='aa:bb:cc:dd:ee:ff'
  105. `
  106. // --- servidor de test ---
  107. type deviceActionsTestServer struct {
  108. *httptest.Server
  109. db *db.DB
  110. ssh *scriptedSSH
  111. gwID string
  112. apID string
  113. cookie string
  114. }
  115. func makeDeviceActionsTestServer(t *testing.T, ssh *scriptedSSH) *deviceActionsTestServer {
  116. t.Helper()
  117. dataDir := t.TempDir()
  118. cfg, err := config.Load(map[string]string{
  119. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  120. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  121. }, dataDir)
  122. if err != nil {
  123. t.Fatalf("config: %v", err)
  124. }
  125. d, err := db.Open(dataDir)
  126. if err != nil {
  127. t.Fatalf("db: %v", err)
  128. }
  129. secret, err := auth.EnsureSessionSecret(d, cfg)
  130. if err != nil {
  131. t.Fatalf("secret: %v", err)
  132. }
  133. if err := auth.EnsureUsers(d, cfg); err != nil {
  134. t.Fatalf("users: %v", err)
  135. }
  136. gw, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
  137. Name: "gateway", Host: "192.168.1.1", Type: "openwrt", IsGateway: true,
  138. })
  139. if err != nil {
  140. t.Fatalf("AddRouter gateway: %v", err)
  141. }
  142. ap, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
  143. Name: "patio", Host: "192.168.1.2", Type: "openwrt",
  144. })
  145. if err != nil {
  146. t.Fatalf("AddRouter patio: %v", err)
  147. }
  148. agents := adapters.NewAgentRegistry(0)
  149. hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
  150. var runner httpapi.SSHRunner
  151. if ssh != nil {
  152. runner = ssh
  153. }
  154. handler := httpapi.NewHandler(httpapi.Deps{
  155. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
  156. Agents: agents, Pool: runner, Started: time.Now(),
  157. })
  158. srv := httptest.NewServer(handler)
  159. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  160. if status != 204 {
  161. t.Fatalf("login: %d", status)
  162. }
  163. ts := &deviceActionsTestServer{Server: srv, db: d, ssh: ssh, gwID: gw.ID, apID: ap.ID, cookie: cookie}
  164. t.Cleanup(func() {
  165. srv.Close()
  166. d.Close()
  167. })
  168. return ts
  169. }
  170. func deviceReq(t *testing.T, method, base, path, cookie, body string) *http.Response {
  171. t.Helper()
  172. var rdr io.Reader
  173. if body != "" {
  174. rdr = strings.NewReader(body)
  175. }
  176. req, _ := http.NewRequest(method, base+path, rdr)
  177. if body != "" {
  178. req.Header.Set("Content-Type", "application/json")
  179. }
  180. if cookie != "" {
  181. req.Header.Set("Cookie", "session="+cookie)
  182. }
  183. res, err := http.DefaultClient.Do(req)
  184. if err != nil {
  185. t.Fatalf("%s %s: %v", method, path, err)
  186. }
  187. return res
  188. }
  189. func decodeBody(t *testing.T, res *http.Response) map[string]any {
  190. t.Helper()
  191. defer res.Body.Close()
  192. var m map[string]any
  193. if err := json.NewDecoder(res.Body).Decode(&m); err != nil {
  194. t.Fatalf("decode response: %v", err)
  195. }
  196. return m
  197. }
  198. // newSSH crea el fake con el `uci show` scripteado (dhcp + firewall) y reglas
  199. // extra (fallos). Por defecto todo tiene éxito.
  200. func newSSH(dhcp, fw string, extra ...sshRule) *scriptedSSH {
  201. // Los fallos (extra) van PRIMERO para que ganen sobre las salidas por
  202. // defecto cuando comparten subcadena (p. ej. "uci show dhcp").
  203. rules := append([]sshRule{}, extra...)
  204. rules = append(rules,
  205. sshRule{contains: "uci show dhcp", out: dhcp},
  206. sshRule{contains: "uci show firewall", out: fw},
  207. )
  208. return &scriptedSSH{rules: rules}
  209. }
  210. // --- Reserva DHCP ---
  211. func TestReservationCreate(t *testing.T) {
  212. ssh := newSSH(dhcpEmpty, fwEmpty)
  213. ts := makeDeviceActionsTestServer(t, ssh)
  214. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  215. `{"ip":"192.168.1.60","hostname":"tv-salon"}`)
  216. if res.StatusCode != 200 {
  217. t.Fatalf("PUT reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
  218. }
  219. res.Body.Close()
  220. if !ssh.saw("uci set dhcp.np_host_aabbccddeeff=host") {
  221. t.Error("falta la creación de la sección host")
  222. }
  223. if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'") {
  224. t.Error("falta la mac en la sección host")
  225. }
  226. if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.ip='192.168.1.60'") {
  227. t.Error("falta la ip en la sección host")
  228. }
  229. if !ssh.saw("uci commit dhcp") {
  230. t.Error("falta uci commit dhcp")
  231. }
  232. if !ssh.saw("/etc/init.d/dnsmasq restart") {
  233. t.Error("falta el reinicio de dnsmasq")
  234. }
  235. }
  236. func TestReservationUpdate(t *testing.T) {
  237. ssh := newSSH(dhcpDevHost, fwEmpty)
  238. ts := makeDeviceActionsTestServer(t, ssh)
  239. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  240. `{"ip":"192.168.1.70"}`)
  241. if res.StatusCode != 200 {
  242. t.Fatalf("PUT reservation: %d", res.StatusCode)
  243. }
  244. res.Body.Close()
  245. if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.ip='192.168.1.70'") {
  246. t.Error("falta la actualización de ip en la sección existente")
  247. }
  248. }
  249. func TestReservationIdempotent(t *testing.T) {
  250. ssh := newSSH(dhcpDevHost, fwEmpty)
  251. ts := makeDeviceActionsTestServer(t, ssh)
  252. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  253. `{"ip":"192.168.1.60"}`)
  254. if res.StatusCode != 200 {
  255. t.Fatalf("PUT reservation idempotente: %d", res.StatusCode)
  256. }
  257. res.Body.Close()
  258. // La misma IP no debe generar conflicto (es la propia MAC).
  259. if ssh.saw("uci add") {
  260. t.Error("no debe añadir secciones nuevas en update idempotente")
  261. }
  262. }
  263. func TestReservationConflict(t *testing.T) {
  264. ssh := newSSH(dhcpOtherHost, fwEmpty)
  265. ts := makeDeviceActionsTestServer(t, ssh)
  266. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  267. `{"ip":"192.168.1.50"}`)
  268. if res.StatusCode != 409 {
  269. t.Fatalf("conflicto: got %d want 409", res.StatusCode)
  270. }
  271. body := decodeBody(t, res)
  272. if body["error"] != "ip_conflict" {
  273. t.Errorf("error code: %v", body["error"])
  274. }
  275. if ssh.saw("uci commit dhcp") {
  276. t.Error("no debe escribir nada en conflicto")
  277. }
  278. }
  279. func TestReservationGet(t *testing.T) {
  280. ssh := newSSH(dhcpDevHost, fwEmpty)
  281. ts := makeDeviceActionsTestServer(t, ssh)
  282. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  283. if res.StatusCode != 200 {
  284. t.Fatalf("GET reservation: %d", res.StatusCode)
  285. }
  286. body := decodeBody(t, res)
  287. if body["reserved"] != true || body["ip"] != "192.168.1.60" {
  288. t.Errorf("reserved payload: %v", body)
  289. }
  290. }
  291. func TestReservationGetNotReserved(t *testing.T) {
  292. ssh := newSSH(dhcpEmpty, fwEmpty)
  293. ts := makeDeviceActionsTestServer(t, ssh)
  294. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  295. body := decodeBody(t, res)
  296. if body["reserved"] != false {
  297. t.Errorf("reserved debería ser false: %v", body)
  298. }
  299. }
  300. func TestReservationNoGateway(t *testing.T) {
  301. ssh := newSSH(dhcpEmpty, fwEmpty)
  302. ts := makeDeviceActionsTestServer(t, ssh)
  303. if !routerstore.RemoveRouter(ts.db.DB, ts.gwID) {
  304. t.Fatal("no se pudo quitar el gateway")
  305. }
  306. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  307. if res.StatusCode != 400 {
  308. t.Fatalf("sin gateway: got %d want 400", res.StatusCode)
  309. }
  310. body := decodeBody(t, res)
  311. if body["error"] != "no_gateway" {
  312. t.Errorf("error code: %v", body["error"])
  313. }
  314. }
  315. func TestReservationSSHReadFailure(t *testing.T) {
  316. ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "uci show dhcp", err: errors.New("ssh down")})
  317. ts := makeDeviceActionsTestServer(t, ssh)
  318. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  319. if res.StatusCode != 500 {
  320. t.Fatalf("ssh read failure: got %d want 500", res.StatusCode)
  321. }
  322. body := decodeBody(t, res)
  323. if body["error"] != "ssh_error" {
  324. t.Errorf("error code: %v", body["error"])
  325. }
  326. }
  327. func TestReservationApplyFailure(t *testing.T) {
  328. ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "uci commit dhcp", err: errors.New("commit fail")})
  329. ts := makeDeviceActionsTestServer(t, ssh)
  330. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  331. `{"ip":"192.168.1.60"}`)
  332. if res.StatusCode != 500 {
  333. t.Fatalf("apply failure: got %d want 500", res.StatusCode)
  334. }
  335. body := decodeBody(t, res)
  336. if body["error"] != "apply_error" {
  337. t.Errorf("error code: %v", body["error"])
  338. }
  339. if ssh.saw("/etc/init.d/dnsmasq restart") {
  340. t.Error("no debe reiniciar dnsmasq si el commit falló")
  341. }
  342. }
  343. func TestReservationReloadFailureRollsBack(t *testing.T) {
  344. ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{contains: "restart", err: errors.New("reload fail")})
  345. ts := makeDeviceActionsTestServer(t, ssh)
  346. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  347. `{"ip":"192.168.1.60"}`)
  348. if res.StatusCode != 500 {
  349. t.Fatalf("reload failure: got %d want 500", res.StatusCode)
  350. }
  351. res.Body.Close()
  352. if !ssh.saw("uci delete dhcp.np_host_aabbccddeeff") {
  353. t.Error("falta el rollback (borrado de la sección recién creada)")
  354. }
  355. }
  356. func TestReservationDelete(t *testing.T) {
  357. ssh := newSSH(dhcpDevHost, fwEmpty)
  358. ts := makeDeviceActionsTestServer(t, ssh)
  359. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  360. if res.StatusCode != 200 {
  361. t.Fatalf("DELETE reservation: %d", res.StatusCode)
  362. }
  363. res.Body.Close()
  364. if !ssh.saw("uci delete dhcp.np_host_aabbccddeeff") {
  365. t.Error("falta el borrado de la sección host")
  366. }
  367. if !ssh.saw("/etc/init.d/dnsmasq restart") {
  368. t.Error("falta el reinicio de dnsmasq")
  369. }
  370. }
  371. func TestReservationDeleteNotFound(t *testing.T) {
  372. ssh := newSSH(dhcpEmpty, fwEmpty)
  373. ts := makeDeviceActionsTestServer(t, ssh)
  374. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
  375. if res.StatusCode != 404 {
  376. t.Fatalf("DELETE not reserved: got %d want 404", res.StatusCode)
  377. }
  378. body := decodeBody(t, res)
  379. if body["error"] != "not_reserved" {
  380. t.Errorf("error code: %v", body["error"])
  381. }
  382. }
  383. // --- Bloqueo ---
  384. func TestBlockAdd(t *testing.T) {
  385. ssh := newSSH(dhcpEmpty, fwEmpty)
  386. ts := makeDeviceActionsTestServer(t, ssh)
  387. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  388. `{"router":"`+ts.apID+`"}`)
  389. if res.StatusCode != 200 {
  390. t.Fatalf("PUT block: %d", res.StatusCode)
  391. }
  392. res.Body.Close()
  393. if !ssh.saw("uci set firewall.np_block_aabbccddeeff=rule") {
  394. t.Error("falta la sección rule nombrada")
  395. }
  396. if !ssh.saw("uci set firewall.np_block_aabbccddeeff.src_mac='aa:bb:cc:dd:ee:ff'") {
  397. t.Error("falta src_mac")
  398. }
  399. if !ssh.saw("uci set firewall.np_block_aabbccddeeff.target='DROP'") {
  400. t.Error("falta target DROP")
  401. }
  402. if !ssh.saw("/etc/init.d/firewall restart") {
  403. t.Error("falta el reinicio del firewall")
  404. }
  405. }
  406. func TestBlockIdempotent(t *testing.T) {
  407. ssh := newSSH(dhcpEmpty, fwBlocked)
  408. ts := makeDeviceActionsTestServer(t, ssh)
  409. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  410. `{"router":"`+ts.apID+`"}`)
  411. if res.StatusCode != 200 {
  412. t.Fatalf("PUT block ya bloqueado: %d", res.StatusCode)
  413. }
  414. body := decodeBody(t, res)
  415. if body["already"] != true {
  416. t.Errorf("already: %v", body["already"])
  417. }
  418. if ssh.saw("uci commit firewall") {
  419. t.Error("no debe reescribir si ya está bloqueado")
  420. }
  421. }
  422. func TestBlockGet(t *testing.T) {
  423. ssh := newSSH(dhcpEmpty, fwBlocked)
  424. ts := makeDeviceActionsTestServer(t, ssh)
  425. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/block?router="+ts.apID, ts.cookie, "")
  426. body := decodeBody(t, res)
  427. if body["blocked"] != true {
  428. t.Errorf("blocked debería ser true: %v", body)
  429. }
  430. }
  431. func TestBlockRemove(t *testing.T) {
  432. ssh := newSSH(dhcpEmpty, fwBlocked)
  433. ts := makeDeviceActionsTestServer(t, ssh)
  434. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  435. `{"router":"`+ts.apID+`"}`)
  436. if res.StatusCode != 200 {
  437. t.Fatalf("DELETE block: %d", res.StatusCode)
  438. }
  439. res.Body.Close()
  440. if !ssh.saw("uci delete firewall.np_block_aabbccddeeff") {
  441. t.Error("falta el borrado de la regla")
  442. }
  443. if !ssh.saw("/etc/init.d/firewall restart") {
  444. t.Error("falta el reinicio del firewall")
  445. }
  446. }
  447. func TestBlockUnblockIdempotent(t *testing.T) {
  448. ssh := newSSH(dhcpEmpty, fwEmpty)
  449. ts := makeDeviceActionsTestServer(t, ssh)
  450. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  451. `{"router":"`+ts.apID+`"}`)
  452. if res.StatusCode != 200 {
  453. t.Fatalf("DELETE block no bloqueado: %d", res.StatusCode)
  454. }
  455. body := decodeBody(t, res)
  456. if body["already"] != true {
  457. t.Errorf("already: %v", body["already"])
  458. }
  459. }
  460. func TestBlockReloadFailureRollsBack(t *testing.T) {
  461. ssh := newSSH(dhcpEmpty, fwBlocked, sshRule{contains: "restart", err: errors.New("reload fail")})
  462. ts := makeDeviceActionsTestServer(t, ssh)
  463. res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  464. `{"router":"`+ts.apID+`"}`)
  465. if res.StatusCode != 500 {
  466. t.Fatalf("reload failure: got %d want 500", res.StatusCode)
  467. }
  468. res.Body.Close()
  469. if !ssh.saw("uci set firewall.np_block_aabbccddeeff=rule") {
  470. t.Error("falta el rollback (re-crear la regla)")
  471. }
  472. }
  473. // --- Validación y gate admin ---
  474. func TestReservationInvalidMAC(t *testing.T) {
  475. ssh := newSSH(dhcpEmpty, fwEmpty)
  476. ts := makeDeviceActionsTestServer(t, ssh)
  477. res := deviceReq(t, "GET", ts.URL, "/api/devices/aa:bb:cc:dd:ee/reservation", ts.cookie, "")
  478. if res.StatusCode != 400 {
  479. t.Fatalf("mac inválida: got %d want 400", res.StatusCode)
  480. }
  481. body := decodeBody(t, res)
  482. if body["error"] != "invalid_mac" {
  483. t.Errorf("error code: %v", body["error"])
  484. }
  485. }
  486. func TestReservationInvalidIP(t *testing.T) {
  487. ssh := newSSH(dhcpEmpty, fwEmpty)
  488. ts := makeDeviceActionsTestServer(t, ssh)
  489. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
  490. `{"ip":"no-es-ip"}`)
  491. if res.StatusCode != 400 {
  492. t.Fatalf("ip inválida: got %d want 400", res.StatusCode)
  493. }
  494. body := decodeBody(t, res)
  495. if body["error"] != "invalid_ip" {
  496. t.Errorf("error code: %v", body["error"])
  497. }
  498. }
  499. func TestBlockMissingRouter(t *testing.T) {
  500. ssh := newSSH(dhcpEmpty, fwEmpty)
  501. ts := makeDeviceActionsTestServer(t, ssh)
  502. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie, `{}`)
  503. if res.StatusCode != 400 {
  504. t.Fatalf("router ausente: got %d want 400", res.StatusCode)
  505. }
  506. body := decodeBody(t, res)
  507. if body["error"] != "missing_router" {
  508. t.Errorf("error code: %v", body["error"])
  509. }
  510. }
  511. func TestBlockUnknownRouter(t *testing.T) {
  512. ssh := newSSH(dhcpEmpty, fwEmpty)
  513. ts := makeDeviceActionsTestServer(t, ssh)
  514. res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block", ts.cookie,
  515. `{"router":"no-existe"}`)
  516. if res.StatusCode != 400 {
  517. t.Fatalf("router desconocido: got %d want 400", res.StatusCode)
  518. }
  519. body := decodeBody(t, res)
  520. if body["error"] != "no_router" {
  521. t.Errorf("error code: %v", body["error"])
  522. }
  523. }
  524. func TestDeviceActionsAdminOnly(t *testing.T) {
  525. ssh := newSSH(dhcpEmpty, fwEmpty)
  526. ts := makeDeviceActionsTestServer(t, ssh)
  527. // Sin sesión → 401 (requireAuth global).
  528. res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", "", "")
  529. if res.StatusCode != 401 {
  530. t.Errorf("sin sesión: got %d want 401", res.StatusCode)
  531. }
  532. res.Body.Close()
  533. // Rol user → 403 (RequireAdmin).
  534. _, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  535. userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewer", "clave12345", "user")
  536. for _, rt := range []struct{ method, path string }{
  537. {"GET", "/api/devices/" + devMAC + "/reservation"},
  538. {"PUT", "/api/devices/" + devMAC + "/reservation"},
  539. {"GET", "/api/devices/" + devMAC + "/block?router=" + ts.apID},
  540. {"PUT", "/api/devices/" + devMAC + "/block"},
  541. } {
  542. if got := do(t, rt.method, ts.URL, rt.path, userCookie).StatusCode; got != 403 {
  543. t.Errorf("%s %s como user: got %d want 403", rt.method, rt.path, got)
  544. }
  545. }
  546. }