cowboy_cookies.erl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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, {cowboy_clock:date(), cowboy_clock:time()}}
  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))/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 seperator.
  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 seperator character.
  133. -spec has_seperator(binary()) -> boolean().
  134. has_seperator(<<>>) ->
  135. false;
  136. has_seperator(<<$/, Rest/binary>>) ->
  137. has_seperator(Rest);
  138. has_seperator(<<C, Rest/binary>>) ->
  139. case is_separator(C) of
  140. true ->
  141. true;
  142. false ->
  143. has_seperator(Rest)
  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()) -> binary().
  150. quote(V0) ->
  151. V = any_to_binary(V0),
  152. case has_seperator(V) of
  153. true ->
  154. erlang:error({cookie_quoting_required, V});
  155. false ->
  156. V
  157. end.
  158. -spec add_seconds(integer(), cowboy_clock:datetime())
  159. -> cowboy_clock:datetime().
  160. add_seconds(Secs, LocalTime) ->
  161. Greg = calendar:datetime_to_gregorian_seconds(LocalTime),
  162. calendar:gregorian_seconds_to_datetime(Greg + Secs).
  163. -spec age_to_cookie_date(integer(), cowboy_clock:datetime()) -> binary().
  164. age_to_cookie_date(Age, LocalTime) ->
  165. cowboy_clock:rfc2109(add_seconds(Age, LocalTime)).
  166. -spec parse_cookie(binary(), kvlist()) -> kvlist().
  167. parse_cookie(<<>>, Acc) ->
  168. lists:reverse(Acc);
  169. parse_cookie(String, Acc) ->
  170. {{Token, Value}, Rest} = read_pair(String),
  171. Acc1 = case Token of
  172. <<"">> ->
  173. Acc;
  174. <<"$", _R/binary>> ->
  175. Acc;
  176. _ ->
  177. [{Token, Value} | Acc]
  178. end,
  179. parse_cookie(Rest, Acc1).
  180. -spec read_pair(binary()) -> {{binary(), binary()}, binary()}.
  181. read_pair(String) ->
  182. {Token, Rest} = read_token(skip_whitespace(String)),
  183. {Value, Rest1} = read_value(skip_whitespace(Rest)),
  184. {{Token, Value}, skip_past_separator(Rest1)}.
  185. -spec read_value(binary()) -> {binary(), binary()}.
  186. read_value(<<"=", Value/binary>>) ->
  187. Value1 = skip_whitespace(Value),
  188. case Value1 of
  189. <<?QUOTE, _R/binary>> ->
  190. read_quoted(Value1);
  191. _ ->
  192. read_token(Value1)
  193. end;
  194. read_value(String) ->
  195. {<<"">>, String}.
  196. -spec read_quoted(binary()) -> {binary(), binary()}.
  197. read_quoted(<<?QUOTE, String/binary>>) ->
  198. read_quoted(String, <<"">>).
  199. -spec read_quoted(binary(), binary()) -> {binary(), binary()}.
  200. read_quoted(<<"">>, Acc) ->
  201. {Acc, <<"">>};
  202. read_quoted(<<?QUOTE, Rest/binary>>, Acc) ->
  203. {Acc, Rest};
  204. read_quoted(<<$\\, Any, Rest/binary>>, Acc) ->
  205. read_quoted(Rest, <<Acc/binary, Any>>);
  206. read_quoted(<<C, Rest/binary>>, Acc) ->
  207. read_quoted(Rest, <<Acc/binary, C>>).
  208. %% @doc Drop characters while a function returns true.
  209. -spec binary_dropwhile(fun((char()) -> boolean()), binary()) -> binary().
  210. binary_dropwhile(_F, <<"">>) ->
  211. <<"">>;
  212. binary_dropwhile(F, String) ->
  213. <<C, Rest/binary>> = String,
  214. case F(C) of
  215. true ->
  216. binary_dropwhile(F, Rest);
  217. false ->
  218. String
  219. end.
  220. %% @doc Remove leading whitespace.
  221. -spec skip_whitespace(binary()) -> binary().
  222. skip_whitespace(String) ->
  223. binary_dropwhile(fun is_whitespace/1, String).
  224. %% @doc Split a binary when the current character causes F to return true.
  225. -spec binary_splitwith(fun((char()) -> boolean()), binary(), binary())
  226. -> {binary(), binary()}.
  227. binary_splitwith(_F, Head, <<>>) ->
  228. {Head, <<>>};
  229. binary_splitwith(F, Head, Tail) ->
  230. <<C, NTail/binary>> = Tail,
  231. case F(C) of
  232. true ->
  233. {Head, Tail};
  234. false ->
  235. binary_splitwith(F, <<Head/binary, C>>, NTail)
  236. end.
  237. %% @doc Split a binary with a function returning true or false on each char.
  238. -spec binary_splitwith(fun((char()) -> boolean()), binary())
  239. -> {binary(), binary()}.
  240. binary_splitwith(F, String) ->
  241. binary_splitwith(F, <<>>, String).
  242. %% @doc Split the binary when the next seperator is found.
  243. -spec read_token(binary()) -> {binary(), binary()}.
  244. read_token(String) ->
  245. binary_splitwith(fun is_separator/1, String).
  246. %% @doc Return string after ; or , characters.
  247. -spec skip_past_separator(binary()) -> binary().
  248. skip_past_separator(<<"">>) ->
  249. <<"">>;
  250. skip_past_separator(<<";", Rest/binary>>) ->
  251. Rest;
  252. skip_past_separator(<<",", Rest/binary>>) ->
  253. Rest;
  254. skip_past_separator(<<_C, Rest/binary>>) ->
  255. skip_past_separator(Rest).
  256. -spec any_to_binary(binary() | string() | atom() | integer()) -> binary().
  257. any_to_binary(V) when is_binary(V) ->
  258. V;
  259. any_to_binary(V) when is_list(V) ->
  260. erlang:list_to_binary(V);
  261. any_to_binary(V) when is_atom(V) ->
  262. erlang:atom_to_binary(V, latin1);
  263. any_to_binary(V) when is_integer(V) ->
  264. list_to_binary(integer_to_list(V)).
  265. %% Tests.
  266. -ifdef(TEST).
  267. quote_test() ->
  268. %% ?assertError eunit macro is not compatible with coverage module
  269. _ = try quote(<<":wq">>)
  270. catch error:{cookie_quoting_required, <<":wq">>} -> ok
  271. end,
  272. ?assertEqual(<<"foo">>,quote(foo)),
  273. ok.
  274. parse_cookie_test() ->
  275. %% RFC example
  276. C1 = <<"$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\";
  277. Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\";
  278. Shipping=\"FedEx\"; $Path=\"/acme\"">>,
  279. ?assertEqual(
  280. [{<<"Customer">>,<<"WILE_E_COYOTE">>},
  281. {<<"Part_Number">>,<<"Rocket_Launcher_0001">>},
  282. {<<"Shipping">>,<<"FedEx">>}],
  283. parse_cookie(C1)),
  284. %% Potential edge cases
  285. ?assertEqual(
  286. [{<<"foo">>, <<"x">>}],
  287. parse_cookie(<<"foo=\"\\x\"">>)),
  288. ?assertEqual(
  289. [],
  290. parse_cookie(<<"=">>)),
  291. ?assertEqual(
  292. [{<<"foo">>, <<"">>}, {<<"bar">>, <<"">>}],
  293. parse_cookie(<<" foo ; bar ">>)),
  294. ?assertEqual(
  295. [{<<"foo">>, <<"">>}, {<<"bar">>, <<"">>}],
  296. parse_cookie(<<"foo=;bar=">>)),
  297. ?assertEqual(
  298. [{<<"foo">>, <<"\";">>}, {<<"bar">>, <<"">>}],
  299. parse_cookie(<<"foo = \"\\\";\";bar ">>)),
  300. ?assertEqual(
  301. [{<<"foo">>, <<"\";bar">>}],
  302. parse_cookie(<<"foo=\"\\\";bar">>)),
  303. ?assertEqual(
  304. [],
  305. parse_cookie(<<"">>)),
  306. ?assertEqual(
  307. [{<<"foo">>, <<"bar">>}, {<<"baz">>, <<"wibble">>}],
  308. parse_cookie(<<"foo=bar , baz=wibble ">>)),
  309. ok.
  310. domain_test() ->
  311. ?assertEqual(
  312. {<<"Set-Cookie">>,
  313. <<"Customer=WILE_E_COYOTE; "
  314. "Version=1; "
  315. "Domain=acme.com; "
  316. "HttpOnly">>},
  317. cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  318. [{http_only, true}, {domain, <<"acme.com">>}])),
  319. ok.
  320. local_time_test() ->
  321. {<<"Set-Cookie">>, B} = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  322. [{max_age, 111}, {secure, true}]),
  323. ?assertMatch(
  324. [<<"Customer=WILE_E_COYOTE">>,
  325. <<" Version=1">>,
  326. <<" Expires=", _R/binary>>,
  327. <<" Max-Age=111">>,
  328. <<" Secure">>],
  329. binary:split(B, <<";">>, [global])),
  330. ok.
  331. -spec cookie_test() -> no_return(). %% Not actually true, just a bad option.
  332. cookie_test() ->
  333. C1 = {<<"Set-Cookie">>,
  334. <<"Customer=WILE_E_COYOTE; "
  335. "Version=1; "
  336. "Path=/acme">>},
  337. C1 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>, [{path, <<"/acme">>}]),
  338. C1 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  339. [{path, <<"/acme">>}, {badoption, <<"negatory">>}]),
  340. {<<"Set-Cookie">>,<<"=NoKey; Version=1">>}
  341. = cookie(<<"">>, <<"NoKey">>, []),
  342. {<<"Set-Cookie">>,<<"=NoKey; Version=1">>}
  343. = cookie(<<"">>, <<"NoKey">>),
  344. LocalTime = calendar:universal_time_to_local_time(
  345. {{2007, 5, 15}, {13, 45, 33}}),
  346. C2 = {<<"Set-Cookie">>,
  347. <<"Customer=WILE_E_COYOTE; "
  348. "Version=1; "
  349. "Expires=Tue, 15 May 2007 13:45:33 GMT; "
  350. "Max-Age=0">>},
  351. C2 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  352. [{max_age, -111}, {local_time, LocalTime}]),
  353. C3 = {<<"Set-Cookie">>,
  354. <<"Customer=WILE_E_COYOTE; "
  355. "Version=1; "
  356. "Expires=Wed, 16 May 2007 13:45:50 GMT; "
  357. "Max-Age=86417">>},
  358. C3 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
  359. [{max_age, 86417}, {local_time, LocalTime}]),
  360. ok.
  361. -endif.