http_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package http
  14. import (
  15. "bytes"
  16. "fmt"
  17. "net"
  18. "net/http"
  19. "net/http/httptest"
  20. "net/url"
  21. "os"
  22. "strconv"
  23. "strings"
  24. "testing"
  25. "time"
  26. "github.com/stretchr/testify/assert"
  27. "github.com/stretchr/testify/require"
  28. "k8s.io/apimachinery/pkg/util/wait"
  29. "k8s.io/kubernetes/pkg/probe"
  30. )
  31. const FailureCode int = -1
  32. func setEnv(key, value string) func() {
  33. originalValue := os.Getenv(key)
  34. os.Setenv(key, value)
  35. if len(originalValue) > 0 {
  36. return func() {
  37. os.Setenv(key, originalValue)
  38. }
  39. }
  40. return func() {}
  41. }
  42. func unsetEnv(key string) func() {
  43. originalValue := os.Getenv(key)
  44. os.Unsetenv(key)
  45. if len(originalValue) > 0 {
  46. return func() {
  47. os.Setenv(key, originalValue)
  48. }
  49. }
  50. return func() {}
  51. }
  52. func TestHTTPProbeProxy(t *testing.T) {
  53. res := "welcome to http probe proxy"
  54. localProxy := "http://127.0.0.1:9098/"
  55. defer setEnv("http_proxy", localProxy)()
  56. defer setEnv("HTTP_PROXY", localProxy)()
  57. defer unsetEnv("no_proxy")()
  58. defer unsetEnv("NO_PROXY")()
  59. followNonLocalRedirects := true
  60. prober := New(followNonLocalRedirects)
  61. go func() {
  62. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  63. fmt.Fprintf(w, res)
  64. })
  65. err := http.ListenAndServe(":9098", nil)
  66. if err != nil {
  67. t.Errorf("Failed to start foo server: localhost:9098")
  68. }
  69. }()
  70. // take some time to wait server boot
  71. time.Sleep(2 * time.Second)
  72. url, err := url.Parse("http://example.com")
  73. if err != nil {
  74. t.Errorf("proxy test unexpected error: %v", err)
  75. }
  76. _, response, _ := prober.Probe(url, http.Header{}, time.Second*3)
  77. if response == res {
  78. t.Errorf("proxy test unexpected error: the probe is using proxy")
  79. }
  80. }
  81. func TestHTTPProbeChecker(t *testing.T) {
  82. handleReq := func(s int, body string) func(w http.ResponseWriter, r *http.Request) {
  83. return func(w http.ResponseWriter, r *http.Request) {
  84. w.WriteHeader(s)
  85. w.Write([]byte(body))
  86. }
  87. }
  88. // Echo handler that returns the contents of request headers in the body
  89. headerEchoHandler := func(w http.ResponseWriter, r *http.Request) {
  90. w.WriteHeader(200)
  91. output := ""
  92. for k, arr := range r.Header {
  93. for _, v := range arr {
  94. output += fmt.Sprintf("%s: %s\n", k, v)
  95. }
  96. }
  97. w.Write([]byte(output))
  98. }
  99. redirectHandler := func(s int, bad bool) func(w http.ResponseWriter, r *http.Request) {
  100. return func(w http.ResponseWriter, r *http.Request) {
  101. if r.URL.Path == "/" {
  102. http.Redirect(w, r, "/new", s)
  103. } else if bad && r.URL.Path == "/new" {
  104. http.Error(w, "", http.StatusInternalServerError)
  105. }
  106. }
  107. }
  108. followNonLocalRedirects := true
  109. prober := New(followNonLocalRedirects)
  110. testCases := []struct {
  111. handler func(w http.ResponseWriter, r *http.Request)
  112. reqHeaders http.Header
  113. health probe.Result
  114. accBody string
  115. notBody string
  116. }{
  117. // The probe will be filled in below. This is primarily testing that an HTTP GET happens.
  118. {
  119. handler: handleReq(http.StatusOK, "ok body"),
  120. health: probe.Success,
  121. accBody: "ok body",
  122. },
  123. {
  124. handler: headerEchoHandler,
  125. reqHeaders: http.Header{
  126. "X-Muffins-Or-Cupcakes": {"muffins"},
  127. },
  128. health: probe.Success,
  129. accBody: "X-Muffins-Or-Cupcakes: muffins",
  130. },
  131. {
  132. handler: headerEchoHandler,
  133. reqHeaders: http.Header{
  134. "User-Agent": {"foo/1.0"},
  135. },
  136. health: probe.Success,
  137. accBody: "User-Agent: foo/1.0",
  138. },
  139. {
  140. handler: headerEchoHandler,
  141. reqHeaders: http.Header{
  142. "User-Agent": {""},
  143. },
  144. health: probe.Success,
  145. notBody: "User-Agent",
  146. },
  147. {
  148. handler: headerEchoHandler,
  149. reqHeaders: http.Header{},
  150. health: probe.Success,
  151. accBody: "User-Agent: kube-probe/",
  152. },
  153. {
  154. // Echo handler that returns the contents of Host in the body
  155. handler: func(w http.ResponseWriter, r *http.Request) {
  156. w.WriteHeader(200)
  157. w.Write([]byte(r.Host))
  158. },
  159. reqHeaders: http.Header{
  160. "Host": {"muffins.cupcakes.org"},
  161. },
  162. health: probe.Success,
  163. accBody: "muffins.cupcakes.org",
  164. },
  165. {
  166. handler: handleReq(FailureCode, "fail body"),
  167. health: probe.Failure,
  168. },
  169. {
  170. handler: handleReq(http.StatusInternalServerError, "fail body"),
  171. health: probe.Failure,
  172. },
  173. {
  174. handler: func(w http.ResponseWriter, r *http.Request) {
  175. time.Sleep(3 * time.Second)
  176. },
  177. health: probe.Failure,
  178. },
  179. {
  180. handler: redirectHandler(http.StatusMovedPermanently, false), // 301
  181. health: probe.Success,
  182. },
  183. {
  184. handler: redirectHandler(http.StatusMovedPermanently, true), // 301
  185. health: probe.Failure,
  186. },
  187. {
  188. handler: redirectHandler(http.StatusFound, false), // 302
  189. health: probe.Success,
  190. },
  191. {
  192. handler: redirectHandler(http.StatusFound, true), // 302
  193. health: probe.Failure,
  194. },
  195. {
  196. handler: redirectHandler(http.StatusTemporaryRedirect, false), // 307
  197. health: probe.Success,
  198. },
  199. {
  200. handler: redirectHandler(http.StatusTemporaryRedirect, true), // 307
  201. health: probe.Failure,
  202. },
  203. {
  204. handler: redirectHandler(http.StatusPermanentRedirect, false), // 308
  205. health: probe.Success,
  206. },
  207. {
  208. handler: redirectHandler(http.StatusPermanentRedirect, true), // 308
  209. health: probe.Failure,
  210. },
  211. }
  212. for i, test := range testCases {
  213. t.Run(fmt.Sprintf("case-%2d", i), func(t *testing.T) {
  214. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  215. test.handler(w, r)
  216. }))
  217. defer server.Close()
  218. u, err := url.Parse(server.URL)
  219. if err != nil {
  220. t.Errorf("case %d: unexpected error: %v", i, err)
  221. }
  222. _, port, err := net.SplitHostPort(u.Host)
  223. if err != nil {
  224. t.Errorf("case %d: unexpected error: %v", i, err)
  225. }
  226. _, err = strconv.Atoi(port)
  227. if err != nil {
  228. t.Errorf("case %d: unexpected error: %v", i, err)
  229. }
  230. health, output, err := prober.Probe(u, test.reqHeaders, 1*time.Second)
  231. if test.health == probe.Unknown && err == nil {
  232. t.Errorf("case %d: expected error", i)
  233. }
  234. if test.health != probe.Unknown && err != nil {
  235. t.Errorf("case %d: unexpected error: %v", i, err)
  236. }
  237. if health != test.health {
  238. t.Errorf("case %d: expected %v, got %v", i, test.health, health)
  239. }
  240. if health != probe.Failure && test.health != probe.Failure {
  241. if !strings.Contains(output, test.accBody) {
  242. t.Errorf("Expected response body to contain %v, got %v", test.accBody, output)
  243. }
  244. if test.notBody != "" && strings.Contains(output, test.notBody) {
  245. t.Errorf("Expected response not to contain %v, got %v", test.notBody, output)
  246. }
  247. }
  248. })
  249. }
  250. }
  251. func TestHTTPProbeChecker_NonLocalRedirects(t *testing.T) {
  252. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  253. switch r.URL.Path {
  254. case "/redirect":
  255. loc, _ := url.QueryUnescape(r.URL.Query().Get("loc"))
  256. http.Redirect(w, r, loc, http.StatusFound)
  257. case "/loop":
  258. http.Redirect(w, r, "/loop", http.StatusFound)
  259. case "/success":
  260. w.WriteHeader(http.StatusOK)
  261. default:
  262. http.Error(w, "", http.StatusInternalServerError)
  263. }
  264. })
  265. server := httptest.NewServer(handler)
  266. defer server.Close()
  267. newportServer := httptest.NewServer(handler)
  268. defer newportServer.Close()
  269. testCases := map[string]struct {
  270. redirect string
  271. expectLocalResult probe.Result
  272. expectNonLocalResult probe.Result
  273. }{
  274. "local success": {"/success", probe.Success, probe.Success},
  275. "local fail": {"/fail", probe.Failure, probe.Failure},
  276. "newport success": {newportServer.URL + "/success", probe.Success, probe.Success},
  277. "newport fail": {newportServer.URL + "/fail", probe.Failure, probe.Failure},
  278. "bogus nonlocal": {"http://0.0.0.0/fail", probe.Warning, probe.Failure},
  279. "redirect loop": {"/loop", probe.Failure, probe.Failure},
  280. }
  281. for desc, test := range testCases {
  282. t.Run(desc+"-local", func(t *testing.T) {
  283. followNonLocalRedirects := false
  284. prober := New(followNonLocalRedirects)
  285. target, err := url.Parse(server.URL + "/redirect?loc=" + url.QueryEscape(test.redirect))
  286. require.NoError(t, err)
  287. result, _, _ := prober.Probe(target, nil, wait.ForeverTestTimeout)
  288. assert.Equal(t, test.expectLocalResult, result)
  289. })
  290. t.Run(desc+"-nonlocal", func(t *testing.T) {
  291. followNonLocalRedirects := true
  292. prober := New(followNonLocalRedirects)
  293. target, err := url.Parse(server.URL + "/redirect?loc=" + url.QueryEscape(test.redirect))
  294. require.NoError(t, err)
  295. result, _, _ := prober.Probe(target, nil, wait.ForeverTestTimeout)
  296. assert.Equal(t, test.expectNonLocalResult, result)
  297. })
  298. }
  299. }
  300. func TestHTTPProbeChecker_HostHeaderPreservedAfterRedirect(t *testing.T) {
  301. successHostHeader := "www.success.com"
  302. failHostHeader := "www.fail.com"
  303. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  304. switch r.URL.Path {
  305. case "/redirect":
  306. http.Redirect(w, r, "/success", http.StatusFound)
  307. case "/success":
  308. if r.Host == successHostHeader {
  309. w.WriteHeader(http.StatusOK)
  310. } else {
  311. http.Error(w, "", http.StatusBadRequest)
  312. }
  313. default:
  314. http.Error(w, "", http.StatusInternalServerError)
  315. }
  316. })
  317. server := httptest.NewServer(handler)
  318. defer server.Close()
  319. testCases := map[string]struct {
  320. hostHeader string
  321. expectedResult probe.Result
  322. }{
  323. "success": {successHostHeader, probe.Success},
  324. "fail": {failHostHeader, probe.Failure},
  325. }
  326. for desc, test := range testCases {
  327. headers := http.Header{}
  328. headers.Add("Host", test.hostHeader)
  329. t.Run(desc+"local", func(t *testing.T) {
  330. followNonLocalRedirects := false
  331. prober := New(followNonLocalRedirects)
  332. target, err := url.Parse(server.URL + "/redirect")
  333. require.NoError(t, err)
  334. result, _, _ := prober.Probe(target, headers, wait.ForeverTestTimeout)
  335. assert.Equal(t, test.expectedResult, result)
  336. })
  337. t.Run(desc+"nonlocal", func(t *testing.T) {
  338. followNonLocalRedirects := true
  339. prober := New(followNonLocalRedirects)
  340. target, err := url.Parse(server.URL + "/redirect")
  341. require.NoError(t, err)
  342. result, _, _ := prober.Probe(target, headers, wait.ForeverTestTimeout)
  343. assert.Equal(t, test.expectedResult, result)
  344. })
  345. }
  346. }
  347. func TestHTTPProbeChecker_PayloadTruncated(t *testing.T) {
  348. successHostHeader := "www.success.com"
  349. oversizePayload := bytes.Repeat([]byte("a"), maxRespBodyLength+1)
  350. truncatedPayload := bytes.Repeat([]byte("a"), maxRespBodyLength)
  351. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  352. switch r.URL.Path {
  353. case "/success":
  354. if r.Host == successHostHeader {
  355. w.WriteHeader(http.StatusOK)
  356. w.Write(oversizePayload)
  357. } else {
  358. http.Error(w, "", http.StatusBadRequest)
  359. }
  360. default:
  361. http.Error(w, "", http.StatusInternalServerError)
  362. }
  363. })
  364. server := httptest.NewServer(handler)
  365. defer server.Close()
  366. headers := http.Header{}
  367. headers.Add("Host", successHostHeader)
  368. t.Run("truncated payload", func(t *testing.T) {
  369. prober := New(false)
  370. target, err := url.Parse(server.URL + "/success")
  371. require.NoError(t, err)
  372. result, body, err := prober.Probe(target, headers, wait.ForeverTestTimeout)
  373. assert.NoError(t, err)
  374. assert.Equal(t, result, probe.Success)
  375. assert.Equal(t, body, string(truncatedPayload))
  376. })
  377. }
  378. func TestHTTPProbeChecker_PayloadNormal(t *testing.T) {
  379. successHostHeader := "www.success.com"
  380. normalPayload := bytes.Repeat([]byte("a"), maxRespBodyLength-1)
  381. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  382. switch r.URL.Path {
  383. case "/success":
  384. if r.Host == successHostHeader {
  385. w.WriteHeader(http.StatusOK)
  386. w.Write(normalPayload)
  387. } else {
  388. http.Error(w, "", http.StatusBadRequest)
  389. }
  390. default:
  391. http.Error(w, "", http.StatusInternalServerError)
  392. }
  393. })
  394. server := httptest.NewServer(handler)
  395. defer server.Close()
  396. headers := http.Header{}
  397. headers.Add("Host", successHostHeader)
  398. t.Run("normal payload", func(t *testing.T) {
  399. prober := New(false)
  400. target, err := url.Parse(server.URL + "/success")
  401. require.NoError(t, err)
  402. result, body, err := prober.Probe(target, headers, wait.ForeverTestTimeout)
  403. assert.NoError(t, err)
  404. assert.Equal(t, result, probe.Success)
  405. assert.Equal(t, body, string(normalPayload))
  406. })
  407. }