Debian Codegraph @

t/integration/session/lifecycle.t

raw
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Plack::Test;
6 use HTTP::Request::Common;
7 use HTTP::Date ();
8
9 # Session lifecycle end to end: what survives destroy_session and
10 # change_session_id, when the store is actually written, and what the
11 # Set-Cookie header says.
12 #
13 # Two things about the setup are load-bearing:
14 #
15 # 1. 'set engines' must come BEFORE 'set session'. Setting 'session' fires a
16 # config trigger that builds the session engine immediately, reading the
17 # 'engines' config as it stands at that moment
18 # (Dancer2/Core/App.pm:199-217). Written the other way round, the engine
19 # options are silently ignored and every cookie assertion below would be
20 # testing the defaults while appearing to test the configured values.
21 #
22 # 2. Dancer2::Session::Simple keeps all sessions in one package-level hash
23 # shared by every app in the process, so a count of stored sessions is not
24 # a meaningful assertion here. The tests ask whether one specific id is
25 # present instead, which is unaffected by the other apps in this file.
26 #
27 # Writes to the store are counted through the engine's own
28 # 'engine.session.before_flush' hook - the framework's own instrumentation,
29 # so nothing is faked.
30
31 {
32 package SessApp;
33 use Dancer2;
34 set logger => 'null';
35 set session => 'Simple';
36
37 our @flushed;
38 hook 'engine.session.before_flush' => sub { push @flushed, $_[0]->id };
39
40 get '/write' => sub { session foo => 'bar'; session->id };
41 get '/read' => sub { 'foo=' . ( session('foo') // 'undef' ) };
42 get '/id' => sub { session->id };
43
44 # Touches no session at all - not even a read.
45 get '/untouched' => sub { 'nothing' };
46
47 # Is this id in the store right now?
48 get '/stored' => sub {
49 my $id = query_parameters->get('id');
50 return ( grep { $_ eq $id } @{ app->session_engine->sessions } )
51 ? 'PRESENT'
52 : 'ABSENT';
53 };
54
55 get '/destroy' => sub {
56 session foo => 'bar';
57 my $id = session->id;
58 app->destroy_session;
59 return "id=$id after=" . ( session('foo') // 'undef' );
60 };
61
62 get '/change-id' => sub {
63 session foo => 'bar';
64 my $old = session->id;
65 my $new = app->change_session_id;
66 return join ' ',
67 "old=$old",
68 "new=$new",
69 'data=' . ( session('foo') // 'undef' ),
70 'current=' . session->id;
71 };
72 }
73
74 # Every attribute the session cookie can carry, all set at once.
75 {
76 package HardenedApp;
77 use Dancer2;
78 set logger => 'null';
79 set engines => {
80 session => {
81 Simple => {
82 cookie_name => 'my.sid',
83 cookie_path => '/app',
84 cookie_duration => '2 hours',
85 cookie_same_site => 'lax', # deliberately lower case
86 is_secure => 1,
87 }
88 }
89 };
90 set session => 'Simple';
91
92 get '/write' => sub { session foo => 'bar'; 'ok' };
93 }
94
95 {
96 package NoHttpOnlyApp;
97 use Dancer2;
98 set logger => 'null';
99 set engines => { session => { Simple => { is_http_only => 0 } } };
100 set session => 'Simple';
101
102 get '/write' => sub { session foo => 'bar'; 'ok' };
103 }
104
105 # --- helpers --------------------------------------------------------------
106
107 # The cookie as a client would send it back: name=value, attributes dropped.
108 sub cookie_pair {
109 my $set_cookie = shift;
110 defined $set_cookie or return undef;
111 ( my $pair = $set_cookie ) =~ s/;.*//;
112 return $pair;
113 }
114
115 sub get_with_cookie {
116 my ( $test, $path, $cookie ) = @_;
117 my $req = GET "http://localhost$path";
118 defined $cookie and $req->header( Cookie => $cookie );
119 return $test->request($req);
120 }
121
122 # --- tests ---------------------------------------------------------------
123
124 subtest 'a session survives across requests and is written once' => sub {
125 my $test = Plack::Test->create( SessApp->to_app );
126
127 @SessApp::flushed = ();
128 my $first = $test->request( GET '/write' );
129 my $id = $first->content;
130 my $cookie = cookie_pair( $first->header('Set-Cookie') );
131
132 ok( length $id, 'the first request has a session id' );
133 ok( defined $cookie, 'and sends a session cookie' );
134 is( scalar @SessApp::flushed, 1,
135 'writing to the session flushes it to the store exactly once' );
136
137 is( get_with_cookie( $test, '/read', $cookie )->content, 'foo=bar',
138 'a later request carrying the cookie reads the value back' );
139
140 is( $test->request( GET '/read' )->content, 'foo=undef',
141 'a request without the cookie gets a different, empty session' );
142 };
143
144 subtest 'a session that was not modified is not written back' => sub {
145 my $test = Plack::Test->create( SessApp->to_app );
146
147 my $first = $test->request( GET '/write' );
148 my $cookie = cookie_pair( $first->header('Set-Cookie') );
149
150 # A read is not a modification. This is the assertion that goes red if
151 # is_dirty stops gating the flush - every request would write to the
152 # store, on every backend, forever.
153 @SessApp::flushed = ();
154 my $read = get_with_cookie( $test, '/read', $cookie );
155 is( $read->content, 'foo=bar', 'the value is still readable' );
156 is( scalar @SessApp::flushed, 0,
157 'reading the session does not write it back to the store' );
158
159 # No session keyword used at all, but the cookie is still echoed back so
160 # the client keeps its session. Nothing is retrieved or written for it.
161 @SessApp::flushed = ();
162 my $untouched = get_with_cookie( $test, '/untouched', $cookie );
163 is( scalar @SessApp::flushed, 0,
164 'a request that never touches the session does not write it either' );
165 is( cookie_pair( $untouched->header('Set-Cookie') ), $cookie,
166 'and the session cookie is still returned unchanged' );
167
168 # Without a cookie there is no session to speak of, so no cookie is set.
169 my $bare = $test->request( GET '/untouched' );
170 is( $bare->header('Set-Cookie'), undef,
171 'a request with no cookie that never touches the session gets none' );
172 };
173
174 subtest 'destroy_session discards the data and expires the cookie' => sub {
175 my $test = Plack::Test->create( SessApp->to_app );
176
177 my $res = $test->request( GET '/destroy' );
178 my ($id) = $res->content =~ /id=(\S+)/;
179
180 like( $res->content, qr/after=undef/,
181 'the data is gone from the session within the same request' );
182
183 is( get_with_cookie( $test, "/stored?id=$id" )->content, 'ABSENT',
184 'and the session is gone from the store' );
185
186 my $set_cookie = $res->header('Set-Cookie');
187 like( $set_cookie, qr/\bExpires=/,
188 'the response cookie carries an Expires attribute' );
189
190 my ($expires) = $set_cookie =~ /Expires=([^;]+)/;
191 my $epoch = HTTP::Date::str2time($expires);
192 ok( defined $epoch, "the Expires value parses as a date ($expires)" );
193 cmp_ok( $epoch, '<', time,
194 'and it is in the past, so the client drops the cookie' );
195
196 # The destroyed id must not still be usable. Replaying the old cookie has
197 # to produce a new session, not resurrect the old one.
198 my $replay = get_with_cookie( $test, '/read', "dancer.session=$id" );
199 is( $replay->content, 'foo=undef',
200 'replaying the destroyed cookie does not bring the data back' );
201 isnt( cookie_pair( $replay->header('Set-Cookie') ), "dancer.session=$id",
202 'and a fresh session id is issued instead' );
203 };
204
205 subtest 'change_session_id keeps the data and retires the old id' => sub {
206 my $test = Plack::Test->create( SessApp->to_app );
207
208 my $res = $test->request( GET '/change-id' );
209 my ($old) = $res->content =~ /old=(\S+)/;
210 my ($new) = $res->content =~ /new=(\S+)/;
211
212 isnt( $new, $old, 'the id actually changes' );
213 like( $res->content, qr/\bdata=bar\b/,
214 'the session data survives the change' );
215 like( $res->content, qr/current=\Q$new\E/,
216 'and the app is now on the new id' );
217
218 is( cookie_pair( $res->header('Set-Cookie') ), "dancer.session=$new",
219 'the response cookie carries the new id, not the old one' );
220
221 # Session fixation: the old id must not remain a usable session.
222 is( get_with_cookie( $test, "/stored?id=$old" )->content, 'ABSENT',
223 'the old id is removed from the store' );
224 is( get_with_cookie( $test, "/stored?id=$new" )->content, 'PRESENT',
225 'and the new id is in the store' );
226
227 is( get_with_cookie( $test, '/read', "dancer.session=$new" )->content,
228 'foo=bar', 'the data is readable under the new id' );
229 is( get_with_cookie( $test, '/read', "dancer.session=$old" )->content,
230 'foo=undef', 'and not under the old one' );
231 };
232
233 subtest 'the session cookie is HttpOnly by default' => sub {
234 my $test = Plack::Test->create( SessApp->to_app );
235 my $set_cookie = $test->request( GET '/write' )->header('Set-Cookie');
236
237 like( $set_cookie, qr/\bHttpOnly\b/,
238 'HttpOnly is present without being asked for' );
239 like( $set_cookie, qr{^dancer\.session=},
240 'under the default cookie name' );
241 like( $set_cookie, qr{\bPath=/},
242 'with the default path' );
243
244 # Off by default, and correctly so - Secure would break a plain-HTTP
245 # development server. Asserted so that a change of default is visible.
246 unlike( $set_cookie, qr/\bSecure\b/,
247 'Secure is not set unless configured' );
248 unlike( $set_cookie, qr/\bSameSite=/,
249 'SameSite is not set unless configured' );
250 unlike( $set_cookie, qr/\bExpires=/,
251 'and there is no Expires, so it is a browser-session cookie' );
252 };
253
254 subtest 'configured cookie attributes reach the header' => sub {
255 my $test = Plack::Test->create( HardenedApp->to_app );
256 my $set_cookie = $test->request( GET '/write' )->header('Set-Cookie');
257
258 like( $set_cookie, qr{^my\.sid=}, 'cookie_name is used' );
259 like( $set_cookie, qr{\bPath=/app\b}, 'cookie_path is used' );
260 like( $set_cookie, qr/\bSecure\b/, 'is_secure adds Secure' );
261 like( $set_cookie, qr/\bHttpOnly\b/, 'HttpOnly is still there too' );
262
263 # 'lax' was configured; the attribute coerces to ucfirst, because
264 # SameSite values are case-sensitive to some clients.
265 like( $set_cookie, qr/\bSameSite=Lax\b/,
266 'cookie_same_site is capitalised on the way out' );
267
268 # cookie_duration '2 hours' becomes an absolute expiry in the future.
269 # The exact instant is not asserted - it depends on when the test ran.
270 my ($expires) = $set_cookie =~ /Expires=([^;]+)/;
271 ok( defined $expires, 'cookie_duration produces an Expires attribute' );
272 my $epoch = HTTP::Date::str2time($expires);
273 ok( defined $epoch, "and it parses as a date ($expires)" );
274 cmp_ok( $epoch, '>', time + 3000,
275 'roughly two hours ahead, not the literal string "2 hours"' );
276 cmp_ok( $epoch, '<', time + 10800, 'and not much more than that' );
277 };
278
279 subtest 'is_http_only => 0 drops HttpOnly' => sub {
280 my $test = Plack::Test->create( NoHttpOnlyApp->to_app );
281 my $set_cookie = $test->request( GET '/write' )->header('Set-Cookie');
282
283 unlike( $set_cookie, qr/\bHttpOnly\b/,
284 'HttpOnly is gone when explicitly turned off' );
285 like( $set_cookie, qr{^dancer\.session=},
286 'but the cookie is otherwise still issued' );
287 };
288
289 subtest 'a cookie naming an unknown session starts a fresh one' => sub {
290 my $test = Plack::Test->create( SessApp->to_app );
291
292 # Well-formed id, but no such session. The retrieve fails and the app is
293 # expected to swallow that and create a new session rather than 500.
294 my $unknown = get_with_cookie(
295 $test, '/read', 'dancer.session=WellFormedButNotAKnownSession'
296 );
297 is( $unknown->code, 200, 'an unknown session id does not blow up' );
298 is( $unknown->content, 'foo=undef', 'the new session is empty' );
299 isnt(
300 cookie_pair( $unknown->header('Set-Cookie') ),
301 'dancer.session=WellFormedButNotAKnownSession',
302 'and a different id is issued rather than trusting the one supplied',
303 );
304
305 # An id that could escape a filesystem-backed store. validate_id rejects
306 # it before any backend sees it, so this must not reach _retrieve.
307 my $nasty = get_with_cookie( $test, '/read', 'dancer.session=../../etc/passwd' );
308 is( $nasty->code, 200, 'a malformed session id does not blow up either' );
309 is( $nasty->content, 'foo=undef', 'and yields an empty session' );
310 unlike(
311 cookie_pair( $nasty->header('Set-Cookie') ) // '',
312 qr{\.\./},
313 'the rejected id is not echoed back in the new cookie',
314 );
315 };
316
317 done_testing();