runtime_test.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // runtime_test.go: tests del paquete runtime - parsing/validación de config
  2. // (espejo de los configError del antiguo main), writePairedToken y emisión
  3. // de Status del bucle contra un servidor de prueba local.
  4. package runtime
  5. import (
  6. "context"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "sync"
  13. "testing"
  14. "time"
  15. )
  16. func writeFile(t *testing.T, path, content string) {
  17. t.Helper()
  18. if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
  19. t.Fatalf("WriteFile: %v", err)
  20. }
  21. }
  22. func TestLoadConfigFromEnvFile(t *testing.T) {
  23. dir := t.TempDir()
  24. env := filepath.Join(dir, "agent.env")
  25. writeFile(t, env, `
  26. # comentario
  27. NETPULSE_SERVER=https://example.com:3000/
  28. NETPULSE_TOKEN=abc123
  29. NETPULSE_SLUG=patio
  30. NETPULSE_SERVER_FP=AA-BB-CC
  31. NETPULSE_INTERVAL=15s
  32. NETPULSE_WAN_TARGET=1.1.1.1
  33. NETPULSE_GW_TARGET=192.168.8.1
  34. NETPULSE_HEARTBEAT_FILE=/tmp/hb
  35. `)
  36. opts, err := LoadConfigFromEnv(env)
  37. if err != nil {
  38. t.Fatalf("LoadConfigFromEnv: %v", err)
  39. }
  40. if opts.Server != "https://example.com:3000" {
  41. t.Fatalf("Server: %q (quiero sin / final)", opts.Server)
  42. }
  43. if opts.Token != "abc123" || opts.Slug != "patio" {
  44. t.Fatalf("token/slug: %q/%q", opts.Token, opts.Slug)
  45. }
  46. if opts.ServerFP == "AA-BB-CC" {
  47. t.Fatalf("ServerFP sin normalizar: %q", opts.ServerFP)
  48. }
  49. if opts.Interval != 15*time.Second {
  50. t.Fatalf("Interval: %v", opts.Interval)
  51. }
  52. if opts.WanTarget != "1.1.1.1" || opts.GwTarget != "192.168.8.1" {
  53. t.Fatalf("targets: %q/%q", opts.WanTarget, opts.GwTarget)
  54. }
  55. if opts.HeartbeatFile != "/tmp/hb" || opts.EnvFile != env {
  56. t.Fatalf("files: %q/%q", opts.HeartbeatFile, opts.EnvFile)
  57. }
  58. }
  59. func TestLoadConfigIntervalFormats(t *testing.T) {
  60. dir := t.TempDir()
  61. base := "NETPULSE_SERVER=http://s\nNETPULSE_TOKEN=t\nNETPULSE_SLUG=s\n"
  62. env := filepath.Join(dir, "secs.env")
  63. writeFile(t, env, base+"NETPULSE_INTERVAL=20")
  64. opts, err := LoadConfigFromEnv(env)
  65. if err != nil || opts.Interval != 20*time.Second {
  66. t.Fatalf("NETPULSE_INTERVAL=20: %v %v", opts.Interval, err)
  67. }
  68. env = filepath.Join(dir, "dur.env")
  69. writeFile(t, env, base+"NETPULSE_INTERVAL=1m")
  70. opts, err = LoadConfigFromEnv(env)
  71. if err != nil || opts.Interval != time.Minute {
  72. t.Fatalf("NETPULSE_INTERVAL=1m: %v %v", opts.Interval, err)
  73. }
  74. // Valor inválido: default 30s (y no error).
  75. env = filepath.Join(dir, "bad.env")
  76. writeFile(t, env, base+"NETPULSE_INTERVAL=nada")
  77. opts, err = LoadConfigFromEnv(env)
  78. if err != nil || opts.Interval != DefaultInterval {
  79. t.Fatalf("NETPULSE_INTERVAL inválido: %v %v (quiero default 30s)", opts.Interval, err)
  80. }
  81. }
  82. func TestLoadConfigValidationErrors(t *testing.T) {
  83. dir := t.TempDir()
  84. env := filepath.Join(dir, "no-server.env")
  85. writeFile(t, env, "NETPULSE_TOKEN=t\nNETPULSE_SLUG=s\n")
  86. if _, err := LoadConfigFromEnv(env); err == nil || !strings.Contains(err.Error(), "NETPULSE_SERVER") {
  87. t.Fatalf("sin server: quiero ConfigError NETPULSE_SERVER, got %v", err)
  88. }
  89. env = filepath.Join(dir, "no-slug.env")
  90. writeFile(t, env, "NETPULSE_SERVER=http://s\nNETPULSE_TOKEN=t\n")
  91. if _, err := LoadConfigFromEnv(env); err == nil || !strings.Contains(err.Error(), "NETPULSE_SLUG") {
  92. t.Fatalf("sin slug: quiero ConfigError NETPULSE_SLUG, got %v", err)
  93. }
  94. env = filepath.Join(dir, "no-token.env")
  95. writeFile(t, env, "NETPULSE_SERVER=http://s\nNETPULSE_SLUG=s\n")
  96. if _, err := LoadConfigFromEnv(env); err == nil || !strings.Contains(err.Error(), "NETPULSE_TOKEN") {
  97. t.Fatalf("sin token: quiero ConfigError NETPULSE_TOKEN, got %v", err)
  98. }
  99. // Pairing token sustituye a TOKEN.
  100. env = filepath.Join(dir, "pairing.env")
  101. writeFile(t, env, "NETPULSE_SERVER=http://s\nNETPULSE_SLUG=s\nNETPULSE_PAIRING_TOKEN=p\n")
  102. if _, err := LoadConfigFromEnv(env); err != nil {
  103. t.Fatalf("pairing válido: no quiero error, got %v", err)
  104. }
  105. // Options.Validate directo (embedders que no usan LoadConfigFromEnv).
  106. if err := (Options{Token: "t"}).Validate(); err == nil {
  107. t.Fatal("Validate sin server/slug: quiero error")
  108. }
  109. if err := (Options{Server: "http://s", Slug: "s"}).Validate(); err == nil {
  110. t.Fatal("Validate sin token ni pairing: quiero error")
  111. }
  112. if err := (Options{Server: "http://s", Slug: "s", Token: "t"}).Validate(); err != nil {
  113. t.Fatalf("Validate completo: %v", err)
  114. }
  115. }
  116. func TestLoadConfigProcessEnvWins(t *testing.T) {
  117. dir := t.TempDir()
  118. env := filepath.Join(dir, "agent.env")
  119. writeFile(t, env, "NETPULSE_SERVER=http://from-file\nNETPULSE_TOKEN=f\nNETPULSE_SLUG=s\n")
  120. t.Setenv("NETPULSE_SERVER", "http://from-env")
  121. opts, err := LoadConfigFromEnv(env)
  122. if err != nil {
  123. t.Fatalf("LoadConfigFromEnv: %v", err)
  124. }
  125. if opts.Server != "http://from-env" {
  126. t.Fatalf("el env del proceso debe ganar: %q", opts.Server)
  127. }
  128. }
  129. func TestLoadConfigMissingEnvFileDefaults(t *testing.T) {
  130. t.Setenv("NETPULSE_SERVER", "http://s")
  131. t.Setenv("NETPULSE_TOKEN", "t")
  132. t.Setenv("NETPULSE_SLUG", "s")
  133. opts, err := LoadConfigFromEnv(filepath.Join(t.TempDir(), "no-existe.env"))
  134. if err != nil {
  135. t.Fatalf("env file inexistente no es error: %v", err)
  136. }
  137. if opts.Interval != DefaultInterval {
  138. t.Fatalf("Interval default: %v", opts.Interval)
  139. }
  140. }
  141. func TestWritePairedToken(t *testing.T) {
  142. dir := t.TempDir()
  143. env := filepath.Join(dir, "agent.env")
  144. writeFile(t, env, "NETPULSE_SERVER=http://s\nNETPULSE_PAIRING_TOKEN=pt\nNETPULSE_SLUG=s\n")
  145. if err := writePairedToken(env, "real-token"); err != nil {
  146. t.Fatalf("writePairedToken: %v", err)
  147. }
  148. data, err := os.ReadFile(env)
  149. if err != nil {
  150. t.Fatalf("ReadFile: %v", err)
  151. }
  152. content := string(data)
  153. if strings.Contains(content, "PAIRING") {
  154. t.Fatalf("PAIRING_TOKEN debe desaparecer: %q", content)
  155. }
  156. if !strings.Contains(content, "NETPULSE_TOKEN=real-token") {
  157. t.Fatalf("TOKEN nuevo debe estar: %q", content)
  158. }
  159. if !strings.Contains(content, "NETPULSE_SERVER=http://s") {
  160. t.Fatalf("conserva el resto: %q", content)
  161. }
  162. st, _ := os.Stat(env)
  163. if st.Mode().Perm() != 0o600 {
  164. t.Fatalf("permisos: %o", st.Mode().Perm())
  165. }
  166. // Env file inexistente: se crea solo con el token.
  167. env2 := filepath.Join(dir, "nuevo.env")
  168. if err := writePairedToken(env2, "tk"); err != nil {
  169. t.Fatalf("writePairedToken nuevo: %v", err)
  170. }
  171. data2, _ := os.ReadFile(env2)
  172. if string(data2) != "NETPULSE_TOKEN=tk\n" {
  173. t.Fatalf("nuevo env: %q", data2)
  174. }
  175. }
  176. // TestRunEmitsStatus: bucle completo contra un servidor de prueba local; el
  177. // callback OnStatus debe ver Running=true y luego un push confirmado.
  178. func TestRunEmitsStatus(t *testing.T) {
  179. var mu sync.Mutex
  180. received := make(chan Status, 16)
  181. onStatus := func(st Status) {
  182. mu.Lock()
  183. defer mu.Unlock()
  184. received <- st
  185. }
  186. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  187. switch r.URL.Path {
  188. case "/api/ingest/agent":
  189. w.WriteHeader(http.StatusAccepted)
  190. case "/api/agents/patio/stream":
  191. // SSE: cuelga hasta que el test cancele el ctx (el cliente cierra).
  192. <-r.Context().Done()
  193. default:
  194. w.WriteHeader(http.StatusNotFound)
  195. }
  196. }))
  197. defer srv.Close()
  198. dir := t.TempDir()
  199. opts := Options{
  200. Server: srv.URL,
  201. Token: "tok",
  202. Slug: "patio",
  203. Interval: 200 * time.Millisecond,
  204. HeartbeatFile: filepath.Join(dir, "hb"),
  205. Version: "test",
  206. OnStatus: onStatus,
  207. }
  208. ctx, cancel := context.WithCancel(context.Background())
  209. done := make(chan error, 1)
  210. go func() { done <- Run(ctx, opts) }()
  211. seenRunning, seenPush := false, false
  212. deadline := time.After(15 * time.Second)
  213. for !(seenRunning && seenPush) {
  214. select {
  215. case st := <-received:
  216. if st.Running && st.Slug == "patio" && st.Server == srv.URL {
  217. seenRunning = true
  218. }
  219. if st.PushOk && !st.LastPush.IsZero() && st.LastError == "" {
  220. seenPush = true
  221. }
  222. case <-deadline:
  223. t.Fatal("no se recibió Running+PushOk via OnStatus")
  224. }
  225. }
  226. cancel()
  227. select {
  228. case err := <-done:
  229. if err != nil {
  230. t.Fatalf("Run: %v", err)
  231. }
  232. case <-time.After(10 * time.Second):
  233. t.Fatal("Run no terminó tras cancelar ctx")
  234. }
  235. // Parada: último estado con Running=false.
  236. var last Status
  237. for {
  238. select {
  239. case last = <-received:
  240. default:
  241. goto checked
  242. }
  243. }
  244. checked:
  245. if last.Running {
  246. t.Fatalf("tras cancelar, Running debe ser false: %+v", last)
  247. }
  248. }
  249. // TestRunEmitsPushError: servidor de ingest caído → estado PushOk=false con
  250. // LastError.
  251. func TestRunEmitsPushError(t *testing.T) {
  252. received := make(chan Status, 16)
  253. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  254. if r.URL.Path == "/api/ingest/agent" {
  255. w.WriteHeader(http.StatusUnauthorized)
  256. return
  257. }
  258. if r.URL.Path == "/api/agents/patio/stream" {
  259. <-r.Context().Done()
  260. return
  261. }
  262. w.WriteHeader(http.StatusNotFound)
  263. }))
  264. defer srv.Close()
  265. opts := Options{
  266. Server: srv.URL,
  267. Token: "tok",
  268. Slug: "patio",
  269. Interval: 200 * time.Millisecond,
  270. OnStatus: func(st Status) { received <- st },
  271. }
  272. ctx, cancel := context.WithCancel(context.Background())
  273. done := make(chan error, 1)
  274. go func() { done <- Run(ctx, opts) }()
  275. deadline := time.After(15 * time.Second)
  276. for {
  277. select {
  278. case st := <-received:
  279. if !st.Running {
  280. continue
  281. }
  282. if !st.PushOk && st.LastError != "" {
  283. cancel()
  284. if err := <-done; err != nil {
  285. t.Fatalf("Run: %v", err)
  286. }
  287. return
  288. }
  289. case <-deadline:
  290. cancel()
  291. t.Fatal("no se recibió PushOk=false con LastError")
  292. }
  293. }
  294. }
  295. // TestRunInvalidOptions: Run sin config válida falla rápido sin arrancar.
  296. func TestRunInvalidOptions(t *testing.T) {
  297. ctx, cancel := context.WithCancel(context.Background())
  298. defer cancel()
  299. if err := Run(ctx, Options{}); err == nil {
  300. t.Fatal("Run sin options: quiero error de validación")
  301. }
  302. }