agent_api_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. // agent_api_test.go — Fase 3 piloto (SPEC-AGENTE-PILOTO §1): ingesta con
  2. // token válido/inválido, body grande, rate limit, payload inválido (no rompe
  3. // el pipeline), y gestión de tokens (crear/listar/revocar; el token solo se
  4. // muestra una vez y NUNCA sale por GET).
  5. package httpapi_test
  6. import (
  7. "crypto/hmac"
  8. "crypto/sha256"
  9. "encoding/hex"
  10. "encoding/json"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. "net/http/httptest"
  15. "strings"
  16. "testing"
  17. "time"
  18. "github.com/gnacho/netpulse/server-go/internal/adapters"
  19. "github.com/gnacho/netpulse/server-go/internal/auth"
  20. "github.com/gnacho/netpulse/server-go/internal/config"
  21. "github.com/gnacho/netpulse/server-go/internal/db"
  22. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  23. "github.com/gnacho/netpulse/server-go/internal/sse"
  24. )
  25. type agentTestServer struct {
  26. *httptest.Server
  27. db *db.DB
  28. agents *adapters.AgentRegistry
  29. cookie string
  30. }
  31. // makeAgentTestServer: app real con registry de agentes + sesión admin.
  32. func makeAgentTestServer(t *testing.T) *agentTestServer {
  33. t.Helper()
  34. // Los helpers de test simulan IPs distintas vía X-Forwarded-For (rate
  35. // limit); el comportamiento por defecto en producción es NO confiar en
  36. // XFF (auditoría #1), así que aquí se activa explícitamente.
  37. auth.SetTrustProxy(true)
  38. t.Cleanup(func() { auth.SetTrustProxy(false) })
  39. dataDir := t.TempDir()
  40. cfg, err := config.Load(map[string]string{
  41. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  42. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  43. }, dataDir)
  44. if err != nil {
  45. t.Fatalf("config: %v", err)
  46. }
  47. d, err := db.Open(dataDir)
  48. if err != nil {
  49. t.Fatalf("db: %v", err)
  50. }
  51. secret, err := auth.EnsureSessionSecret(d, cfg)
  52. if err != nil {
  53. t.Fatalf("secret: %v", err)
  54. }
  55. if err := auth.EnsureUsers(d, cfg); err != nil {
  56. t.Fatalf("users: %v", err)
  57. }
  58. reg := adapters.NewAgentRegistry(90 * time.Second)
  59. hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
  60. // AgentHub con el checkToken de producción (sha256 del token vs kv):
  61. // registra rutas de comandos SSE (/upgrade, /refresh) como en prod.
  62. agentHub := sse.NewAgentHub(func(slug, token string) bool {
  63. var stored string
  64. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "agent.token."+slug).Scan(&stored); err != nil {
  65. return false
  66. }
  67. sum := sha256.Sum256([]byte(token))
  68. return hex.EncodeToString(sum[:]) == stored
  69. })
  70. handler := httpapi.NewHandler(httpapi.Deps{
  71. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
  72. Agents: reg, Started: time.Now(), AgentHub: agentHub,
  73. })
  74. srv := httptest.NewServer(handler)
  75. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  76. if status != 204 {
  77. t.Fatalf("login: %d", status)
  78. }
  79. ts := &agentTestServer{Server: srv, db: d, agents: reg, cookie: cookie}
  80. t.Cleanup(func() {
  81. srv.Close()
  82. d.Close()
  83. })
  84. return ts
  85. }
  86. // createAgentToken crea el token de un slug vía API (con sesión) y devuelve
  87. // (status, token, install).
  88. func createAgentToken(t *testing.T, ts *agentTestServer, slug string) (int, string, string) {
  89. t.Helper()
  90. req, _ := http.NewRequest("POST", ts.URL+"/api/agents", strings.NewReader(fmt.Sprintf(`{"slug":%q}`, slug)))
  91. req.Header.Set("Content-Type", "application/json")
  92. req.Header.Set("Cookie", "session="+ts.cookie)
  93. res, err := http.DefaultClient.Do(req)
  94. if err != nil {
  95. t.Fatalf("POST /api/agents: %v", err)
  96. }
  97. defer res.Body.Close()
  98. var body struct {
  99. Slug string `json:"slug"`
  100. Token string `json:"token"`
  101. Install string `json:"install"`
  102. }
  103. data, _ := io.ReadAll(res.Body)
  104. _ = json.Unmarshal(data, &body)
  105. return res.StatusCode, body.Token, body.Install
  106. }
  107. // ingest hace un push de agente; ip fija la X-Forwarded-For (rate limit).
  108. func ingest(t *testing.T, ts *agentTestServer, token, ip, payload string) *http.Response {
  109. t.Helper()
  110. req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(payload))
  111. req.Header.Set("Content-Type", "application/json")
  112. req.Header.Set("X-Forwarded-For", ip)
  113. if token != "" {
  114. req.Header.Set("Authorization", "Bearer "+token)
  115. mac := hmac.New(sha256.New, []byte(token))
  116. mac.Write([]byte(payload))
  117. req.Header.Set("X-Agent-Signature", hex.EncodeToString(mac.Sum(nil)))
  118. }
  119. res, err := http.DefaultClient.Do(req)
  120. if err != nil {
  121. t.Fatalf("ingest: %v", err)
  122. }
  123. return res
  124. }
  125. // validPayload construye un payload de agente válido con ts ACTUAL (el
  126. // anti-replay de la auditoría #2 rechaza ts antiguos, así que el payload de
  127. // test no puede llevar un ts fijo del pasado).
  128. func validPayload(ts ...int64) string {
  129. t := time.Now().Unix()
  130. if len(ts) > 0 {
  131. t = ts[0]
  132. }
  133. return fmt.Sprintf(`{"router":"patio","ts":%d,"version":"0.1.0","data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`, t)
  134. }
  135. func TestIngestTokenValidoEInvalido(t *testing.T) {
  136. ts := makeAgentTestServer(t)
  137. status, token, install := createAgentToken(t, ts, "patio")
  138. if status != 201 || token == "" {
  139. t.Fatalf("create: %d token=%q", status, token)
  140. }
  141. if !strings.Contains(install, "install-agent.sh") || !strings.Contains(install, token) || !strings.Contains(install, "--slug=patio") || !strings.Contains(install, "--ssh-key=") {
  142. t.Fatalf("one-liner: %q", install)
  143. }
  144. // #1577: el one-liner descarga a fichero y lo ejecuta tras `&&`. Con
  145. // `curl | sh` un curl a medias (descarga truncada) alimentaba al shell con
  146. // un script incompleto y el error real (exit de curl) se perdía.
  147. if strings.Contains(install, "| sh") {
  148. t.Fatalf("one-liner no debe encadenar curl a sh: %q", install)
  149. }
  150. if !strings.Contains(install, "-o /tmp/netpulse-install-agent.sh") || !strings.Contains(install, "&& sh /tmp/netpulse-install-agent.sh") {
  151. t.Fatalf("one-liner debe descargar a fichero y ejecutarlo: %q", install)
  152. }
  153. // kv guarda sha256, NUNCA el token en claro
  154. var stored string
  155. if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.token.patio'").Scan(&stored); err != nil {
  156. t.Fatalf("kv: %v", err)
  157. }
  158. sum := sha256.Sum256([]byte(token))
  159. if stored != hex.EncodeToString(sum[:]) || strings.Contains(stored, token) {
  160. t.Fatalf("kv debería guardar sha256: %q", stored)
  161. }
  162. // Ingesta sin sesión (exenta del middleware) + token válido → 202
  163. res := ingest(t, ts, token, "10.0.0.1", validPayload())
  164. res.Body.Close()
  165. if res.StatusCode != 202 {
  166. t.Fatalf("ingest válido: %d", res.StatusCode)
  167. }
  168. if _, version, _, _, ok := ts.agents.Info("patio"); !ok || version != "0.1.0" {
  169. t.Fatalf("registry no actualizado: %v %q", ok, version)
  170. }
  171. // Token inválido → 401; sin token → 401; token de otro slug → 401
  172. for _, tok := range []string{"", "deadbeef", token + "00"} {
  173. res := ingest(t, ts, tok, "10.0.0.2", validPayload())
  174. res.Body.Close()
  175. if res.StatusCode != 401 {
  176. t.Fatalf("token %q debería dar 401, dio %d", tok, res.StatusCode)
  177. }
  178. }
  179. }
  180. func TestIngestBodyGrandeYPayloadInvalido(t *testing.T) {
  181. ts := makeAgentTestServer(t)
  182. _, token, _ := createAgentToken(t, ts, "patio")
  183. // 413: body > 2 MB
  184. big := strings.Repeat("x", (2<<20)+100)
  185. res := ingest(t, ts, token, "10.0.1.1", big)
  186. res.Body.Close()
  187. if res.StatusCode != 413 {
  188. t.Fatalf("body grande: %d", res.StatusCode)
  189. }
  190. // 400: JSON roto, slug inválido, ts ausente — y NADA se rompe después
  191. for _, p := range []string{
  192. `{no json`,
  193. `{"router":"PATIO!","ts":1,"data":{}}`,
  194. `{"router":"patio","data":{}}`,
  195. `{"router":"patio","ts":-3,"data":{}}`,
  196. } {
  197. res := ingest(t, ts, token, "10.0.1.2", p)
  198. res.Body.Close()
  199. if res.StatusCode != 400 {
  200. t.Fatalf("payload %q debería dar 400, dio %d", p, res.StatusCode)
  201. }
  202. }
  203. // El pipeline sigue sano tras los 400
  204. res = ingest(t, ts, token, "10.0.1.2", validPayload())
  205. res.Body.Close()
  206. if res.StatusCode != 202 {
  207. t.Fatalf("ingest tras 400s: %d", res.StatusCode)
  208. }
  209. }
  210. func TestIngestRateLimit(t *testing.T) {
  211. ts := makeAgentTestServer(t)
  212. _, token, _ := createAgentToken(t, ts, "patio")
  213. // 30/min por IP: las 30 primeras pasan, la 31 es 429 con Retry-After
  214. for i := 0; i < 30; i++ {
  215. res := ingest(t, ts, token, "10.0.2.1", validPayload())
  216. res.Body.Close()
  217. if res.StatusCode != 202 {
  218. t.Fatalf("push %d: %d", i, res.StatusCode)
  219. }
  220. }
  221. res := ingest(t, ts, token, "10.0.2.1", validPayload())
  222. defer res.Body.Close()
  223. if res.StatusCode != 429 {
  224. t.Fatalf("push 31 debería ser 429, dio %d", res.StatusCode)
  225. }
  226. var body map[string]any
  227. if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
  228. t.Fatalf("429 json: %v", err)
  229. }
  230. if body["error"] != "rate_limited" || res.Header.Get("Retry-After") == "" {
  231. t.Fatalf("429 shape: %v retry=%q", body, res.Header.Get("Retry-After"))
  232. }
  233. // Otra IP no está limitada
  234. res2 := ingest(t, ts, token, "10.0.2.2", validPayload())
  235. res2.Body.Close()
  236. if res2.StatusCode != 202 {
  237. t.Fatalf("otra IP: %d", res2.StatusCode)
  238. }
  239. }
  240. func TestAgentsListYRevocacion(t *testing.T) {
  241. ts := makeAgentTestServer(t)
  242. // GET /api/agents exige sesión
  243. res := get(t, ts.URL, "/api/agents", "")
  244. res.Body.Close()
  245. if res.StatusCode != 401 {
  246. t.Fatalf("GET /api/agents sin sesión: %d", res.StatusCode)
  247. }
  248. _, token, _ := createAgentToken(t, ts, "patio")
  249. if _, token2, _ := createAgentToken(t, ts, "living"); token2 == "" {
  250. t.Fatal("segundo token")
  251. }
  252. // Lista: 2 slugs, lastSeen null (nunca empujaron), SIN token ni hash
  253. res = get(t, ts.URL, "/api/agents", ts.cookie)
  254. body := readJSON(t, res)
  255. agents, _ := body["agents"].([]any)
  256. if len(agents) != 2 {
  257. t.Fatalf("agents: %v", body)
  258. }
  259. raw, _ := json.Marshal(body)
  260. if strings.Contains(string(raw), token) || strings.Contains(string(raw), "token") {
  261. t.Fatalf("GET /api/agents no debería exponer tokens: %s", raw)
  262. }
  263. // Tras un push: lastSeen (unix s) + versión + fresh
  264. res2 := ingest(t, ts, token, "10.0.3.1", validPayload())
  265. res2.Body.Close()
  266. res = get(t, ts.URL, "/api/agents", ts.cookie)
  267. body = readJSON(t, res)
  268. agents, _ = body["agents"].([]any)
  269. var patio map[string]any
  270. for _, a := range agents {
  271. m, _ := a.(map[string]any)
  272. if m["slug"] == "patio" {
  273. patio = m
  274. }
  275. }
  276. if patio == nil || patio["lastSeen"] == nil || patio["version"] != "0.1.0" || patio["fresh"] != true {
  277. t.Fatalf("patio tras push: %v", patio)
  278. }
  279. // Revocar → 204; el push siguiente recibe 401; GET ya no lo lista
  280. req, _ := http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
  281. req.Header.Set("Cookie", "session="+ts.cookie)
  282. resDel, err := http.DefaultClient.Do(req)
  283. if err != nil {
  284. t.Fatalf("DELETE: %v", err)
  285. }
  286. resDel.Body.Close()
  287. if resDel.StatusCode != 204 {
  288. t.Fatalf("DELETE: %d", resDel.StatusCode)
  289. }
  290. res3 := ingest(t, ts, token, "10.0.3.2", validPayload())
  291. res3.Body.Close()
  292. if res3.StatusCode != 401 {
  293. t.Fatalf("push tras revocar: %d", res3.StatusCode)
  294. }
  295. res = get(t, ts.URL, "/api/agents", ts.cookie)
  296. body = readJSON(t, res)
  297. agents, _ = body["agents"].([]any)
  298. if len(agents) != 1 {
  299. t.Fatalf("tras revocar: %v", body)
  300. }
  301. // Revocar de nuevo → 404
  302. req, _ = http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
  303. req.Header.Set("Cookie", "session="+ts.cookie)
  304. resDel, _ = http.DefaultClient.Do(req)
  305. resDel.Body.Close()
  306. if resDel.StatusCode != 404 {
  307. t.Fatalf("DELETE 2ª vez: %d", resDel.StatusCode)
  308. }
  309. }
  310. func TestAgentsCreateValidaSlug(t *testing.T) {
  311. ts := makeAgentTestServer(t)
  312. for _, slug := range []string{"", "PATIO", "con espacios", "-x", strings.Repeat("a", 65)} {
  313. status, _, _ := createAgentToken(t, ts, slug)
  314. if status != 400 {
  315. t.Fatalf("slug %q debería dar 400, dio %d", slug, status)
  316. }
  317. }
  318. }
  319. // TestAgentStatePersistenciaYRestauracion (Fase 8.2, R8): tras una ingesta,
  320. // el último push queda en kv (agent.state.<slug>); un registry nuevo que
  321. // restaura desde kv recupera lastSeen/versión/payload (simula reinicio).
  322. func TestAgentStatePersistenciaYRestauracion(t *testing.T) {
  323. ts := makeAgentTestServer(t)
  324. _, token, _ := createAgentToken(t, ts, "patio")
  325. res := ingest(t, ts, token, "10.0.0.1", validPayload())
  326. res.Body.Close()
  327. if res.StatusCode != 202 {
  328. t.Fatalf("ingest: %d", res.StatusCode)
  329. }
  330. // El estado debe estar en kv tras la ingesta
  331. var raw string
  332. if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.state.patio'").Scan(&raw); err != nil {
  333. t.Fatalf("kv agent.state: %v", err)
  334. }
  335. // Simular reinicio: registry nuevo + restaurador desde la misma BD
  336. reg2 := adapters.NewAgentRegistry(90 * time.Second)
  337. httpapi.NewStateRestorer(ts.db)(reg2)
  338. _, version, _, _, ok := reg2.Info("patio")
  339. if !ok {
  340. t.Fatal("estado no restaurado tras reinicio")
  341. }
  342. if version != "0.1.0" {
  343. t.Fatalf("versión restaurada: %q", version)
  344. }
  345. payload, fresh := reg2.Fresh("patio")
  346. if !fresh || payload == nil || payload.Router != "patio" {
  347. t.Fatalf("payload no fresco tras restauración: fresh=%v", fresh)
  348. }
  349. }
  350. // TestIngestAntiReplay (auditoría #2): un payload con ts fuera de la ventana
  351. // de frescura (pasado o futuro) se rechaza con 401 stale_payload, aunque el
  352. // token y el HMAC sean correctos — evita reinyectar pushes viejos capturados.
  353. func TestIngestAntiReplay(t *testing.T) {
  354. ts := makeAgentTestServer(t)
  355. _, token, _ := createAgentToken(t, ts, "patio")
  356. stale := validPayload(time.Now().Add(-10 * time.Minute).Unix())
  357. res := ingest(t, ts, token, "10.0.4.1", stale)
  358. res.Body.Close()
  359. if res.StatusCode != 401 {
  360. t.Fatalf("ts pasado debería dar 401, dio %d", res.StatusCode)
  361. }
  362. future := validPayload(time.Now().Add(10 * time.Minute).Unix())
  363. res = ingest(t, ts, token, "10.0.4.2", future)
  364. res.Body.Close()
  365. if res.StatusCode != 401 {
  366. t.Fatalf("ts futuro debería dar 401, dio %d", res.StatusCode)
  367. }
  368. // ts justo dentro de la ventana → 202
  369. res = ingest(t, ts, token, "10.0.4.3", validPayload(time.Now().Add(-2*time.Minute).Unix()))
  370. res.Body.Close()
  371. if res.StatusCode != 202 {
  372. t.Fatalf("ts en ventana debería dar 202, dio %d", res.StatusCode)
  373. }
  374. }