blib/lib/PAGI/Middleware/Session.pm

filter: Statementstmt 97.9% 95 / 97 Branchbran 90.9% 20 / 22 Conditioncond 57.1% 12 / 21 MC/DCmcdc 27.2% 3 / 11 Subroutinesub 100% 16 / 16 Podpod 50.0% 1 / 2 totaltotal 86.9% 147 / 169 CC 21 SCAR 14.2
CC
21
Cov
91%
_init
7.1
__ANON__
6.0
_load_or_create_session
5.0
CRAP 4.1
« blib/lib/PAGI/WebSocket.pm ↑ Summary blib/lib/PAGI/Middleware/Session/State/Cookie.pm »
1 package PAGI::Middleware::Session;
2 2 $PAGI::Middleware::Session::VERSION = '0.002001';
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use parent 'PAGI::Middleware';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Digest::SHA qw(sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use PAGI::Utils::Random qw(secure_random_bytes);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 PAGI::Middleware::Session - Session management middleware with pluggable State/Store
13  
14 =head1 SYNOPSIS
15  
16 use PAGI::Middleware::Builder;
17  
18 # Default (cookie-based, in-memory store)
19 my $app = builder {
20 enable 'Session', secret => 'your-secret-key';
21 $my_app;
22 };
23  
24 # Explicit state and store
25 use PAGI::Middleware::Session::State::Header;
26 use PAGI::Middleware::Session::Store::Memory;
27  
28 my $app = builder {
29 enable 'Session',
30 secret => 'your-secret-key',
31 state => PAGI::Middleware::Session::State::Header->new(
32 header_name => 'X-Session-ID',
33 ),
34 store => PAGI::Middleware::Session::Store::Memory->new;
35 $my_app;
36 };
37  
38 # In your app:
39 async sub app {
40 my ($scope, $receive, $send) = @_;
41  
42 # Raw hashref access
43 my $session = $scope->{'pagi.session'};
44 $session->{user_id} = 123;
45  
46 # Or use the PAGI::Session helper
47 use PAGI::Session;
48 my $s = PAGI::Session->new($scope);
49 $s->set('user_id', 123);
50 my $uid = $s->get('user_id'); # dies if key missing
51 }
52  
53 =head1 DESCRIPTION
54  
55 PAGI::Middleware::Session provides server-side session management with a
56 pluggable architecture for session ID transport (State) and session data
57 storage (Store).
58  
59 The B<State> layer controls how the session ID travels between client and
60 server (cookies, headers, bearer tokens, or custom logic). The B<Store>
61 layer controls where session data is persisted (memory, Redis, database).
62  
63 By default, sessions use cookie-based IDs and in-memory storage.
64  
65 B<Warning:> The default in-memory store is suitable for development and
66 single-process deployments only. Sessions are not shared between workers
67 and are lost on restart. For production multi-worker deployments, provide
68 a C<store> object backed by Redis, a database, or another shared storage.
69  
70 =head1 CONFIGURATION
71  
72 =over 4
73  
74 =item * secret (required)
75  
76 Secret key used for session ID generation.
77  
78 =item * expire (default: 3600)
79  
80 Session expiration time in seconds.
81  
82 =item * state (optional)
83  
84 A L<PAGI::Middleware::Session::State> object that implements C<extract($scope)>
85 and C<inject(\@headers, $id, \%options)>. If not provided, a
86 L<PAGI::Middleware::Session::State::Cookie> instance is created using
87 C<cookie_name>, C<cookie_options>, and C<expire>.
88  
89 =item * store (optional)
90  
91 A L<PAGI::Middleware::Session::Store> object that implements async C<get($id)>,
92 C<set($id, $data)>, and C<delete($id)>. If not provided, a
93 L<PAGI::Middleware::Session::Store::Memory> instance is created.
94  
95 =item * cookie_name (default: 'pagi_session')
96  
97 Name of the session cookie. Only used when C<state> defaults to
98 L<PAGI::Middleware::Session::State::Cookie>.
99  
100 =item * cookie_options (default: { httponly => 1, path => '/', samesite => 'Lax' })
101  
102 Options for the session cookie. Only used when C<state> defaults to
103 L<PAGI::Middleware::Session::State::Cookie>. For production HTTPS
104 deployments, add C<< secure => 1 >>.
105  
106 =back
107  
108 =head1 STATE CLASSES
109  
110 State classes control how the session ID is extracted from requests and
111 injected into responses. All implement the L<PAGI::Middleware::Session::State>
112 interface.
113  
114 =over 4
115  
116 =item L<PAGI::Middleware::Session::State::Cookie>
117  
118 Default. Reads the session ID from a request cookie and sets it via
119 C<Set-Cookie> on the response. Suitable for browser-based web applications.
120  
121 =item L<PAGI::Middleware::Session::State::Header>
122  
123 Reads the session ID from a custom HTTP header. Requires C<header_name>;
124 accepts an optional C<pattern> regex with a capture group. Injection is a
125 no-op (the client manages header-based transport).
126  
127 PAGI::Middleware::Session::State::Header->new(
128 header_name => 'X-Session-ID',
129 );
130  
131 =item L<PAGI::Middleware::Session::State::Bearer>
132  
133 Convenience subclass of State::Header that reads an opaque bearer token from
134 the C<Authorization: Bearer E<lt>tokenE<gt>> header. Intended for opaque
135 session tokens, B<not> JWTs. For JWT authentication, use
136 L<PAGI::Middleware::Auth::Bearer> instead.
137  
138 PAGI::Middleware::Session::State::Bearer->new();
139  
140 =item L<PAGI::Middleware::Session::State::Callback>
141  
142 Custom session ID transport using coderefs. Requires an C<extract> coderef;
143 accepts an optional C<inject> coderef (defaults to no-op).
144  
145 PAGI::Middleware::Session::State::Callback->new(
146 extract => sub { my ($scope) = @_; ... },
147 inject => sub { my ($headers, $id, $options) = @_; ... },
148 );
149  
150 =back
151  
152 =head1 STORE CLASSES
153  
154 Store classes control where session data is persisted. All implement the
155 L<PAGI::Middleware::Session::Store> interface; methods return L<Future>
156 objects for async compatibility.
157  
158 =over 4
159  
160 =item L<PAGI::Middleware::Session::Store::Memory>
161  
162 Default. In-memory hash storage. Not shared across workers or restarts.
163 Suitable for development and testing only.
164  
165 =item External stores
166  
167 Redis, database, and other shared stores are available as separate CPAN
168 distributions. Any object implementing C<get($id)>, C<set($id, $data)>,
169 and C<delete($id)> (returning Futures) can be used.
170  
171 =back
172  
173 =head1 PAGI::Session HELPER
174  
175 L<PAGI::Session> is a standalone helper object that wraps the session
176 data with a clean accessor interface.
177  
178 use PAGI::Session;
179 my $session = PAGI::Session->new($scope);
180  
181 Key methods:
182  
183 =over 4
184  
185 =item * C<get($key)> - Dies if the key does not exist (catches typos).
186  
187 =item * C<get($key, $default)> - Returns C<$default> for missing keys.
188  
189 =item * C<set($key, $value)> - Sets a session value.
190  
191 =item * C<exists($key)> - Checks key existence.
192  
193 =item * C<delete($key)> - Removes a key.
194  
195 =item * C<keys> - Lists user keys (excludes internal C<_>-prefixed keys).
196  
197 =item * C<id> - Returns the session ID.
198  
199 =item * C<regenerate> - Requests session ID regeneration on next response.
200  
201 =item * C<destroy> - Marks the session for deletion.
202  
203 =back
204  
205 The helper stores a reference to the underlying hash, so mutations are
206 visible to the middleware.
207  
208 =head1 IDEMPOTENCY
209  
210 The middleware skips processing if C<< $scope-E<gt>{'pagi.session'} >>
211 already exists. This prevents double-initialization when the middleware
212 appears more than once in a stack.
213  
214 For mixed auth patterns (e.g. web cookies for browsers, bearer tokens for
215 APIs), use L<PAGI::Middleware::Session::State::Callback> with fallback
216 logic instead of stacking multiple Session middleware instances:
217  
218 use PAGI::Middleware::Session::State::Callback;
219 use PAGI::Middleware::Session::State::Cookie;
220 use PAGI::Middleware::Session::State::Bearer;
221  
222 my $cookie_state = PAGI::Middleware::Session::State::Cookie->new(
223 cookie_name => 'pagi_session',
224 expire => 3600,
225 );
226 my $bearer_state = PAGI::Middleware::Session::State::Bearer->new();
227  
228 enable 'Session',
229 secret => $ENV{SESSION_SECRET},
230 state => PAGI::Middleware::Session::State::Callback->new(
231 extract => sub {
232 my ($scope) = @_;
233 return $bearer_state->extract($scope)
234 // $cookie_state->extract($scope);
235 },
236 inject => sub {
237 my ($headers, $id, $options) = @_;
238 $cookie_state->inject($headers, $id, $options);
239 },
240 );
241  
242 =cut
243  
244 sub _init {
245 11 ▶ my ($self, $config) = @_;
Subroutine _init: called CC=7 SCAR=19.6
246  
247 $self->{secret} = $config->{secret}
248 11 ▶ // die "Session middleware requires 'secret' option";
Condition50%1/2
$config->{"secret"} // die("Session middleware requires 'secret' option")
l!l
110
MC/DC0%0/1
$config->{"secret"} // die("Session middleware requires 'secret' option")
$config->{"secret"}
Truth table50%1/2
A
A= $config->{"secret"}
Aresult
11
00
249 11 ▶ $self->{expire} = $config->{expire} // 3600;
Condition50%1/2
$config->{"expire"} // 3600
l!l
011
MC/DC0%0/1
$config->{"expire"} // 3600
$config->{"expire"}
Truth table50%1/2
A
A= $config->{"expire"}
Aresult
11
00
250  
251 # State: pluggable session ID transport
252 11 ▶ if ($config->{state}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{'state'}) { } 2 9 11
253 2 $self->{state} = $config->{state};
254 } else {
255 9 require PAGI::Middleware::Session::State::Cookie;
256 $self->{state} = PAGI::Middleware::Session::State::Cookie->new(
257 cookie_name => $config->{cookie_name} // 'pagi_session',
258 cookie_options => $config->{cookie_options} // {
259 httponly => 1,
260 path => '/',
261 samesite => 'Lax',
262 },
263 expire => $self->{expire},
264 9 ▶ );
Condition75%3/4
$config->{"cookie_name"} // "pagi_session"
l!l
09
$config->{"cookie_options"} // {"httponly", 1, "path", "/", "samesite", "Lax"}
l!l
18
MC/DC0%0/1
$config->{"cookie_name"} // "pagi_session"
$config->{"cookie_name"}
MC/DC100%1/1
$config->{"cookie_options"} // {"httponly", 1, "path", "/", "samesite", "Lax"}
$config->{"cookie_options"}
Truth table50%1/2
A
A= $config->{"cookie_name"}
Aresult
11
00
Truth table100%2/2
A
A= $config->{"cookie_options"}
Aresult
11
00
265 }
266  
267 # Store: pluggable async session storage
268 11 ▶ if ($config->{store}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{'store'}) { } 2 9 11
269 2 $self->{store} = $config->{store};
270 } else {
271 9 require PAGI::Middleware::Session::Store::Memory;
272 9 $self->{store} = PAGI::Middleware::Session::Store::Memory->new();
273 }
274 }
275  
276 sub wrap {
277 18 ▶ my ($self, $app) = @_;
Subroutine wrap: called CC=1 SCAR=0.0
Pod documented
278  
279 18 ▶ return async sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
280 18 my ($scope, $receive, $send) = @_;
281 18 ▶ if ($scope->{type} ne 'http') {
Branch: 1 branch
BranchTrueFalseTotal
if ($scope->{"type"} ne "http") 0 18 18
282 0 await $app->($scope, $receive, $send);
283 0 return;
284 }
285  
286 # Idempotency: skip if session already exists in scope
287 18 ▶ if (exists $scope->{'pagi.session'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $scope->{"pagi.session"}) 1 17 18
288 warn "Session middleware: pagi.session already in scope, skipping\n"
289 1 ▶ if $ENV{PAGI_DEBUG};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"PAGI_DEBUG"} 0 1 1
290 1 await $app->($scope, $receive, $send);
291 1 return;
292 }
293  
294 # Extract session ID via state handler
295 17 my $session_id = $self->{state}->extract($scope);
296  
297 # Validate and load session
298 17 my ($session, $is_new) = await $self->_load_or_create_session($session_id);
299 17 $session_id = $session->{_id};
300  
301 # Add session to scope
302 17 my $new_scope = $self->modify_scope($scope, {
303 'pagi.session' => $session,
304 'pagi.session_id' => $session_id,
305 });
306  
307 # Wrap send to save session and inject state
308 34 ▶ my $wrapped_send = async sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
309 34 my ($event) = @_;
310 34 ▶ if ($event->{type} eq 'http.response.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event->{"type"} eq "http.response.start") 17 17 34
311 17 ▶ my @headers = @{$event->{headers} // []};
Condition50%1/2
$event->{"headers"} // []
l!l
170
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
312  
313 17 ▶ if ($session->{_destroyed}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($session->{'_destroyed'}) { } 1 16 17
elsif ($session->{'_regenerated'}) { } 1 15 16
314 # Destroy: delete from store, clear client state
315 1 await $self->{store}->delete($session_id);
316 1 $self->{state}->clear(\@headers);
317 }
318 elsif ($session->{_regenerated}) {
319 # Regenerate: new ID, delete old, save under new
320 1 my $old_id = $session_id;
321 1 $session_id = $self->_generate_session_id();
322 1 $session->{_id} = $session_id;
323 1 delete $session->{_regenerated};
324 1 await $self->{store}->delete($old_id);
325 1 my $transport = await $self->_save_session($session_id, $session);
326 1 $self->{state}->inject(\@headers, $transport, {});
327 }
328 else {
329 # Normal: save and inject if new
330 15 my $transport = await $self->_save_session($session_id, $session);
331 15 ▶ if ($is_new) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_new) 12 3 15
332 12 $self->{state}->inject(\@headers, $transport, {});
333 }
334 }
335  
336 17 await $send->({ %$event, headers => \@headers });
337 17 return;
338 }
339 17 await $send->($event);
340 17 };
341  
342 17 await $app->($new_scope, $receive, $wrapped_send);
343 18 };
344 }
345  
346 17 ▶async sub _load_or_create_session {
Subroutine _load_or_create_session: called CC=5 SCAR=16.1
347 17 my ($self, $session_id) = @_;
348  
349 # Try to load existing session. The store handles validation —
350 # server-side stores return undef for unknown IDs, cookie stores
351 # return undef if decoding/verification fails.
352 17 ▶ if (defined $session_id && length $session_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $session_id and length $session_id) 7 10 17
Condition66%2/3
defined $session_id and length $session_id
!ll&&!rl&&r
1007
MC/DC50%1/2
defined $session_id and length $session_id
defined $session_id length $session_id
Truth table66%2/3
A and B
A= defined $session_idB= length $session_id
ABresult
0X0
100
111
353 7 my $session = await $self->_get_session($session_id);
354 7 ▶ if ($session && !$self->_is_expired($session)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($session and not $self->_is_expired($session)) 5 2 7
Condition66%2/3
$session and not $self->_is_expired($session)
!ll&&!rl&&r
205
MC/DC50%1/2
$session and not $self->_is_expired($session)
$session not $self->_is_expired($session)
Truth table66%2/3
A and not(B)
A= $sessionB= not $self->_is_expired($session)
ABresult
0X0
100
111
355 5 $session->{_last_access} = time();
356 5 return ($session, 0);
357 }
358 }
359  
360 # Create new session
361 12 $session_id = $self->_generate_session_id();
362 12 my $session = {
363 _id => $session_id,
364 _created => time(),
365 _last_access => time(),
366 };
367  
368 12 return ($session, 1);
369 2 }
370  
371 sub _generate_session_id {
372 13 ▶ my ($self) = @_;
Subroutine _generate_session_id: called CC=1 SCAR=0.0
373  
374 # Use cryptographically secure random bytes
375 13 my $random = unpack('H*', secure_random_bytes(16));
376 13 my $time = time();
377 13 return sha256_hex("$random-$time-$self->{secret}");
378 }
379  
380 7 ▶async sub _get_session {
Subroutine _get_session: called CC=1 SCAR=0.0
381 7 my ($self, $id) = @_;
382 7 return await $self->{store}->get($id);
383 2 }
384  
385 16 ▶async sub _save_session {
Subroutine _save_session: called CC=1 SCAR=0.0
386 16 my ($self, $id, $session) = @_;
387 16 return await $self->{store}->set($id, $session);
388 2 }
389  
390 sub _is_expired {
391 5 ▶ my ($self, $session) = @_;
Subroutine _is_expired: called CC=3 SCAR=12.5
392  
393 5 ▶ my $last_access = $session->{_last_access} // $session->{_created} // 0;
Condition40%2/5
($session->{"_last_access"} // $session->{"_created"}) // 0
l!l
50
$session->{"_last_access"} // $session->{"_created"}
l!l&&r!l&&!r
500
MC/DC0%0/2
($session->{"_last_access"} // $session->{"_created"}) // 0
$session->{"_last_access"} $session->{"_created"}
Truth table33%1/3
A // B
A= $session->{"_last_access"}B= $session->{"_created"}
ABresult
1X1
011
000
394 5 return (time() - $last_access) > $self->{expire};
395 }
396  
397 # Class method to clear all sessions (useful for testing)
398 sub clear_sessions {
399 7 ▶ require PAGI::Middleware::Session::Store::Memory;
Subroutine clear_sessions: called CC=1 SCAR=0.0
Pod undocumented
400 7 PAGI::Middleware::Session::Store::Memory::clear_all();
401 }
402  
403 2 1;
404  
405 __END__
« blib/lib/PAGI/WebSocket.pm ↑ Summary blib/lib/PAGI/Middleware/Session/State/Cookie.pm »