device_actions_test.go 29 KB

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