summaryrefslogtreecommitdiff
path: root/lib/Dancer2/Core/Role/SessionFactory.pm
blob: 2e450bfeca5f6f618ba1335ff4e933861e2f5efa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package Dancer2::Core::Role::SessionFactory;
# ABSTRACT: Role for session factories
$Dancer2::Core::Role::SessionFactory::VERSION = '1.1.0';
use Moo::Role;
with 'Dancer2::Core::Role::Engine';

use Carp 'croak';
use Dancer2::Core::Session;
use Dancer2::Core::Types;
use Digest::SHA 'sha1';
use List::Util 'shuffle';
use MIME::Base64 'encode_base64url';
use Module::Runtime 'require_module';
use Ref::Util qw< is_ref is_arrayref is_hashref >;

sub hook_aliases { +{} }
sub supported_hooks {
    qw/
      engine.session.before_retrieve
      engine.session.after_retrieve

      engine.session.before_create
      engine.session.after_create

      engine.session.before_change_id
      engine.session.after_change_id

      engine.session.before_destroy
      engine.session.after_destroy

      engine.session.before_flush
      engine.session.after_flush
      /;
}

sub _build_type {
    'SessionFactory';
}    # XXX vs 'Session'?  Unused, so I can't tell -- xdg

has log_cb => (
    is      => 'ro',
    isa     => CodeRef,
    default => sub { sub {1} },
);

has cookie_name => (
    is      => 'ro',
    isa     => Str,
    default => sub {'dancer.session'},
);

has cookie_domain => (
    is        => 'ro',
    isa       => Str,
    predicate => 1,
);

has cookie_path => (
    is      => 'ro',
    isa     => Str,
    default => sub {"/"},
);

has cookie_duration => (
    is        => 'ro',
    isa       => Str,
    predicate => 1,
);

has session_duration => (
    is        => 'ro',
    isa       => Num,
    predicate => 1,
);

has is_secure => (
    is      => 'rw',
    isa     => Bool,
    default => sub {0},
);

has is_http_only => (
    is      => 'rw',
    isa     => Bool,
    default => sub {1},
);

has cookie_same_site => (
    is        => 'ro',
    isa       => Str,
    predicate => 1,
    coerce    => sub { ucfirst $_[0] },
);

sub create {
    my ($self) = @_;

    my %args = ( id => $self->generate_id, );

    $args{expires} = $self->cookie_duration
      if $self->has_cookie_duration;

    my $session = Dancer2::Core::Session->new(%args);

    $self->execute_hook( 'engine.session.before_create', $session );

    # XXX why do we _flush now?  Seems unnecessary -- xdg, 2013-03-03
    eval { $self->_flush( $session->id, $session->data ) };
    croak "Unable to create a new session: $@"
      if $@;

    $self->execute_hook( 'engine.session.after_create', $session );
    return $session;
}

{
    my $COUNTER     = 0;
    my $CPRNG_AVAIL = eval { require_module('Math::Random::ISAAC::XS'); 1; } &&
                      eval { require_module('Crypt::URandom'); 1; };

    # don't initialize until generate_id is called so the ISAAC algorithm
    # is seeded after any pre-forking
    my $CPRNG;

    # prepend epoch seconds so session ID is roughly monotonic
    sub generate_id {
        my ($self) = @_;

        if ($CPRNG_AVAIL) {
            $CPRNG ||= Math::Random::ISAAC::XS->new(
                map { unpack( "N", Crypt::URandom::urandom(4) ) } 1 .. 256 );

            # include $$ to ensure $CPRNG wasn't forked by accident
            return encode_base64url(
                pack(
                    "N6",
                    time,          $$,            $CPRNG->irand,
                    $CPRNG->irand, $CPRNG->irand, $CPRNG->irand
                )
            );
        }
        else {
            my $seed = (
                rand(1_000_000_000)   # a random number
                  . __FILE__          # the absolute path as a secret key
                  . $COUNTER++        # impossible to have two consecutive dups
                  . $$         # the process ID as another private constant
                  . "$self"    # the instance's memory address for more entropy
                  . join( '', shuffle( 'a' .. 'z', 'A' .. 'Z', 0 .. 9 ) )

                  # a shuffled list of 62 chars, another random component
            );
            return encode_base64url( pack( "Na*", time, sha1($seed) ) );
        }

    }
}

