Debian Codegraph @

t/unit/core/cookie.t

raw
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Fatal qw<exception>;
6
7 use Dancer2::Core::Cookie;
8 use Dancer2::Core::Time;
9
10 # Cookie header generation and the time expressions that feed the Expires
11 # attribute.
12 #
13 # Time expressions come in two kinds, and the difference is easy to get wrong:
14 #
15 # a bare digit string -> an absolute Unix epoch
16 # anything else -> an offset from now ("2 hours", "1h30m", "1w")
17 #
18 # So expires => 3600 is 1 Jan 1970, not "in an hour". That is what
19 # Dancer2::Core::Cookie's own documentation says ("Unix epoch time like
20 # 1288817656 ... It also supports a human readable offset from the current time
21 # such as '2 hours'"), and Dancer2::Core::Session compensates for it by adding
22 # time() before handing the value over. Both halves are pinned below.
23 #
24 # Absolute epochs are used wherever an exact string is asserted, so no clock
25 # needs faking. 1288817656 is the value from the module's own POD, together
26 # with the string that POD says it produces.
27
28 my $POD_EPOCH = 1288817656;
29 my $POD_STRING = 'Wed, 03-Nov-2010 20:54:16 GMT';
30
31 sub header_for {
32 return Dancer2::Core::Cookie->new(@_)->pp_to_header;
33 }
34
35 # Split a Set-Cookie header into its name=value pair plus the sorted set of
36 # its attributes, for comparing two headers that must carry the same
37 # information without asserting an order they do not have. RFC 6265 gives
38 # Set-Cookie attributes no significant order, and the XS builder does not
39 # emit them in a stable one -- see the XS-versus-pure-Perl subtest below.
40 sub header_parts {
41 my ( $name_value, @attributes ) = split /; /, shift;
42 return [ $name_value, sort @attributes ];
43 }
44
45 # --- time expressions ----------------------------------------------------
46
47 subtest 'a bare number is an absolute epoch' => sub {
48 my $time = Dancer2::Core::Time->new( expression => $POD_EPOCH );
49
50 is( $time->epoch, $POD_EPOCH, 'the epoch is the number itself' );
51 is( $time->gmt_string, $POD_STRING,
52 'and formats to the string the documentation promises' );
53
54 # Not time() + 1288817656, which is what treating it as an offset would
55 # give. Asserted explicitly because it is the confusing half.
56 cmp_ok( $time->epoch, '<', time,
57 'a 2010 epoch stays in the past rather than being added to now' );
58
59 # The consequence, stated plainly: a number that looks like a duration is
60 # interpreted as an epoch in 1970.
61 is( Dancer2::Core::Time->new( expression => 3600 )->gmt_string,
62 'Thu, 01-Jan-1970 01:00:00 GMT',
63 'expires => 3600 means one hour after the epoch, not one hour from now' );
64 };
65
66 subtest 'a human-readable expression is an offset from now' => sub {
67 my $now = time;
68
69 my %offset = (
70 '1s' => 1,
71 '1m' => 60,
72 '1h' => 3600,
73 '2 hours' => 7200,
74 '1d' => 86400,
75 '1w' => 604800,
76 '1y' => 31536000,
77 '1h30m' => 5400,
78 '1.5h' => 5400,
79 '01:30' => 5400,
80 '01:30:00' => 5400,
81 );
82
83 for my $expression ( sort keys %offset ) {
84 my $seconds = $offset{$expression};
85 my $time = Dancer2::Core::Time->new( expression => $expression );
86
87 is( $time->seconds, $seconds,
88 "'$expression' is $seconds seconds" );
89
90 # The epoch is now + seconds. Allowing a few seconds of slack keeps
91 # this from being flaky if the clock ticks mid-test.
92 cmp_ok( $time->epoch, '>=', $now + $seconds,
93 "'$expression' resolves to a time at least that far ahead" );
94 cmp_ok( $time->epoch, '<=', $now + $seconds + 10,
95 "'$expression' resolves to a time not much further ahead" );
96 }
97
98 # 'M' is months and 'm' is minutes: single-character units are not
99 # lower-cased, and confusing them is a factor of 43200.
100 is( Dancer2::Core::Time->new( expression => '1M' )->seconds, 2592000,
101 'a capital M is one month' );
102 is( Dancer2::Core::Time->new( expression => '1m' )->seconds, 60,
103 'while a lower-case m is one minute' );
104
105 # A negative offset is how a cookie is expired in the past - this is what
106 # destroy_session relies on.
107 my $past = Dancer2::Core::Time->new( expression => -86400 );
108 is( $past->seconds, -86400, 'a negative expression stays negative' );
109 cmp_ok( $past->epoch, '<', time, 'and resolves to a time in the past' );
110 };
111
112 subtest 'an unparseable expression is passed through unchanged' => sub {
113 # Deliberate: Dancer2::Core::Time documents that "anything else is used
114 # verbatim". Silently turning it into a wrong date would be worse - the
115 # value reaches the header where it is visible.
116 for my $expression ( 'not a time', '3 fortnights', '2 hours and cheese' ) {
117 my $time = Dancer2::Core::Time->new( expression => $expression );
118
119 is( $time->seconds, $expression, "'$expression': seconds is verbatim" );
120 is( $time->epoch, $expression, "'$expression': epoch is verbatim" );
121 is( $time->gmt_string, $expression, "'$expression': gmt_string is verbatim" );
122 }
123
124 # A partially-valid expression is rejected whole, not silently truncated
125 # to the part that parsed.
126 isnt( Dancer2::Core::Time->new( expression => '2 hours and cheese' )->seconds,
127 7200, 'the parseable prefix of a bad expression is not used on its own' );
128 };
129
130 # --- cookie headers ------------------------------------------------------
131
132 subtest 'a minimal cookie gets a path and HttpOnly' => sub {
133 is( header_for( name => 'n', value => 'v' ), 'n=v; Path=/; HttpOnly',
134 'name, value, the default path, and HttpOnly' );
135 };
136
137 subtest 'every attribute reaches the header' => sub {
138 my $header = header_for(
139 name => 'sid',
140 value => 'abc',
141 path => '/app',
142 domain => '.example.com',
143 expires => $POD_EPOCH,
144 same_site => 'Strict',
145 secure => 1,
146 http_only => 1,
147 );
148
149 # Asserted as one exact string: it pins the attribute order too, which a
150 # set of independent regexes would not.
151 is(
152 $header,
153 "sid=abc; Path=/app; Expires=$POD_STRING; Domain=.example.com;"
154 . ' SameSite=Strict; Secure; HttpOnly',
155 'all attributes are present, in order',
156 );
157
158 # And individually, so a failure says which one went missing.
159 like( $header, qr/\bPath=\/app\b/, 'Path' );
160 like( $header, qr/\bExpires=\Q$POD_STRING\E/, 'Expires' );
161 like( $header, qr/\bDomain=\.example\.com\b/, 'Domain' );
162 like( $header, qr/\bSameSite=Strict\b/, 'SameSite' );
163 like( $header, qr/\bSecure\b/, 'Secure' );
164 like( $header, qr/\bHttpOnly\b/, 'HttpOnly' );
165 };
166
167 subtest 'the boolean attributes are omitted rather than negated' => sub {
168 # There is no "Secure=0" in HTTP - a false flag means the attribute is
169 # absent.
170 unlike( header_for( name => 'n', value => 'v', secure => 0 ), qr/Secure/,
171 'secure => 0 omits Secure' );
172 like( header_for( name => 'n', value => 'v', secure => 1 ), qr/; Secure\b/,
173 'secure => 1 emits it' );
174
175 unlike( header_for( name => 'n', value => 'v', http_only => 0 ), qr/HttpOnly/,
176 'http_only => 0 omits HttpOnly' );
177 like( header_for( name => 'n', value => 'v', http_only => 1 ), qr/HttpOnly/,
178 'http_only => 1 emits it' );
179
180 # HttpOnly is on by default, so leaving it out is not the same as
181 # turning it off.
182 like( header_for( name => 'n', value => 'v' ), qr/HttpOnly/,
183 'HttpOnly is emitted when nothing was said about it' );
184
185 # A falsy path is omitted too.
186 unlike( header_for( name => 'n', value => 'v', path => '' ), qr/Path/,
187 'an empty path omits the Path attribute' );
188 };
189
190 subtest 'same_site only accepts the values the standard defines' => sub {
191 for my $value (qw< Strict Lax None >) {
192 like( header_for( name => 'n', value => 'v', same_site => $value ),
193 qr/\bSameSite=$value\b/, "SameSite=$value is accepted" );
194 }
195
196 # A typo is refused at construction rather than emitted as a header a
197 # browser would ignore.
198 ok(
199 defined exception {
200 Dancer2::Core::Cookie->new(
201 name => 'n', value => 'v', same_site => 'strict' )
202 },
203 'a lower-case value is refused',
204 );
205 ok(
206 defined exception {
207 Dancer2::Core::Cookie->new(
208 name => 'n', value => 'v', same_site => 'Nonsense' )
209 },
210 'and so is a value that is not in the enum',
211 );
212 };
213
214 subtest 'a multi-value cookie keeps every value, escaped' => sub {
215 is( header_for( name => 'n', value => [ 'a', 'b', 'c' ] ),
216 'n=a&b&c; Path=/; HttpOnly',
217 'values are joined with an ampersand' );
218
219 # Each value is escaped individually, so a separator inside a value cannot
220 # be mistaken for a separator between values.
221 is( header_for( name => 'n', value => [ 'a b', 'c;d' ] ),
222 'n=a%20b&c%3Bd; Path=/; HttpOnly',
223 'each value is URI-escaped on its own' );
224
225 # A single value with every character that would otherwise confuse a
226 # parser.
227 is( header_for( name => 'n', value => 'a b;c,d=e&f' ),
228 'n=a%20b%3Bc%2Cd%3De%26f; Path=/; HttpOnly',
229 'space, semicolon, comma, equals and ampersand are all escaped' );
230
231 my $cookie = Dancer2::Core::Cookie->new( name => 'n', value => [ 'a', 'b' ] );
232 is_deeply( [ $cookie->value ], [ 'a', 'b' ],
233 'the accessor returns every value in list context' );
234 is_deeply( [ $cookie->values ], [ 'a', 'b' ],
235 'and values() does the same' );
236 is( scalar $cookie->value, 'a',
237 'while scalar context gives the first' );
238 is( "$cookie", 'a',
239 'and stringification gives the first, per the documented overload' );
240 };
241
242 subtest 'an unparseable expires reaches the header verbatim' => sub {
243 # Following from the Time behavior above: the bad value is visible in the
244 # header rather than being turned into a plausible-looking wrong date.
245 my $header = header_for( name => 'n', value => 'v', expires => 'not a time' );
246
247 is( $header, 'n=v; Path=/; Expires=not a time; HttpOnly',
248 'the expression appears as given' );
249 unlike( $header, qr/1970|GMT/,
250 'and is not converted into a date' );
251 };
252
253 subtest 'the XS header builder agrees with the pure-Perl one' => sub {
254 # Dancer2::Core::Cookie picks one of two implementations at load time and
255 # aliases to_header to it. Both must produce the same header, or which
256 # optional modules happen to be installed changes the response.
257 SKIP: {
258 skip 'HTTP::XSCookies is not installed, so xs_to_header cannot run', 3
259 if !Dancer2::Core::Cookie::_USE_XS();
260
261 my %args = (
262 name => 'sid',
263 value => 'abc',
264 path => '/app',
265 expires => $POD_EPOCH,
266 secure => 1,
267 http_only => 1,
268 );
269 my $cookie = Dancer2::Core::Cookie->new(%args);
270
271 my $xs = $cookie->xs_to_header;
272 like( $xs, qr/^sid=abc/, 'the XS builder emits the name and value' );
273 like( $xs, qr/\bSecure\b/, 'and the Secure attribute' );
274
275 # Multi-value cookies are explicitly delegated to the pure-Perl
276 # builder, so those must match exactly.
277 my $multi = Dancer2::Core::Cookie->new(
278 name => 'n', value => [ 'a', 'b' ] );
279 is( $multi->xs_to_header, $multi->pp_to_header,
280 'a multi-value cookie is delegated to the pure-Perl builder' );
281 }
282
283 # Whichever implementation is active, to_header must be one of the two -
284 # asserted unconditionally so this subtest is never vacuous.
285 #
286 # Compared as a set rather than as a string. HTTP::XSCookies::bake_cookie
287 # is handed a hashref and walks it to build the attribute list, so with
288 # XS active the order of Path, HttpOnly and the rest varies from call to
289 # call -- two calls in one process can disagree:
290 #
291 # to_header n=v; Path=/; HttpOnly
292 # xs_to_header n=v; HttpOnly; Path=/
293 #
294 # Asserting the string would fail about half the time. RFC 6265 gives
295 # these attributes no significant order, so the content is what matters
296 # and is all this can honestly check.
297 my $cookie = Dancer2::Core::Cookie->new( name => 'n', value => 'v' );
298 my $expected = Dancer2::Core::Cookie::_USE_XS()
299 ? $cookie->xs_to_header
300 : $cookie->pp_to_header;
301 is_deeply( header_parts( $cookie->to_header ), header_parts($expected),
302 'to_header is aliased to the implementation this build selected' );
303 };
304
305 done_testing();