req_SUITE.erl 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. %% Copyright (c) 2016-2017, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(req_SUITE).
  15. -compile(export_all).
  16. -import(ct_helper, [config/2]).
  17. -import(ct_helper, [doc/1]).
  18. -import(cowboy_test, [gun_open/1]).
  19. %% ct.
  20. all() ->
  21. cowboy_test:common_all().
  22. groups() ->
  23. cowboy_test:common_groups(ct_helper:all(?MODULE)).
  24. init_per_suite(Config) ->
  25. ct_helper:create_static_dir(config(priv_dir, Config) ++ "/static"),
  26. Config.
  27. end_per_suite(Config) ->
  28. ct_helper:delete_static_dir(config(priv_dir, Config) ++ "/static").
  29. init_per_group(Name, Config) ->
  30. cowboy_test:init_common_groups(Name, Config, ?MODULE).
  31. end_per_group(Name, _) ->
  32. cowboy:stop_listener(Name).
  33. %% Routes.
  34. init_dispatch(Config) ->
  35. cowboy_router:compile([{"[...]", [
  36. {"/static/[...]", cowboy_static, {dir, config(priv_dir, Config) ++ "/static"}},
  37. %% @todo Seriously InitialState should be optional.
  38. {"/resp/:key[/:arg]", resp_h, []},
  39. {"/multipart[/:key]", multipart_h, []},
  40. {"/args/:key/:arg[/:default]", echo_h, []},
  41. {"/crash/:key/period", echo_h, #{length => 999999999, period => 1000, crash => true}},
  42. {"/no-opts/:key", echo_h, #{crash => true}},
  43. {"/opts/:key/length", echo_h, #{length => 1000}},
  44. {"/opts/:key/period", echo_h, #{length => 999999999, period => 1000}},
  45. {"/opts/:key/timeout", echo_h, #{timeout => 1000, crash => true}},
  46. {"/full/:key", echo_h, []},
  47. {"/no/:key", echo_h, []},
  48. {"/direct/:key/[...]", echo_h, []},
  49. {"/:key/[...]", echo_h, []}
  50. ]}]).
  51. %% Internal.
  52. do_body(Method, Path, Config) ->
  53. do_body(Method, Path, [], Config).
  54. do_body(Method, Path, Headers, Config) ->
  55. do_body(Method, Path, Headers, <<>>, Config).
  56. do_body(Method, Path, Headers0, Body, Config) ->
  57. ConnPid = gun_open(Config),
  58. Headers = [{<<"accept-encoding">>, <<"gzip">>}|Headers0],
  59. Ref = case Body of
  60. <<>> -> gun:request(ConnPid, Method, Path, Headers);
  61. _ -> gun:request(ConnPid, Method, Path, Headers, Body)
  62. end,
  63. {response, IsFin, 200, RespHeaders} = gun:await(ConnPid, Ref),
  64. {ok, RespBody} = case IsFin of
  65. nofin -> gun:await_body(ConnPid, Ref);
  66. fin -> {ok, <<>>}
  67. end,
  68. gun:close(ConnPid),
  69. do_decode(RespHeaders, RespBody).
  70. do_body_error(Method, Path, Headers0, Body, Config) ->
  71. ConnPid = gun_open(Config),
  72. Headers = [{<<"accept-encoding">>, <<"gzip">>}|Headers0],
  73. Ref = case Body of
  74. <<>> -> gun:request(ConnPid, Method, Path, Headers);
  75. _ -> gun:request(ConnPid, Method, Path, Headers, Body)
  76. end,
  77. {response, _, Status, RespHeaders} = gun:await(ConnPid, Ref),
  78. gun:close(ConnPid),
  79. {Status, RespHeaders}.
  80. do_get(Path, Config) ->
  81. do_get(Path, [], Config).
  82. do_get(Path, Headers, Config) ->
  83. ConnPid = gun_open(Config),
  84. Ref = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}|Headers]),
  85. {response, IsFin, Status, RespHeaders} = gun:await(ConnPid, Ref),
  86. {ok, RespBody} = case IsFin of
  87. nofin -> gun:await_body(ConnPid, Ref);
  88. fin -> {ok, <<>>}
  89. end,
  90. gun:close(ConnPid),
  91. {Status, RespHeaders, do_decode(RespHeaders, RespBody)}.
  92. do_get_body(Path, Config) ->
  93. do_get_body(Path, [], Config).
  94. do_get_body(Path, Headers, Config) ->
  95. do_body("GET", Path, Headers, Config).
  96. do_decode(Headers, Body) ->
  97. case lists:keyfind(<<"content-encoding">>, 1, Headers) of
  98. {_, <<"gzip">>} -> zlib:gunzip(Body);
  99. _ -> Body
  100. end.
  101. %% Tests: Request.
  102. binding(Config) ->
  103. doc("Value bound from request URI path with/without default."),
  104. <<"binding">> = do_get_body("/args/binding/key", Config),
  105. <<"binding">> = do_get_body("/args/binding/key/default", Config),
  106. <<"default">> = do_get_body("/args/binding/undefined/default", Config),
  107. ok.
  108. bindings(Config) ->
  109. doc("Values bound from request URI path."),
  110. <<"#{key => <<\"bindings\">>}">> = do_get_body("/bindings", Config),
  111. ok.
  112. header(Config) ->
  113. doc("Request header with/without default."),
  114. <<"value">> = do_get_body("/args/header/defined", [{<<"defined">>, "value"}], Config),
  115. <<"value">> = do_get_body("/args/header/defined/default", [{<<"defined">>, "value"}], Config),
  116. <<"default">> = do_get_body("/args/header/undefined/default", [{<<"defined">>, "value"}], Config),
  117. ok.
  118. headers(Config) ->
  119. doc("Request headers."),
  120. do_headers("/headers", Config),
  121. do_headers("/direct/headers", Config).
  122. do_headers(Path, Config) ->
  123. %% We always send accept-encoding with this test suite's requests.
  124. <<"#{<<\"accept-encoding\">> => <<\"gzip\">>,<<\"header\">> => <<\"value\">>", _/bits>>
  125. = do_get_body(Path, [{<<"header">>, "value"}], Config),
  126. ok.
  127. host(Config) ->
  128. doc("Request URI host."),
  129. <<"localhost">> = do_get_body("/host", Config),
  130. <<"localhost">> = do_get_body("/direct/host", Config),
  131. ok.
  132. host_info(Config) ->
  133. doc("Request host_info."),
  134. <<"[<<\"localhost\">>]">> = do_get_body("/host_info", Config),
  135. ok.
  136. %% @todo Actually write the related unit tests.
  137. match_cookies(Config) ->
  138. doc("Matched request cookies."),
  139. <<"#{}">> = do_get_body("/match/cookies", [{<<"cookie">>, "a=b; c=d"}], Config),
  140. <<"#{a => <<\"b\">>}">> = do_get_body("/match/cookies/a", [{<<"cookie">>, "a=b; c=d"}], Config),
  141. <<"#{c => <<\"d\">>}">> = do_get_body("/match/cookies/c", [{<<"cookie">>, "a=b; c=d"}], Config),
  142. <<"#{a => <<\"b\">>,c => <<\"d\">>}">> = do_get_body("/match/cookies/a/c",
  143. [{<<"cookie">>, "a=b; c=d"}], Config),
  144. %% Ensure match errors result in a 400 response.
  145. {400, _, _} = do_get("/match/cookies/a/c",
  146. [{<<"cookie">>, "a=b"}], Config),
  147. %% This function is tested more extensively through unit tests.
  148. ok.
  149. %% @todo Actually write the related unit tests.
  150. match_qs(Config) ->
  151. doc("Matched request URI query string."),
  152. <<"#{}">> = do_get_body("/match/qs?a=b&c=d", Config),
  153. <<"#{a => <<\"b\">>}">> = do_get_body("/match/qs/a?a=b&c=d", Config),
  154. <<"#{c => <<\"d\">>}">> = do_get_body("/match/qs/c?a=b&c=d", Config),
  155. <<"#{a => <<\"b\">>,c => <<\"d\">>}">> = do_get_body("/match/qs/a/c?a=b&c=d", Config),
  156. <<"#{a => <<\"b\">>,c => true}">> = do_get_body("/match/qs/a/c?a=b&c", Config),
  157. <<"#{a => true,c => <<\"d\">>}">> = do_get_body("/match/qs/a/c?a&c=d", Config),
  158. %% Ensure match errors result in a 400 response.
  159. {400, _, _} = do_get("/match/qs/a/c?a=b", [], Config),
  160. %% This function is tested more extensively through unit tests.
  161. ok.
  162. method(Config) ->
  163. doc("Request method."),
  164. do_method("/method", Config),
  165. do_method("/direct/method", Config).
  166. do_method(Path, Config) ->
  167. <<"GET">> = do_body("GET", Path, Config),
  168. <<>> = do_body("HEAD", Path, Config),
  169. <<"OPTIONS">> = do_body("OPTIONS", Path, Config),
  170. <<"PATCH">> = do_body("PATCH", Path, Config),
  171. <<"POST">> = do_body("POST", Path, Config),
  172. <<"PUT">> = do_body("PUT", Path, Config),
  173. <<"ZZZZZZZZ">> = do_body("ZZZZZZZZ", Path, Config),
  174. ok.
  175. parse_cookies(Config) ->
  176. doc("Request cookies."),
  177. <<"[]">> = do_get_body("/parse_cookies", Config),
  178. <<"[{<<\"cake\">>,<<\"strawberry\">>}]">>
  179. = do_get_body("/parse_cookies", [{<<"cookie">>, "cake=strawberry"}], Config),
  180. <<"[{<<\"cake\">>,<<\"strawberry\">>},{<<\"color\">>,<<\"blue\">>}]">>
  181. = do_get_body("/parse_cookies", [{<<"cookie">>, "cake=strawberry; color=blue"}], Config),
  182. <<"[{<<\"cake\">>,<<\"strawberry\">>},{<<\"color\">>,<<\"blue\">>}]">>
  183. = do_get_body("/parse_cookies",
  184. [{<<"cookie">>, "cake=strawberry"}, {<<"cookie">>, "color=blue"}], Config),
  185. %% Ensure parse errors result in a 400 response.
  186. {400, _, _} = do_get("/parse_cookies",
  187. [{<<"cookie">>, "bad name=strawberry"}], Config),
  188. {400, _, _} = do_get("/parse_cookies",
  189. [{<<"cookie">>, "goodname=strawberry\tmilkshake"}], Config),
  190. ok.
  191. parse_header(Config) ->
  192. doc("Parsed request header with/without default."),
  193. <<"[{{<<\"text\">>,<<\"html\">>,[]},1000,[]}]">>
  194. = do_get_body("/args/parse_header/accept", [{<<"accept">>, "text/html"}], Config),
  195. <<"[{{<<\"text\">>,<<\"html\">>,[]},1000,[]}]">>
  196. = do_get_body("/args/parse_header/accept/default", [{<<"accept">>, "text/html"}], Config),
  197. %% Header not in request but with default defined by Cowboy.
  198. <<"0">> = do_get_body("/args/parse_header/content-length", Config),
  199. %% Header not in request and no default from Cowboy.
  200. <<"undefined">> = do_get_body("/args/parse_header/upgrade", Config),
  201. %% Header in request and with default provided.
  202. <<"100-continue">> = do_get_body("/args/parse_header/expect/100-continue", Config),
  203. %% Ensure parse errors result in a 400 response.
  204. {400, _, _} = do_get("/args/parse_header/accept",
  205. [{<<"accept">>, "bad media type"}], Config),
  206. ok.
  207. parse_qs(Config) ->
  208. doc("Parsed request URI query string."),
  209. <<"[]">> = do_get_body("/parse_qs", Config),
  210. <<"[{<<\"abc\">>,true}]">> = do_get_body("/parse_qs?abc", Config),
  211. <<"[{<<\"a\">>,<<\"b\">>},{<<\"c\">>,<<\"d e\">>}]">> = do_get_body("/parse_qs?a=b&c=d+e", Config),
  212. %% Ensure parse errors result in a 400 response.
  213. {400, _, _} = do_get("/parse_qs?%%%%%%%", Config),
  214. ok.
  215. path(Config) ->
  216. doc("Request URI path."),
  217. do_path("/path", Config),
  218. do_path("/direct/path", Config).
  219. do_path(Path0, Config) ->
  220. Path = list_to_binary(Path0 ++ "/to/the/resource"),
  221. Path = do_get_body(Path, Config),
  222. Path = do_get_body([Path, "?query"], Config),
  223. Path = do_get_body([Path, "?query#fragment"], Config),
  224. Path = do_get_body([Path, "#fragment"], Config),
  225. ok.
  226. path_info(Config) ->
  227. doc("Request path_info."),
  228. <<"undefined">> = do_get_body("/no/path_info", Config),
  229. <<"[]">> = do_get_body("/path_info", Config),
  230. <<"[]">> = do_get_body("/path_info/", Config),
  231. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource", Config),
  232. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource?query", Config),
  233. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource?query#fragment", Config),
  234. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource#fragment", Config),
  235. ok.
  236. peer(Config) ->
  237. doc("Request peer."),
  238. <<"{{127,0,0,1},", _/bits >> = do_get_body("/peer", Config),
  239. <<"{{127,0,0,1},", _/bits >> = do_get_body("/direct/peer", Config),
  240. ok.
  241. port(Config) ->
  242. doc("Request URI port."),
  243. Port = integer_to_binary(config(port, Config)),
  244. Port = do_get_body("/port", Config),
  245. Port = do_get_body("/direct/port", Config),
  246. ok.
  247. qs(Config) ->
  248. doc("Request URI query string."),
  249. do_qs("/qs", Config),
  250. do_qs("/direct/qs", Config).
  251. do_qs(Path, Config) ->
  252. <<>> = do_get_body(Path, Config),
  253. <<"abc">> = do_get_body(Path ++ "?abc", Config),
  254. <<"a=b&c=d+e">> = do_get_body(Path ++ "?a=b&c=d+e", Config),
  255. ok.
  256. scheme(Config) ->
  257. doc("Request URI scheme."),
  258. do_scheme("/scheme", Config),
  259. do_scheme("/direct/scheme", Config).
  260. do_scheme(Path, Config) ->
  261. Transport = config(type, Config),
  262. case do_get_body(Path, Config) of
  263. <<"http">> when Transport =:= tcp -> ok;
  264. <<"https">> when Transport =:= ssl -> ok
  265. end.
  266. uri(Config) ->
  267. doc("Request URI building/modification."),
  268. Scheme = case config(type, Config) of
  269. tcp -> <<"http">>;
  270. ssl -> <<"https">>
  271. end,
  272. SLen = byte_size(Scheme),
  273. Port = integer_to_binary(config(port, Config)),
  274. PLen = byte_size(Port),
  275. %% Absolute form.
  276. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary, "/uri?qs" >>
  277. = do_get_body("/uri?qs", Config),
  278. %% Origin form.
  279. << "/uri/origin?qs" >> = do_get_body("/uri/origin?qs", Config),
  280. %% Protocol relative.
  281. << "//localhost:", Port:PLen/binary, "/uri/protocol-relative?qs" >>
  282. = do_get_body("/uri/protocol-relative?qs", Config),
  283. %% No query string.
  284. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary, "/uri/no-qs" >>
  285. = do_get_body("/uri/no-qs?qs", Config),
  286. %% No path or query string.
  287. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary >>
  288. = do_get_body("/uri/no-path?qs", Config),
  289. %% Changed port.
  290. << Scheme:SLen/binary, "://localhost:123/uri/set-port?qs" >>
  291. = do_get_body("/uri/set-port?qs", Config),
  292. %% This function is tested more extensively through unit tests.
  293. ok.
  294. version(Config) ->
  295. doc("Request HTTP version."),
  296. do_version("/version", Config),
  297. do_version("/direct/version", Config).
  298. do_version(Path, Config) ->
  299. Protocol = config(protocol, Config),
  300. case do_get_body(Path, Config) of
  301. <<"HTTP/1.1">> when Protocol =:= http -> ok;
  302. <<"HTTP/2">> when Protocol =:= http2 -> ok
  303. end.
  304. %% Tests: Request body.
  305. body_length(Config) ->
  306. doc("Request body length."),
  307. <<"0">> = do_get_body("/body_length", Config),
  308. <<"12">> = do_body("POST", "/body_length", [], "hello world!", Config),
  309. ok.
  310. has_body(Config) ->
  311. doc("Has a request body?"),
  312. <<"false">> = do_get_body("/has_body", Config),
  313. <<"true">> = do_body("POST", "/has_body", [], "hello world!", Config),
  314. ok.
  315. read_body(Config) ->
  316. doc("Request body."),
  317. <<>> = do_get_body("/read_body", Config),
  318. <<"hello world!">> = do_body("POST", "/read_body", [], "hello world!", Config),
  319. %% We expect to have read *at least* 1000 bytes.
  320. <<0:8000, _/bits>> = do_body("POST", "/opts/read_body/length", [], <<0:8000000>>, Config),
  321. %% We read any length for at most 1 second.
  322. %%
  323. %% The body is sent twice, first with nofin, then wait 2 seconds, then again with fin.
  324. <<0:8000000>> = do_read_body_period("/opts/read_body/period", <<0:8000000>>, Config),
  325. %% The timeout value is set too low on purpose to ensure a crash occurs.
  326. ok = do_read_body_timeout("/opts/read_body/timeout", <<0:8000000>>, Config),
  327. %% 10MB body larger than default length.
  328. <<0:80000000>> = do_body("POST", "/full/read_body", [], <<0:80000000>>, Config),
  329. ok.
  330. do_read_body_period(Path, Body, Config) ->
  331. ConnPid = gun_open(Config),
  332. Ref = gun:request(ConnPid, "POST", Path, [
  333. {<<"content-length">>, integer_to_binary(byte_size(Body) * 2)}
  334. ]),
  335. gun:data(ConnPid, Ref, nofin, Body),
  336. timer:sleep(2000),
  337. gun:data(ConnPid, Ref, fin, Body),
  338. {response, nofin, 200, _} = gun:await(ConnPid, Ref),
  339. {ok, RespBody} = gun:await_body(ConnPid, Ref),
  340. gun:close(ConnPid),
  341. RespBody.
  342. %% We expect a crash.
  343. do_read_body_timeout(Path, Body, Config) ->
  344. ConnPid = gun_open(Config),
  345. Ref = gun:request(ConnPid, "POST", Path, [
  346. {<<"content-length">>, integer_to_binary(byte_size(Body))}
  347. ]),
  348. {response, _, 500, _} = gun:await(ConnPid, Ref),
  349. gun:close(ConnPid).
  350. read_urlencoded_body(Config) ->
  351. doc("application/x-www-form-urlencoded request body."),
  352. <<"[]">> = do_body("POST", "/read_urlencoded_body", [], <<>>, Config),
  353. <<"[{<<\"abc\">>,true}]">> = do_body("POST", "/read_urlencoded_body", [], "abc", Config),
  354. <<"[{<<\"a\">>,<<\"b\">>},{<<\"c\">>,<<\"d e\">>}]">>
  355. = do_body("POST", "/read_urlencoded_body", [], "a=b&c=d+e", Config),
  356. %% Send a 10MB body, larger than the default length, to ensure a crash occurs.
  357. ok = do_read_urlencoded_body_too_large("/no-opts/read_urlencoded_body",
  358. string:chars($a, 10000000), Config),
  359. %% We read any length for at most 1 second.
  360. %%
  361. %% The body is sent twice, first with nofin, then wait 1.1 second, then again with fin.
  362. %% We expect the handler to crash because read_urlencoded_body expects the full body.
  363. ok = do_read_urlencoded_body_too_long("/crash/read_urlencoded_body/period", <<"abc">>, Config),
  364. %% The timeout value is set too low on purpose to ensure a crash occurs.
  365. ok = do_read_body_timeout("/opts/read_urlencoded_body/timeout", <<"abc">>, Config),
  366. %% Ensure parse errors result in a 400 response.
  367. {400, _} = do_body_error("POST", "/read_urlencoded_body", [], "%%%%%", Config),
  368. ok.
  369. %% We expect a crash.
  370. do_read_urlencoded_body_too_large(Path, Body, Config) ->
  371. ConnPid = gun_open(Config),
  372. Ref = gun:request(ConnPid, "POST", Path, [
  373. {<<"content-length">>, integer_to_binary(iolist_size(Body))}
  374. ]),
  375. gun:data(ConnPid, Ref, fin, Body),
  376. {response, _, 413, _} = gun:await(ConnPid, Ref),
  377. gun:close(ConnPid).
  378. %% We expect a crash.
  379. do_read_urlencoded_body_too_long(Path, Body, Config) ->
  380. ConnPid = gun_open(Config),
  381. Ref = gun:request(ConnPid, "POST", Path, [
  382. {<<"content-length">>, integer_to_binary(byte_size(Body) * 2)}
  383. ]),
  384. gun:data(ConnPid, Ref, nofin, Body),
  385. timer:sleep(1100),
  386. gun:data(ConnPid, Ref, fin, Body),
  387. {response, _, 408, RespHeaders} = gun:await(ConnPid, Ref),
  388. _ = case config(protocol, Config) of
  389. http ->
  390. %% 408 error responses should close HTTP/1.1 connections.
  391. {_, <<"close">>} = lists:keyfind(<<"connection">>, 1, RespHeaders);
  392. http2 ->
  393. ok
  394. end,
  395. gun:close(ConnPid).
  396. multipart(Config) ->
  397. doc("Multipart request body."),
  398. do_multipart("/multipart", Config).
  399. do_multipart(Path, Config) ->
  400. LargeBody = iolist_to_binary(string:chars($a, 10000000)),
  401. ReqBody = [
  402. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  403. "--deadbeef\r\nContent-Type: application/octet-stream\r\nX-Custom: value\r\n\r\n", LargeBody, "\r\n"
  404. "--deadbeef--"
  405. ],
  406. RespBody = do_body("POST", Path, [
  407. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  408. ], ReqBody, Config),
  409. [
  410. {#{<<"content-type">> := <<"text/plain">>}, <<"Cowboy is an HTTP server.">>},
  411. {LargeHeaders, LargeBody}
  412. ] = binary_to_term(RespBody),
  413. #{
  414. <<"content-type">> := <<"application/octet-stream">>,
  415. <<"x-custom">> := <<"value">>
  416. } = LargeHeaders,
  417. ok.
  418. multipart_error_headers(Config) ->
  419. doc("Multipart request body with invalid part headers."),
  420. ReqBody = [
  421. "--deadbeef\r\nbad-header text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  422. "--deadbeef--"
  423. ],
  424. %% Ensure parse errors result in a 400 response.
  425. {400, _} = do_body_error("POST", "/multipart", [
  426. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  427. ], ReqBody, Config),
  428. ok.
  429. %% The function to parse the multipart body currently does not crash,
  430. %% as far as I can tell. There is therefore no test for it.
  431. multipart_missing_boundary(Config) ->
  432. doc("Multipart request body without a boundary in the media type."),
  433. ReqBody = [
  434. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  435. "--deadbeef--"
  436. ],
  437. %% Ensure parse errors result in a 400 response.
  438. {400, _} = do_body_error("POST", "/multipart", [
  439. {<<"content-type">>, <<"multipart/mixed">>}
  440. ], ReqBody, Config),
  441. ok.
  442. read_part_skip_body(Config) ->
  443. doc("Multipart request body skipping part bodies."),
  444. LargeBody = iolist_to_binary(string:chars($a, 10000000)),
  445. ReqBody = [
  446. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  447. "--deadbeef\r\nContent-Type: application/octet-stream\r\nX-Custom: value\r\n\r\n", LargeBody, "\r\n"
  448. "--deadbeef--"
  449. ],
  450. RespBody = do_body("POST", "/multipart/skip_body", [
  451. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  452. ], ReqBody, Config),
  453. [
  454. #{<<"content-type">> := <<"text/plain">>},
  455. LargeHeaders
  456. ] = binary_to_term(RespBody),
  457. #{
  458. <<"content-type">> := <<"application/octet-stream">>,
  459. <<"x-custom">> := <<"value">>
  460. } = LargeHeaders,
  461. ok.
  462. %% @todo When reading a multipart body, length and period
  463. %% only apply to a single read_body call. We may want a
  464. %% separate option to know how many reads we want to do
  465. %% before we give up.
  466. read_part2(Config) ->
  467. doc("Multipart request body using read_part/2."),
  468. %% Override the length and period values only, making
  469. %% the request process use more read_body calls.
  470. %%
  471. %% We do not try a custom timeout value since this would
  472. %% be the same test as read_body/2.
  473. do_multipart("/multipart/read_part2", Config).
  474. read_part_body2(Config) ->
  475. doc("Multipart request body using read_part_body/2."),
  476. %% Override the length and period values only, making
  477. %% the request process use more read_body calls.
  478. %%
  479. %% We do not try a custom timeout value since this would
  480. %% be the same test as read_body/2.
  481. do_multipart("/multipart/read_part_body2", Config).
  482. %% Tests: Response.
  483. %% @todo We want to crash when calling set_resp_* or related
  484. %% functions after the reply has been sent.
  485. set_resp_cookie(Config) ->
  486. doc("Response using set_resp_cookie."),
  487. %% Single cookie, no options.
  488. {200, Headers1, _} = do_get("/resp/set_resp_cookie3", Config),
  489. {_, <<"mycookie=myvalue; Version=1">>}
  490. = lists:keyfind(<<"set-cookie">>, 1, Headers1),
  491. %% Single cookie, with options.
  492. {200, Headers2, _} = do_get("/resp/set_resp_cookie4", Config),
  493. {_, <<"mycookie=myvalue; Version=1; Path=/resp/set_resp_cookie4">>}
  494. = lists:keyfind(<<"set-cookie">>, 1, Headers2),
  495. %% Multiple cookies.
  496. {200, Headers3, _} = do_get("/resp/set_resp_cookie3/multiple", Config),
  497. [_, _] = [H || H={<<"set-cookie">>, _} <- Headers3],
  498. %% Overwrite previously set cookie.
  499. {200, Headers4, _} = do_get("/resp/set_resp_cookie3/overwrite", Config),
  500. {_, <<"mycookie=overwrite; Version=1">>}
  501. = lists:keyfind(<<"set-cookie">>, 1, Headers4),
  502. ok.
  503. set_resp_header(Config) ->
  504. doc("Response using set_resp_header."),
  505. {200, Headers, <<"OK">>} = do_get("/resp/set_resp_header", Config),
  506. true = lists:keymember(<<"content-type">>, 1, Headers),
  507. ok.
  508. set_resp_headers(Config) ->
  509. doc("Response using set_resp_headers."),
  510. {200, Headers, <<"OK">>} = do_get("/resp/set_resp_headers", Config),
  511. true = lists:keymember(<<"content-type">>, 1, Headers),
  512. true = lists:keymember(<<"content-encoding">>, 1, Headers),
  513. ok.
  514. resp_header(Config) ->
  515. doc("Response header with/without default."),
  516. {200, _, <<"OK">>} = do_get("/resp/resp_header_defined", Config),
  517. {200, _, <<"OK">>} = do_get("/resp/resp_header_default", Config),
  518. ok.
  519. resp_headers(Config) ->
  520. doc("Get all response headers."),
  521. {200, _, <<"OK">>} = do_get("/resp/resp_headers", Config),
  522. {200, _, <<"OK">>} = do_get("/resp/resp_headers_empty", Config),
  523. ok.
  524. set_resp_body(Config) ->
  525. doc("Response using set_resp_body."),
  526. {200, _, <<"OK">>} = do_get("/resp/set_resp_body", Config),
  527. {200, _, <<"OVERRIDE">>} = do_get("/resp/set_resp_body/override", Config),
  528. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  529. {200, _, AppFile} = do_get("/resp/set_resp_body/sendfile", Config),
  530. ok.
  531. set_resp_body_sendfile0(Config) ->
  532. doc("Response using set_resp_body with a sendfile of length 0."),
  533. Path = "/resp/set_resp_body/sendfile0",
  534. ConnPid = gun_open(Config),
  535. %% First request.
  536. Ref1 = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  537. {response, IsFin, 200, _} = gun:await(ConnPid, Ref1),
  538. {ok, <<>>} = case IsFin of
  539. nofin -> gun:await_body(ConnPid, Ref1);
  540. fin -> {ok, <<>>}
  541. end,
  542. %% Second request will confirm everything works as intended.
  543. Ref2 = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  544. {response, IsFin, 200, _} = gun:await(ConnPid, Ref2),
  545. {ok, <<>>} = case IsFin of
  546. nofin -> gun:await_body(ConnPid, Ref2);
  547. fin -> {ok, <<>>}
  548. end,
  549. gun:close(ConnPid),
  550. ok.
  551. has_resp_header(Config) ->
  552. doc("Has response header?"),
  553. {200, Headers, <<"OK">>} = do_get("/resp/has_resp_header", Config),
  554. true = lists:keymember(<<"content-type">>, 1, Headers),
  555. ok.
  556. has_resp_body(Config) ->
  557. doc("Has response body?"),
  558. {200, _, <<"OK">>} = do_get("/resp/has_resp_body", Config),
  559. {200, _, <<"OK">>} = do_get("/resp/has_resp_body/sendfile", Config),
  560. ok.
  561. delete_resp_header(Config) ->
  562. doc("Delete response header."),
  563. {200, Headers, <<"OK">>} = do_get("/resp/delete_resp_header", Config),
  564. false = lists:keymember(<<"content-type">>, 1, Headers),
  565. ok.
  566. reply2(Config) ->
  567. doc("Response with default headers and no body."),
  568. {200, _, _} = do_get("/resp/reply2/200", Config),
  569. {201, _, _} = do_get("/resp/reply2/201", Config),
  570. {404, _, _} = do_get("/resp/reply2/404", Config),
  571. {200, _, _} = do_get("/resp/reply2/binary", Config),
  572. {500, _, _} = do_get("/resp/reply2/error", Config),
  573. %% @todo We want to crash when reply or stream_reply is called twice.
  574. %% How to test this properly? This isn't enough.
  575. {200, _, _} = do_get("/resp/reply2/twice", Config),
  576. ok.
  577. reply3(Config) ->
  578. doc("Response with additional headers and no body."),
  579. {200, Headers1, _} = do_get("/resp/reply3/200", Config),
  580. true = lists:keymember(<<"content-type">>, 1, Headers1),
  581. {201, Headers2, _} = do_get("/resp/reply3/201", Config),
  582. true = lists:keymember(<<"content-type">>, 1, Headers2),
  583. {404, Headers3, _} = do_get("/resp/reply3/404", Config),
  584. true = lists:keymember(<<"content-type">>, 1, Headers3),
  585. {500, _, _} = do_get("/resp/reply3/error", Config),
  586. ok.
  587. reply4(Config) ->
  588. doc("Response with additional headers and body."),
  589. {200, _, <<"OK">>} = do_get("/resp/reply4/200", Config),
  590. {201, _, <<"OK">>} = do_get("/resp/reply4/201", Config),
  591. {404, _, <<"OK">>} = do_get("/resp/reply4/404", Config),
  592. {500, _, _} = do_get("/resp/reply4/error", Config),
  593. ok.
  594. %% @todo Crash when stream_reply is called twice.
  595. stream_reply2(Config) ->
  596. doc("Response with default headers and streamed body."),
  597. Body = <<0:8000000>>,
  598. {200, _, Body} = do_get("/resp/stream_reply2/200", Config),
  599. {201, _, Body} = do_get("/resp/stream_reply2/201", Config),
  600. {404, _, Body} = do_get("/resp/stream_reply2/404", Config),
  601. {200, _, Body} = do_get("/resp/stream_reply2/binary", Config),
  602. {500, _, _} = do_get("/resp/stream_reply2/error", Config),
  603. ok.
  604. stream_reply3(Config) ->
  605. doc("Response with additional headers and streamed body."),
  606. Body = <<0:8000000>>,
  607. {200, Headers1, Body} = do_get("/resp/stream_reply3/200", Config),
  608. true = lists:keymember(<<"content-type">>, 1, Headers1),
  609. {201, Headers2, Body} = do_get("/resp/stream_reply3/201", Config),
  610. true = lists:keymember(<<"content-type">>, 1, Headers2),
  611. {404, Headers3, Body} = do_get("/resp/stream_reply3/404", Config),
  612. true = lists:keymember(<<"content-type">>, 1, Headers3),
  613. {500, _, _} = do_get("/resp/stream_reply3/error", Config),
  614. ok.
  615. %% @todo Crash when calling stream_body after the fin flag has been set.
  616. %% @todo Crash when calling stream_body after calling reply.
  617. %% @todo Crash when calling stream_body before calling stream_reply.
  618. %% Tests: Push.
  619. %% @todo We want to crash when push is called after reply has been initiated.
  620. push(Config) ->
  621. case config(protocol, Config) of
  622. http -> do_push_http("/resp/push", Config);
  623. http2 -> do_push_http2(Config)
  624. end.
  625. push_method(Config) ->
  626. case config(protocol, Config) of
  627. http -> do_push_http("/resp/push/method", Config);
  628. http2 -> do_push_http2_method(Config)
  629. end.
  630. push_origin(Config) ->
  631. case config(protocol, Config) of
  632. http -> do_push_http("/resp/push/origin", Config);
  633. http2 -> do_push_http2_origin(Config)
  634. end.
  635. push_qs(Config) ->
  636. case config(protocol, Config) of
  637. http -> do_push_http("/resp/push/qs", Config);
  638. http2 -> do_push_http2_qs(Config)
  639. end.
  640. do_push_http(Path, Config) ->
  641. doc("Ignore pushed responses when protocol is HTTP/1.1."),
  642. ConnPid = gun_open(Config),
  643. Ref = gun:get(ConnPid, Path, []),
  644. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  645. ok.
  646. do_push_http2(Config) ->
  647. doc("Pushed responses."),
  648. ConnPid = gun_open(Config),
  649. Ref = gun:get(ConnPid, "/resp/push", []),
  650. %% We expect two pushed resources.
  651. Origin = iolist_to_binary([
  652. case config(type, Config) of
  653. tcp -> "http";
  654. ssl -> "https"
  655. end,
  656. "://localhost:",
  657. integer_to_binary(config(port, Config))
  658. ]),
  659. OriginLen = byte_size(Origin),
  660. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css">>,
  661. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  662. {push, PushTXT, <<"GET">>, <<Origin:OriginLen/binary, "/static/plain.txt">>,
  663. [{<<"accept">>,<<"text/plain">>}]} = gun:await(ConnPid, Ref),
  664. %% Pushed CSS.
  665. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  666. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  667. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  668. %% Pushed TXT is 406 because the pushed accept header uses an undefined type.
  669. {response, fin, 406, _} = gun:await(ConnPid, PushTXT),
  670. %% Let's not forget about the response to the client's request.
  671. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  672. gun:close(ConnPid).
  673. do_push_http2_method(Config) ->
  674. doc("Pushed response with non-GET method."),
  675. ConnPid = gun_open(Config),
  676. Ref = gun:get(ConnPid, "/resp/push/method", []),
  677. %% Pushed CSS.
  678. {push, PushCSS, <<"HEAD">>, _, [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  679. {response, fin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  680. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  681. %% Let's not forget about the response to the client's request.
  682. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  683. gun:close(ConnPid).
  684. do_push_http2_origin(Config) ->
  685. doc("Pushed response with custom scheme/host/port."),
  686. ConnPid = gun_open(Config),
  687. Ref = gun:get(ConnPid, "/resp/push/origin", []),
  688. %% Pushed CSS.
  689. {push, PushCSS, <<"GET">>, <<"ftp://127.0.0.1:21/static/style.css">>,
  690. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  691. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  692. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  693. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  694. %% Let's not forget about the response to the client's request.
  695. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  696. gun:close(ConnPid).
  697. do_push_http2_qs(Config) ->
  698. doc("Pushed response with query string."),
  699. ConnPid = gun_open(Config),
  700. Ref = gun:get(ConnPid, "/resp/push/qs", []),
  701. %% Pushed CSS.
  702. Origin = iolist_to_binary([
  703. case config(type, Config) of
  704. tcp -> "http";
  705. ssl -> "https"
  706. end,
  707. "://localhost:",
  708. integer_to_binary(config(port, Config))
  709. ]),
  710. OriginLen = byte_size(Origin),
  711. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css?server=cowboy&version=2.0">>,
  712. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  713. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  714. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  715. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  716. %% Let's not forget about the response to the client's request.
  717. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  718. gun:close(ConnPid).