config.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. // config.go: carga de config del agente desde el entorno del proceso y el
  2. // env file (KEY=VALUE), extraída de cmd/netpulse-agent para que los
  3. // embedders reutilicen el mismo formato y validación.
  4. package runtime
  5. import (
  6. "log/slog"
  7. "os"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/gnacho/netpulse/agent/internal/tlspin"
  12. "github.com/gnacho/netpulse/agent/probe"
  13. )
  14. // DefaultEnvFile: env file por defecto del agente standalone.
  15. const DefaultEnvFile = "/etc/netpulse-agent.env"
  16. // ConfigError: falta una key obligatoria (env o env file).
  17. type ConfigError struct{ Key string }
  18. func (e *ConfigError) Error() string {
  19. return "falta " + e.Key + " (env o " + DefaultEnvFile + ")"
  20. }
  21. // LoadConfigFromEnv lee la config del entorno del proceso y del env file
  22. // (el env del proceso gana). envFile vacío respeta NETPULSE_ENV_FILE y, en
  23. // su defecto, DefaultEnvFile. Fail-fast si falta lo obligatorio.
  24. func LoadConfigFromEnv(envFile string) (Options, error) {
  25. if envFile == "" {
  26. envFile = os.Getenv("NETPULSE_ENV_FILE")
  27. if envFile == "" {
  28. envFile = DefaultEnvFile
  29. }
  30. }
  31. fromFile := loadEnvFile(envFile)
  32. get := func(key string) string {
  33. if v := os.Getenv(key); v != "" {
  34. return v
  35. }
  36. return fromFile[key]
  37. }
  38. opts := Options{
  39. Server: strings.TrimRight(get("NETPULSE_SERVER"), "/"),
  40. Token: get("NETPULSE_TOKEN"),
  41. Slug: get("NETPULSE_SLUG"),
  42. ServerFP: tlspin.Normalize(get("NETPULSE_SERVER_FP")),
  43. PairingToken: get("NETPULSE_PAIRING_TOKEN"),
  44. Interval: DefaultInterval,
  45. WanTarget: get("NETPULSE_WAN_TARGET"),
  46. GwTarget: get("NETPULSE_GW_TARGET"),
  47. HeartbeatFile: get("NETPULSE_HEARTBEAT_FILE"),
  48. EnvFile: envFile,
  49. }
  50. switch strings.ToLower(strings.TrimSpace(get("NETPULSE_ALLOW_INSECURE_COMMANDS"))) {
  51. case "1", "true", "yes", "on":
  52. opts.AllowInsecureCommands = true
  53. case "", "0", "false", "no", "off":
  54. default:
  55. slog.Warn("[netpulse-agent] NETPULSE_ALLOW_INSECURE_COMMANDS inválido, se ignora",
  56. "value", get("NETPULSE_ALLOW_INSECURE_COMMANDS"))
  57. }
  58. if v := get("NETPULSE_INTERVAL"); v != "" {
  59. if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
  60. opts.Interval = time.Duration(sec) * time.Second
  61. } else if d, err := time.ParseDuration(v); err == nil && d > 0 {
  62. opts.Interval = d
  63. } else {
  64. slog.Warn("[netpulse-agent] NETPULSE_INTERVAL inválido, usando 30s", "value", v)
  65. }
  66. }
  67. // NETPULSE_SCAN_INTERVAL (#699): mínimo entre scans de vecinos. "0" =
  68. // sin scans periódicos (solo on-demand vía refresh del server); número
  69. // en segundos o duración Go ("15m"). Sin valor: DefaultScanInterval.
  70. opts.ScanInterval = probe.DefaultScanInterval
  71. if v := get("NETPULSE_SCAN_INTERVAL"); v != "" {
  72. if v == "0" {
  73. opts.ScanInterval = probe.ScanDisabled
  74. } else if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
  75. opts.ScanInterval = time.Duration(sec) * time.Second
  76. } else if d, err := time.ParseDuration(v); err == nil && d > 0 {
  77. opts.ScanInterval = d
  78. } else {
  79. slog.Warn("[netpulse-agent] NETPULSE_SCAN_INTERVAL inválido, usando 30m", "value", v)
  80. }
  81. }
  82. if err := opts.Validate(); err != nil {
  83. return Options{}, err
  84. }
  85. return opts, nil
  86. }
  87. // Validate comprueba lo obligatorio: SERVER y SLUG siempre; TOKEN salvo en
  88. // modo pairing (donde PAIRING_TOKEN lo sustituye).
  89. func (o Options) Validate() error {
  90. for _, kv := range [][2]string{
  91. {"NETPULSE_SERVER", o.Server},
  92. {"NETPULSE_SLUG", o.Slug},
  93. } {
  94. if strings.TrimSpace(kv[1]) == "" {
  95. return &ConfigError{kv[0]}
  96. }
  97. }
  98. if o.Token == "" && o.PairingToken == "" {
  99. return &ConfigError{"NETPULSE_TOKEN (o NETPULSE_PAIRING_TOKEN para bootstrap)"}
  100. }
  101. return nil
  102. }
  103. // loadEnvFile lee KEY=VALUE de un fichero env. Soporta líneas de comentario
  104. // completas (# al inicio) y comentarios inline (" #" tras el valor); estos
  105. // últimos se recortan antes de quitar comillas y espacios. Los valores que
  106. // genera el server (URL, token, FP SPKI) nunca contienen " #", así que
  107. // recortar en el primero es seguro.
  108. func loadEnvFile(path string) map[string]string {
  109. out := map[string]string{}
  110. data, err := os.ReadFile(path)
  111. if err != nil {
  112. return out
  113. }
  114. for _, line := range strings.Split(string(data), "\n") {
  115. line = strings.TrimSpace(line)
  116. if line == "" || strings.HasPrefix(line, "#") {
  117. continue
  118. }
  119. k, v, ok := strings.Cut(line, "=")
  120. if !ok {
  121. continue
  122. }
  123. if before, _, found := strings.Cut(v, " #"); found {
  124. v = before
  125. }
  126. out[strings.TrimSpace(k)] = strings.Trim(strings.TrimSpace(v), `"'`)
  127. }
  128. return out
  129. }