pairing.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. // pairing.go: modo bootstrap (Fase 9 R3). Con pairing_token en vez de
  2. // token, el agente contacta al servidor una vez, obtiene el token real, lo
  3. // escribe al env file y sale. procd (o el embedder) reinicia, y el agente
  4. // arranca en modo normal.
  5. package runtime
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "os"
  12. "strings"
  13. "time"
  14. )
  15. // pairWithServer contacta POST /api/agents/pair con el pairing token,
  16. // recibe el token real del agente y lo escribe al env file. Usa el
  17. // server_fp para validar TLS (el admin lo proporciona junto con el
  18. // pairing token).
  19. func pairWithServer(opts Options) error {
  20. // FORK: over https with no pin, prove the server's key with the pairing
  21. // token first, then pair over a connection pinned to it.
  22. learnedFP := ""
  23. if strings.HasPrefix(opts.Server, "https://") && opts.ServerFP == "" {
  24. fp, err := ProveServerKey(opts.Server, opts.PairingToken)
  25. if err != nil {
  26. return err
  27. }
  28. opts.ServerFP, learnedFP = fp, fp
  29. }
  30. transport, err := buildTransport(opts)
  31. if err != nil {
  32. return err
  33. }
  34. body := fmt.Sprintf(`{"pairing_token":%q,"slug":%q}`, opts.PairingToken, opts.Slug)
  35. req, err := http.NewRequest("POST", opts.Server+"/api/agents/pair", strings.NewReader(body))
  36. if err != nil {
  37. return err
  38. }
  39. req.Header.Set("Content-Type", "application/json")
  40. hc := &http.Client{Transport: transport, Timeout: 15 * time.Second}
  41. log := opts.logger()
  42. log.Info("[netpulse-agent] pairing", "server", opts.Server, "slug", opts.Slug)
  43. res, err := hc.Do(req)
  44. if err != nil {
  45. return fmt.Errorf("pairing: %w", err)
  46. }
  47. defer res.Body.Close()
  48. if res.StatusCode != http.StatusCreated {
  49. respBody, _ := io.ReadAll(io.LimitReader(res.Body, 512))
  50. return fmt.Errorf("pairing fallido (HTTP %d): %s", res.StatusCode, respBody)
  51. }
  52. var pr struct {
  53. Slug string `json:"slug"`
  54. Token string `json:"token"`
  55. ServerFP string `json:"server_fp"`
  56. }
  57. if err := json.NewDecoder(res.Body).Decode(&pr); err != nil {
  58. return fmt.Errorf("parse pairing response: %w", err)
  59. }
  60. if pr.Token == "" {
  61. return fmt.Errorf("pairing: empty token in response")
  62. }
  63. // Escribir el token real al env file (reemplaza PAIRING_TOKEN por TOKEN).
  64. if err := writePairedToken(opts.EnvFile, pr.Token, learnedFP); err != nil {
  65. return fmt.Errorf("write token to env file: %w", err)
  66. }
  67. log.Info("[netpulse-agent] pairing OK", "slug", pr.Slug, "env_file", opts.EnvFile)
  68. // Salir limpiamente: quien arranque el agente lo relanza y este lee
  69. // NETPULSE_TOKEN del env file en modo normal.
  70. return nil
  71. }
  72. // writePairedToken reescribe el env file: quita NETPULSE_PAIRING_TOKEN y
  73. // añade/actualiza NETPULSE_TOKEN. Conserva el resto de líneas.
  74. //
  75. // FORK: fp, when not empty, is a pin proven during pairing and is written as
  76. // NETPULSE_SERVER_FP, so the agent keeps pinning it after the restart.
  77. func writePairedToken(path, token, fp string) error {
  78. data, err := os.ReadFile(path)
  79. if err != nil {
  80. // Si no existe, crear uno nuevo con el token.
  81. out := "NETPULSE_TOKEN=" + token + "\n"
  82. if fp != "" {
  83. out += "NETPULSE_SERVER_FP=" + fp + "\n"
  84. }
  85. return os.WriteFile(path, []byte(out), 0o600)
  86. }
  87. var out []string
  88. haveToken := false
  89. for _, line := range strings.Split(string(data), "\n") {
  90. trimmed := strings.TrimSpace(line)
  91. if trimmed == "" || strings.HasPrefix(trimmed, "#") {
  92. out = append(out, line)
  93. continue
  94. }
  95. k, _, ok := strings.Cut(trimmed, "=")
  96. if !ok {
  97. out = append(out, line)
  98. continue
  99. }
  100. key := strings.TrimSpace(k)
  101. if key == "NETPULSE_PAIRING_TOKEN" {
  102. continue // eliminar
  103. }
  104. if key == "NETPULSE_TOKEN" {
  105. out = append(out, "NETPULSE_TOKEN="+token)
  106. haveToken = true
  107. continue
  108. }
  109. if key == "NETPULSE_SERVER_FP" && fp != "" {
  110. continue // replaced by the proven pin below
  111. }
  112. out = append(out, line)
  113. }
  114. if !haveToken {
  115. out = append(out, "NETPULSE_TOKEN="+token)
  116. }
  117. if fp != "" {
  118. out = append(out, "NETPULSE_SERVER_FP="+fp)
  119. }
  120. return os.WriteFile(path, []byte(strings.Join(out, "\n")+"\n"), 0o600)
  121. }