req_SUITE.erl 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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. cert(Config) ->
  113. case config(type, Config) of
  114. tcp -> doc("TLS certificates can only be provided over TLS.");
  115. ssl -> do_cert(Config)
  116. end.
  117. do_cert(Config0) ->
  118. doc("A client TLS certificate was provided."),
  119. {CaCert, Cert, Key} = ct_helper:make_certs(),
  120. Config = [{transport_opts, [
  121. {cert, Cert},
  122. {key, Key},
  123. {cacerts, [CaCert]}
  124. ]}|Config0],
  125. Cert = do_get_body("/cert", Config),
  126. Cert = do_get_body("/direct/cert", Config),
  127. ok.
  128. cert_undefined(Config) ->
  129. doc("No client TLS certificate was provided."),
  130. <<"undefined">> = do_get_body("/cert", Config),
  131. <<"undefined">> = do_get_body("/direct/cert", Config),
  132. ok.
  133. header(Config) ->
  134. doc("Request header with/without default."),
  135. <<"value">> = do_get_body("/args/header/defined", [{<<"defined">>, "value"}], Config),
  136. <<"value">> = do_get_body("/args/header/defined/default", [{<<"defined">>, "value"}], Config),
  137. <<"default">> = do_get_body("/args/header/undefined/default", [{<<"defined">>, "value"}], Config),
  138. ok.
  139. headers(Config) ->
  140. doc("Request headers."),
  141. do_headers("/headers", Config),
  142. do_headers("/direct/headers", Config).
  143. do_headers(Path, Config) ->
  144. %% We always send accept-encoding with this test suite's requests.
  145. <<"#{<<\"accept-encoding\">> => <<\"gzip\">>,<<\"header\">> => <<\"value\">>", _/bits>>
  146. = do_get_body(Path, [{<<"header">>, "value"}], Config),
  147. ok.
  148. host(Config) ->
  149. doc("Request URI host."),
  150. <<"localhost">> = do_get_body("/host", Config),
  151. <<"localhost">> = do_get_body("/direct/host", Config),
  152. ok.
  153. host_info(Config) ->
  154. doc("Request host_info."),
  155. <<"[<<\"localhost\">>]">> = do_get_body("/host_info", Config),
  156. ok.
  157. %% @todo Actually write the related unit tests.
  158. match_cookies(Config) ->
  159. doc("Matched request cookies."),
  160. <<"#{}">> = do_get_body("/match/cookies", [{<<"cookie">>, "a=b; c=d"}], Config),
  161. <<"#{a => <<\"b\">>}">> = do_get_body("/match/cookies/a", [{<<"cookie">>, "a=b; c=d"}], Config),
  162. <<"#{c => <<\"d\">>}">> = do_get_body("/match/cookies/c", [{<<"cookie">>, "a=b; c=d"}], Config),
  163. <<"#{a => <<\"b\">>,c => <<\"d\">>}">> = do_get_body("/match/cookies/a/c",
  164. [{<<"cookie">>, "a=b; c=d"}], Config),
  165. %% Ensure match errors result in a 400 response.
  166. {400, _, _} = do_get("/match/cookies/a/c",
  167. [{<<"cookie">>, "a=b"}], Config),
  168. %% This function is tested more extensively through unit tests.
  169. ok.
  170. %% @todo Actually write the related unit tests.
  171. match_qs(Config) ->
  172. doc("Matched request URI query string."),
  173. <<"#{}">> = do_get_body("/match/qs?a=b&c=d", Config),
  174. <<"#{a => <<\"b\">>}">> = do_get_body("/match/qs/a?a=b&c=d", Config),
  175. <<"#{c => <<\"d\">>}">> = do_get_body("/match/qs/c?a=b&c=d", Config),
  176. <<"#{a => <<\"b\">>,c => <<\"d\">>}">> = do_get_body("/match/qs/a/c?a=b&c=d", Config),
  177. <<"#{a => <<\"b\">>,c => true}">> = do_get_body("/match/qs/a/c?a=b&c", Config),
  178. <<"#{a => true,c => <<\"d\">>}">> = do_get_body("/match/qs/a/c?a&c=d", Config),
  179. %% Ensure match errors result in a 400 response.
  180. {400, _, _} = do_get("/match/qs/a/c?a=b", [], Config),
  181. %% This function is tested more extensively through unit tests.
  182. ok.
  183. method(Config) ->
  184. doc("Request method."),
  185. do_method("/method", Config),
  186. do_method("/direct/method", Config).
  187. do_method(Path, Config) ->
  188. <<"GET">> = do_body("GET", Path, Config),
  189. <<>> = do_body("HEAD", Path, Config),
  190. <<"OPTIONS">> = do_body("OPTIONS", Path, Config),
  191. <<"PATCH">> = do_body("PATCH", Path, Config),
  192. <<"POST">> = do_body("POST", Path, Config),
  193. <<"PUT">> = do_body("PUT", Path, Config),
  194. <<"ZZZZZZZZ">> = do_body("ZZZZZZZZ", Path, Config),
  195. ok.
  196. parse_cookies(Config) ->
  197. doc("Request cookies."),
  198. <<"[]">> = do_get_body("/parse_cookies", Config),
  199. <<"[{<<\"cake\">>,<<\"strawberry\">>}]">>
  200. = do_get_body("/parse_cookies", [{<<"cookie">>, "cake=strawberry"}], Config),
  201. <<"[{<<\"cake\">>,<<\"strawberry\">>},{<<\"color\">>,<<\"blue\">>}]">>
  202. = do_get_body("/parse_cookies", [{<<"cookie">>, "cake=strawberry; color=blue"}], Config),
  203. <<"[{<<\"cake\">>,<<\"strawberry\">>},{<<\"color\">>,<<\"blue\">>}]">>
  204. = do_get_body("/parse_cookies",
  205. [{<<"cookie">>, "cake=strawberry"}, {<<"cookie">>, "color=blue"}], Config),
  206. %% Ensure parse errors result in a 400 response.
  207. {400, _, _} = do_get("/parse_cookies",
  208. [{<<"cookie">>, "bad name=strawberry"}], Config),
  209. {400, _, _} = do_get("/parse_cookies",
  210. [{<<"cookie">>, "goodname=strawberry\tmilkshake"}], Config),
  211. ok.
  212. parse_header(Config) ->
  213. doc("Parsed request header with/without default."),
  214. <<"[{{<<\"text\">>,<<\"html\">>,[]},1000,[]}]">>
  215. = do_get_body("/args/parse_header/accept", [{<<"accept">>, "text/html"}], Config),
  216. <<"[{{<<\"text\">>,<<\"html\">>,[]},1000,[]}]">>
  217. = do_get_body("/args/parse_header/accept/default", [{<<"accept">>, "text/html"}], Config),
  218. %% Header not in request but with default defined by Cowboy.
  219. <<"0">> = do_get_body("/args/parse_header/content-length", Config),
  220. %% Header not in request and no default from Cowboy.
  221. <<"undefined">> = do_get_body("/args/parse_header/upgrade", Config),
  222. %% Header in request and with default provided.
  223. <<"100-continue">> = do_get_body("/args/parse_header/expect/100-continue", Config),
  224. %% Ensure parse errors result in a 400 response.
  225. {400, _, _} = do_get("/args/parse_header/accept",
  226. [{<<"accept">>, "bad media type"}], Config),
  227. ok.
  228. parse_qs(Config) ->
  229. doc("Parsed request URI query string."),
  230. <<"[]">> = do_get_body("/parse_qs", Config),
  231. <<"[{<<\"abc\">>,true}]">> = do_get_body("/parse_qs?abc", Config),
  232. <<"[{<<\"a\">>,<<\"b\">>},{<<\"c\">>,<<\"d e\">>}]">> = do_get_body("/parse_qs?a=b&c=d+e", Config),
  233. %% Ensure parse errors result in a 400 response.
  234. {400, _, _} = do_get("/parse_qs?%%%%%%%", Config),
  235. ok.
  236. path(Config) ->
  237. doc("Request URI path."),
  238. do_path("/path", Config),
  239. do_path("/direct/path", Config).
  240. do_path(Path0, Config) ->
  241. Path = list_to_binary(Path0 ++ "/to/the/resource"),
  242. Path = do_get_body(Path, Config),
  243. Path = do_get_body([Path, "?query"], Config),
  244. Path = do_get_body([Path, "?query#fragment"], Config),
  245. Path = do_get_body([Path, "#fragment"], Config),
  246. ok.
  247. path_info(Config) ->
  248. doc("Request path_info."),
  249. <<"undefined">> = do_get_body("/no/path_info", Config),
  250. <<"[]">> = do_get_body("/path_info", Config),
  251. <<"[]">> = do_get_body("/path_info/", Config),
  252. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource", Config),
  253. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource?query", Config),
  254. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource?query#fragment", Config),
  255. <<"[<<\"to\">>,<<\"the\">>,<<\"resource\">>]">> = do_get_body("/path_info/to/the/resource#fragment", Config),
  256. ok.
  257. peer(Config) ->
  258. doc("Remote socket address."),
  259. <<"{{127,0,0,1},", _/bits >> = do_get_body("/peer", Config),
  260. <<"{{127,0,0,1},", _/bits >> = do_get_body("/direct/peer", Config),
  261. ok.
  262. port(Config) ->
  263. doc("Request URI port."),
  264. Port = integer_to_binary(config(port, Config)),
  265. Port = do_get_body("/port", Config),
  266. Port = do_get_body("/direct/port", Config),
  267. ok.
  268. qs(Config) ->
  269. doc("Request URI query string."),
  270. do_qs("/qs", Config),
  271. do_qs("/direct/qs", Config).
  272. do_qs(Path, Config) ->
  273. <<>> = do_get_body(Path, Config),
  274. <<"abc">> = do_get_body(Path ++ "?abc", Config),
  275. <<"a=b&c=d+e">> = do_get_body(Path ++ "?a=b&c=d+e", Config),
  276. ok.
  277. scheme(Config) ->
  278. doc("Request URI scheme."),
  279. do_scheme("/scheme", Config),
  280. do_scheme("/direct/scheme", Config).
  281. do_scheme(Path, Config) ->
  282. Transport = config(type, Config),
  283. case do_get_body(Path, Config) of
  284. <<"http">> when Transport =:= tcp -> ok;
  285. <<"https">> when Transport =:= ssl -> ok
  286. end.
  287. sock(Config) ->
  288. doc("Local socket address."),
  289. <<"{{127,0,0,1},", _/bits >> = do_get_body("/sock", Config),
  290. <<"{{127,0,0,1},", _/bits >> = do_get_body("/direct/sock", Config),
  291. ok.
  292. uri(Config) ->
  293. doc("Request URI building/modification."),
  294. Scheme = case config(type, Config) of
  295. tcp -> <<"http">>;
  296. ssl -> <<"https">>
  297. end,
  298. SLen = byte_size(Scheme),
  299. Port = integer_to_binary(config(port, Config)),
  300. PLen = byte_size(Port),
  301. %% Absolute form.
  302. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary, "/uri?qs" >>
  303. = do_get_body("/uri?qs", Config),
  304. %% Origin form.
  305. << "/uri/origin?qs" >> = do_get_body("/uri/origin?qs", Config),
  306. %% Protocol relative.
  307. << "//localhost:", Port:PLen/binary, "/uri/protocol-relative?qs" >>
  308. = do_get_body("/uri/protocol-relative?qs", Config),
  309. %% No query string.
  310. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary, "/uri/no-qs" >>
  311. = do_get_body("/uri/no-qs?qs", Config),
  312. %% No path or query string.
  313. << Scheme:SLen/binary, "://localhost:", Port:PLen/binary >>
  314. = do_get_body("/uri/no-path?qs", Config),
  315. %% Changed port.
  316. << Scheme:SLen/binary, "://localhost:123/uri/set-port?qs" >>
  317. = do_get_body("/uri/set-port?qs", Config),
  318. %% This function is tested more extensively through unit tests.
  319. ok.
  320. version(Config) ->
  321. doc("Request HTTP version."),
  322. do_version("/version", Config),
  323. do_version("/direct/version", Config).
  324. do_version(Path, Config) ->
  325. Protocol = config(protocol, Config),
  326. case do_get_body(Path, Config) of
  327. <<"HTTP/1.1">> when Protocol =:= http -> ok;
  328. <<"HTTP/2">> when Protocol =:= http2 -> ok
  329. end.
  330. %% Tests: Request body.
  331. body_length(Config) ->
  332. doc("Request body length."),
  333. <<"0">> = do_get_body("/body_length", Config),
  334. <<"12">> = do_body("POST", "/body_length", [], "hello world!", Config),
  335. ok.
  336. has_body(Config) ->
  337. doc("Has a request body?"),
  338. <<"false">> = do_get_body("/has_body", Config),
  339. <<"true">> = do_body("POST", "/has_body", [], "hello world!", Config),
  340. ok.
  341. read_body(Config) ->
  342. doc("Request body."),
  343. <<>> = do_get_body("/read_body", Config),
  344. <<"hello world!">> = do_body("POST", "/read_body", [], "hello world!", Config),
  345. %% We expect to have read *at least* 1000 bytes.
  346. <<0:8000, _/bits>> = do_body("POST", "/opts/read_body/length", [], <<0:8000000>>, Config),
  347. %% We read any length for at most 1 second.
  348. %%
  349. %% The body is sent twice, first with nofin, then wait 2 seconds, then again with fin.
  350. <<0:8000000>> = do_read_body_period("/opts/read_body/period", <<0:8000000>>, Config),
  351. %% The timeout value is set too low on purpose to ensure a crash occurs.
  352. ok = do_read_body_timeout("/opts/read_body/timeout", <<0:8000000>>, Config),
  353. %% 10MB body larger than default length.
  354. <<0:80000000>> = do_body("POST", "/full/read_body", [], <<0:80000000>>, Config),
  355. ok.
  356. do_read_body_period(Path, Body, Config) ->
  357. ConnPid = gun_open(Config),
  358. Ref = gun:request(ConnPid, "POST", Path, [
  359. {<<"content-length">>, integer_to_binary(byte_size(Body) * 2)}
  360. ]),
  361. gun:data(ConnPid, Ref, nofin, Body),
  362. timer:sleep(2000),
  363. gun:data(ConnPid, Ref, fin, Body),
  364. {response, nofin, 200, _} = gun:await(ConnPid, Ref),
  365. {ok, RespBody} = gun:await_body(ConnPid, Ref),
  366. gun:close(ConnPid),
  367. RespBody.
  368. %% We expect a crash.
  369. do_read_body_timeout(Path, Body, Config) ->
  370. ConnPid = gun_open(Config),
  371. Ref = gun:request(ConnPid, "POST", Path, [
  372. {<<"content-length">>, integer_to_binary(byte_size(Body))}
  373. ]),
  374. {response, _, 500, _} = gun:await(ConnPid, Ref),
  375. gun:close(ConnPid).
  376. read_urlencoded_body(Config) ->
  377. doc("application/x-www-form-urlencoded request body."),
  378. <<"[]">> = do_body("POST", "/read_urlencoded_body", [], <<>>, Config),
  379. <<"[{<<\"abc\">>,true}]">> = do_body("POST", "/read_urlencoded_body", [], "abc", Config),
  380. <<"[{<<\"a\">>,<<\"b\">>},{<<\"c\">>,<<\"d e\">>}]">>
  381. = do_body("POST", "/read_urlencoded_body", [], "a=b&c=d+e", Config),
  382. %% Send a 10MB body, larger than the default length, to ensure a crash occurs.
  383. ok = do_read_urlencoded_body_too_large("/no-opts/read_urlencoded_body",
  384. string:chars($a, 10000000), Config),
  385. %% We read any length for at most 1 second.
  386. %%
  387. %% The body is sent twice, first with nofin, then wait 1.1 second, then again with fin.
  388. %% We expect the handler to crash because read_urlencoded_body expects the full body.
  389. ok = do_read_urlencoded_body_too_long("/crash/read_urlencoded_body/period", <<"abc">>, Config),
  390. %% The timeout value is set too low on purpose to ensure a crash occurs.
  391. ok = do_read_body_timeout("/opts/read_urlencoded_body/timeout", <<"abc">>, Config),
  392. %% Ensure parse errors result in a 400 response.
  393. {400, _} = do_body_error("POST", "/read_urlencoded_body", [], "%%%%%", Config),
  394. ok.
  395. %% We expect a crash.
  396. do_read_urlencoded_body_too_large(Path, Body, Config) ->
  397. ConnPid = gun_open(Config),
  398. Ref = gun:request(ConnPid, "POST", Path, [
  399. {<<"content-length">>, integer_to_binary(iolist_size(Body))}
  400. ]),
  401. gun:data(ConnPid, Ref, fin, Body),
  402. {response, _, 413, _} = gun:await(ConnPid, Ref),
  403. gun:close(ConnPid).
  404. %% We expect a crash.
  405. do_read_urlencoded_body_too_long(Path, Body, Config) ->
  406. ConnPid = gun_open(Config),
  407. Ref = gun:request(ConnPid, "POST", Path, [
  408. {<<"content-length">>, integer_to_binary(byte_size(Body) * 2)}
  409. ]),
  410. gun:data(ConnPid, Ref, nofin, Body),
  411. timer:sleep(1100),
  412. gun:data(ConnPid, Ref, fin, Body),
  413. {response, _, 408, RespHeaders} = gun:await(ConnPid, Ref),
  414. _ = case config(protocol, Config) of
  415. http ->
  416. %% 408 error responses should close HTTP/1.1 connections.
  417. {_, <<"close">>} = lists:keyfind(<<"connection">>, 1, RespHeaders);
  418. http2 ->
  419. ok
  420. end,
  421. gun:close(ConnPid).
  422. multipart(Config) ->
  423. doc("Multipart request body."),
  424. do_multipart("/multipart", Config).
  425. do_multipart(Path, Config) ->
  426. LargeBody = iolist_to_binary(string:chars($a, 10000000)),
  427. ReqBody = [
  428. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  429. "--deadbeef\r\nContent-Type: application/octet-stream\r\nX-Custom: value\r\n\r\n", LargeBody, "\r\n"
  430. "--deadbeef--"
  431. ],
  432. RespBody = do_body("POST", Path, [
  433. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  434. ], ReqBody, Config),
  435. [
  436. {#{<<"content-type">> := <<"text/plain">>}, <<"Cowboy is an HTTP server.">>},
  437. {LargeHeaders, LargeBody}
  438. ] = binary_to_term(RespBody),
  439. #{
  440. <<"content-type">> := <<"application/octet-stream">>,
  441. <<"x-custom">> := <<"value">>
  442. } = LargeHeaders,
  443. ok.
  444. multipart_error_empty(Config) ->
  445. doc("Multipart request body is empty."),
  446. %% We use an empty list as a body to make sure Gun knows
  447. %% we want to send an empty body.
  448. %% @todo This is a terrible hack. Improve Gun!
  449. Body = [],
  450. %% Ensure an empty body results in a 400 error.
  451. {400, _} = do_body_error("POST", "/multipart", [
  452. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  453. ], Body, Config),
  454. ok.
  455. multipart_error_preamble_only(Config) ->
  456. doc("Multipart request body only contains a preamble."),
  457. %% Ensure an empty body results in a 400 error.
  458. {400, _} = do_body_error("POST", "/multipart", [
  459. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  460. ], <<"Preamble.">>, Config),
  461. ok.
  462. multipart_error_headers(Config) ->
  463. doc("Multipart request body with invalid part headers."),
  464. ReqBody = [
  465. "--deadbeef\r\nbad-header text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  466. "--deadbeef--"
  467. ],
  468. %% Ensure parse errors result in a 400 response.
  469. {400, _} = do_body_error("POST", "/multipart", [
  470. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  471. ], ReqBody, Config),
  472. ok.
  473. %% The function to parse the multipart body currently does not crash,
  474. %% as far as I can tell. There is therefore no test for it.
  475. multipart_error_no_final_boundary(Config) ->
  476. doc("Multipart request body with no final boundary."),
  477. ReqBody = [
  478. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  479. ],
  480. %% Ensure parse errors result in a 400 response.
  481. {400, _} = do_body_error("POST", "/multipart", [
  482. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  483. ], ReqBody, Config),
  484. ok.
  485. multipart_missing_boundary(Config) ->
  486. doc("Multipart request body without a boundary in the media type."),
  487. ReqBody = [
  488. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  489. "--deadbeef--"
  490. ],
  491. %% Ensure parse errors result in a 400 response.
  492. {400, _} = do_body_error("POST", "/multipart", [
  493. {<<"content-type">>, <<"multipart/mixed">>}
  494. ], ReqBody, Config),
  495. ok.
  496. read_part_skip_body(Config) ->
  497. doc("Multipart request body skipping part bodies."),
  498. LargeBody = iolist_to_binary(string:chars($a, 10000000)),
  499. ReqBody = [
  500. "--deadbeef\r\nContent-Type: text/plain\r\n\r\nCowboy is an HTTP server.\r\n"
  501. "--deadbeef\r\nContent-Type: application/octet-stream\r\nX-Custom: value\r\n\r\n", LargeBody, "\r\n"
  502. "--deadbeef--"
  503. ],
  504. RespBody = do_body("POST", "/multipart/skip_body", [
  505. {<<"content-type">>, <<"multipart/mixed; boundary=deadbeef">>}
  506. ], ReqBody, Config),
  507. [
  508. #{<<"content-type">> := <<"text/plain">>},
  509. LargeHeaders
  510. ] = binary_to_term(RespBody),
  511. #{
  512. <<"content-type">> := <<"application/octet-stream">>,
  513. <<"x-custom">> := <<"value">>
  514. } = LargeHeaders,
  515. ok.
  516. %% @todo When reading a multipart body, length and period
  517. %% only apply to a single read_body call. We may want a
  518. %% separate option to know how many reads we want to do
  519. %% before we give up.
  520. read_part2(Config) ->
  521. doc("Multipart request body using read_part/2."),
  522. %% Override the length and period values only, making
  523. %% the request process use more read_body calls.
  524. %%
  525. %% We do not try a custom timeout value since this would
  526. %% be the same test as read_body/2.
  527. do_multipart("/multipart/read_part2", Config).
  528. read_part_body2(Config) ->
  529. doc("Multipart request body using read_part_body/2."),
  530. %% Override the length and period values only, making
  531. %% the request process use more read_body calls.
  532. %%
  533. %% We do not try a custom timeout value since this would
  534. %% be the same test as read_body/2.
  535. do_multipart("/multipart/read_part_body2", Config).
  536. %% Tests: Response.
  537. %% @todo We want to crash when calling set_resp_* or related
  538. %% functions after the reply has been sent.
  539. set_resp_cookie(Config) ->
  540. doc("Response using set_resp_cookie."),
  541. %% Single cookie, no options.
  542. {200, Headers1, _} = do_get("/resp/set_resp_cookie3", Config),
  543. {_, <<"mycookie=myvalue; Version=1">>}
  544. = lists:keyfind(<<"set-cookie">>, 1, Headers1),
  545. %% Single cookie, with options.
  546. {200, Headers2, _} = do_get("/resp/set_resp_cookie4", Config),
  547. {_, <<"mycookie=myvalue; Version=1; Path=/resp/set_resp_cookie4">>}
  548. = lists:keyfind(<<"set-cookie">>, 1, Headers2),
  549. %% Multiple cookies.
  550. {200, Headers3, _} = do_get("/resp/set_resp_cookie3/multiple", Config),
  551. [_, _] = [H || H={<<"set-cookie">>, _} <- Headers3],
  552. %% Overwrite previously set cookie.
  553. {200, Headers4, _} = do_get("/resp/set_resp_cookie3/overwrite", Config),
  554. {_, <<"mycookie=overwrite; Version=1">>}
  555. = lists:keyfind(<<"set-cookie">>, 1, Headers4),
  556. ok.
  557. set_resp_header(Config) ->
  558. doc("Response using set_resp_header."),
  559. {200, Headers, <<"OK">>} = do_get("/resp/set_resp_header", Config),
  560. true = lists:keymember(<<"content-type">>, 1, Headers),
  561. ok.
  562. set_resp_headers(Config) ->
  563. doc("Response using set_resp_headers."),
  564. {200, Headers, <<"OK">>} = do_get("/resp/set_resp_headers", Config),
  565. true = lists:keymember(<<"content-type">>, 1, Headers),
  566. true = lists:keymember(<<"content-encoding">>, 1, Headers),
  567. ok.
  568. resp_header(Config) ->
  569. doc("Response header with/without default."),
  570. {200, _, <<"OK">>} = do_get("/resp/resp_header_defined", Config),
  571. {200, _, <<"OK">>} = do_get("/resp/resp_header_default", Config),
  572. ok.
  573. resp_headers(Config) ->
  574. doc("Get all response headers."),
  575. {200, _, <<"OK">>} = do_get("/resp/resp_headers", Config),
  576. {200, _, <<"OK">>} = do_get("/resp/resp_headers_empty", Config),
  577. ok.
  578. set_resp_body(Config) ->
  579. doc("Response using set_resp_body."),
  580. {200, _, <<"OK">>} = do_get("/resp/set_resp_body", Config),
  581. {200, _, <<"OVERRIDE">>} = do_get("/resp/set_resp_body/override", Config),
  582. {ok, AppFile} = file:read_file(code:where_is_file("cowboy.app")),
  583. {200, _, AppFile} = do_get("/resp/set_resp_body/sendfile", Config),
  584. ok.
  585. set_resp_body_sendfile0(Config) ->
  586. doc("Response using set_resp_body with a sendfile of length 0."),
  587. Path = "/resp/set_resp_body/sendfile0",
  588. ConnPid = gun_open(Config),
  589. %% First request.
  590. Ref1 = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  591. {response, IsFin, 200, _} = gun:await(ConnPid, Ref1),
  592. {ok, <<>>} = case IsFin of
  593. nofin -> gun:await_body(ConnPid, Ref1);
  594. fin -> {ok, <<>>}
  595. end,
  596. %% Second request will confirm everything works as intended.
  597. Ref2 = gun:get(ConnPid, Path, [{<<"accept-encoding">>, <<"gzip">>}]),
  598. {response, IsFin, 200, _} = gun:await(ConnPid, Ref2),
  599. {ok, <<>>} = case IsFin of
  600. nofin -> gun:await_body(ConnPid, Ref2);
  601. fin -> {ok, <<>>}
  602. end,
  603. gun:close(ConnPid),
  604. ok.
  605. has_resp_header(Config) ->
  606. doc("Has response header?"),
  607. {200, Headers, <<"OK">>} = do_get("/resp/has_resp_header", Config),
  608. true = lists:keymember(<<"content-type">>, 1, Headers),
  609. ok.
  610. has_resp_body(Config) ->
  611. doc("Has response body?"),
  612. {200, _, <<"OK">>} = do_get("/resp/has_resp_body", Config),
  613. {200, _, <<"OK">>} = do_get("/resp/has_resp_body/sendfile", Config),
  614. ok.
  615. delete_resp_header(Config) ->
  616. doc("Delete response header."),
  617. {200, Headers, <<"OK">>} = do_get("/resp/delete_resp_header", Config),
  618. false = lists:keymember(<<"content-type">>, 1, Headers),
  619. ok.
  620. reply2(Config) ->
  621. doc("Response with default headers and no body."),
  622. {200, _, _} = do_get("/resp/reply2/200", Config),
  623. {201, _, _} = do_get("/resp/reply2/201", Config),
  624. {404, _, _} = do_get("/resp/reply2/404", Config),
  625. {200, _, _} = do_get("/resp/reply2/binary", Config),
  626. {500, _, _} = do_get("/resp/reply2/error", Config),
  627. %% @todo We want to crash when reply or stream_reply is called twice.
  628. %% How to test this properly? This isn't enough.
  629. {200, _, _} = do_get("/resp/reply2/twice", Config),
  630. ok.
  631. reply3(Config) ->
  632. doc("Response with additional headers and no body."),
  633. {200, Headers1, _} = do_get("/resp/reply3/200", Config),
  634. true = lists:keymember(<<"content-type">>, 1, Headers1),
  635. {201, Headers2, _} = do_get("/resp/reply3/201", Config),
  636. true = lists:keymember(<<"content-type">>, 1, Headers2),
  637. {404, Headers3, _} = do_get("/resp/reply3/404", Config),
  638. true = lists:keymember(<<"content-type">>, 1, Headers3),
  639. {500, _, _} = do_get("/resp/reply3/error", Config),
  640. ok.
  641. reply4(Config) ->
  642. doc("Response with additional headers and body."),
  643. {200, _, <<"OK">>} = do_get("/resp/reply4/200", Config),
  644. {201, _, <<"OK">>} = do_get("/resp/reply4/201", Config),
  645. {404, _, <<"OK">>} = do_get("/resp/reply4/404", Config),
  646. {500, _, _} = do_get("/resp/reply4/error", Config),
  647. ok.
  648. %% @todo Crash when stream_reply is called twice.
  649. stream_reply2(Config) ->
  650. doc("Response with default headers and streamed body."),
  651. Body = <<0:8000000>>,
  652. {200, _, Body} = do_get("/resp/stream_reply2/200", Config),
  653. {201, _, Body} = do_get("/resp/stream_reply2/201", Config),
  654. {404, _, Body} = do_get("/resp/stream_reply2/404", Config),
  655. {200, _, Body} = do_get("/resp/stream_reply2/binary", Config),
  656. {500, _, _} = do_get("/resp/stream_reply2/error", Config),
  657. ok.
  658. stream_reply3(Config) ->
  659. doc("Response with additional headers and streamed body."),
  660. Body = <<0:8000000>>,
  661. {200, Headers1, Body} = do_get("/resp/stream_reply3/200", Config),
  662. true = lists:keymember(<<"content-type">>, 1, Headers1),
  663. {201, Headers2, Body} = do_get("/resp/stream_reply3/201", Config),
  664. true = lists:keymember(<<"content-type">>, 1, Headers2),
  665. {404, Headers3, Body} = do_get("/resp/stream_reply3/404", Config),
  666. true = lists:keymember(<<"content-type">>, 1, Headers3),
  667. {500, _, _} = do_get("/resp/stream_reply3/error", Config),
  668. ok.
  669. %% @todo Crash when calling stream_body after the fin flag has been set.
  670. %% @todo Crash when calling stream_body after calling reply.
  671. %% @todo Crash when calling stream_body before calling stream_reply.
  672. %% Tests: Push.
  673. %% @todo We want to crash when push is called after reply has been initiated.
  674. push(Config) ->
  675. case config(protocol, Config) of
  676. http -> do_push_http("/resp/push", Config);
  677. http2 -> do_push_http2(Config)
  678. end.
  679. push_method(Config) ->
  680. case config(protocol, Config) of
  681. http -> do_push_http("/resp/push/method", Config);
  682. http2 -> do_push_http2_method(Config)
  683. end.
  684. push_origin(Config) ->
  685. case config(protocol, Config) of
  686. http -> do_push_http("/resp/push/origin", Config);
  687. http2 -> do_push_http2_origin(Config)
  688. end.
  689. push_qs(Config) ->
  690. case config(protocol, Config) of
  691. http -> do_push_http("/resp/push/qs", Config);
  692. http2 -> do_push_http2_qs(Config)
  693. end.
  694. do_push_http(Path, Config) ->
  695. doc("Ignore pushed responses when protocol is HTTP/1.1."),
  696. ConnPid = gun_open(Config),
  697. Ref = gun:get(ConnPid, Path, []),
  698. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  699. ok.
  700. do_push_http2(Config) ->
  701. doc("Pushed responses."),
  702. ConnPid = gun_open(Config),
  703. Ref = gun:get(ConnPid, "/resp/push", []),
  704. %% We expect two pushed resources.
  705. Origin = iolist_to_binary([
  706. case config(type, Config) of
  707. tcp -> "http";
  708. ssl -> "https"
  709. end,
  710. "://localhost:",
  711. integer_to_binary(config(port, Config))
  712. ]),
  713. OriginLen = byte_size(Origin),
  714. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css">>,
  715. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  716. {push, PushTXT, <<"GET">>, <<Origin:OriginLen/binary, "/static/plain.txt">>,
  717. [{<<"accept">>,<<"text/plain">>}]} = gun:await(ConnPid, Ref),
  718. %% Pushed CSS.
  719. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  720. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  721. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  722. %% Pushed TXT is 406 because the pushed accept header uses an undefined type.
  723. {response, fin, 406, _} = gun:await(ConnPid, PushTXT),
  724. %% Let's not forget about the response to the client's request.
  725. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  726. gun:close(ConnPid).
  727. do_push_http2_method(Config) ->
  728. doc("Pushed response with non-GET method."),
  729. ConnPid = gun_open(Config),
  730. Ref = gun:get(ConnPid, "/resp/push/method", []),
  731. %% Pushed CSS.
  732. {push, PushCSS, <<"HEAD">>, _, [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  733. {response, fin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  734. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  735. %% Let's not forget about the response to the client's request.
  736. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  737. gun:close(ConnPid).
  738. do_push_http2_origin(Config) ->
  739. doc("Pushed response with custom scheme/host/port."),
  740. ConnPid = gun_open(Config),
  741. Ref = gun:get(ConnPid, "/resp/push/origin", []),
  742. %% Pushed CSS.
  743. {push, PushCSS, <<"GET">>, <<"ftp://127.0.0.1:21/static/style.css">>,
  744. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  745. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  746. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  747. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  748. %% Let's not forget about the response to the client's request.
  749. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  750. gun:close(ConnPid).
  751. do_push_http2_qs(Config) ->
  752. doc("Pushed response with query string."),
  753. ConnPid = gun_open(Config),
  754. Ref = gun:get(ConnPid, "/resp/push/qs", []),
  755. %% Pushed CSS.
  756. Origin = iolist_to_binary([
  757. case config(type, Config) of
  758. tcp -> "http";
  759. ssl -> "https"
  760. end,
  761. "://localhost:",
  762. integer_to_binary(config(port, Config))
  763. ]),
  764. OriginLen = byte_size(Origin),
  765. {push, PushCSS, <<"GET">>, <<Origin:OriginLen/binary, "/static/style.css?server=cowboy&version=2.0">>,
  766. [{<<"accept">>,<<"text/css">>}]} = gun:await(ConnPid, Ref),
  767. {response, nofin, 200, HeadersCSS} = gun:await(ConnPid, PushCSS),
  768. {_, <<"text/css">>} = lists:keyfind(<<"content-type">>, 1, HeadersCSS),
  769. {ok, <<"body{color:red}\n">>} = gun:await_body(ConnPid, PushCSS),
  770. %% Let's not forget about the response to the client's request.
  771. {response, fin, 200, _} = gun:await(ConnPid, Ref),
  772. gun:close(ConnPid).