agent_api_test.go 15 KB

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