pair_hello_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package httpapi_test
  2. // FORK: end to end tests for proving the server's key at pairing - the real
  3. // handler on a real TLS listener, and the agent's runtime.ProveServerKey on
  4. // the other end.
  5. import (
  6. "context"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rand"
  10. "crypto/sha256"
  11. "crypto/tls"
  12. "crypto/x509"
  13. "crypto/x509/pkix"
  14. "encoding/hex"
  15. "fmt"
  16. "io"
  17. "math/big"
  18. "net"
  19. "net/http"
  20. "net/http/httptest"
  21. "os"
  22. "strings"
  23. "sync"
  24. "testing"
  25. "time"
  26. agentruntime "github.com/gnacho/netpulse/agent/runtime"
  27. "github.com/gnacho/netpulse/server-go/internal/adapters"
  28. "github.com/gnacho/netpulse/server-go/internal/auth"
  29. "github.com/gnacho/netpulse/server-go/internal/config"
  30. "github.com/gnacho/netpulse/server-go/internal/db"
  31. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  32. "github.com/gnacho/netpulse/server-go/internal/sse"
  33. )
  34. const testPairingToken = "11111111-2222-4333-8444-555555555555"
  35. // ownCert is a certificate of its own for a test server: httptest's servers
  36. // all share one, which would make a "different key" test vacuous.
  37. func ownCert(t *testing.T) (tls.Certificate, string) {
  38. t.Helper()
  39. k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. serial, _ := rand.Int(rand.Reader, big.NewInt(1<<62))
  44. tmpl := &x509.Certificate{
  45. SerialNumber: serial,
  46. Subject: pkix.Name{CommonName: "test"},
  47. NotBefore: time.Now().Add(-time.Hour),
  48. NotAfter: time.Now().Add(time.Hour),
  49. KeyUsage: x509.KeyUsageDigitalSignature,
  50. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  51. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  52. }
  53. der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &k.PublicKey, k)
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. c, _ := x509.ParseCertificate(der)
  58. sum := sha256.Sum256(c.RawSubjectPublicKeyInfo)
  59. return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: k}, hex.EncodeToString(sum[:])
  60. }
  61. // pairServer is the real API on a TLS listener with a key of its own, which
  62. // is also the key it hands to agents. bodies records every request body.
  63. type pairServer struct {
  64. *httptest.Server
  65. fp string
  66. mu sync.Mutex
  67. bodies []string
  68. }
  69. func newPairServer(t *testing.T) *pairServer {
  70. t.Helper()
  71. auth.SetTrustProxy(true)
  72. t.Cleanup(func() { auth.SetTrustProxy(false) })
  73. dataDir := t.TempDir()
  74. cfg, err := config.Load(map[string]string{
  75. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  76. "DATA_DIR": dataDir, "NODE_ENV": "test",
  77. }, dataDir)
  78. if err != nil {
  79. t.Fatal(err)
  80. }
  81. d, err := db.Open(dataDir)
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. t.Cleanup(func() { d.Close() })
  86. secret, err := auth.EnsureSessionSecret(d, cfg)
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. if _, err := d.Exec("INSERT INTO kv (key, value) VALUES ('pairing.token', ?)", testPairingToken); err != nil {
  91. t.Fatal(err)
  92. }
  93. cert, fp := ownCert(t)
  94. ps := &pairServer{fp: fp}
  95. api := httpapi.NewHandler(httpapi.Deps{
  96. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Secret: secret,
  97. Hub: sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
  98. Agents: adapters.NewAgentRegistry(0),
  99. Started: time.Now(),
  100. ServerFP: fp,
  101. })
  102. ps.Server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  103. b, _ := io.ReadAll(r.Body)
  104. ps.mu.Lock()
  105. ps.bodies = append(ps.bodies, string(b))
  106. ps.mu.Unlock()
  107. r.Body = io.NopCloser(strings.NewReader(string(b)))
  108. api.ServeHTTP(w, r)
  109. }))
  110. ps.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
  111. ps.StartTLS()
  112. t.Cleanup(ps.Close)
  113. return ps
  114. }
  115. func TestProveServerKeyLearnsTheServedKey(t *testing.T) {
  116. ps := newPairServer(t)
  117. fp, err := agentruntime.ProveServerKey(ps.URL, testPairingToken)
  118. if err != nil {
  119. t.Fatalf("ProveServerKey: %v", err)
  120. }
  121. if fp != ps.fp {
  122. t.Fatalf("learned %s, the server serves %s", fp, ps.fp)
  123. }
  124. // The pairing token never went to the server on this connection.
  125. ps.mu.Lock()
  126. defer ps.mu.Unlock()
  127. for _, b := range ps.bodies {
  128. if strings.Contains(b, testPairingToken) {
  129. t.Fatalf("the pairing token was sent: %s", b)
  130. }
  131. }
  132. }
  133. func TestProveServerKeyRefusesAServerWithoutTheToken(t *testing.T) {
  134. ps := newPairServer(t)
  135. if _, err := agentruntime.ProveServerKey(ps.URL, "not-the-token"); err == nil {
  136. t.Fatal("a server that does not know the agent's token was accepted")
  137. }
  138. }
  139. // A man in the middle relays the hello to the real server and returns its
  140. // genuine answer - over a connection that presents the middle's own key,
  141. // with or without the real server's certificate attached to its chain.
  142. func TestProveServerKeyRefusesARelayedProof(t *testing.T) {
  143. for _, attachReal := range []bool{false, true} {
  144. t.Run(fmt.Sprintf("real certificate attached=%v", attachReal), func(t *testing.T) {
  145. relayedProof(t, attachReal)
  146. })
  147. }
  148. }
  149. func relayedProof(t *testing.T, attachReal bool) {
  150. ps := newPairServer(t)
  151. relay := &http.Client{Transport: &http.Transport{
  152. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // the attacker's own client
  153. }}
  154. middleCert, _ := ownCert(t)
  155. middle := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  156. req, _ := http.NewRequest(r.Method, ps.URL+r.URL.Path, r.Body)
  157. req.Header = r.Header.Clone()
  158. res, err := relay.Do(req)
  159. if err != nil {
  160. http.Error(w, err.Error(), http.StatusBadGateway)
  161. return
  162. }
  163. defer res.Body.Close()
  164. w.WriteHeader(res.StatusCode)
  165. io.Copy(w, res.Body)
  166. }))
  167. if attachReal {
  168. middleCert.Certificate = append(middleCert.Certificate, ps.TLS.Certificates[0].Certificate[0])
  169. }
  170. middle.TLS = &tls.Config{Certificates: []tls.Certificate{middleCert}}
  171. middle.StartTLS()
  172. defer middle.Close()
  173. _, err := agentruntime.ProveServerKey(middle.URL, testPairingToken)
  174. if err == nil || !strings.Contains(err.Error(), "intercepting") {
  175. t.Fatalf("a relayed proof was accepted or refused for the wrong reason: %v", err)
  176. }
  177. }
  178. // Over plain HTTP there is no chain to bind the proof to.
  179. func TestPairHelloIsRefusedOverPlainHTTP(t *testing.T) {
  180. ts := makeTestServer(t)
  181. res, err := http.Post(ts.URL+"/api/agents/pair/hello", "application/json",
  182. strings.NewReader(`{"nonce":"`+strings.Repeat("ab", 32)+`"}`))
  183. if err != nil {
  184. t.Fatal(err)
  185. }
  186. res.Body.Close()
  187. if res.StatusCode != http.StatusBadRequest {
  188. t.Fatalf("status = %d, want 400", res.StatusCode)
  189. }
  190. if _, err := agentruntime.ProveServerKey(ts.URL, testPairingToken); err == nil {
  191. t.Fatal("the agent tried to prove a key over plain http")
  192. }
  193. }
  194. // The whole bootstrap: an agent with a pairing token and no pin pairs with an
  195. // HTTPS server, and leaves an env file that pins the proven key next to its
  196. // new token.
  197. func TestAnAgentPairsOverHTTPSWithoutAPin(t *testing.T) {
  198. ps := newPairServer(t)
  199. env := t.TempDir() + "/netpulse-agent.env"
  200. if err := os.WriteFile(env, []byte("NETPULSE_SERVER="+ps.URL+"\nNETPULSE_SLUG=test-agent\n"+
  201. "NETPULSE_PAIRING_TOKEN="+testPairingToken+"\n"), 0o600); err != nil {
  202. t.Fatal(err)
  203. }
  204. err := agentruntime.Run(context.Background(), agentruntime.Options{
  205. Server: ps.URL, Slug: "test-agent", PairingToken: testPairingToken, EnvFile: env,
  206. })
  207. if err != nil {
  208. t.Fatalf("pairing: %v", err)
  209. }
  210. got, err := os.ReadFile(env)
  211. if err != nil {
  212. t.Fatal(err)
  213. }
  214. s := string(got)
  215. if !strings.Contains(s, "NETPULSE_SERVER_FP="+ps.fp+"\n") {
  216. t.Fatalf("the proven pin was not written:\n%s", s)
  217. }
  218. if !strings.Contains(s, "NETPULSE_TOKEN=") || strings.Contains(s, "NETPULSE_PAIRING_TOKEN") {
  219. t.Fatalf("the env was not switched to the agent token:\n%s", s)
  220. }
  221. }