agent.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. // agent.go — Fase 3 piloto (SPEC-AGENTE-PILOTO §1):
  2. //
  3. // POST /api/ingest/agent — ingesta de agentes nativos. NO va detrás del
  4. // middleware de sesión: auth propia Bearer con
  5. // token por equipo (guardado sha256 en kv
  6. // agent.token.<slug>). Rate limit por IP 30/min,
  7. // body cap 2 MB.
  8. // POST /api/agents — crear token para un slug (sesión). El token se
  9. // muestra UNA sola vez, con el one-liner de
  10. // instalación. Nunca se vuelve a servir.
  11. // GET /api/agents — slugs con agente + last_seen + versión.
  12. // DELETE /api/agents/{slug} — revocar (borra el token; el agente recibe 401).
  13. package httpapi
  14. import (
  15. "crypto/hmac"
  16. "crypto/rand"
  17. "crypto/sha256"
  18. "crypto/subtle"
  19. "encoding/hex"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "net/http"
  25. "regexp"
  26. "strings"
  27. "sync"
  28. "time"
  29. "github.com/gnacho/netpulse/agent/probe"
  30. "github.com/gnacho/netpulse/server-go/internal/agentbin"
  31. "github.com/gnacho/netpulse/server-go/internal/auth"
  32. "github.com/gnacho/netpulse/server-go/internal/rearmer"
  33. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  34. )
  35. const (
  36. // ingestBodyCap: body máximo del push del agente (2 MB, SPEC §1).
  37. ingestBodyCap = 2 << 20
  38. // ingestRateLimit: pushes por IP y ventana (30/min, SPEC §1).
  39. ingestRateLimit = 30
  40. ingestRateWindow = time.Minute
  41. // agentTokenKeyPrefix: kv agent.token.<slug> = sha256 hex del token.
  42. agentTokenKeyPrefix = "agent.token."
  43. // maxTsDrift: ventana de frescura del `ts` del agente (anti-replay,
  44. // auditoría de seguridad #2). Payloads con ts fuera de |±maxTsDrift|
  45. // respecto al reloj del servidor se rechazan con 401 (evita reinyectar
  46. // pushes viejos capturados). Configurable vía AGENT_MAX_TS_DRIFT_S.
  47. maxTsDriftDefault = 5 * time.Minute
  48. )
  49. // agentSlugRe: slugs de equipo válidos (mismo alfabeto que routerstore).
  50. var agentSlugRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`)
  51. // SSHRunner ejecuta comandos en los routers (adapters.SSHPool en
  52. // producción; fake en tests). Fase 5: rearme de agentes.
  53. type SSHRunner interface {
  54. Run(host, cmd string, timeout time.Duration) (string, error)
  55. }
  56. // ---------------------------------------------------------------------------
  57. // Rate limit por IP (ventana fija de 1 min; purga oportunista)
  58. // ---------------------------------------------------------------------------
  59. type ipRateLimit struct {
  60. mu sync.Mutex
  61. hits map[string]*ipHit
  62. limit int
  63. window time.Duration
  64. now func() time.Time
  65. }
  66. type ipHit struct {
  67. count int
  68. reset time.Time
  69. }
  70. func newIPRateLimit(limit int, window time.Duration) *ipRateLimit {
  71. return &ipRateLimit{hits: map[string]*ipHit{}, limit: limit, window: window, now: time.Now}
  72. }
  73. // allow registra un intento de ip; false → retryAfterSec hasta el reset.
  74. func (l *ipRateLimit) allow(ip string) (bool, int) {
  75. l.mu.Lock()
  76. defer l.mu.Unlock()
  77. // Purga oportunista para no crecer sin límite en redes con muchos clientes
  78. if len(l.hits) > 1024 {
  79. now := l.now()
  80. for k, h := range l.hits {
  81. if now.After(h.reset) {
  82. delete(l.hits, k)
  83. }
  84. }
  85. }
  86. h, ok := l.hits[ip]
  87. if !ok || l.now().After(h.reset) {
  88. l.hits[ip] = &ipHit{count: 1, reset: l.now().Add(l.window)}
  89. return true, 0
  90. }
  91. if h.count >= l.limit {
  92. return false, int(time.Until(h.reset).Seconds()) + 1
  93. }
  94. h.count++
  95. return true, 0
  96. }
  97. // ---------------------------------------------------------------------------
  98. // Tokens de agente (kv, sha256 — el token en claro solo vive en la respuesta
  99. // de creación y en el env del router)
  100. // ---------------------------------------------------------------------------
  101. func agentTokenKey(slug string) string { return agentTokenKeyPrefix + slug }
  102. // hashAgentToken: sha256 hex del token (lo único que se persiste).
  103. func hashAgentToken(token string) string {
  104. sum := sha256.Sum256([]byte(token))
  105. return hex.EncodeToString(sum[:])
  106. }
  107. // newAgentToken genera un token aleatorio de 32 bytes en hex (64 chars).
  108. func newAgentToken() (string, error) {
  109. buf := make([]byte, 32)
  110. if _, err := rand.Read(buf); err != nil {
  111. return "", err
  112. }
  113. return hex.EncodeToString(buf), nil
  114. }
  115. // checkAgentToken: ¿el Bearer es válido para el slug? (comparación en
  116. // tiempo constante sobre los hashes).
  117. func (s *server) checkAgentToken(slug, token string) bool {
  118. if token == "" || s.db == nil {
  119. return false
  120. }
  121. var stored string
  122. if err := s.db.QueryRow("SELECT value FROM kv WHERE key = ?", agentTokenKey(slug)).Scan(&stored); err != nil {
  123. return false
  124. }
  125. got := hashAgentToken(token)
  126. return subtle.ConstantTimeCompare([]byte(got), []byte(stored)) == 1
  127. }
  128. // checkHMAC verifica que X-Agent-Signature coincida con HMAC-SHA256(token, body).
  129. // Devuelve nil si la firma es correcta; error si falta o no coincide.
  130. func checkHMAC(token string, body []byte, sig string) error {
  131. if sig == "" {
  132. return errors.New("falta X-Agent-Signature")
  133. }
  134. mac := hmac.New(sha256.New, []byte(token))
  135. mac.Write(body)
  136. expected := hex.EncodeToString(mac.Sum(nil))
  137. if subtle.ConstantTimeCompare([]byte(sig), []byte(expected)) != 1 {
  138. return errors.New("HMAC no coincide")
  139. }
  140. return nil
  141. }
  142. // ---------------------------------------------------------------------------
  143. // POST /api/ingest/agent (auth Bearer propia; exenta del middleware de sesión)
  144. // ---------------------------------------------------------------------------
  145. func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
  146. // 429: ráfaga por IP (antes de leer el body, como el login)
  147. if ok, retry := s.ingestLimit.allow(auth.ClientIP(r)); !ok {
  148. w.Header().Set("Retry-After", fmt.Sprintf("%d", retry))
  149. writeJSON(w, http.StatusTooManyRequests, map[string]any{
  150. "error": "rate_limited",
  151. "retryAfterSec": retry,
  152. })
  153. return
  154. }
  155. // 413: body cap 2 MB
  156. body, err := io.ReadAll(io.LimitReader(r.Body, ingestBodyCap+1))
  157. if err != nil {
  158. writeError(w, http.StatusBadRequest, "invalid_payload")
  159. return
  160. }
  161. if len(body) > ingestBodyCap {
  162. writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large")
  163. return
  164. }
  165. // 400: JSON + campos mínimos del contrato
  166. var p probe.Payload
  167. if err := json.Unmarshal(body, &p); err != nil {
  168. writeError(w, http.StatusBadRequest, "invalid_payload", "JSON inválido")
  169. return
  170. }
  171. if !agentSlugRe.MatchString(p.Router) || p.Ts <= 0 {
  172. writeError(w, http.StatusBadRequest, "invalid_payload",
  173. `Se esperaba { "router": "<slug>", "ts": <unix>, "data": {...} }`)
  174. return
  175. }
  176. // 401: Bearer inválido para ese slug
  177. token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
  178. if !s.checkAgentToken(p.Router, token) {
  179. writeError(w, http.StatusUnauthorized, "unauthorized")
  180. return
  181. }
  182. // 401: HMAC-SHA256 del payload no coincide (R4: firma obligatoria)
  183. sig := r.Header.Get("X-Agent-Signature")
  184. if err := checkHMAC(token, body, sig); err != nil {
  185. writeError(w, http.StatusUnauthorized, "invalid_signature", err.Error())
  186. return
  187. }
  188. // 401: anti-replay (auditoría #2) — el `ts` debe estar dentro de la
  189. // ventana de frescura respecto al reloj del servidor. Rechaza pushes
  190. // viejos capturados/reinyectados y saltos de reloj grandes del agente.
  191. if drift := time.Since(time.Unix(p.Ts, 0)); drift < -s.maxTsDrift || drift > s.maxTsDrift {
  192. writeError(w, http.StatusUnauthorized, "stale_payload",
  193. "ts fuera de la ventana de frescura (revisa el reloj del router)")
  194. return
  195. }
  196. if s.agents == nil {
  197. writeError(w, http.StatusServiceUnavailable, "unavailable",
  198. "el servidor no tiene registry de agentes")
  199. return
  200. }
  201. // En modo demo los scrapers/colectores externos siguen empujando (issue
  202. // #168): se acepta como no-op (202) sin tocar el registry ni la BD. La
  203. // demo sirve un dataset canónico en memoria; los datos reales no existen.
  204. if s.cfg != nil && s.cfg.DemoMode {
  205. writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "demo": true})
  206. return
  207. }
  208. s.agents.Ingest(&p)
  209. // Fase 8.2 (R8): persistir el último push en kv (agent.state.<slug>) para
  210. // que lastSeen/versión/payload sobrevivan a un reinicio del servidor.
  211. s.persistAgentState(p.Router, s.agents.Snapshot(p.Router))
  212. writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
  213. }
  214. // ---------------------------------------------------------------------------
  215. // GET /api/agents/{slug}/binary?arch=... — Fase 6.2: servir el binario del
  216. // agente desde el propio servidor (embebido vía go:embed en agentbin/).
  217. // Elimina la dependencia de GitHub para instalar/reinstalar agentes.
  218. // Auth por token de agente (Bearer), igual que la ingesta — el one-liner de
  219. // instalación incluye el token y se ejecuta en el router.
  220. // ---------------------------------------------------------------------------
  221. func (s *server) handleAgentBinary(w http.ResponseWriter, r *http.Request) {
  222. slug := r.PathValue("slug")
  223. if !agentSlugRe.MatchString(slug) {
  224. writeError(w, http.StatusNotFound, "not_found")
  225. return
  226. }
  227. // Auth por token de agente (no sesión admin)
  228. token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
  229. if !s.checkAgentToken(slug, token) {
  230. writeError(w, http.StatusUnauthorized, "unauthorized")
  231. return
  232. }
  233. arch := r.URL.Query().Get("arch")
  234. if arch == "" {
  235. arch = "arm64"
  236. }
  237. f, err := agentbin.Open(arch)
  238. if err != nil {
  239. writeError(w, http.StatusNotFound, "not_found",
  240. "binario no disponible para "+arch+" (compila el servidor con los binarios de agente embebidos)")
  241. return
  242. }
  243. defer f.Close()
  244. st, _ := f.Stat()
  245. rs, ok := f.(io.ReadSeeker)
  246. if !ok {
  247. writeError(w, http.StatusInternalServerError, "internal_error")
  248. return
  249. }
  250. w.Header().Set("Content-Type", "application/octet-stream")
  251. w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="netpulse-agent-%s"`, arch))
  252. // #284: sha256 del binario embebido para que el agente verifique la
  253. // integridad de la descarga antes de hacer el swap.
  254. if d := agentbin.Digest(arch); d != "" {
  255. w.Header().Set("X-Checksum-Sha256", d)
  256. }
  257. http.ServeContent(w, r, st.Name(), st.ModTime(), rs)
  258. }
  259. // ---------------------------------------------------------------------------
  260. // Gestión de tokens (sesión): POST/GET /api/agents, DELETE /api/agents/{slug}
  261. // ---------------------------------------------------------------------------
  262. // agentCreateResponse es la ÚNICA respuesta que incluye el token en claro.
  263. type agentCreateResponse struct {
  264. Slug string `json:"slug"`
  265. Token string `json:"token"`
  266. Install string `json:"install"`
  267. }
  268. // handleAgentsCreate: genera (o rota) el token de un slug. 201 con el token
  269. // en claro UNA vez + el one-liner de instalación.
  270. func (s *server) handleAgentsCreate(w http.ResponseWriter, r *http.Request) {
  271. var body struct {
  272. Slug string `json:"slug"`
  273. }
  274. if st := readJSONBody(w, r, &body); st != 0 {
  275. writeBodyError(w, st, "invalid_body", `Se esperaba { "slug": "<equipo>" } (a-z, 0-9, guiones)`)
  276. return
  277. }
  278. if !agentSlugRe.MatchString(body.Slug) {
  279. writeError(w, http.StatusBadRequest, "invalid_body",
  280. `Se esperaba { "slug": "<equipo>" } (a-z, 0-9, guiones)`)
  281. return
  282. }
  283. token, err := newAgentToken()
  284. if err != nil {
  285. writeError(w, http.StatusInternalServerError, "token_error")
  286. return
  287. }
  288. if _, err := s.db.Exec(
  289. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  290. agentTokenKey(body.Slug), hashAgentToken(token)); err != nil {
  291. writeError(w, http.StatusInternalServerError, "token_error")
  292. return
  293. }
  294. writeJSON(w, http.StatusCreated, agentCreateResponse{
  295. Slug: body.Slug,
  296. Token: token,
  297. Install: s.agentInstallLine(r, body.Slug, token),
  298. })
  299. }
  300. // agentInstallLine: one-liner de instalación vía SSH desde esta máquina.
  301. // El host del router se resuelve de la tabla routers si el slug existe.
  302. // Fase 6.2: el binario se descarga del propio servidor con el token del agente
  303. // en vez de GitHub, eliminando la dependencia de internet y el token en argv.
  304. func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
  305. host := "<ip-del-router>"
  306. if s.db != nil {
  307. for _, rc := range routerstore.ListRouters(s.db.DB) {
  308. if rc.ID == slug {
  309. host = rc.Host
  310. break
  311. }
  312. }
  313. }
  314. scheme := "http"
  315. if auth.IsSecureRequest(r) {
  316. scheme = "https"
  317. }
  318. server := scheme + "://" + r.Host
  319. return fmt.Sprintf(
  320. "curl -fsSL -H 'Authorization: Bearer %s' %s/api/agents/%s/binary -o /tmp/netpulse-agent && curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --binary /tmp/netpulse-agent --host %s --server %s --slug %s --token %s",
  321. token, server, slug, host, server, slug, token)
  322. }
  323. // agentListItem: lo que ve la UI — NUNCA el token ni su hash.
  324. type agentListItem struct {
  325. Slug string `json:"slug"`
  326. RouterID string `json:"routerId,omitempty"` // id del router asociado (#282)
  327. LastSeen *int64 `json:"lastSeen"` // unix SEGUNDOS; null si nunca empujó
  328. Version string `json:"version,omitempty"`
  329. Fresh bool `json:"fresh"`
  330. // UpdateAvailable: true si el agente reportó una versión distinta de la
  331. // del binario embebido (agentbin.EmbeddedAgentVersion) → hay upgrade
  332. // disponible vía POST /api/agents/{slug}/upgrade (Fase 6.3, issue #243).
  333. // SOLO se marca para routers OpenWrt (type openwrt/glinet): los de tipo
  334. // managed-switch/external son scrapers que no usan el agente nativo.
  335. UpdateAvailable bool `json:"updateAvailable"`
  336. // Upgrade: último paso del self-update en marcha (requested/downloading/
  337. // swapping/restarting/failed) con su marca de tiempo. null si no hay
  338. // actividad reciente (#284: progreso en vivo para la UI).
  339. Upgrade *agentUpgradeInfo `json:"upgrade,omitempty"`
  340. // Kind: "native" (agente netpulse-agent) o "external" (pusher externo
  341. // tipo scraper de switch gestionado, #285/#288). Default "native".
  342. Kind string `json:"kind"`
  343. // Interval: cadencia de push declarada en segundos (solo externos, #288).
  344. Interval int `json:"interval,omitempty"`
  345. }
  346. // agentUpgradeStep es un paso de la historia (timeline de la UI, #284).
  347. type agentUpgradeStep struct {
  348. Step string `json:"step"`
  349. Pct int `json:"pct,omitempty"`
  350. Ts int64 `json:"ts"` // unix segundos
  351. }
  352. // agentUpgradeInfo es el paso de progreso expuesto en GET /api/agents.
  353. type agentUpgradeInfo struct {
  354. Step string `json:"step"`
  355. Pct int `json:"pct,omitempty"` // 0-100 en "downloading"
  356. Error string `json:"error,omitempty"`
  357. Ts int64 `json:"ts"` // unix segundos del último reporte
  358. Steps []agentUpgradeStep `json:"steps,omitempty"` // historia de pasos (#284)
  359. }
  360. // agentUpgradeable: ¿un agente de un router con este type es actualizable?
  361. // Un router openwrt/glinet (o sin type) usa el binario netpulse-agent y es
  362. // actualizable; los de type managed-switch/external NO (son scrapers que no
  363. // usan el agente nativo y no entienden el comando "upgrade").
  364. func agentUpgradeable(typ string) bool {
  365. return typ == "" || typ == "openwrt" || typ == "glinet"
  366. }
  367. // routerUpgradeable: variante por slug que consulta la tabla routers. NO usar
  368. // dentro de un bucle con rows abiertos (SetMaxOpenConns(1) → deadlock);
  369. // para listados precarga los types (ver handleAgentsList).
  370. func (s *server) routerUpgradeable(slug string) bool {
  371. if s.db == nil {
  372. return true
  373. }
  374. var typ string
  375. if err := s.db.QueryRow("SELECT type FROM routers WHERE id = ?", slug).Scan(&typ); err != nil {
  376. return true
  377. }
  378. return agentUpgradeable(typ)
  379. }
  380. // handleAgentsList: slugs con token + last_seen + versión.
  381. func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
  382. out := []agentListItem{}
  383. // Routers precargados en UNA consulta: con SetMaxOpenConns(1) un QueryRow
  384. // dentro del bucle de rows de abajo esperaría la conexión que el rows
  385. // activo mantiene (deadlock). Guardamos id, type, name, host y mac para
  386. // resolver la asociación agente↔router (#282).
  387. routerByID := map[string]routerIdentity{}
  388. if s.db != nil {
  389. if rows, err := s.db.Query("SELECT id, type, name, host, COALESCE(mac,'') FROM routers"); err == nil {
  390. for rows.Next() {
  391. var id, typ, name, host, mac string
  392. if rows.Scan(&id, &typ, &name, &host, &mac) == nil {
  393. routerByID[id] = routerIdentity{ID: id, Type: typ, Name: name, Host: host, Mac: mac}
  394. }
  395. }
  396. rows.Close()
  397. }
  398. }
  399. if s.db != nil {
  400. rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
  401. if err == nil {
  402. defer rows.Close()
  403. for rows.Next() {
  404. var key string
  405. if rows.Scan(&key) != nil {
  406. continue
  407. }
  408. slug := strings.TrimPrefix(key, agentTokenKeyPrefix)
  409. item := agentListItem{Slug: slug}
  410. var payload *probe.Payload
  411. agentKind := ""
  412. if s.agents != nil {
  413. if st := s.agents.Snapshot(slug); st != nil {
  414. payload = st.Payload
  415. }
  416. if seen, version, kind, interval, ok := s.agents.Info(slug); ok {
  417. ts := seen.Unix()
  418. item.LastSeen = &ts
  419. item.Version = version
  420. agentKind = kind
  421. switch kind {
  422. case "external", "netgrip":
  423. item.Kind = kind
  424. default:
  425. item.Kind = "native"
  426. }
  427. item.Interval = interval
  428. }
  429. _, item.Fresh = s.agents.Fresh(slug)
  430. }
  431. item.RouterID = resolveAgentRouter(slug, payload, routerByID)
  432. // Fase 6.3 (issue #243): upgrade disponible si el agente
  433. // reporta una versión distinta del binario embebido y el router
  434. // asociado es actualizable (nativo OpenWrt/GL.iNet).
  435. matchedType := ""
  436. if r, ok := routerByID[item.RouterID]; ok {
  437. matchedType = r.Type
  438. }
  439. // #363: un agente embebido en NetGrip se actualiza vía el
  440. // evento SSE upgrade (NetGrip corre su propio self-update);
  441. // "hay novedad" = versión reportada < última release de NetGrip.
  442. if agentKind == "netgrip" {
  443. item.UpdateAvailable = item.Version != "" && cmpSemver(netgripLatest(), item.Version) > 0
  444. } else {
  445. item.UpdateAvailable = agentUpgradeable(matchedType) && item.Version != "" && item.Version != agentbin.EmbeddedAgentVersion
  446. }
  447. // Progreso en vivo del upgrade (#284), si hay actividad reciente.
  448. if st, ok := s.upgrades.snapshot(slug); ok {
  449. ts := st.Ts.Unix()
  450. info := &agentUpgradeInfo{Step: st.Step, Pct: st.Pct, Error: st.Error, Ts: ts}
  451. for _, e := range st.History {
  452. info.Steps = append(info.Steps, agentUpgradeStep{Step: e.Step, Pct: e.Pct, Ts: e.Ts.Unix()})
  453. }
  454. item.Upgrade = info
  455. }
  456. out = append(out, item)
  457. }
  458. }
  459. }
  460. writeJSON(w, http.StatusOK, map[string]any{"agents": out})
  461. }
  462. // routerIdentity es la información mínima de un router para resolver la
  463. // asociación agente↔router sin exponer credenciales.
  464. type routerIdentity struct {
  465. ID string
  466. Type string
  467. Name string
  468. Host string
  469. Mac string
  470. }
  471. // resolveAgentRouter devuelve el id del router asociado a un agente. Primero
  472. // intenta slug == router.id; si no, empareja por hostname del board del
  473. // payload o por bridge MAC persistida (#282).
  474. func resolveAgentRouter(slug string, payload *probe.Payload, routers map[string]routerIdentity) string {
  475. if slug != "" {
  476. if _, ok := routers[slug]; ok {
  477. return slug
  478. }
  479. }
  480. if payload == nil || payload.Data.System == nil || payload.Data.System.Board == nil {
  481. return ""
  482. }
  483. norm := func(s string) string { return strings.ToLower(strings.TrimSpace(s)) }
  484. hostname := norm(payload.Data.System.Board.Hostname)
  485. if hostname != "" {
  486. for _, r := range routers {
  487. if hostname == norm(r.Host) || hostname == norm(r.Name) {
  488. return r.ID
  489. }
  490. }
  491. }
  492. if payload.Data.System.BridgeMAC != "" {
  493. for _, r := range routers {
  494. if strings.EqualFold(payload.Data.System.BridgeMAC, r.Mac) {
  495. return r.ID
  496. }
  497. }
  498. }
  499. return ""
  500. }
  501. // handleAgentsDelete: revoca el token del slug (el agente recibirá 401 en su
  502. // próximo push) y olvida su estado. 404 si no existía.
  503. func (s *server) handleAgentsDelete(w http.ResponseWriter, r *http.Request) {
  504. slug := r.PathValue("slug")
  505. if !agentSlugRe.MatchString(slug) {
  506. writeError(w, http.StatusNotFound, "not_found")
  507. return
  508. }
  509. res, err := s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
  510. if err != nil {
  511. writeError(w, http.StatusInternalServerError, "db_error")
  512. return
  513. }
  514. if n, _ := res.RowsAffected(); n == 0 {
  515. writeError(w, http.StatusNotFound, "not_found")
  516. return
  517. }
  518. if s.agents != nil {
  519. s.agents.Forget(slug)
  520. }
  521. w.WriteHeader(http.StatusNoContent)
  522. }
  523. // ---------------------------------------------------------------------------
  524. // POST /api/agents/{slug}/rearm — Fase 5 (Plan B): reiniciar el servicio
  525. // procd del agente en el router vía SSH (el mismo canal del sondeo). La
  526. // lógica completa vive en el paquete rearmer (compartida con el supervisor
  527. // de auto-rearme); este handler solo mapea errores tipificados a status.
  528. // ---------------------------------------------------------------------------
  529. type rearmResponse struct {
  530. Slug string `json:"slug"`
  531. Restarted bool `json:"restarted"` // el comando SSH se ejecutó
  532. Recovered bool `json:"recovered"` // llegó un push nuevo tras el reinicio
  533. Message string `json:"message,omitempty"`
  534. }
  535. func (s *server) handleAgentRearm(w http.ResponseWriter, r *http.Request) {
  536. slug := r.PathValue("slug")
  537. if !agentSlugRe.MatchString(slug) {
  538. writeError(w, http.StatusNotFound, "not_found")
  539. return
  540. }
  541. if s.rearmer == nil {
  542. writeError(w, http.StatusInternalServerError, "db_error")
  543. return
  544. }
  545. res, err := s.rearmer.Rearm(slug)
  546. switch {
  547. case err == nil:
  548. writeJSON(w, http.StatusOK, rearmResponse{
  549. Slug: res.Slug, Restarted: res.Restarted, Recovered: res.Recovered, Message: res.Message,
  550. })
  551. case errors.Is(err, rearmer.ErrNoDB):
  552. writeError(w, http.StatusInternalServerError, "db_error")
  553. case errors.Is(err, rearmer.ErrNoToken):
  554. writeError(w, http.StatusNotFound, "not_found", err.Error())
  555. case errors.Is(err, rearmer.ErrNoRouter):
  556. writeError(w, http.StatusConflict, "router_unknown", err.Error())
  557. case errors.Is(err, rearmer.ErrExternalAgent):
  558. writeError(w, http.StatusConflict, "not_openwrt", err.Error())
  559. case errors.Is(err, rearmer.ErrNetgripAgent):
  560. writeError(w, http.StatusConflict, "netgrip_managed", err.Error())
  561. case errors.Is(err, rearmer.ErrNoSSH):
  562. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", err.Error())
  563. default:
  564. var cd rearmer.ErrCooldown
  565. if errors.As(err, &cd) {
  566. writeError(w, http.StatusTooManyRequests, "cooldown", cd.Error())
  567. return
  568. }
  569. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  570. }
  571. }
  572. // ---------------------------------------------------------------------------
  573. // POST /api/agents/{slug}/reinstall — #246: reinstalar el agente en el router
  574. // vía SSH (recupera un agente borrado por update de firmware/desinstalación).
  575. // Replica el flujo de install-agent.sh sin depender del PC del admin:
  576. // 1. Verifica slug + router en la tabla routers.
  577. // 2. Rota el token (genera uno nuevo en claro y persiste su hash en kv).
  578. // 3. Ejecuta por SSH: detecta arch, descarga el binario del propio server
  579. // (GET /api/agents/{slug}/binary con el token nuevo), lo instala,
  580. // escribe /etc/netpulse-agent.env, instala el init procd y lo arranca.
  581. // 4. Espera a que el agente vuelva a empujar (misma lógica que el rearm).
  582. // ---------------------------------------------------------------------------
  583. type reinstallResponse struct {
  584. Slug string `json:"slug"`
  585. Token string `json:"token"` // en claro UNA vez, para reutilizar en el router
  586. Installed bool `json:"installed"`
  587. Recovered bool `json:"recovered"` // llegó un push nuevo tras la instalación
  588. Message string `json:"message,omitempty"`
  589. }
  590. func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
  591. slug := r.PathValue("slug")
  592. if !agentSlugRe.MatchString(slug) {
  593. writeError(w, http.StatusNotFound, "not_found")
  594. return
  595. }
  596. if s.db == nil || s.pool == nil {
  597. writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
  598. return
  599. }
  600. // #363: jamás desplegar el binario standalone sobre un router cuyo
  601. // agente es el NetGrip embebido (lo destrozaría: duplicado + token roto).
  602. if s.agentKindOf(slug) == "netgrip" {
  603. writeError(w, http.StatusConflict, "netgrip_managed", "agente embebido en NetGrip: actualiza o reinstala el panel NetGrip en el propio router")
  604. return
  605. }
  606. // Router del slug (tabla routers; mismo host que usa el rearm).
  607. host := ""
  608. for _, rc := range routerstore.ListRouters(s.db.DB) {
  609. if rc.ID == slug {
  610. host = rc.Host
  611. break
  612. }
  613. }
  614. if host == "" {
  615. writeError(w, http.StatusConflict, "router_unknown", "no hay router con ese slug en la tabla routers")
  616. return
  617. }
  618. // Solo agentes nativos OpenWrt: un dispositivo managed-switch/external es
  619. // un scraper que no usa el binario netpulse-agent → no se reinstala así.
  620. if !s.routerUpgradeable(slug) {
  621. writeError(w, http.StatusConflict, "not_openwrt",
  622. "este dispositivo no usa el agente nativo OpenWrt (scraper); reinstálalo con su propio mecanismo")
  623. return
  624. }
  625. // Rotar el token (el env del router se reescribe con el nuevo).
  626. token, err := newAgentToken()
  627. if err != nil {
  628. writeError(w, http.StatusInternalServerError, "token_error")
  629. return
  630. }
  631. if _, err := s.db.Exec(
  632. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  633. agentTokenKey(slug), hashAgentToken(token)); err != nil {
  634. writeError(w, http.StatusInternalServerError, "token_error")
  635. return
  636. }
  637. // URL base del server (para que el router descargue el binario). Mismo
  638. // esquema que agentInstallLine: http en LAN, https si la request es segura.
  639. scheme := "http"
  640. if auth.IsSecureRequest(r) {
  641. scheme = "https"
  642. }
  643. serverURL := scheme + "://" + r.Host
  644. // Script de instalación (replica install-agent.sh vía SSH, sin scp).
  645. script := reinstallScript(host, slug, token, serverURL)
  646. before := time.Now()
  647. var prevSeen time.Time
  648. if s.agents != nil {
  649. if seen, _, _, _, ok := s.agents.Info(slug); ok {
  650. prevSeen = seen
  651. }
  652. }
  653. if _, err := s.pool.Run(host, script, 60*time.Second); err != nil {
  654. writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
  655. return
  656. }
  657. // Esperar a que el agente vuelva a empujar (poll 2s hasta 40s).
  658. recovered := false
  659. deadline := time.Now().Add(40 * time.Second)
  660. for time.Now().Before(deadline) {
  661. time.Sleep(2 * time.Second)
  662. if s.agents == nil {
  663. break
  664. }
  665. if seen, _, _, _, ok := s.agents.Info(slug); ok && seen.After(prevSeen) && seen.After(before.Add(-5*time.Second)) {
  666. recovered = true
  667. break
  668. }
  669. }
  670. writeJSON(w, http.StatusOK, reinstallResponse{
  671. Slug: slug, Token: token, Installed: true, Recovered: recovered,
  672. Message: map[bool]string{true: "agente instalado y empujando", false: "agente instalado; aún no ha empujado en 40 s"}[recovered],
  673. })
  674. }
  675. // reinstallScript construye el script POSIX sh que se ejecuta en el router.
  676. func reinstallScript(host, slug, token, serverURL string) string {
  677. return `#!/bin/sh
  678. set -e
  679. INIT=/etc/init.d/netpulse-agent
  680. BIN=/usr/sbin/netpulse-agent
  681. ENV_FILE=/etc/netpulse-agent.env
  682. SERVER="` + serverURL + `"
  683. SLUG="` + slug + `"
  684. TOKEN="` + token + `"
  685. # Detectar arquitectura del router
  686. ARCH=$(uname -m)
  687. case "$ARCH" in
  688. aarch64|arm64) GOARCH=arm64 ;;
  689. armv7l|armv7) GOARCH=armv7 ;;
  690. *) echo "arch no soportado: $ARCH"; exit 20 ;;
  691. esac
  692. # Parar servicio previo si existe (el proceso vivo mantiene el binario abierto)
  693. [ -f "$INIT" ] && $INIT stop >/dev/null 2>&1 || true
  694. # Descargar el binario del propio server (auth por token)
  695. if command -v curl >/dev/null 2>&1; then
  696. curl -fsSL --connect-timeout 10 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new
  697. else
  698. wget -q -O /tmp/netpulse-agent.new --header="Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"
  699. fi
  700. chmod 0755 /tmp/netpulse-agent.new
  701. mv /tmp/netpulse-agent.new "$BIN"
  702. chmod 0755 "$BIN"
  703. # Config (chmod 600)
  704. cat > "$ENV_FILE" <<EOF
  705. # netpulse-agent — config (generado por reinstall)
  706. NETPULSE_SERVER=$SERVER
  707. NETPULSE_SLUG=$SLUG
  708. NETPULSE_TOKEN=$TOKEN
  709. EOF
  710. chmod 600 "$ENV_FILE"
  711. # Init script procd (respawn)
  712. cat > "$INIT" <<'INITEOF'
  713. #!/bin/sh /etc/rc.common
  714. # netpulse-agent — agente nativo NetPulse para OpenWrt
  715. START=99
  716. STOP=10
  717. USE_PROCD=1
  718. BIN=/usr/sbin/netpulse-agent
  719. [ -x "$BIN" ] || BIN=/tmp/netpulse-agent
  720. start_service() {
  721. procd_open_instance netpulse-agent
  722. procd_set_param command "$BIN"
  723. procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
  724. procd_set_param stdout 1
  725. procd_set_param stderr 1
  726. procd_set_param file /etc/netpulse-agent.env
  727. procd_close_instance
  728. }
  729. INITEOF
  730. chmod 0755 "$INIT"
  731. $INIT enable
  732. $INIT restart
  733. `
  734. }
  735. // ---------------------------------------------------------------------------
  736. // POST /api/agents/{slug}/refresh — Fase 7.3: enviar comando refresh al
  737. // agente vía SSE para que haga un sondeo inmediato. Admin solo.
  738. // ---------------------------------------------------------------------------
  739. func (s *server) handleAgentRefresh(w http.ResponseWriter, r *http.Request) {
  740. slug := r.PathValue("slug")
  741. if !agentSlugRe.MatchString(slug) {
  742. writeError(w, http.StatusNotFound, "not_found")
  743. return
  744. }
  745. if s.agentHub == nil {
  746. writeError(w, http.StatusServiceUnavailable, "unavailable", "SSE agentHub no configurado")
  747. return
  748. }
  749. if !s.agentHub.Send(slug, "refresh", map[string]any{}) {
  750. writeError(w, http.StatusNotFound, "not_found", "el agente "+slug+" no está conectado por SSE")
  751. return
  752. }
  753. writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
  754. }
  755. // agentKindOf devuelve el kind del último push del slug ("" si no hay).
  756. func (s *server) agentKindOf(slug string) string {
  757. if s.agents == nil {
  758. return ""
  759. }
  760. if _, _, kind, _, ok := s.agents.Info(slug); ok {
  761. return kind
  762. }
  763. return ""
  764. }
  765. // ------------------------------------------------------------ netgrip latest --
  766. // netgripLatest resuelve la última release de gnacho/netgrip con cache (TTL):
  767. // los agentes kind=netgrip comparan su versión contra ELLA (el binario
  768. // embebido del server no aplica). Falla de red → cache/"" → sin botón.
  769. var (
  770. netgripLatestMu sync.Mutex
  771. netgripLatestVer string
  772. netgripLatestAt time.Time
  773. netgripLatestFetch = fetchNetgripLatestVersion // sustituible en tests
  774. )
  775. const netgripLatestTTL = 5 * time.Minute
  776. func fetchNetgripLatestVersion() string {
  777. client := &http.Client{Timeout: 8 * time.Second}
  778. req, err := http.NewRequest("GET", "https://api.github.com/repos/gnacho/netgrip/releases/latest", nil)
  779. if err != nil {
  780. return ""
  781. }
  782. req.Header.Set("Accept", "application/vnd.github+json")
  783. req.Header.Set("User-Agent", "netpulse-server")
  784. resp, err := client.Do(req)
  785. if err != nil || resp.StatusCode != 200 {
  786. if resp != nil {
  787. resp.Body.Close()
  788. }
  789. return ""
  790. }
  791. defer resp.Body.Close()
  792. var rel struct {
  793. TagName string `json:"tag_name"`
  794. }
  795. if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<16)).Decode(&rel); err != nil {
  796. return ""
  797. }
  798. return strings.TrimPrefix(rel.TagName, "v")
  799. }
  800. func netgripLatest() string {
  801. netgripLatestMu.Lock()
  802. defer netgripLatestMu.Unlock()
  803. if netgripLatestVer != "" && time.Since(netgripLatestAt) < netgripLatestTTL {
  804. return netgripLatestVer
  805. }
  806. if v := netgripLatestFetch(); v != "" {
  807. netgripLatestVer, netgripLatestAt = v, time.Now()
  808. }
  809. return netgripLatestVer
  810. }
  811. // cmpSemver compara dos versiones x.y.z (-rN se ignora): -1, 0, 1. Malparse
  812. // → 0 (sin señal de novedad).
  813. func cmpSemver(a, b string) int {
  814. pa, okA := parseSemver3(a)
  815. pb, okB := parseSemver3(b)
  816. if !okA || !okB {
  817. return 0
  818. }
  819. for i := 0; i < 3; i++ {
  820. if pa[i] != pb[i] {
  821. if pa[i] > pb[i] {
  822. return 1
  823. }
  824. return -1
  825. }
  826. }
  827. return 0
  828. }
  829. func parseSemver3(v string) ([3]int, bool) {
  830. v = strings.TrimPrefix(strings.TrimSpace(v), "v")
  831. if i := strings.IndexAny(v, "- +"); i >= 0 {
  832. v = v[:i]
  833. }
  834. var x [3]int
  835. if n, _ := fmt.Sscanf(v, "%d.%d.%d", &x[0], &x[1], &x[2]); n != 3 {
  836. return x, false
  837. }
  838. return x, true
  839. }