https_settings_test.go 19 KB

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