agent_api_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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") {
  142. t.Fatalf("one-liner: %q", install)
  143. }
  144. // kv guarda sha256, NUNCA el token en claro
  145. var stored string
  146. if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.token.patio'").Scan(&stored); err != nil {
  147. t.Fatalf("kv: %v", err)
  148. }
  149. sum := sha256.Sum256([]byte(token))
  150. if stored != hex.EncodeToString(sum[:]) || strings.Contains(stored, token) {
  151. t.Fatalf("kv debería guardar sha256: %q", stored)
  152. }
  153. // Ingesta sin sesión (exenta del middleware) + token válido → 202
  154. res := ingest(t, ts, token, "10.0.0.1", validPayload())
  155. res.Body.Close()
  156. if res.StatusCode != 202 {
  157. t.Fatalf("ingest válido: %d", res.StatusCode)
  158. }
  159. if _, version, _, _, ok := ts.agents.Info("patio"); !ok || version != "0.1.0" {
  160. t.Fatalf("registry no actualizado: %v %q", ok, version)
  161. }
  162. // Token inválido → 401; sin token → 401; token de otro slug → 401
  163. for _, tok := range []string{"", "deadbeef", token + "00"} {
  164. res := ingest(t, ts, tok, "10.0.0.2", validPayload())
  165. res.Body.Close()
  166. if res.StatusCode != 401 {
  167. t.Fatalf("token %q debería dar 401, dio %d", tok, res.StatusCode)
  168. }
  169. }
  170. }
  171. func TestIngestBodyGrandeYPayloadInvalido(t *testing.T) {
  172. ts := makeAgentTestServer(t)
  173. _, token, _ := createAgentToken(t, ts, "patio")
  174. // 413: body > 2 MB
  175. big := strings.Repeat("x", (2<<20)+100)
  176. res := ingest(t, ts, token, "10.0.1.1", big)
  177. res.Body.Close()
  178. if res.StatusCode != 413 {
  179. t.Fatalf("body grande: %d", res.StatusCode)
  180. }
  181. // 400: JSON roto, slug inválido, ts ausente — y NADA se rompe después
  182. for _, p := range []string{
  183. `{no json`,
  184. `{"router":"PATIO!","ts":1,"data":{}}`,
  185. `{"router":"patio","data":{}}`,
  186. `{"router":"patio","ts":-3,"data":{}}`,
  187. } {
  188. res := ingest(t, ts, token, "10.0.1.2", p)
  189. res.Body.Close()
  190. if res.StatusCode != 400 {
  191. t.Fatalf("payload %q debería dar 400, dio %d", p, res.StatusCode)
  192. }
  193. }
  194. // El pipeline sigue sano tras los 400
  195. res = ingest(t, ts, token, "10.0.1.2", validPayload())
  196. res.Body.Close()
  197. if res.StatusCode != 202 {
  198. t.Fatalf("ingest tras 400s: %d", res.StatusCode)
  199. }
  200. }
  201. func TestIngestRateLimit(t *testing.T) {
  202. ts := makeAgentTestServer(t)
  203. _, token, _ := createAgentToken(t, ts, "patio")
  204. // 30/min por IP: las 30 primeras pasan, la 31 es 429 con Retry-After
  205. for i := 0; i < 30; i++ {
  206. res := ingest(t, ts, token, "10.0.2.1", validPayload())
  207. res.Body.Close()
  208. if res.StatusCode != 202 {
  209. t.Fatalf("push %d: %d", i, res.StatusCode)
  210. }
  211. }
  212. res := ingest(t, ts, token, "10.0.2.1", validPayload())
  213. defer res.Body.Close()
  214. if res.StatusCode != 429 {
  215. t.Fatalf("push 31 debería ser 429, dio %d", res.StatusCode)
  216. }
  217. var body map[string]any
  218. if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
  219. t.Fatalf("429 json: %v", err)
  220. }
  221. if body["error"] != "rate_limited" || res.Header.Get("Retry-After") == "" {
  222. t.Fatalf("429 shape: %v retry=%q", body, res.Header.Get("Retry-After"))
  223. }
  224. // Otra IP no está limitada
  225. res2 := ingest(t, ts, token, "10.0.2.2", validPayload())
  226. res2.Body.Close()
  227. if res2.StatusCode != 202 {
  228. t.Fatalf("otra IP: %d", res2.StatusCode)
  229. }
  230. }
  231. func TestAgentsListYRevocacion(t *testing.T) {
  232. ts := makeAgentTestServer(t)
  233. // GET /api/agents exige sesión
  234. res := get(t, ts.URL, "/api/agents", "")
  235. res.Body.Close()
  236. if res.StatusCode != 401 {
  237. t.Fatalf("GET /api/agents sin sesión: %d", res.StatusCode)
  238. }
  239. _, token, _ := createAgentToken(t, ts, "patio")
  240. if _, token2, _ := createAgentToken(t, ts, "living"); token2 == "" {
  241. t.Fatal("segundo token")
  242. }
  243. // Lista: 2 slugs, lastSeen null (nunca empujaron), SIN token ni hash
  244. res = get(t, ts.URL, "/api/agents", ts.cookie)
  245. body := readJSON(t, res)
  246. agents, _ := body["agents"].([]any)
  247. if len(agents) != 2 {
  248. t.Fatalf("agents: %v", body)
  249. }
  250. raw, _ := json.Marshal(body)
  251. if strings.Contains(string(raw), token) || strings.Contains(string(raw), "token") {
  252. t.Fatalf("GET /api/agents no debería exponer tokens: %s", raw)
  253. }
  254. // Tras un push: lastSeen (unix s) + versión + fresh
  255. res2 := ingest(t, ts, token, "10.0.3.1", validPayload())
  256. res2.Body.Close()
  257. res = get(t, ts.URL, "/api/agents", ts.cookie)
  258. body = readJSON(t, res)
  259. agents, _ = body["agents"].([]any)
  260. var patio map[string]any
  261. for _, a := range agents {
  262. m, _ := a.(map[string]any)
  263. if m["slug"] == "patio" {
  264. patio = m
  265. }
  266. }
  267. if patio == nil || patio["lastSeen"] == nil || patio["version"] != "0.1.0" || patio["fresh"] != true {
  268. t.Fatalf("patio tras push: %v", patio)
  269. }
  270. // Revocar → 204; el push siguiente recibe 401; GET ya no lo lista
  271. req, _ := http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
  272. req.Header.Set("Cookie", "session="+ts.cookie)
  273. resDel, err := http.DefaultClient.Do(req)
  274. if err != nil {
  275. t.Fatalf("DELETE: %v", err)
  276. }
  277. resDel.Body.Close()
  278. if resDel.StatusCode != 204 {
  279. t.Fatalf("DELETE: %d", resDel.StatusCode)
  280. }
  281. res3 := ingest(t, ts, token, "10.0.3.2", validPayload())
  282. res3.Body.Close()
  283. if res3.StatusCode != 401 {
  284. t.Fatalf("push tras revocar: %d", res3.StatusCode)
  285. }
  286. res = get(t, ts.URL, "/api/agents", ts.cookie)
  287. body = readJSON(t, res)
  288. agents, _ = body["agents"].([]any)
  289. if len(agents) != 1 {
  290. t.Fatalf("tras revocar: %v", body)
  291. }
  292. // Revocar de nuevo → 404
  293. req, _ = http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
  294. req.Header.Set("Cookie", "session="+ts.cookie)
  295. resDel, _ = http.DefaultClient.Do(req)
  296. resDel.Body.Close()
  297. if resDel.StatusCode != 404 {
  298. t.Fatalf("DELETE 2ª vez: %d", resDel.StatusCode)
  299. }
  300. }
  301. func TestAgentsCreateValidaSlug(t *testing.T) {
  302. ts := makeAgentTestServer(t)
  303. for _, slug := range []string{"", "PATIO", "con espacios", "-x", strings.Repeat("a", 65)} {
  304. status, _, _ := createAgentToken(t, ts, slug)
  305. if status != 400 {
  306. t.Fatalf("slug %q debería dar 400, dio %d", slug, status)
  307. }
  308. }
  309. }
  310. // TestAgentStatePersistenciaYRestauracion (Fase 8.2, R8): tras una ingesta,
  311. // el último push queda en kv (agent.state.<slug>); un registry nuevo que
  312. // restaura desde kv recupera lastSeen/versión/payload (simula reinicio).
  313. func TestAgentStatePersistenciaYRestauracion(t *testing.T) {
  314. ts := makeAgentTestServer(t)
  315. _, token, _ := createAgentToken(t, ts, "patio")
  316. res := ingest(t, ts, token, "10.0.0.1", validPayload())
  317. res.Body.Close()
  318. if res.StatusCode != 202 {
  319. t.Fatalf("ingest: %d", res.StatusCode)
  320. }
  321. // El estado debe estar en kv tras la ingesta
  322. var raw string
  323. if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.state.patio'").Scan(&raw); err != nil {
  324. t.Fatalf("kv agent.state: %v", err)
  325. }
  326. // Simular reinicio: registry nuevo + restaurador desde la misma BD
  327. reg2 := adapters.NewAgentRegistry(90 * time.Second)
  328. httpapi.NewStateRestorer(ts.db)(reg2)
  329. _, version, _, _, ok := reg2.Info("patio")
  330. if !ok {
  331. t.Fatal("estado no restaurado tras reinicio")
  332. }
  333. if version != "0.1.0" {
  334. t.Fatalf("versión restaurada: %q", version)
  335. }
  336. payload, fresh := reg2.Fresh("patio")
  337. if !fresh || payload == nil || payload.Router != "patio" {
  338. t.Fatalf("payload no fresco tras restauración: fresh=%v", fresh)
  339. }
  340. }
  341. // TestIngestAntiReplay (auditoría #2): un payload con ts fuera de la ventana
  342. // de frescura (pasado o futuro) se rechaza con 401 stale_payload, aunque el
  343. // token y el HMAC sean correctos — evita reinyectar pushes viejos capturados.
  344. func TestIngestAntiReplay(t *testing.T) {
  345. ts := makeAgentTestServer(t)
  346. _, token, _ := createAgentToken(t, ts, "patio")
  347. stale := validPayload(time.Now().Add(-10 * time.Minute).Unix())
  348. res := ingest(t, ts, token, "10.0.4.1", stale)
  349. res.Body.Close()
  350. if res.StatusCode != 401 {
  351. t.Fatalf("ts pasado debería dar 401, dio %d", res.StatusCode)
  352. }
  353. future := validPayload(time.Now().Add(10 * time.Minute).Unix())
  354. res = ingest(t, ts, token, "10.0.4.2", future)
  355. res.Body.Close()
  356. if res.StatusCode != 401 {
  357. t.Fatalf("ts futuro debería dar 401, dio %d", res.StatusCode)
  358. }
  359. // ts justo dentro de la ventana → 202
  360. res = ingest(t, ts, token, "10.0.4.3", validPayload(time.Now().Add(-2*time.Minute).Unix()))
  361. res.Body.Close()
  362. if res.StatusCode != 202 {
  363. t.Fatalf("ts en ventana debería dar 202, dio %d", res.StatusCode)
  364. }
  365. }