blib/lib/PAGI/Middleware/CSRF.pm

filter: Statementstmt 96.5% 84 / 87 Branchbran 86.3% 19 / 22 Conditioncond 66.6% 16 / 24 MC/DCmcdc 30.7% 4 / 13 Subroutinesub 100% 16 / 16 Podpod 100% 1 / 1 totaltotal 85.8% 140 / 163 CC 24 SCAR 14.9
CC
24
Cov
89%
__ANON__
8.2
_init
6.8
_secure_compare
5.0
CRAP 4.4
« lib/PAGI/Middleware/SSE/Retry.pm ↑ Summary blib/lib/PAGI/WebSocket.pm »
1 package PAGI::Middleware::CSRF;
2 2 $PAGI::Middleware::CSRF::VERSION = '0.002000';
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::CSRF - Cross-Site Request Forgery protection middleware
13  
14 =head1 SYNOPSIS
15  
16 use PAGI::Middleware::Builder;
17  
18 my $app = builder {
19 enable 'CSRF',
20 secret => 'your-secret-key',
21 token_header => 'X-CSRF-Token',
22 cookie_name => 'csrf_token',
23 safe_methods => ['GET', 'HEAD', 'OPTIONS'];
24 $my_app;
25 };
26  
27 =head1 DESCRIPTION
28  
29 PAGI::Middleware::CSRF provides protection against Cross-Site Request
30 Forgery attacks by validating tokens on state-changing requests.
31  
32 =head1 CONFIGURATION
33  
34 =over 4
35  
36 =item * secret (required)
37  
38 Secret key used for token generation.
39  
40 =item * token_header (default: 'X-CSRF-Token')
41  
42 Header name to look for the CSRF token.
43  
44 =item * token_param (default: '_csrf_token')
45  
46 Form parameter name to look for the CSRF token.
47  
48 =item * cookie_name (default: 'csrf_token')
49  
50 Cookie name for the CSRF token.
51  
52 =item * safe_methods (default: ['GET', 'HEAD', 'OPTIONS', 'TRACE'])
53  
54 HTTP methods that don't require CSRF validation.
55  
56 =back
57  
58 =cut
59  
60 sub _init {
61 5 ▶ my ($self, $config) = @_;
Subroutine _init: called CC=6 SCAR=19.1
62  
63 5 ▶ $self->{secret} = $config->{secret} // die "CSRF middleware requires 'secret' option";
Condition50%1/2
$config->{"secret"} // die("CSRF middleware requires 'secret' option")
l!l
50
MC/DC0%0/1
$config->{"secret"} // die("CSRF middleware requires 'secret' option")
$config->{"secret"}
Truth table50%1/2
A
A= $config->{"secret"}
Aresult
11
00
64 5 ▶ $self->{token_header} = $config->{token_header} // 'X-CSRF-Token';
Condition50%1/2
$config->{"token_header"} // "X-CSRF-Token"
l!l
05
MC/DC0%0/1
$config->{"token_header"} // "X-CSRF-Token"
$config->{"token_header"}
Truth table50%1/2
A
A= $config->{"token_header"}
Aresult
11
00
65 5 ▶ $self->{token_param} = $config->{token_param} // '_csrf_token';
Condition50%1/2
$config->{"token_param"} // "_csrf_token"
l!l
05
MC/DC0%0/1
$config->{"token_param"} // "_csrf_token"
$config->{"token_param"}
Truth table50%1/2
A
A= $config->{"token_param"}
Aresult
11
00
66 5 ▶ $self->{cookie_name} = $config->{cookie_name} // 'csrf_token';
Condition50%1/2
$config->{"cookie_name"} // "csrf_token"
l!l
05
MC/DC0%0/1
$config->{"cookie_name"} // "csrf_token"
$config->{"cookie_name"}
Truth table50%1/2
A
A= $config->{"cookie_name"}
Aresult
11
00
67 5 ▶ $self->{safe_methods} = { map { $_ => 1 } @{$config->{safe_methods} // [qw(GET HEAD OPTIONS TRACE)]} };
Condition50%1/2
$config->{"safe_methods"} // ["GET", "HEAD", "OPTIONS", "TRACE"]
l!l
05
MC/DC0%0/1
$config->{"safe_methods"} // ["GET", "HEAD", "OPTIONS", "TRACE"]
$config->{"safe_methods"}
Truth table50%1/2
A
A= $config->{"safe_methods"}
Aresult
11
00
68 }
69  
70 sub wrap {
71 5 ▶ my ($self, $app) = @_;
Subroutine wrap: called CC=1 SCAR=0.0
Pod documented
72  
73 8 ▶ return async sub {
Subroutine __ANON__: called CC=8 SCAR=21.0
74 8 my ($scope, $receive, $send) = @_;
75 # Only handle HTTP requests
76 8 ▶ if ($scope->{type} ne 'http') {
Branch: 1 branch
BranchTrueFalseTotal
if ($scope->{"type"} ne "http") 0 8 8
77 0 await $app->($scope, $receive, $send);
78 0 return;
79 }
80  
81 8 my $method = $scope->{method};
82  
83 # Get existing token from cookie
84 8 my $cookie_token = $self->_get_cookie_token($scope);
85  
86 # Generate new token if none exists
87 8 ▶ my $token = $cookie_token // $self->_generate_token();
Condition66%2/3
$cookie_token // $self->_generate_token
l!l&&r!l&&!r
440
MC/DC0%0/2
$cookie_token // $self->_generate_token
$cookie_token $self->_generate_token
Truth table66%2/3
A // B
A= $cookie_tokenB= $self->_generate_token
ABresult
1X1
011
000
88  
89 # For safe methods, just add token to scope and continue
90 8 ▶ if ($self->{safe_methods}{$method}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"safe_methods"}{$method}) 3 5 8
91 3 my $modified_scope = $self->modify_scope($scope, {
92 csrf_token => $token,
93 });
94  
95 # Add Set-Cookie if token is new
96 6 ▶ my $wrapped_send = $cookie_token ? $send : async sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
97 6 my ($event) = @_;
98 6 ▶ if ($event->{type} eq 'http.response.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event->{"type"} eq "http.response.start") 3 3 6
99 3 push @{$event->{headers}}, [
100 'Set-Cookie',
101 "$self->{cookie_name}=$token; Path=/; HttpOnly; SameSite=Strict"
102 ];
103 }
104 6 await $send->($event);
105 3 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$cookie_token ? : 0 3 3
106  
107 3 await $app->($modified_scope, $receive, $wrapped_send);
108 3 return;
109 }
110  
111 # For unsafe methods, validate token
112 5 my $submitted_token = $self->_get_submitted_token($scope);
113  
114 # Use timing-safe comparison to prevent timing attacks
115 5 ▶ if (!$submitted_token || !$cookie_token || !$self->_secure_compare($submitted_token, $cookie_token)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($submitted_token and $cookie_token and $self->_secure_compare($submitted_token, $cookie_token)) 1 2 3
Condition83%5/6
$submitted_token and $cookie_token and $self->_secure_compare($submitted_token, $cookie_token)
!ll&&!rl&&r
212
$submitted_token and $cookie_token
!ll&&!rl&&r
203
MC/DC66%2/3
$submitted_token and $cookie_token and $self->_secure_compare($submitted_token, $cookie_token)
$submitted_token $cookie_token $self->_secure_compare($submitted_token, $cookie_token)
Truth table75%3/4
A and B and C
A= $submitted_tokenB= $cookie_tokenC= $self->_secure_compare($submitted_token, $cookie_token)
ABCresult
0XX0
10X0
1100
1111
116 3 await $self->_send_error($send, 403, 'CSRF token validation failed');
117 3 return;
118 }
119  
120 # Token valid, continue with request
121 2 my $modified_scope = $self->modify_scope($scope, {
122 csrf_token => $token,
123 });
124  
125 2 await $app->($modified_scope, $receive, $send);
126 5 };
127 }
128  
129 sub _generate_token {
130 5 ▶ my ($self) = @_;
Subroutine _generate_token: called CC=1 SCAR=0.0
131  
132 # Use cryptographically secure random bytes
133 5 my $random = secure_random_bytes(32);
134 5 return sha256_hex($self->{secret} . time() . $random . $$);
135 }
136  
137 sub _get_cookie_token {
138 8 ▶ my ($self, $scope) = @_;
Subroutine _get_cookie_token: called CC=3 SCAR=11.2
139  
140 8 my $cookie_header = $self->_get_header($scope, 'cookie');
141 8 ▶ return unless $cookie_header;
Branch: 1 branch
BranchTrueFalseTotal
unless $cookie_header 4 4 8
142  
143 4 my $name = $self->{cookie_name};
144 4 ▶ if ($cookie_header =~ /(?:^|;\s*)\Q$name\E=([^;]+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cookie_header =~ /(?:^|;\s*)\Q$name\E=([^;]+)/) 4 0 4
145 4 return $1;
146 }
147 0 return;
148 }
149  
150 sub _get_submitted_token {
151 5 ▶ my ($self, $scope) = @_;
Subroutine _get_submitted_token: called CC=2 SCAR=6.9
152  
153 # First check header
154 5 my $token = $self->_get_header($scope, $self->{token_header});
155 5 ▶ return $token if $token;
Branch: 1 branch
BranchTrueFalseTotal
if $token 3 2 5
156  
157 # Could also check query string for token_param, but that requires
158 # parsing query string which we'll skip for now
159 2 return;
160 }
161  
162 sub _get_header {
163 13 ▶ my ($self, $scope, $name) = @_;
Subroutine _get_header: called CC=4 SCAR=13.9
164  
165 13 $name = lc($name);
166 13 ▶ for my $h (@{$scope->{headers} // []}) {
Condition50%1/2
$scope->{"headers"} // []
l!l
130
MC/DC0%0/1
$scope->{"headers"} // []
$scope->{"headers"}
Truth table50%1/2
A
A= $scope->{"headers"}
Aresult
11
00
167 11 ▶ return $h->[1] if lc($h->[0]) eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if lc $h->[0] eq $name 7 4 11
168 }
169 6 return;
170 }
171  
172 # Constant-time string comparison to prevent timing attacks
173 sub _secure_compare {
174 17 ▶ my ($self, $a, $b) = @_;
Subroutine _secure_compare: called CC=5 SCAR=16.1
175  
176 17 ▶ return 0 unless defined $a && defined $b;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $a and defined $b 3 14 17
Condition100%3/3
defined $a and defined $b
!ll&&!rl&&r
2114
MC/DC100%2/2
defined $a and defined $b
defined $a defined $b
Truth table100%3/3
A and B
A= defined $aB= defined $b
ABresult
0X0
100
111
177 14 ▶ return 0 unless length($a) == length($b);
Branch: 1 branch
BranchTrueFalseTotal
unless length $a == length $b 5 9 14
178  
179 9 my $result = 0;
180 9 for my $i (0 .. length($a) - 1) {
181 2198 $result |= ord(substr($a, $i, 1)) ^ ord(substr($b, $i, 1));
182 }
183 9 return $result == 0;
184 }
185  
186 3 ▶async sub _send_error {
Subroutine _send_error: called CC=1 SCAR=0.0
187 3 my ($self, $send, $status, $message) = @_;
188  
189 3 await $send->({
190 type => 'http.response.start',
191 status => $status,
192 headers => [
193 ['content-type', 'text/plain'],
194 ['content-length', length($message)],
195 ],
196 });
197 3 await $send->({
198 type => 'http.response.body',
199 body => $message,
200 more => 0,
201 });
202 2 }
203  
204 2 1;
205  
206 __END__
« lib/PAGI/Middleware/SSE/Retry.pm ↑ Summary blib/lib/PAGI/WebSocket.pm »