sub validate_id {
    my ($self, $id) = @_;
    return $id =~ m/^[A-Za-z0-9_\-~]+$/;
}

requires '_retrieve';

sub retrieve {
    my ( $self, %params ) = @_;
    my $id = $params{id};

    $self->execute_hook( 'engine.session.before_retrieve', $id );

    my $data;
    # validate format of session id before attempt to retrieve
    my $rc = eval {
        $self->validate_id($id) && ( $data = $self->_retrieve($id) );
    };
    croak "Unable to retrieve session with id '$id'"
      if ! $rc;

    my %args = ( id => $id, );

    $args{data} = $data
      if $data and is_hashref($data);

    $args{expires} = $self->cookie_duration
      if $self->has_cookie_duration;

    my $session = Dancer2::Core::Session->new(%args);

    $self->execute_hook( 'engine.session.after_retrieve', $session );
    return $session;
}

# XXX eventually we could perhaps require '_change_id'?

sub change_id {
    my ( $self, %params ) = @_;
    my $session = $params{session};
    my $old_id  = $session->id;

    $self->execute_hook( 'engine.session.before_change_id', $old_id );

    my $new_id = $self->generate_id;
    $session->id( $new_id );

    eval { $self->_change_id( $old_id, $new_id ) };
    croak "Unable to change session id for session with id $old_id: $@"
      if $@;

    $self->execute_hook( 'engine.session.after_change_id', $new_id );
}

requires '_destroy';

sub destroy {
    my ( $self, %params ) = @_;
    my $id = $params{id};
    $self->execute_hook( 'engine.session.before_destroy', $id );

    eval { $self->_destroy($id) };
    croak "Unable to destroy session with id '$id': $@"
      if $@;

    $self->execute_hook( 'engine.session.after_destroy', $id );
    return $id;
}

requires '_flush';

sub flush {
    my ( $self, %params ) = @_;
    my $session = $params{session};
    $self->execute_hook( 'engine.session.before_flush', $session );

    eval { $self->_flush( $session->id, $session->data ) };
    croak "Unable to flush session: $@"
      if $@;

    $self->execute_hook( 'engine.session.after_flush', $session );
    return $session->id;
}

sub set_cookie_header {
    my ( $self, %params ) = @_;
    $params{response}->push_header(
        'Set-Cookie',
        $self->cookie( session => $params{session} )->to_header
    );
}

sub cookie {
    my ( $self, %params ) = @_;
    my $session = $params{session};
    croak "cookie() requires a valid 'session' parameter"
      unless is_ref($session) && $session->isa("Dancer2::Core::Session");

    my %cookie = (
        value     => $session->id,
        name      => $self->cookie_name,
        path      => $self->cookie_path,
        secure    => $self->is_secure,
        http_only => $self->is_http_only,
    );

    $cookie{same_site} = $self->cookie_same_site
      if $self->has_cookie_same_site;

    $cookie{domain} = $self->cookie_domain
      if $self->has_cookie_domain;

    if ( my $expires = $session->expires ) {
        $cookie{expires} = $expires;
    }

    return Dancer2::Core::Cookie->new(%cookie);
}

requires '_sessions';

