http_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. "fmt"
  16. "net"
  17. "net/http"
  18. "net/http/httptest"
  19. "net/url"
  20. "os"
  21. "strconv"
  22. "strings"
  23. "testing"
  24. "time"
  25. "github.com/stretchr/testify/assert"
  26. "github.com/stretchr/testify/require"
  27. "k8s.io/apimachinery/pkg/util/wait"
  28. "k8s.io/kubernetes/pkg/probe"
  29. )
  30. const FailureCode int = -1
  31. func setEnv(key, value string) func() {
  32. originalValue := os.Getenv(key)
  33. os.Setenv(key, value)
  34. if len(originalValue) > 0 {
  35. return func() {
  36. os.Setenv(key, originalValue)
  37. }
  38. }
  39. return func() {}
  40. }
  41. func unsetEnv(key string) func() {
  42. originalValue := os.Getenv(key)
  43. os.Unsetenv(key)
  44. if len(originalValue) > 0 {
  45. return func() {
  46. os.Setenv(key, originalValue)
  47. }
  48. }
  49. return func() {}
  50. }
  51. func TestHTTPProbeProxy(t *testing.T) {
  52. res := "welcome to http probe proxy"
  53. localProxy := "http://127.0.0.1:9098/"
  54. defer setEnv("http_proxy", localProxy)()
  55. defer setEnv("HTTP_PROXY", localProxy)()
  56. defer unsetEnv("no_proxy")()
  57. defer unsetEnv("NO_PROXY")()
  58. prober := New(true)
  59. go func() {
  60. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  61. fmt.Fprintf(w, res)
  62. })
  63. err := http.ListenAndServe(":9098", nil)
  64. if err != nil {
  65. t.Errorf("Failed to start foo server: localhost:9098")
  66. }
  67. }()
  68. // take some time to wait server boot
  69. time.Sleep(2 * time.Second)
  70. url, err := url.Parse("http://example.com")
  71. if err != nil {
  72. t.Errorf("proxy test unexpected error: %v", err)
  73. }
  74. _, response, _ := prober.Probe(url, http.Header{}, time.Second*3)
  75. if response == res {
  76. t.Errorf("proxy test unexpected error: the probe is using proxy")
  77. }
  78. }
  79. func TestHTTPProbeChecker(t *testing.T) {
  80. handleReq := func(s int, body string) func(w http.ResponseWriter, r *http.Request) {
  81. return func(w http.ResponseWriter, r *http.Request) {
  82. w.WriteHeader(s)
  83. w.Write([]byte(body))
  84. }
  85. }
  86. // Echo handler that returns the contents of request headers in the body
  87. headerEchoHandler := func(w http.ResponseWriter, r *http.Request) {
  88. w.WriteHeader(200)
  89. output := ""
  90. for k, arr := range r.Header {
  91. for _, v := range arr {
  92. output += fmt.Sprintf("%s: %s\n", k, v)
  93. }
  94. }
  95. w.Write([]byte(output))
  96. }
  97. redirectHandler := func(s int, bad bool) func(w http.ResponseWriter, r *http.Request) {
  98. return func(w http.ResponseWriter, r *http.Request) {
  99. if r.URL.Path == "/" {
  100. http.Redirect(w, r, "/new", s)
  101. } else if bad && r.URL.Path == "/new" {
  102. http.Error(w, "", http.StatusInternalServerError)
  103. }
  104. }
  105. }
  106. prober := New(true)
  107. testCases := []struct {
  108. handler func(w http.ResponseWriter, r *http.Request)
  109. reqHeaders http.Header
  110. health probe.Result
  111. accBody string
  112. notBody string
  113. }{
  114. // The probe will be filled in below. This is primarily testing that an HTTP GET happens.
  115. {
  116. handler: handleReq(http.StatusOK, "ok body"),
  117. health: probe.Success,
  118. accBody: "ok body",
  119. },
  120. {
  121. handler: headerEchoHandler,
  122. reqHeaders: http.Header{
  123. "X-Muffins-Or-Cupcakes": {"muffins"},
  124. },
  125. health: probe.Success,
  126. accBody: "X-Muffins-Or-Cupcakes: muffins",
  127. },
  128. {
  129. handler: headerEchoHandler,
  130. reqHeaders: http.Header{
  131. "User-Agent": {"foo/1.0"},
  132. },
  133. health: probe.Success,
  134. accBody: "User-Agent: foo/1.0",
  135. },
  136. {
  137. handler: headerEchoHandler,
  138. reqHeaders: http.Header{
  139. "User-Agent": {""},
  140. },
  141. health: probe.Success,
  142. notBody: "User-Agent",
  143. },
  144. {
  145. handler: headerEchoHandler,
  146. reqHeaders: http.Header{},
  147. health: probe.Success,
  148. accBody: "User-Agent: kube-probe/",
  149. },
  150. {
  151. // Echo handler that returns the contents of Host in the body
  152. handler: func(w http.ResponseWriter, r *http.Request) {
  153. w.WriteHeader(200)
  154. w.Write([]byte(r.Host))
  155. },
  156. reqHeaders: http.Header{
  157. "Host": {"muffins.cupcakes.org"},
  158. },
  159. health: probe.Success,
  160. accBody: "muffins.cupcakes.org",
  161. },
  162. {
  163. handler: handleReq(FailureCode, "fail body"),
  164. health: probe.Failure,
  165. },
  166. {
  167. handler: handleReq(http.StatusInternalServerError, "fail body"),
  168. health: probe.Failure,
  169. },
  170. {
  171. handler: func(w http.ResponseWriter, r *http.Request) {
  172. time.Sleep(3 * time.Second)
  173. },
  174. health: probe.Failure,
  175. },
  176. {
  177. handler: redirectHandler(http.StatusMovedPermanently, false), // 301
  178. health: probe.Success,
  179. },
  180. {
  181. handler: redirectHandler(http.StatusMovedPermanently, true), // 301
  182. health: probe.Failure,
  183. },
  184. {
  185. handler: redirectHandler(http.StatusFound, false), // 302
  186. health: probe.Success,
  187. },
  188. {
  189. handler: redirectHandler(http.StatusFound, true), // 302
  190. health: probe.Failure,
  191. },
  192. {
  193. handler: redirectHandler(http.StatusTemporaryRedirect, false), // 307
  194. health: probe.Success,
  195. },
  196. {
  197. handler: redirectHandler(http.StatusTemporaryRedirect, true), // 307
  198. health: probe.Failure,
  199. },
  200. {
  201. handler: redirectHandler(http.StatusPermanentRedirect, false), // 308
  202. health: probe.Success,
  203. },
  204. {
  205. handler: redirectHandler(http.StatusPermanentRedirect, true), // 308
  206. health: probe.Failure,
  207. },
  208. }
  209. for i, test := range testCases {
  210. t.Run(fmt.Sprintf("case-%2d", i), func(t *testing.T) {
  211. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  212. test.handler(w, r)
  213. }))
  214. defer server.Close()
  215. u, err := url.Parse(server.URL)
  216. if err != nil {
  217. t.Errorf("case %d: unexpected error: %v", i, err)
  218. }
  219. _, port, err := net.SplitHostPort(u.Host)
  220. if err != nil {
  221. t.Errorf("case %d: unexpected error: %v", i, err)
  222. }
  223. _, err = strconv.Atoi(port)
  224. if err != nil {
  225. t.Errorf("case %d: unexpected error: %v", i, err)
  226. }
  227. health, output, err := prober.Probe(u, test.reqHeaders, 1*time.Second)
  228. if test.health == probe.Unknown && err == nil {
  229. t.Errorf("case %d: expected error", i)
  230. }
  231. if test.health != probe.Unknown && err != nil {
  232. t.Errorf("case %d: unexpected error: %v", i, err)
  233. }
  234. if health != test.health {
  235. t.Errorf("case %d: expected %v, got %v", i, test.health, health)
  236. }
  237. if health != probe.Failure && test.health != probe.Failure {
  238. if !strings.Contains(output, test.accBody) {
  239. t.Errorf("Expected response body to contain %v, got %v", test.accBody, output)
  240. }
  241. if test.notBody != "" && strings.Contains(output, test.notBody) {
  242. t.Errorf("Expected response not to contain %v, got %v", test.notBody, output)
  243. }
  244. }
  245. })
  246. }
  247. }
  248. func TestHTTPProbeChecker_NonLocalRedirects(t *testing.T) {
  249. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  250. switch r.URL.Path {
  251. case "/redirect":
  252. loc, _ := url.QueryUnescape(r.URL.Query().Get("loc"))
  253. http.Redirect(w, r, loc, http.StatusFound)
  254. case "/loop":
  255. http.Redirect(w, r, "/loop", http.StatusFound)
  256. case "/success":
  257. w.WriteHeader(http.StatusOK)
  258. default:
  259. http.Error(w, "", http.StatusInternalServerError)
  260. }
  261. })
  262. server := httptest.NewServer(handler)
  263. defer server.Close()
  264. newportServer := httptest.NewServer(handler)
  265. defer newportServer.Close()
  266. testCases := map[string]struct {
  267. redirect string
  268. expectLocalResult probe.Result
  269. expectNonLocalResult probe.Result
  270. }{
  271. "local success": {"/success", probe.Success, probe.Success},
  272. "local fail": {"/fail", probe.Failure, probe.Failure},
  273. "newport success": {newportServer.URL + "/success", probe.Success, probe.Success},
  274. "newport fail": {newportServer.URL + "/fail", probe.Failure, probe.Failure},
  275. "bogus nonlocal": {"http://0.0.0.0/fail", probe.Warning, probe.Failure},
  276. "redirect loop": {"/loop", probe.Failure, probe.Failure},
  277. }
  278. for desc, test := range testCases {
  279. t.Run(desc+"-local", func(t *testing.T) {
  280. prober := New(false)
  281. target, err := url.Parse(server.URL + "/redirect?loc=" + url.QueryEscape(test.redirect))
  282. require.NoError(t, err)
  283. result, _, _ := prober.Probe(target, nil, wait.ForeverTestTimeout)
  284. assert.Equal(t, test.expectLocalResult, result)
  285. })
  286. t.Run(desc+"-nonlocal", func(t *testing.T) {
  287. prober := New(true)
  288. target, err := url.Parse(server.URL + "/redirect?loc=" + url.QueryEscape(test.redirect))
  289. require.NoError(t, err)
  290. result, _, _ := prober.Probe(target, nil, wait.ForeverTestTimeout)
  291. assert.Equal(t, test.expectNonLocalResult, result)
  292. })
  293. }
  294. }
  295. func TestHTTPProbeChecker_HostHeaderPreservedAfterRedirect(t *testing.T) {
  296. successHostHeader := "www.success.com"
  297. failHostHeader := "www.fail.com"
  298. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  299. switch r.URL.Path {
  300. case "/redirect":
  301. http.Redirect(w, r, "/success", http.StatusFound)
  302. case "/success":
  303. if r.Host == successHostHeader {
  304. w.WriteHeader(http.StatusOK)
  305. } else {
  306. http.Error(w, "", http.StatusBadRequest)
  307. }
  308. default:
  309. http.Error(w, "", http.StatusInternalServerError)
  310. }
  311. })
  312. server := httptest.NewServer(handler)
  313. defer server.Close()
  314. testCases := map[string]struct {
  315. hostHeader string
  316. expectedResult probe.Result
  317. }{
  318. "success": {successHostHeader, probe.Success},
  319. "fail": {failHostHeader, probe.Failure},
  320. }
  321. for desc, test := range testCases {
  322. headers := http.Header{}
  323. headers.Add("Host", test.hostHeader)
  324. t.Run(desc+"local", func(t *testing.T) {
  325. followNonLocalRedirects := false
  326. prober := New(followNonLocalRedirects)
  327. target, err := url.Parse(server.URL + "/redirect")
  328. require.NoError(t, err)
  329. result, _, _ := prober.Probe(target, headers, wait.ForeverTestTimeout)
  330. assert.Equal(t, test.expectedResult, result)
  331. })
  332. t.Run(desc+"nonlocal", func(t *testing.T) {
  333. followNonLocalRedirects := true
  334. prober := New(followNonLocalRedirects)
  335. target, err := url.Parse(server.URL + "/redirect")
  336. require.NoError(t, err)
  337. result, _, _ := prober.Probe(target, headers, wait.ForeverTestTimeout)
  338. assert.Equal(t, test.expectedResult, result)
  339. })
  340. }
  341. }