https_settings_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package httpapi_test
  2. // FORK: tests for Settings > HTTPS (https_settings.go). Addresses are from
  3. // the private and documentation ranges, names invented.
  4. import (
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "encoding/hex"
  10. "encoding/json"
  11. "fmt"
  12. "io"
  13. "net"
  14. "net/http"
  15. "net/http/httptest"
  16. "os"
  17. "os/exec"
  18. "strings"
  19. "testing"
  20. "time"
  21. "github.com/gnacho/netpulse/server-go/internal/adapters"
  22. "github.com/gnacho/netpulse/server-go/internal/auth"
  23. "github.com/gnacho/netpulse/server-go/internal/config"
  24. "github.com/gnacho/netpulse/server-go/internal/db"
  25. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  26. "github.com/gnacho/netpulse/server-go/internal/sse"
  27. "github.com/gnacho/netpulse/server-go/internal/tlscert"
  28. "github.com/gnacho/netpulse/server-go/internal/tlsmode"
  29. )
  30. func makeHTTPSTestServer(t *testing.T) (*agentTestServer, *tlsmode.Manager) {
  31. t.Helper()
  32. auth.SetTrustProxy(true)
  33. t.Cleanup(func() { auth.SetTrustProxy(false) })
  34. dataDir := t.TempDir()
  35. cfg, err := config.Load(map[string]string{
  36. "AUTH_USER": "admin", "AUTH_PASS": "test123456",
  37. "DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
  38. }, dataDir)
  39. if err != nil {
  40. t.Fatal(err)
  41. }
  42. d, err := db.Open(dataDir)
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. secret, err := auth.EnsureSessionSecret(d, cfg)
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. if err := auth.EnsureUsers(d, cfg); err != nil {
  51. t.Fatal(err)
  52. }
  53. ln, _ := net.Listen("tcp", "127.0.0.1:0")
  54. port := ln.Addr().(*net.TCPAddr).Port
  55. ln.Close()
  56. mgr := tlsmode.New(tlsmode.Options{
  57. DB: d, DataDir: dataDir, Port: port,
  58. NewServer: func(addr string, h http.Handler) *http.Server { return &http.Server{Addr: addr, Handler: h} },
  59. CAOptions: func(o tlscert.CAOptions) tlscert.CAOptions {
  60. o.Addrs = func() ([]net.IP, error) { return []net.IP{net.ParseIP("192.168.50.2")}, nil }
  61. o.Hostname = func() (string, error) { return "monitor-box", nil }
  62. o.SearchDomains = func() []string { return nil }
  63. return o
  64. },
  65. })
  66. reg := adapters.NewAgentRegistry(90 * time.Second)
  67. handler := httpapi.NewHandler(httpapi.Deps{
  68. Config: cfg, DB: d, Adapter: adapters.NewDemo(), Secret: secret,
  69. Hub: sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
  70. Agents: reg, Started: time.Now(), TLS: mgr,
  71. ServerFPFunc: mgr.Fingerprint,
  72. })
  73. if err := mgr.Start(handler); err != nil {
  74. t.Fatal(err)
  75. }
  76. srv := httptest.NewServer(mgr.PlainHandler(handler))
  77. status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
  78. if status != 204 {
  79. t.Fatalf("login: %d", status)
  80. }
  81. t.Cleanup(func() {
  82. mgr.Close()
  83. srv.Close()
  84. d.Close()
  85. })
  86. return &agentTestServer{Server: srv, db: d, agents: reg, cookie: cookie}, mgr
  87. }
  88. // httpsCall makes an admin request; secure marks it as having arrived over
  89. // HTTPS through a proxy the server trusts.
  90. func httpsCall(t *testing.T, ts *agentTestServer, method, path, body string, secure bool) (int, map[string]any) {
  91. t.Helper()
  92. req, _ := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
  93. req.Header.Set("Content-Type", "application/json")
  94. req.Header.Set("Cookie", "session="+ts.cookie)
  95. if secure {
  96. req.Header.Set("X-Forwarded-Proto", "https")
  97. }
  98. res, err := http.DefaultClient.Do(req)
  99. if err != nil {
  100. t.Fatal(err)
  101. }
  102. defer res.Body.Close()
  103. var out map[string]any
  104. data, _ := io.ReadAll(res.Body)
  105. _ = json.Unmarshal(data, &out)
  106. return res.StatusCode, out
  107. }
  108. func TestEveryHTTPSChangeAsksForThePassword(t *testing.T) {
  109. ts, mgr := makeHTTPSTestServer(t)
  110. for _, pw := range []string{"", "not-the-password"} {
  111. if st, _ := httpsCall(t, ts, "POST", "/api/settings/https",
  112. fmt.Sprintf(`{"enabled":true,"password":%q}`, pw), true); st != http.StatusUnauthorized {
  113. t.Fatalf("password %q: status %d, want 401", pw, st)
  114. }
  115. }
  116. if mgr.Enabled() {
  117. t.Fatal("HTTPS was turned on without the password")
  118. }
  119. st, body := httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":true,"password":"test123456"}`, true)
  120. if st != http.StatusOK || !mgr.Enabled() {
  121. t.Fatalf("enable: %d %v", st, body)
  122. }
  123. _, status := httpsCall(t, ts, "GET", "/api/settings/https", "", true)
  124. if status["rootSha256"] == "" || status["fingerprint"] == "" || status["mode"] != "full" {
  125. t.Fatalf("status: %v", status)
  126. }
  127. }
  128. func TestTheRootIsServedToAnyone(t *testing.T) {
  129. ts, mgr := makeHTTPSTestServer(t)
  130. res, _ := http.Get(ts.URL + "/netpulse-ca.crt")
  131. res.Body.Close()
  132. if res.StatusCode != http.StatusNotFound {
  133. t.Fatalf("with HTTPS off: %d, want 404", res.StatusCode)
  134. }
  135. if err := mgr.SetEnabled(true, "test"); err != nil {
  136. t.Fatal(err)
  137. }
  138. res, err := http.Get(ts.URL + "/netpulse-ca.crt") // no session
  139. if err != nil {
  140. t.Fatal(err)
  141. }
  142. der, _ := io.ReadAll(res.Body)
  143. res.Body.Close()
  144. if res.Header.Get("Content-Type") != "application/x-x509-ca-cert" {
  145. t.Fatalf("content type %q", res.Header.Get("Content-Type"))
  146. }
  147. root, err := x509.ParseCertificate(der)
  148. if err != nil || !root.IsCA || tlscert.Fingerprint(root) != mgr.Fingerprint() {
  149. t.Fatalf("served root is not the CA agents pin: %v", err)
  150. }
  151. }
  152. func TestAStricterModeIsConfirmedOverHTTPSOnly(t *testing.T) {
  153. ts, mgr := makeHTTPSTestServer(t)
  154. _ = mgr.SetEnabled(true, "test")
  155. st, body := httpsCall(t, ts, "POST", "/api/settings/https", `{"mode":"migrate","password":"test123456"}`, false)
  156. if st != http.StatusOK || body["pending"] != "migrate" || mgr.Mode() != tlsmode.Full {
  157. t.Fatalf("request: %d %v, mode %s", st, body, mgr.Mode())
  158. }
  159. confirmURL, _ := body["confirmUrl"].(string)
  160. if !strings.HasPrefix(confirmURL, "https://") || !strings.Contains(confirmURL, "confirm=") {
  161. t.Fatalf("confirmUrl %q", confirmURL)
  162. }
  163. code := confirmURL[strings.Index(confirmURL, "confirm=")+len("confirm="):]
  164. if i := strings.IndexByte(code, '&'); i >= 0 {
  165. code = code[:i]
  166. }
  167. // Over plain HTTP the confirmation is refused - and in fact the request
  168. // is already refused as a session call, even before the mode applies.
  169. if st, _ := httpsCall(t, ts, "POST", "/api/settings/https/confirm", fmt.Sprintf(`{"code":%q}`, code), false); st == http.StatusOK {
  170. t.Fatal("confirmed over plain HTTP")
  171. }
  172. if st, body := httpsCall(t, ts, "POST", "/api/settings/https/confirm", fmt.Sprintf(`{"code":%q}`, code), true); st != http.StatusOK || mgr.Mode() != tlsmode.Migrate {
  173. t.Fatalf("confirm over HTTPS: %d %v, mode %s", st, body, mgr.Mode())
  174. }
  175. // Now plain HTTP refuses the session call outright.
  176. if st, _ := httpsCall(t, ts, "GET", "/api/settings/https", "", false); st != http.StatusForbidden {
  177. t.Fatalf("a session call over plain HTTP in migrate: %d, want 403", st)
  178. }
  179. }
  180. // Redirect would cut off agents still on plain HTTP; the page says which, and
  181. // only an explicit force goes ahead.
  182. func TestRedirectWaitsForAgentsOnHTTP(t *testing.T) {
  183. ts, mgr := makeHTTPSTestServer(t)
  184. _ = mgr.SetEnabled(true, "test")
  185. _, token, _ := createAgentToken(t, ts, "test-router")
  186. res := ingest(t, ts, token, "192.0.2.50", validPayloadFor("test-router"))
  187. res.Body.Close()
  188. if res.StatusCode != http.StatusAccepted {
  189. t.Fatalf("ingest: %d", res.StatusCode)
  190. }
  191. st, body := httpsCall(t, ts, "POST", "/api/settings/https", `{"mode":"redirect","password":"test123456"}`, true)
  192. if st != http.StatusConflict || body["error"] != "agents_on_http" || !strings.Contains(fmt.Sprint(body["agents"]), "test-router") {
  193. t.Fatalf("redirect with an agent on HTTP: %d %v", st, body)
  194. }
  195. st, body = httpsCall(t, ts, "POST", "/api/settings/https", `{"mode":"redirect","force":true,"password":"test123456"}`, true)
  196. if st != http.StatusOK || body["pending"] != "redirect" {
  197. t.Fatalf("forced: %d %v", st, body)
  198. }
  199. }
  200. func validPayloadFor(slug string) string {
  201. return fmt.Sprintf(`{"router":%q,"ts":%d,"version":"test","data":{}}`, slug, time.Now().Unix())
  202. }
  203. // The confirmation arrives over the real HTTPS listener - the one it is
  204. // meant to prove works - and applies the mode.
  205. func TestAModeIsConfirmedThroughTheRealHTTPSListener(t *testing.T) {
  206. ts, mgr := makeHTTPSTestServer(t)
  207. if err := mgr.SetEnabled(true, "test"); err != nil {
  208. t.Fatal(err)
  209. }
  210. code, _, err := mgr.RequestMode(tlsmode.Migrate, "test")
  211. if err != nil {
  212. t.Fatal(err)
  213. }
  214. pool := x509.NewCertPool()
  215. pool.AppendCertsFromPEM(mgr.CA().RootPEM())
  216. client := &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{
  217. TLSClientConfig: &tls.Config{RootCAs: pool},
  218. }}
  219. url := fmt.Sprintf("https://127.0.0.1:%d/api/settings/https/confirm", mgr.Status().Port)
  220. var res *http.Response
  221. for i := 0; i < 50; i++ { // the listener starts in a goroutine
  222. req, _ := http.NewRequest("POST", url, strings.NewReader(fmt.Sprintf(`{"code":%q}`, code)))
  223. req.Header.Set("Content-Type", "application/json")
  224. req.Header.Set("Cookie", "session="+ts.cookie)
  225. if res, err = client.Do(req); err == nil {
  226. break
  227. }
  228. time.Sleep(20 * time.Millisecond)
  229. }
  230. if err != nil {
  231. t.Fatal(err)
  232. }
  233. res.Body.Close()
  234. if res.StatusCode != http.StatusOK || mgr.Mode() != tlsmode.Migrate {
  235. t.Fatalf("confirm over the HTTPS listener: %d, mode %s", res.StatusCode, mgr.Mode())
  236. }
  237. }
  238. // Agents already on HTTPS would be cut off by turning it off; the page says
  239. // which, and only an explicit force goes ahead. Turning it off in a stricter
  240. // mode is refused outright.
  241. func TestTurningHTTPSOffWarnsAboutAgentsOnIt(t *testing.T) {
  242. ts, mgr := makeHTTPSTestServer(t)
  243. _ = mgr.SetEnabled(true, "test")
  244. _, token, _ := createAgentToken(t, ts, "test-router")
  245. req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(validPayloadFor("test-router")))
  246. res := ingestSecure(t, req, token)
  247. if res.StatusCode != http.StatusAccepted {
  248. t.Fatalf("ingest over https: %d", res.StatusCode)
  249. }
  250. st, body := httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":false,"password":"test123456"}`, true)
  251. if st != http.StatusConflict || body["error"] != "agents_on_https" {
  252. t.Fatalf("turning off with an agent on HTTPS: %d %v", st, body)
  253. }
  254. code, _, _ := mgr.RequestMode(tlsmode.Migrate, "test")
  255. _, _ = mgr.Confirm(code, true, "test")
  256. st, body = httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":false,"force":true,"password":"test123456"}`, true)
  257. if st != http.StatusConflict || body["error"] != "not_full" {
  258. t.Fatalf("turning off in migrate: %d %v", st, body)
  259. }
  260. _, _, _ = mgr.RequestMode(tlsmode.Full, "test")
  261. st, _ = httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":false,"force":true,"password":"test123456"}`, true)
  262. if st != http.StatusOK || mgr.Enabled() {
  263. t.Fatalf("forced off from full: %d, enabled %v", st, mgr.Enabled())
  264. }
  265. }
  266. // ingestSecure pushes as an agent would through a trusted TLS proxy.
  267. func ingestSecure(t *testing.T, req *http.Request, token string) *http.Response {
  268. t.Helper()
  269. body, _ := io.ReadAll(req.Body)
  270. req.Body = io.NopCloser(strings.NewReader(string(body)))
  271. req.Header.Set("Content-Type", "application/json")
  272. req.Header.Set("X-Forwarded-Proto", "https")
  273. req.Header.Set("X-Forwarded-For", "192.0.2.51")
  274. req.Header.Set("Authorization", "Bearer "+token)
  275. mac := hmac.New(sha256.New, []byte(token))
  276. mac.Write(body)
  277. req.Header.Set("X-Agent-Signature", hex.EncodeToString(mac.Sum(nil)))
  278. res, err := http.DefaultClient.Do(req)
  279. if err != nil {
  280. t.Fatal(err)
  281. }
  282. res.Body.Close()
  283. return res
  284. }
  285. // In migrate, the admin pairing token is refused over plain HTTP, and
  286. // accepted over HTTPS.
  287. func TestMigrateRefusesThePairingTokenOverPlainHTTP(t *testing.T) {
  288. ts, mgr := makeHTTPSTestServer(t)
  289. _ = mgr.SetEnabled(true, "test")
  290. code, _, _ := mgr.RequestMode(tlsmode.Migrate, "test")
  291. _, _ = mgr.Confirm(code, true, "test")
  292. var tok string
  293. if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'pairing.token'").Scan(&tok); err != nil {
  294. // Created on first use.
  295. tok = "11111111-2222-4333-8444-555555555555"
  296. if _, err := ts.db.Exec("INSERT INTO kv (key, value) VALUES ('pairing.token', ?)", tok); err != nil {
  297. t.Fatal(err)
  298. }
  299. }
  300. pair := func(secure bool) int {
  301. req, _ := http.NewRequest("POST", ts.URL+"/api/agents/pair",
  302. strings.NewReader(fmt.Sprintf(`{"pairing_token":%q,"slug":"new-router"}`, tok)))
  303. req.Header.Set("Content-Type", "application/json")
  304. if secure {
  305. req.Header.Set("X-Forwarded-Proto", "https")
  306. }
  307. res, err := http.DefaultClient.Do(req)
  308. if err != nil {
  309. t.Fatal(err)
  310. }
  311. res.Body.Close()
  312. return res.StatusCode
  313. }
  314. if st := pair(false); st != http.StatusForbidden {
  315. t.Fatalf("over plain HTTP: %d, want 403", st)
  316. }
  317. if st := pair(true); st != http.StatusCreated {
  318. t.Fatalf("over HTTPS: %d, want 201", st)
  319. }
  320. }
  321. // Wrong passwords here count towards the sign-in lockout.
  322. func TestThePasswordCheckIsRateLimited(t *testing.T) {
  323. ts, _ := makeHTTPSTestServer(t)
  324. last := 0
  325. for i := 0; i < 6; i++ {
  326. last, _ = httpsCall(t, ts, "POST", "/api/settings/https", `{"enabled":true,"password":"wrong"}`, true)
  327. }
  328. if last != http.StatusTooManyRequests {
  329. t.Fatalf("after six wrong passwords: %d, want 429", last)
  330. }
  331. }
  332. // A sign-in over HTTPS gets its own Secure cookie, so it does not replace -
  333. // and cannot lock out - a sign-in over plain HTTP on the same host.
  334. func TestHTTPSAndHTTPSignInsKeepTheirOwnCookies(t *testing.T) {
  335. ts, _ := makeHTTPSTestServer(t)
  336. _, _, plainSet := loginCookie(t, ts.URL, "admin", "test123456")
  337. if !strings.HasPrefix(plainSet, "session=") || strings.Contains(plainSet, "Secure") {
  338. t.Fatalf("plain sign-in: %q", plainSet)
  339. }
  340. _, _, secureSet := loginCookie(t, ts.URL, "admin", "test123456", "X-Forwarded-Proto", "https")
  341. if !strings.HasPrefix(secureSet, "__Host-session=") || !strings.Contains(secureSet, "; Secure") {
  342. t.Fatalf("secure sign-in: %q", secureSet)
  343. }
  344. secureVal := strings.SplitN(strings.TrimPrefix(secureSet, "__Host-session="), ";", 2)[0]
  345. // Both cookies at once, as a browser sends them over HTTPS.
  346. req, _ := http.NewRequest("GET", ts.URL+"/api/auth/me", nil)
  347. req.Header.Set("Cookie", "session=stale.value; __Host-session="+secureVal)
  348. req.Header.Set("X-Forwarded-Proto", "https")
  349. res, err := http.DefaultClient.Do(req)
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. res.Body.Close()
  354. if res.StatusCode != http.StatusOK {
  355. t.Fatalf("the Secure session was not accepted: %d", res.StatusCode)
  356. }
  357. // Signing out over HTTPS clears both, and ends the session.
  358. req, _ = http.NewRequest("POST", ts.URL+"/api/auth/logout", nil)
  359. req.Header.Set("Cookie", "__Host-session="+secureVal)
  360. req.Header.Set("X-Forwarded-Proto", "https")
  361. res, err = http.DefaultClient.Do(req)
  362. if err != nil {
  363. t.Fatal(err)
  364. }
  365. res.Body.Close()
  366. cleared := strings.Join(res.Header.Values("Set-Cookie"), " | ")
  367. if !strings.Contains(cleared, "session=; Path=/") || !strings.Contains(cleared, "__Host-session=; Path=/; HttpOnly; Secure") {
  368. t.Fatalf("logout cleared: %s", cleared)
  369. }
  370. req, _ = http.NewRequest("GET", ts.URL+"/api/auth/me", nil)
  371. req.Header.Set("Cookie", "__Host-session="+secureVal)
  372. req.Header.Set("X-Forwarded-Proto", "https")
  373. res, _ = http.DefaultClient.Do(req)
  374. res.Body.Close()
  375. if res.StatusCode != http.StatusUnauthorized {
  376. t.Fatalf("the session outlived logout: %d", res.StatusCode)
  377. }
  378. }
  379. // The install line carries the root and the pin once HTTPS is on, and the
  380. // printf that writes the root reproduces it exactly.
  381. func TestTheInstallLineCarriesTheRoot(t *testing.T) {
  382. ts, mgr := makeHTTPSTestServer(t)
  383. _, _, before := createAgentToken(t, ts, "test-router")
  384. if strings.Contains(before, "NPCA") || strings.Contains(before, "--server-fp") {
  385. t.Fatalf("with HTTPS off the line changed: %s", before)
  386. }
  387. if err := mgr.SetEnabled(true, "test"); err != nil {
  388. t.Fatal(err)
  389. }
  390. _, _, line := createAgentToken(t, ts, "test-router-2")
  391. wantServer := fmt.Sprintf("--server=https://192.168.50.2:%d", mgr.Status().Port)
  392. for _, want := range []string{`--cacert "$NPCA"`, "NPCA=$(mktemp)", "--server-fp=" + mgr.Fingerprint(), wantServer} {
  393. if !strings.Contains(line, want) {
  394. t.Fatalf("install line lacks %q:\n%s", want, line)
  395. }
  396. }
  397. dir := t.TempDir()
  398. // Up to the download: create the file, write the root, show where.
  399. upTo := line[:strings.Index(line, " && curl")]
  400. upTo = strings.Replace(upTo, "$(mktemp)", dir+"/ca.pem", 1)
  401. if out, err := exec.Command("sh", "-c", upTo).CombinedOutput(); err != nil {
  402. t.Fatalf("%v: %s", err, out)
  403. }
  404. got, _ := os.ReadFile(dir + "/ca.pem")
  405. if string(got) != string(mgr.CA().RootPEM()) {
  406. t.Fatalf("the line writes:\n%s\nwant:\n%s", got, mgr.CA().RootPEM())
  407. }
  408. }
  409. // With no agent reporting, the list is empty, never null: the page reads its
  410. // length, and a null took the whole Settings page down.
  411. func TestTheAgentListIsNeverNull(t *testing.T) {
  412. ts, mgr := makeHTTPSTestServer(t)
  413. _ = mgr.SetEnabled(true, "test")
  414. req, _ := http.NewRequest("GET", ts.URL+"/api/settings/https", nil)
  415. req.Header.Set("Cookie", "session="+ts.cookie)
  416. res, err := http.DefaultClient.Do(req)
  417. if err != nil {
  418. t.Fatal(err)
  419. }
  420. body, _ := io.ReadAll(res.Body)
  421. res.Body.Close()
  422. if !strings.Contains(string(body), `"agentsOnHttp":[]`) {
  423. t.Fatalf("status: %s", body)
  424. }
  425. }