sub sessions {
    my ($self) = @_;
    my $sessions = $self->_sessions;

    croak "_sessions() should return an array ref"
      unless is_arrayref($sessions);

    return $sessions;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Dancer2::Core::Role::SessionFactory - Role for session factories

=head1 VERSION

version 1.1.0

=head1 DESCRIPTION

Any class that consumes this role will be able to store, create, retrieve and
destroy session objects.

The default values for attributes can be overridden in your Dancer2
configuration. See L<Dancer2::Config/Session-engine>.

=head1 ATTRIBUTES

=head2 cookie_name

The name of the cookie to create for storing the session key

Defaults to C<dancer.session>

=head2 cookie_domain

The domain of the cookie to create for storing the session key.
Defaults to the empty string and is unused as a result.

=head2 cookie_path

The path of the cookie to create for storing the session key.
Defaults to "/".

=head2 cookie_duration

Default duration before session cookie expiration.  If set, the
L<Dancer2::Core::Session> C<expires> attribute will be set to the current time
plus this duration (expression parsed by L<Dancer2::Core::Time>).

=head2 cookie_same_site

Restricts the session cookie to a first-party or same-site context.
Defaults to the empty string and is unused as a result.
See L<Dancer2::Core::Cookie/same_site>.

=head2 session_duration

Duration in seconds before sessions should expire, regardless of cookie
expiration.  If set, then SessionFactories should use this to enforce a limit
on session validity.

=head2 is_secure

Boolean flag to tell if the session cookie is secure or not.

Default is false.

=head2 is_http_only

Boolean flag to tell if the session cookie is http only.

Default is true.

=head1 INTERFACE

Following is the interface provided by this role. When specified the required
methods to implement are described.

=head2 create

Create a brand new session object and store it. Returns the newly created
session object.

Triggers an exception if the session is unable to be created.

    my $session = MySessionFactory->create();

This method does not need to be implemented in the class.

=head2 generate_id

Returns a randomly-generated, guaranteed-unique string.
By default, it is a 32-character, URL-safe, Base64 encoded combination
of a 32 bit timestamp and a 160 bit SHA1 digest of random seed data.
The timestamp ensures that session IDs are generally monotonic.

The default algorithm is not guaranteed cryptographically secure, but it's
still reasonably strong for general use.

If you have installed L<Math::Random::ISAAC::XS> and L<Crypt::URandom>,
the seed data will be generated from a cryptographically-strong
random number generator.

This method is used internally by create() to set the session ID.

This method does not need to be implemented in the class unless an
alternative method for session ID generation is desired.

=head2 validate_id

Returns true if a session id is of the correct format, or false otherwise.

By default, this ensures that the session ID is a string of characters
from the Base64 schema for "URL Applications" plus the C<~> character.

This method does not need to be implemented in the class unless an
alternative set of characters for session IDs is desired.

=head2 retrieve

Return the session object corresponding to the session ID given. If none is
found, triggers an exception.

    my $session = MySessionFactory->retrieve(id => $id);

The method C<_retrieve> must be implemented.  It must take C<$id> as a single
argument and must return a hash reference of session data.

=head2 change_id

Changes the session ID of the corresponding session.

    MySessionFactory->change_id(session => $session_object);

The method C<_change_id> must be implemented. It must take C<$old_id> and
C<$new_id> as arguments and change the ID from the old one to the new one
in the underlying session storage.

=head2 destroy

Purges the session object that matches the ID given. Returns the ID of the
destroyed session if succeeded, triggers an exception otherwise.

    MySessionFactory->destroy(id => $id);

The C<_destroy> method must be implemented. It must take C<$id> as a single
argument and destroy the underlying data.

=head2 flush

Make sure the session object is stored in the factory's backend. This method is
called to notify the backend about the change in the session object.

The Dancer application will not call flush unless the session C<is_dirty>
attribute is true to avoid unnecessary writes to the database when no
data has been modified.

An exception is triggered if the session is unable to be updated in the backend.

    MySessionFactory->flush(session => $session);

The C<_flush> method must be implemented.  It must take two arguments: the C<$id>
and a hash reference of session data.

=head2 set_cookie_header

Sets the session cookie into the response object

    MySessionFactory->set_cookie_header(
        response  => $response,
        session   => $session,
        destroyed => undef,
    );

The C<response> parameter contains a L<Dancer2::Core::Response> object.
The C<session> parameter contains a L<Dancer2::Core::Session> object.

The C<destroyed> parameter is optional.  If true, it indicates the
session was marked destroyed by the request context.  The default
C<set_cookie_header> method doesn't need that information, but it is
included in case a SessionFactory must handle destroyed sessions
differently (such as signalling to middleware).

=head2 cookie

Coerce a session object into a L<Dancer2::Core::Cookie> object.

    MySessionFactory->cookie(session => $session);

=head2 sessions

Return a list of all session IDs stored in the backend.
Useful to create cleaning scripts, in conjunction with session's creation time.

The C<_sessions> method must be implemented.  It must return an array reference
of session IDs (or an empty array reference).

=head1 CONFIGURATION

If there are configuration values specific to your session factory in your config.yml or
environment, those will be passed to the constructor of the session factory automatically.
In order to accept and store them, you need to define accessors for them.

    engines:
      session:
        Example:
          database_connection: "some_data"

In your session factory:

    package Dancer2::Session::Example;
    use Moo;
    with "Dancer2::Core::Role::SessionFactory";

    has database_connection => ( is => "ro" );

You need to do this for every configuration key. The ones that do not have accessors
defined will just go to the void.

=head1 AUTHOR

Dancer Core Developers

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2023 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut