cowboy_cookies.erl 12 KB

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