device_actions_test.go 30 KB

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