cowboy_cookies.erl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. %% Copyright 2007 Mochi Media, Inc.
  2. %% Copyright 2011 Thomas Burdick <thomas.burdick@gmail.com>
  3. %%
  4. %% Permission to use, copy, modify, and/or distribute this software for any
  5. %% purpose with or without fee is hereby granted, provided that the above
  6. %% copyright notice and this permission notice appear in all copies.
  7. %%
  8. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. %% @doc HTTP Cookie parsing and generating (RFC 2965).
  16. -module(cowboy_cookies).
  17. %% API.
  18. -export([parse_cookie/1]).
  19. -export([cookie/3]).
  20. -export([cookie/2]).
  21. %% Types.
  22. -type kv() :: {Name::binary(), Value::binary()}.
  23. -type kvlist() :: [kv()].
  24. -type cookie_option() :: {max_age, integer()}
  25. | {local_time, calendar:datetime()}
  26. | {domain, binary()} | {path, binary()}
  27. | {secure, true | false} | {http_only, true | false}.
  28. -export_type([kv/0]).
  29. -export_type([kvlist/0]).
  30. -export_type([cookie_option/0]).
  31. -define(QUOTE, $\").
  32. -include_lib("eunit/include/eunit.hrl").
  33. %% API.
  34. %% @doc Parse the contents of a Cookie header field, ignoring cookie
  35. %% attributes, and return a simple property list.
  36. -spec parse_cookie(binary()) -> kvlist().
  37. parse_cookie(<<>>) ->
  38. [];
  39. parse_cookie(Cookie) when is_binary(Cookie) ->
  40. parse_cookie(Cookie, []).
  41. %% @equiv cookie(Key, Value, [])
  42. -spec cookie(binary(), binary()) -> kv().
  43. cookie(Key, Value) when is_binary(Key) andalso is_binary(Value) ->
  44. cookie(Key, Value, []).
  45. %% @doc Generate a Set-Cookie header field tuple.
  46. -spec cookie(binary(), binary(), [cookie_option()]) -> kv().
  47. cookie(Key, Value, Options) when is_binary(Key)
  48. andalso is_binary(Value) andalso is_list(Options) ->
  49. Cookie = <<(any_to_binary(Key))/binary, "=",
  50. (quote(Value))/binary, "; Version=1">>,
  51. %% Set-Cookie:
  52. %% Comment, Domain, Max-Age, Path, Secure, Version
  53. ExpiresPart =
  54. case proplists:get_value(max_age, Options) of
  55. undefined ->
  56. <<"">>;
  57. RawAge ->
  58. When = case proplists:get_value(local_time, Options) of
  59. undefined ->
  60. calendar:local_time();
  61. LocalTime ->
  62. LocalTime
  63. end,
  64. Age = case RawAge < 0 of
  65. true ->
  66. 0;
  67. false ->
  68. RawAge
  69. end,
  70. AgeBinary = quote(Age),
  71. CookieDate = age_to_cookie_date(Age, When),
  72. <<"; Expires=", CookieDate/binary,
  73. "; Max-Age=", AgeBinary/binary>>
  74. end,
  75. SecurePart =
  76. case proplists:get_value(secure, Options) of
  77. true ->
  78. <<"; Secure">>;
  79. _ ->
  80. <<"">>
  81. end,
  82. DomainPart =
  83. case proplists:get_value(domain, Options) of
  84. undefined ->
  85. <<"">>;
  86. Domain ->
  87. <<"; Domain=", (quote(Domain))/binary>>
  88. end,
  89. PathPart =
  90. case proplists:get_value(path, Options) of
  91. undefined ->
  92. <<"">>;
  93. Path ->
  94. <<"; Path=", (quote(Path, true))/binary>>
  95. end,
  96. HttpOnlyPart =
  97. case proplists:get_value(http_only, Options) of
  98. true ->
  99. <<"; HttpOnly">>;
  100. _ ->
  101. <<"">>
  102. end,
  103. CookieParts = <<Cookie/binary, ExpiresPart/binary, SecurePart/binary,
  104. DomainPart/binary, PathPart/binary, HttpOnlyPart/binary>>,
  105. {<<"Set-Cookie">>, CookieParts}.
  106. %% Internal.
  107. %% @doc Check if a character is a white space character.
  108. -spec is_whitespace(char()) -> boolean().
  109. is_whitespace($\s) -> true;
  110. is_whitespace($\t) -> true;
  111. is_whitespace($\r) -> true;
  112. is_whitespace($\n) -> true;
  113. is_whitespace(_) -> false.
  114. %% @doc Check if a character is a separator.
  115. -spec is_separator(char()) -> boolean().
  116. is_separator(C) when C < 32 -> true;
  117. is_separator($\s) -> true;
  118. is_separator($\t) -> true;
  119. is_separator($() -> true;
  120. is_separator($)) -> true;
  121. is_separator($<) -> true;
  122. is_separator($>) -> true;
  123. is_separator($@) -> true;
  124. is_separator($,) -> true;
  125. is_separator($;) -> true;
  126. is_separator($:) -> true;
  127. is_separator($\\) -> true;
  128. is_separator(?QUOTE) -> true;
  129. is_separator($/) -> true;
  130. is_separator($[) -> true;
  131. is_separator($]) -> true;
  132. is_separator($?) -> true;
  133. is_separator($=) -> true;
  134. is_separator(${) -> true;
  135. is_separator($}) -> true;
  136. is_separator(_) -> false.
  137. %% @doc Check if a binary has an ASCII separator character.
  138. -spec has_separator(binary(), boolean()) -> boolean().
  139. has_separator(<<>>, _) ->
  140. false;
  141. has_separator(<<$/, Rest/binary>>, true) ->
  142. has_separator(Rest, true);
  143. has_separator(<<C, Rest/binary>>, IgnoreSlash) ->
  144. case is_separator(C) of
  145. true ->
  146. true;
  147. false ->
  148. has_separator(Rest, IgnoreSlash)
  149. end.
  150. %% @doc Convert to a binary and raise an error if quoting is required. Quoting
  151. %% is broken in different ways for different browsers. Its better to simply
  152. %% avoiding doing it at all.
  153. %% @end
  154. -spec quote(term(), boolean()) -> binary().
  155. quote(V0, IgnoreSlash) ->
  156. V = any_to_binary(V0),
  157. case has_separator(V, IgnoreSlash) of
  158. true ->
  159. erlang:error({cookie_quoting_required, V});
  160. false ->
  161. V
  162. end.
  163. %% @equiv quote(Bin, false)
  164. -spec quote(term()) -> binary().
  165. quote(V0) ->
  166. quote(V0, false).
  167. -spec add_seconds(integer(), calendar:datetime()) -> calendar:datetime().
  168. add_seconds(Secs, LocalTime) ->
  169. Greg = calendar:datetime_to_gregorian_seconds(LocalTime),
  170. calendar:gregorian_seconds_to_datetime(Greg + Secs).
  171. -spec age_to_cookie_date(integer(), calendar:datetime()) -> binary().
  172. age_to_cookie_date(Age, LocalTime) ->
  173. cowboy_clock:rfc2109(add_seconds(Age, LocalTime)).
  174. -spec parse_cookie(binary(), kvlist()) -> kvlist().
  175. parse_cookie(<<>>, Acc) ->
  176. lists:reverse(Acc);
  177. parse_cookie(String, Acc) ->
  178. {{Token, Value}, Rest} = read_pair(String),
  179. Acc1 = case Token of
  180. <<"">> ->
  181. Acc;
  182. <<"$", _R/binary>> ->
  183. Acc;
  184. _ ->
  185. [{Token, Value} | Acc]
  186. end,
  187. parse_cookie(Rest, Acc1).
  188. -spec read_pair(binary()) -> {{binary(), binary()}, binary()}.
  189. read_pair(String) ->
  190. {Token, Rest} = read_token(skip_whitespace(String)),
  191. {Value, Rest1} = read_value(skip_whitespace(Rest)),
  192. {{Token, Value}, skip_past_separator(Rest1)}.
  193. -spec read_value(binary()) -> {binary(), binary()}.
  194. read_value(<<"=", Value/binary>>) ->
  195. Value1 = skip_whitespace(Value),
  196. case Value1 of
  197. <<?QUOTE, _R/binary>> ->
  198. read_quoted(Value1);
  199. _ ->
  200. read_token(Value1)
  201. end;
  202. read_value(String) ->
  203. {<<"">>, String}.
  204. -spec read_quoted(binary()) -> {binary(), binary()}.
  205. read_quoted(<<?QUOTE, String/binary>>) ->
  206. read_quoted(String, <<"">>).
  207. -spec read_quoted(binary(), binary()) -> {binary(), binary()}.
  208. read_quoted(<<"">>, Acc) ->
  209. {Acc, <<"">>};
  210. read_quoted(<<?QUOTE, Rest/binary>>, Acc) ->
  211. {Acc, Rest};
  212. read_quoted(<<$\\, Any, Rest/binary>>, Acc) ->
  213. read_quoted(Rest, <<Acc/binary, Any>>);
  214. read_quoted(<<C, Rest/binary>>, Acc) ->
  215. read_quoted(Rest, <<Acc/binary, C>>).
  216. %% @doc Drop characters while a function returns true.
  217. -spec binary_dropwhile(fun((char()) -> boolean()), binary()) -> binary().
  218. binary_dropwhile(_F, <<"">>) ->
  219. <<"">>;
  220. binary_dropwhile(F, String) ->
  221. <<C, Rest/binary>> = String,
  222. case F(C) of
  223. true ->
  224. binary_dropwhile(F, Rest);
  225. false ->
  226. String
  227. end.
  228. %% @doc Remove leading whitespace.
  229. -spec skip_whitespace(binary()) -> binary().
  230. skip_whitespace(String) ->
  231. binary_dropwhile(fun is_whitespace/1, String).
  232. %% @doc Split a binary when the current character causes F to return true.
  233. -spec binary_splitwith(fun((char()) -> boolean()), binary(), binary())
  234. -> {binary(), binary()}.
  235. binary_splitwith(_F, Head, <<>>) ->
  236. {Head, <<>>};
  237. binary_splitwith(F, Head, Tail) ->
  238. <<C, NTail/binary>> = Tail,
  239. case F(C) of
  240. true ->
  241. {Head, Tail};
  242. false ->
  243. binary_splitwith(F, <<Head/binary, C>>, NTail)
  244. end.
  245. %% @doc Split a binary with a function returning true or false on each char.
  246. -spec binary_splitwith(fun((char()) -> boolean()), binary())
  247. -> {binary(), binary()}.
  248. binary_splitwith(F, String) ->
  249. binary_splitwith(F, <<>>, String).
  250. %% @doc Split the binary when the next separator is found.
  251. -spec read_token(binary()) -> {binary(), binary()}.
  252. read_token(String) ->
  253. binary_splitwith(fun is_separator/1, String).
  254. %% @doc Return string after ; or , characters.
  255. -spec skip_past_separator(binary()) -> binary().
  256. skip_past_separator(<<"">>) ->
  257. <<"">>;
  258. skip_past_separator(<<";", Rest/binary>>) ->
  259. Rest;
  260. skip_past_separator(<<",", Rest/binary>>) ->
  261. Rest;
  262. skip_past_separator(<<_C, Rest/binary>>) ->
  263. skip_past_separator(Rest).
  264. -spec any_to_binary(binary() | string() | atom() | integer()) -> binary().
  265. any_to_binary(V) when is_binary(V) ->
  266. V;
  267. any_to_binary(V) when is_list(V) ->
  268. erlang:list_to_binary(V);
  269. any_to_binary(V) when is_atom(V) ->
  270. erlang:atom_to_binary(V, latin1);
  271. any_to_binary(V) when is_integer(V) ->
  272. list_to_binary(integer_to_list(V)).
  273. %% Tests.
  274. -ifdef(TEST).
  275. quote_test() ->
  276. %% ?assertError eunit macro is not compatible with coverage module
  277. _ = try quote(<<":wq">>)
  278. catch error:{cookie_quoting_required, <<":wq">>} -> ok
  279. end,
  280. ?assertEqual(<<"foo">>,quote(foo)),
  281. _ = try quote(<<"/test/slashes/">>)
  282. catch error:{cookie_quoting_required, <<"/test/slashes/">>} -> ok
  283. end,
  284. ok.
  285. parse_cookie_test() ->
  286. %% RFC example
  287. C1 = <<"$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\";
  288. Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\";
  289. Shipping=\"FedEx\"; $Path=\"/acme\"">>,
  290. ?assertEqual(
  291. [{<<"Customer">>,<<"WILE_E_COYOTE">>},
  292. {<<"Part_Number">>,<<"Rocket_Launcher_0001">>},
  293. {<<"Shipping">>,<<"FedEx">>}],
  294. parse_cookie(C1)),
  295. %% Potential edge cases
  296. ?assertEqual(
  297. [{<<"foo">>, <<"x">>}],
  298. parse_cookie(<<"foo=\"\\x\"">>)),
  299. ?assertEqual(
  300. [],
  301. parse_cookie(<<"=">>)),
  302. ?assertEqual(
  303. [{<<"foo">>, <<"">>}, {<<"bar">>, <<"">>}],
  304. parse_cookie(<<" foo ; bar ">>)),
  305. ?assertEqual(
  306. [{<<"foo">>, <<"">>}, {<<"bar">>, <<"">>}],
  307. parse_cookie(<<"foo=;bar=">>)),
  308. ?assertEqual(
  309. [{<<"foo">>, <<"\";">>}, {<<"bar">>, <<"">>}],
  310. parse_cookie(<<"foo = \"\\\";\";bar ">>)),
  311. ?assertEqual(
  312. [{<<"foo">>, <<"\";bar">>}],
  313. parse_cookie(<<"foo=\"\\\";bar">>)),
  314. ?assertEqual(
  315. [],
  316. parse_cookie(<<"">>)),
  317. ?assertEqual(
  318. [{<<"foo">>, <<"bar">>}, {<<"baz">>, <<"wibble">>}],
  319. parse_cookie(<<"foo=bar , baz=wibble ">>)),
  320. ok.
  321. domain_test() ->
  322. ?assertEqual(
  323. {<<"Set-Cookie">>,
  324. <<"Customer=WILE_E_COYOTE; "
  325. "Version=1; "
  326. "Domain=acme.com; "
  327. "HttpOnly">>},
  328. cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  329. [{http_only, true}, {domain, <<"acme.com">>}])),
  330. ok.
  331. local_time_test() ->
  332. {<<"Set-Cookie">>, B} = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  333. [{max_age, 111}, {secure, true}]),
  334. ?assertMatch(
  335. [<<"Customer=WILE_E_COYOTE">>,
  336. <<" Version=1">>,
  337. <<" Expires=", _R/binary>>,
  338. <<" Max-Age=111">>,
  339. <<" Secure">>],
  340. binary:split(B, <<";">>, [global])),
  341. ok.
  342. -spec cookie_test() -> no_return(). %% Not actually true, just a bad option.
  343. cookie_test() ->
  344. C1 = {<<"Set-Cookie">>,
  345. <<"Customer=WILE_E_COYOTE; "
  346. "Version=1; "
  347. "Path=/acme">>},
  348. C1 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>, [{path, <<"/acme">>}]),
  349. C1 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  350. [{path, <<"/acme">>}, {badoption, <<"negatory">>}]),
  351. {<<"Set-Cookie">>,<<"=NoKey; Version=1">>}
  352. = cookie(<<"">>, <<"NoKey">>, []),
  353. {<<"Set-Cookie">>,<<"=NoKey; Version=1">>}
  354. = cookie(<<"">>, <<"NoKey">>),
  355. LocalTime = calendar:universal_time_to_local_time(
  356. {{2007, 5, 15}, {13, 45, 33}}),
  357. C2 = {<<"Set-Cookie">>,
  358. <<"Customer=WILE_E_COYOTE; "
  359. "Version=1; "
  360. "Expires=Tue, 15 May 2007 13:45:33 GMT; "
  361. "Max-Age=0">>},
  362. C2 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  363. [{max_age, -111}, {local_time, LocalTime}]),
  364. C3 = {<<"Set-Cookie">>,
  365. <<"Customer=WILE_E_COYOTE; "
  366. "Version=1; "
  367. "Expires=Wed, 16 May 2007 13:45:50 GMT; "
  368. "Max-Age=86417">>},
  369. C3 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  370. [{max_age, 86417}, {local_time, LocalTime}]),
  371. ok.
  372. -endif.