device_actions.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. // device_actions.go — acciones directas sobre routers para un dispositivo
  2. // (issue #439): reserva DHCP estática en el gateway y bloqueo MAC en el router
  3. // de atache. Escriben /etc/config/dhcp y /etc/config/firewall vía SSH
  4. // (SSHRunner, fakeable en tests) usando uci, con `uci commit` como límite
  5. // atómico y rollback si el reinicio del servicio falla (sin config a medias).
  6. package httpapi
  7. import (
  8. "fmt"
  9. "log"
  10. "net"
  11. "net/http"
  12. "regexp"
  13. "strings"
  14. "time"
  15. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  16. )
  17. // Techos para los comandos uci sobre SSH (show = lectura, apply = escritura
  18. // + commit + reload). Los fija el skill de ejecución; no son configurables.
  19. const (
  20. uciShowTimeout = 10 * time.Second
  21. uciApplyTimeout = 20 * time.Second
  22. )
  23. var reUciLine = regexp.MustCompile(`^([a-z0-9_]+)\.([^=]+)=(.*)$`)
  24. var reUciQuoted = regexp.MustCompile(`^'(.*)'$`)
  25. // uciValue devuelve el valor sin comillas de una línea `cfg.sect.opt='val'`.
  26. func uciValue(raw string) string {
  27. if m := reUciQuoted.FindStringSubmatch(raw); m != nil {
  28. return m[1]
  29. }
  30. return raw
  31. }
  32. // gatewayHost devuelve el host SSH del gateway (router con is_gateway), o ""
  33. // si no hay gateway configurado o es agent-only. El gateway es quien sirve
  34. // DHCP (dnsmasq), así que es el target de las reservas de lease.
  35. func (s *server) gatewayHost() string {
  36. for _, r := range routerstore.ListRouters(s.db.DB) {
  37. if r.IsGateway && !r.AgentOnly && r.Host != "" {
  38. return r.Host
  39. }
  40. }
  41. return ""
  42. }
  43. // uciShow ejecuta `uci show <config>` en un host y devuelve líneas parseables.
  44. func (s *server) uciShow(host, config string) ([]string, error) {
  45. if s.pool == nil {
  46. return nil, fmt.Errorf("no hay pool SSH")
  47. }
  48. out, err := s.pool.Run(host, fmt.Sprintf("uci show %s", config), uciShowTimeout)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return strings.Split(out, "\n"), nil
  53. }
  54. // runUCICommands encadena comandos uci + `uci commit <config>` en UNA sesión
  55. // SSH. `uci commit` es el límite atómico: si un `uci set/delete` falla antes,
  56. // el `&&` corta y /etc/config queda intacto (staging descartado).
  57. func (s *server) runUCICommands(host, config string, commands []string) error {
  58. if s.pool == nil {
  59. return fmt.Errorf("no hay pool SSH")
  60. }
  61. script := strings.Join(append(commands, "uci commit "+config), " && ")
  62. _, err := s.pool.Run(host, script, uciApplyTimeout)
  63. return err
  64. }
  65. // reloadService reinicia el servicio procd que aplica la config commitada.
  66. func (s *server) reloadService(host, service string) error {
  67. if s.pool == nil {
  68. return fmt.Errorf("no hay pool SSH")
  69. }
  70. _, err := s.pool.Run(host, "/etc/init.d/"+service+" restart", uciApplyTimeout)
  71. return err
  72. }
  73. // ---------------------------------------------------------------------------
  74. // Reserva DHCP (host sections de /etc/config/dhcp)
  75. // ---------------------------------------------------------------------------
  76. // dhcpHost representa una sección host de dhcp UCI.
  77. type dhcpHost struct {
  78. Section string
  79. Name string
  80. MAC string
  81. IP string
  82. }
  83. // uciTypeSections devuelve el conjunto de secciones de un config cuya línea de
  84. // tipo (`cfg.<section>=<type>`) coincide con el tipo pedido.
  85. func uciTypeSections(lines []string, config, typ string) map[string]bool {
  86. sections := map[string]bool{}
  87. for _, raw := range lines {
  88. line := strings.TrimSpace(raw)
  89. m := reUciLine.FindStringSubmatch(line)
  90. if m == nil || m[1] != config {
  91. continue
  92. }
  93. if strings.Index(m[2], ".") >= 0 {
  94. continue // es una opción, no la línea de tipo
  95. }
  96. if uciValue(m[3]) == typ {
  97. sections[m[2]] = true
  98. }
  99. }
  100. return sections
  101. }
  102. // parseDhcpHosts parsea `uci show dhcp` y devuelve SOLO las secciones de tipo
  103. // host (named `dhcp.np_host_x=host` y anónimas `dhcp.@host[0]=host`), filtrando
  104. // el ruido de @dnsmasq[0], lan, wan, etc.
  105. func parseDhcpHosts(lines []string) []*dhcpHost {
  106. hostSections := uciTypeSections(lines, "dhcp", "host")
  107. var hosts []*dhcpHost
  108. bySection := map[string]*dhcpHost{}
  109. for _, raw := range lines {
  110. line := strings.TrimSpace(raw)
  111. if line == "" {
  112. continue
  113. }
  114. m := reUciLine.FindStringSubmatch(line)
  115. if m == nil || m[1] != "dhcp" {
  116. continue
  117. }
  118. dot := strings.Index(m[2], ".")
  119. if dot < 0 {
  120. continue
  121. }
  122. section, option := m[2][:dot], m[2][dot+1:]
  123. if !hostSections[section] {
  124. continue
  125. }
  126. h := bySection[section]
  127. if h == nil {
  128. h = &dhcpHost{Section: section}
  129. bySection[section] = h
  130. hosts = append(hosts, h)
  131. }
  132. switch option {
  133. case "name":
  134. h.Name = uciValue(m[3])
  135. case "mac":
  136. h.MAC = uciValue(m[3])
  137. case "ip":
  138. h.IP = uciValue(m[3])
  139. }
  140. }
  141. return hosts
  142. }
  143. // findDhcpHost busca una sección host cuya MAC coincida (sin importar el
  144. // formato; admite varias MACs separadas por coma/espacio en una misma sección).
  145. func findDhcpHost(hosts []*dhcpHost, mac string) *dhcpHost {
  146. macNorm := normalizeMAC(mac)
  147. for _, h := range hosts {
  148. for _, m := range strings.FieldsFunc(h.MAC, func(r rune) bool { return r == ',' || r == ' ' }) {
  149. if normalizeMAC(m) == macNorm {
  150. return h
  151. }
  152. }
  153. }
  154. return nil
  155. }
  156. // dhcpHostSection es el nombre de sección determinista para la reserva de una
  157. // MAC (uci set dhcp.np_host_<mac12>=host).
  158. func dhcpHostSection(mac string) string {
  159. return "np_host_" + strings.ReplaceAll(mac, ":", "")
  160. }
  161. // handleDeviceReservationGet devuelve la reserva DHCP estática de un dispositivo.
  162. func (s *server) handleDeviceReservationGet(w http.ResponseWriter, r *http.Request) {
  163. mac := normalizeMAC(r.PathValue("mac"))
  164. if len(mac) != 17 {
  165. writeError(w, http.StatusBadRequest, "invalid_mac")
  166. return
  167. }
  168. host := s.gatewayHost()
  169. if host == "" {
  170. writeError(w, http.StatusBadRequest, "no_gateway")
  171. return
  172. }
  173. lines, err := s.uciShow(host, "dhcp")
  174. if err != nil {
  175. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  176. return
  177. }
  178. hosts := parseDhcpHosts(lines)
  179. if h := findDhcpHost(hosts, mac); h != nil {
  180. writeJSON(w, http.StatusOK, map[string]any{
  181. "reserved": true,
  182. "ip": h.IP,
  183. "name": h.Name,
  184. })
  185. return
  186. }
  187. writeJSON(w, http.StatusOK, map[string]any{"reserved": false})
  188. }
  189. // handleDeviceReservationPut crea o actualiza una reserva DHCP estática.
  190. // Idempotente (misma MAC+IP → no-op). Rechaza con 409 si OTRA MAC ya tiene
  191. // reservada la IP pedida.
  192. func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Request) {
  193. mac := normalizeMAC(r.PathValue("mac"))
  194. if len(mac) != 17 {
  195. writeError(w, http.StatusBadRequest, "invalid_mac")
  196. return
  197. }
  198. var body struct {
  199. IP string `json:"ip"`
  200. Hostname string `json:"hostname"`
  201. }
  202. if st := readJSONBody(w, r, &body); st != 0 {
  203. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  204. return
  205. }
  206. if net.ParseIP(body.IP) == nil {
  207. writeError(w, http.StatusBadRequest, "invalid_ip")
  208. return
  209. }
  210. host := s.gatewayHost()
  211. if host == "" {
  212. writeError(w, http.StatusBadRequest, "no_gateway")
  213. return
  214. }
  215. lines, err := s.uciShow(host, "dhcp")
  216. if err != nil {
  217. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  218. return
  219. }
  220. hosts := parseDhcpHosts(lines)
  221. // Conflicto: otra MAC (distinta de ésta) ya tiene esa IP reservada.
  222. for _, h := range hosts {
  223. if h.IP != body.IP {
  224. continue
  225. }
  226. if findDhcpHost([]*dhcpHost{h}, mac) != nil {
  227. continue // es la sección de esta misma MAC (update idempotente)
  228. }
  229. writeError(w, http.StatusConflict, "ip_conflict",
  230. fmt.Sprintf("la IP %s ya está reservada para %s", body.IP, h.MAC))
  231. return
  232. }
  233. existing := findDhcpHost(hosts, mac)
  234. var apply, rollback []string
  235. if existing != nil {
  236. oldIP := existing.IP
  237. apply = append(apply, fmt.Sprintf("uci set dhcp.%s.ip='%s'", existing.Section, body.IP))
  238. if body.Hostname != "" && body.Hostname != existing.Name {
  239. apply = append(apply, fmt.Sprintf("uci set dhcp.%s.name='%s'", existing.Section, body.Hostname))
  240. }
  241. rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s.ip='%s'", existing.Section, oldIP))
  242. } else {
  243. section := dhcpHostSection(mac)
  244. name := body.Hostname
  245. if name == "" {
  246. name = mac
  247. }
  248. apply = append(apply,
  249. fmt.Sprintf("uci set dhcp.%s=host", section),
  250. fmt.Sprintf("uci set dhcp.%s.name='%s'", section, name),
  251. fmt.Sprintf("uci set dhcp.%s.mac='%s'", section, mac),
  252. fmt.Sprintf("uci set dhcp.%s.ip='%s'", section, body.IP),
  253. )
  254. rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
  255. }
  256. if err := s.runUCICommands(host, "dhcp", apply); err != nil {
  257. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  258. return
  259. }
  260. if err := s.reloadService(host, "dnsmasq"); err != nil {
  261. if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
  262. log.Printf("[netpulse] rollback reserva %s falló: %v", mac, rbErr)
  263. }
  264. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  265. return
  266. }
  267. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "ip": body.IP})
  268. }
  269. // handleDeviceReservationDelete elimina la reserva DHCP estática.
  270. func (s *server) handleDeviceReservationDelete(w http.ResponseWriter, r *http.Request) {
  271. mac := normalizeMAC(r.PathValue("mac"))
  272. if len(mac) != 17 {
  273. writeError(w, http.StatusBadRequest, "invalid_mac")
  274. return
  275. }
  276. host := s.gatewayHost()
  277. if host == "" {
  278. writeError(w, http.StatusBadRequest, "no_gateway")
  279. return
  280. }
  281. lines, err := s.uciShow(host, "dhcp")
  282. if err != nil {
  283. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  284. return
  285. }
  286. hosts := parseDhcpHosts(lines)
  287. h := findDhcpHost(hosts, mac)
  288. if h == nil {
  289. writeError(w, http.StatusNotFound, "not_reserved")
  290. return
  291. }
  292. // Rollback = re-crear la sección tal cual estaba (si el reload falla).
  293. var rollback []string
  294. rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s=host", h.Section))
  295. if h.Name != "" {
  296. rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s.name='%s'", h.Section, h.Name))
  297. }
  298. if h.MAC != "" {
  299. rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s.mac='%s'", h.Section, h.MAC))
  300. }
  301. if h.IP != "" {
  302. rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s.ip='%s'", h.Section, h.IP))
  303. }
  304. apply := []string{fmt.Sprintf("uci delete dhcp.%s", h.Section)}
  305. if err := s.runUCICommands(host, "dhcp", apply); err != nil {
  306. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  307. return
  308. }
  309. if err := s.reloadService(host, "dnsmasq"); err != nil {
  310. if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
  311. log.Printf("[netpulse] rollback borrado reserva %s falló: %v", mac, rbErr)
  312. }
  313. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  314. return
  315. }
  316. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  317. }
  318. // ---------------------------------------------------------------------------
  319. // Bloqueo de dispositivo (rule de /etc/config/firewall, fw4)
  320. // ---------------------------------------------------------------------------
  321. // firewallRule representa una sección rule de firewall UCI.
  322. type firewallRule struct {
  323. Section string
  324. Name string
  325. SrcMAC string
  326. Target string
  327. }
  328. // parseFirewallRules parsea `uci show firewall` y devuelve las reglas (named
  329. // `firewall.np_block_x=rule` y anónimas `firewall.@rule[0]=rule`).
  330. func parseFirewallRules(lines []string) []*firewallRule {
  331. ruleSections := uciTypeSections(lines, "firewall", "rule")
  332. var rules []*firewallRule
  333. bySection := map[string]*firewallRule{}
  334. for _, raw := range lines {
  335. line := strings.TrimSpace(raw)
  336. if line == "" {
  337. continue
  338. }
  339. m := reUciLine.FindStringSubmatch(line)
  340. if m == nil || m[1] != "firewall" {
  341. continue
  342. }
  343. dot := strings.Index(m[2], ".")
  344. if dot < 0 {
  345. continue
  346. }
  347. section, option := m[2][:dot], m[2][dot+1:]
  348. if !ruleSections[section] {
  349. continue
  350. }
  351. r := bySection[section]
  352. if r == nil {
  353. r = &firewallRule{Section: section}
  354. bySection[section] = r
  355. rules = append(rules, r)
  356. }
  357. switch option {
  358. case "name":
  359. r.Name = uciValue(m[3])
  360. case "src_mac":
  361. r.SrcMAC = uciValue(m[3])
  362. case "target":
  363. r.Target = uciValue(m[3])
  364. }
  365. }
  366. return rules
  367. }
  368. // blockRuleSection es el nombre de sección determinista para el bloqueo de una
  369. // MAC (uci set firewall.np_block_<mac12>=rule).
  370. func blockRuleSection(mac string) string {
  371. return "np_block_" + strings.ReplaceAll(mac, ":", "")
  372. }
  373. // blockRuleName es el nombre legible de la regla (mostrado en LuCI).
  374. func blockRuleName(mac string) string {
  375. return "np-block-" + strings.ReplaceAll(mac, ":", "")
  376. }
  377. // findBlockRule busca la regla de bloqueo de una MAC: por sección determinista
  378. // o por nombre legado (reglas anónimas `@rule[N]` con name='np-block-<mac>').
  379. func findBlockRule(rules []*firewallRule, mac string) *firewallRule {
  380. section := blockRuleSection(mac)
  381. name := blockRuleName(mac)
  382. for _, r := range rules {
  383. if r.Section == section || r.Name == name {
  384. return r
  385. }
  386. }
  387. return nil
  388. }
  389. // blockRuleApply/blockRuleRollback construyen los comandos uci de la regla
  390. // fw4. Forma mínima correcta (drop de tráfico reenviado desde la MAC, sin
  391. // romper su lease DHCP, que es input al router): src=lan, dest=*, target=DROP,
  392. // src_mac=<mac>.
  393. func blockRuleApply(section, mac string) []string {
  394. return []string{
  395. fmt.Sprintf("uci set firewall.%s=rule", section),
  396. fmt.Sprintf("uci set firewall.%s.name='%s'", section, blockRuleName(mac)),
  397. fmt.Sprintf("uci set firewall.%s.src='lan'", section),
  398. fmt.Sprintf("uci set firewall.%s.dest='*'", section),
  399. fmt.Sprintf("uci set firewall.%s.target='DROP'", section),
  400. fmt.Sprintf("uci set firewall.%s.src_mac='%s'", section, mac),
  401. }
  402. }
  403. func blockRuleRollback(section string) []string {
  404. return []string{fmt.Sprintf("uci delete firewall.%s", section)}
  405. }
  406. // handleDeviceBlockGet indica si un dispositivo está bloqueado.
  407. func (s *server) handleDeviceBlockGet(w http.ResponseWriter, r *http.Request) {
  408. mac := normalizeMAC(r.PathValue("mac"))
  409. if len(mac) != 17 {
  410. writeError(w, http.StatusBadRequest, "invalid_mac")
  411. return
  412. }
  413. routerID := r.URL.Query().Get("router")
  414. if routerID == "" {
  415. writeError(w, http.StatusBadRequest, "missing_router")
  416. return
  417. }
  418. host := s.hostOfRouter(routerID)
  419. if host == "" {
  420. writeError(w, http.StatusBadRequest, "no_router")
  421. return
  422. }
  423. lines, err := s.uciShow(host, "firewall")
  424. if err != nil {
  425. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  426. return
  427. }
  428. rules := parseFirewallRules(lines)
  429. blocked := findBlockRule(rules, mac) != nil
  430. writeJSON(w, http.StatusOK, map[string]any{"blocked": blocked})
  431. }
  432. // handleDeviceBlockPut bloquea un dispositivo añadiendo una regla de firewall.
  433. func (s *server) handleDeviceBlockPut(w http.ResponseWriter, r *http.Request) {
  434. mac := normalizeMAC(r.PathValue("mac"))
  435. if len(mac) != 17 {
  436. writeError(w, http.StatusBadRequest, "invalid_mac")
  437. return
  438. }
  439. var body struct {
  440. RouterID string `json:"router"`
  441. }
  442. if st := readJSONBody(w, r, &body); st != 0 {
  443. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  444. return
  445. }
  446. if body.RouterID == "" {
  447. writeError(w, http.StatusBadRequest, "missing_router")
  448. return
  449. }
  450. host := s.hostOfRouter(body.RouterID)
  451. if host == "" {
  452. writeError(w, http.StatusBadRequest, "no_router")
  453. return
  454. }
  455. lines, err := s.uciShow(host, "firewall")
  456. if err != nil {
  457. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  458. return
  459. }
  460. rules := parseFirewallRules(lines)
  461. if findBlockRule(rules, mac) != nil {
  462. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "already": true})
  463. return
  464. }
  465. section := blockRuleSection(mac)
  466. if err := s.runUCICommands(host, "firewall", blockRuleApply(section, mac)); err != nil {
  467. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  468. return
  469. }
  470. if err := s.reloadService(host, "firewall"); err != nil {
  471. if rbErr := s.runUCICommands(host, "firewall", blockRuleRollback(section)); rbErr != nil {
  472. log.Printf("[netpulse] rollback bloqueo %s falló: %v", mac, rbErr)
  473. }
  474. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  475. return
  476. }
  477. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  478. }
  479. // handleDeviceBlockDelete desbloquea un dispositivo.
  480. func (s *server) handleDeviceBlockDelete(w http.ResponseWriter, r *http.Request) {
  481. mac := normalizeMAC(r.PathValue("mac"))
  482. if len(mac) != 17 {
  483. writeError(w, http.StatusBadRequest, "invalid_mac")
  484. return
  485. }
  486. var body struct {
  487. RouterID string `json:"router"`
  488. }
  489. if st := readJSONBody(w, r, &body); st != 0 {
  490. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  491. return
  492. }
  493. if body.RouterID == "" {
  494. writeError(w, http.StatusBadRequest, "missing_router")
  495. return
  496. }
  497. host := s.hostOfRouter(body.RouterID)
  498. if host == "" {
  499. writeError(w, http.StatusBadRequest, "no_router")
  500. return
  501. }
  502. lines, err := s.uciShow(host, "firewall")
  503. if err != nil {
  504. writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
  505. return
  506. }
  507. rules := parseFirewallRules(lines)
  508. br := findBlockRule(rules, mac)
  509. if br == nil {
  510. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "already": true})
  511. return
  512. }
  513. apply := []string{fmt.Sprintf("uci delete firewall.%s", br.Section)}
  514. rollback := []string{fmt.Sprintf("uci set firewall.%s=rule", br.Section)}
  515. if br.Name != "" {
  516. rollback = append(rollback, fmt.Sprintf("uci set firewall.%s.name='%s'", br.Section, br.Name))
  517. }
  518. if br.SrcMAC != "" {
  519. rollback = append(rollback, fmt.Sprintf("uci set firewall.%s.src_mac='%s'", br.Section, br.SrcMAC))
  520. }
  521. if br.Target != "" {
  522. rollback = append(rollback, fmt.Sprintf("uci set firewall.%s.target='%s'", br.Section, br.Target))
  523. }
  524. if err := s.runUCICommands(host, "firewall", apply); err != nil {
  525. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  526. return
  527. }
  528. if err := s.reloadService(host, "firewall"); err != nil {
  529. if rbErr := s.runUCICommands(host, "firewall", rollback); rbErr != nil {
  530. log.Printf("[netpulse] rollback desbloqueo %s falló: %v", mac, rbErr)
  531. }
  532. writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
  533. return
  534. }
  535. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  536. }