device_actions_test.go 25 KB

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