blib/lib/PAGI/Middleware/CSRF.pm

filter: Statementstmt 96.4% 82 / 85 Branchbran 90.0% 18 / 20 Conditioncond 75.8% 22 / 29 MC/DCmcdc 50.0% 8 / 16 Subroutinesub 100% 16 / 16 Podpod 100% 1 / 1 totaltotal 88.0% 147 / 167 CC 24 SCAR 16.8
CC
24
Cov
91%
_init
9.3
__ANON__
9.1
_get_header
4.0
CRAP 5.4
« blib/lib/PAGI/Middleware/ContentNegotiation.pm ↑ Summary lib/PAGI/App/WebSocket/Echo.pm »
1 package PAGI::Middleware::CSRF;
2 2 $PAGI::Middleware::CSRF::VERSION = '0.002002';
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 2 ▶use PAGI::Utils::SecureCompare qw(secure_compare);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =head1 NAME
12  
13 PAGI::Middleware::CSRF - Cross-Site Request Forgery protection middleware
14  
15 =head1 SYNOPSIS
16  
17 use PAGI::Middleware::Builder;
18  
19 my $app = builder {
20 enable 'CSRF',
21 secret => 'your-secret-key',
22 token_header => 'X-CSRF-Token',
23 cookie_name => 'csrf_token',
24 safe_methods => ['GET', 'HEAD', 'OPTIONS'];
25 $my_app;
26 };
27  
28 # Issue-only mode: the middleware never rejects; the app validates via
29 # $ctx->csrf_verify once it has parsed the submitted form/JSON params.
30 my $app2 = builder {
31 enable 'CSRF', secret => 'your-secret-key', enforce => 'app';
32 $my_app;
33 };
34  
35 =head1 DESCRIPTION
36  
37 PAGI::Middleware::CSRF provides protection against Cross-Site Request
38 Forgery attacks by validating tokens on state-changing requests.
39  
40 =head1 CONFIGURATION
41  
42 =over 4
43  
44 =item * secret (required)
45  
46 Secret key used for token generation.
47  
48 =item * token_header (default: 'X-CSRF-Token')
49  
50 Header name to look for the CSRF token.
51  
52 =item * cookie_name (default: 'csrf_token')
53  
54 Cookie name for the CSRF token.
55  
56 =item * safe_methods (default: ['GET', 'HEAD', 'OPTIONS', 'TRACE'])
57  
58 HTTP methods that don't require CSRF validation.
59  
60 =item * secure (default: 0)
61  
62 Add the C<Secure> attribute to the CSRF cookie, restricting it to HTTPS
63 requests. Off by default so plain-HTTP development setups keep working;
64 for production HTTPS deployments, add C<< secure => 1 >>.
65  
66 =item * enforce (default: 'header')
67  
68 How unsafe methods (anything not in C<safe_methods>) are checked:
69  
70 =over 4
71  
72 =item * C<'header'> - the middleware itself validates: the request must
73 carry a C<token_header> whose value matches the cookie token, or the
74 middleware responds 403 and the app is never called. This only works for
75 requests that can set a custom header (typically AJAX/fetch); a plain HTML
76 form POST has no way to add one, so a server-rendered form under this mode
77 would always 403 -- see L</USAGE> for why.
78  
79 =item * C<'app'> - issue-only. The middleware mints/persists the cookie
80 token exactly as it does for safe methods, on I<every> method, and never
81 auto-rejects. It stashes the cookie token (the existing one, or a freshly
82 minted one if none existed yet) into scope as C<csrf_token> for the app to
83 read via C<< $ctx->csrf_token >>. The app owns validation, by calling
84 C<< $ctx->csrf_verify($submitted) >> once it has parsed the request's
85 params, and decides the response for a failed check. This is what
86 server-rendered form POSTs need.
87  
88 =back
89  
90 =back
91  
92 =cut
93  
94 10 ▶sub _init {
Subroutine _init: called CC=9 SCAR=22.3
95 10 my ($self, $config) = @_;
96  
97 10 ▶ $self->{secret} = $config->{secret} // die "CSRF middleware requires 'secret' option";
Condition50%1/2
$config->{"secret"} // die("CSRF middleware requires 'secret' option")
l!l
100
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
98 10 ▶ $self->{token_header} = $config->{token_header} // 'X-CSRF-Token';
Condition50%1/2
$config->{"token_header"} // "X-CSRF-Token"
l!l
010
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
99 10 ▶ $self->{cookie_name} = $config->{cookie_name} // 'csrf_token';
Condition50%1/2
$config->{"cookie_name"} // "csrf_token"
l!l
010
MC/DC0%0/1
$config->{"cookie_name"} // "csrf_token"
$config->{"cookie_name"}
Truth table50%1/2
A
A= $config->{"cookie_name"}
Aresult
11
00
100 10 ▶ $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
010
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
101 10 ▶ $self->{secure} = $config->{secure} // 0;
Condition100%2/2
$config->{"secure"} // 0
l!l
19
MC/DC100%1/1
$config->{"secure"} // 0
$config->{"secure"}
Truth table100%2/2
A
A= $config->{"secure"}
Aresult
11
00
102  
103 10 ▶ $self->{enforce} = $config->{enforce} // 'header';
Condition100%2/2
$config->{"enforce"} // "header"
l!l
46
MC/DC100%1/1
$config->{"enforce"} // "header"
$config->{"enforce"}
Truth table100%2/2
A
A= $config->{"enforce"}
Aresult
11
00
104 die "CSRF middleware 'enforce' must be 'header' or 'app', got '$self->{enforce}'"
105 10 ▶ unless $self->{enforce} eq 'header' || $self->{enforce} eq 'app';
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"enforce"} eq "header" or $self->{"enforce"} eq "app" 1 9 10
Condition100%3/3
$self->{"enforce"} eq "header" or $self->{"enforce"} eq "app"
l!l&&r!l&&!r
721
MC/DC100%2/2
$self->{"enforce"} eq "header" or $self->{"enforce"} eq "app"
$self->{"enforce"} eq "header" $self->{"enforce"} eq "app"
Truth table100%3/3
A or B
A= $self->{"enforce"} eq "header"B= $self->{"enforce"} eq "app"
ABresult
1X1
011
000
106 }
107  
108 11 ▶sub wrap {
Subroutine wrap: called CC=1 SCAR=0.0
Pod documented
109 11 my ($self, $app) = @_;
110  
111 14 ▶ return async sub {
Subroutine __ANON__: called CC=9 SCAR=22.1
112 14 my ($scope, $receive, $send) = @_;
113 # Only handle HTTP requests
114 14 ▶ if ($scope->{type} ne 'http') {
Branch: 1 branch
BranchTrueFalseTotal
if ($scope->{"type"} ne "http") 0 14 14
115 0 await $app->($scope, $receive, $send);
116 0 return;
117 }
118  
119 14 my $method = $scope->{method};
120  
121 # Get existing token from cookie
122 14 my $cookie_token = $self->_get_cookie_token($scope);
123  
124 # Generate new token if none exists
125 14 ▶ my $token = $cookie_token // $self->_generate_token();
Condition66%2/3
$cookie_token // $self->_generate_token
l!l&&r!l&&!r
590
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
126  
127 # Safe methods always just issue the token. Under enforce => 'app', unsafe
128 # methods do too: the middleware never validates, it only issues; the app
129 # calls $ctx->csrf_verify once it has parsed the submitted params. Either
130 # way $token is the existing cookie token if there was one, never a
131 # regenerated one, so a submitted form token still has something to match.
132 14 ▶ if ($self->{safe_methods}{$method} || $self->{enforce} eq 'app') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"safe_methods"}{$method} or $self->{"enforce"} eq "app") 8 6 14
Condition100%3/3
$self->{"safe_methods"}{$method} or $self->{"enforce"} eq "app"
l!l&&r!l&&!r
626
MC/DC100%2/2
$self->{"safe_methods"}{$method} or $self->{"enforce"} eq "app"
$self->{"safe_methods"}{$method} $self->{"enforce"} eq "app"
Truth table100%3/3
A or B
A= $self->{"safe_methods"}{$method}B= $self->{"enforce"} eq "app"
ABresult
1X1
011
000
133 8 my $modified_scope = $self->modify_scope($scope, {
134 csrf_token => $token,
135 });
136  
137 # Add Set-Cookie if token is new
138 14 ▶ my $wrapped_send = $cookie_token ? $send : async sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
139 14 my ($event) = @_;
140 14 ▶ if ($event->{type} eq 'http.response.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event->{"type"} eq "http.response.start") 7 7 14
141 7 my $cookie = "$self->{cookie_name}=$token; Path=/; HttpOnly; SameSite=Strict";
142 7 ▶ $cookie .= "; Secure" if $self->{secure};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"secure"} 1 6 7
143 7 push @{$event->{headers}}, ['Set-Cookie', $cookie];
144 }
145 14 await $send->($event);
146 8 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$cookie_token ? : 1 7 8
147  
148 8 await $app->($modified_scope, $receive, $wrapped_send);
149 8 return;
150 }
151  
152 # Unsafe method under enforce => 'header': the middleware validates itself.
153 6 my $submitted_token = $self->_get_submitted_token($scope);
154  
155 # Use timing-safe comparison to prevent timing attacks
156 6 ▶ if (!$submitted_token || !$cookie_token || !secure_compare($submitted_token, $cookie_token)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($submitted_token and $cookie_token and secure_compare($submitted_token, $cookie_token)) 4 2 6
Condition83%5/6
$submitted_token and $cookie_token and secure_compare($submitted_token, $cookie_token)
!ll&&!rl&&r
312
$submitted_token and $cookie_token
!ll&&!rl&&r
303
MC/DC66%2/3
$submitted_token and $cookie_token and secure_compare($submitted_token, $cookie_token)
$submitted_token $cookie_token secure_compare($submitted_token, $cookie_token)
Truth table75%3/4
A and B and C
A= $submitted_tokenB= $cookie_tokenC= secure_compare($submitted_token, $cookie_token)
ABCresult
0XX0
10X0
1100
1111
157 4 await $self->_send_error($send, 403, 'CSRF token validation failed');
158 4 return;
159 }
160  
161 # Token valid, continue with request
162 2 my $modified_scope = $self->modify_scope($scope, {
163 csrf_token => $token,
164 });
165  
166 2 await $app->($modified_scope, $receive, $send);
167 11 };
168 }
169  
170 10 ▶sub _generate_token {
Subroutine _generate_token: called CC=1 SCAR=0.0
171 10 my ($self) = @_;
172  
173 # Use cryptographically secure random bytes
174 10 my $random = secure_random_bytes(32);
175 10 return sha256_hex($self->{secret} . time() . $random . $$);
176 }
177  
178 14 ▶sub _get_cookie_token {
Subroutine _get_cookie_token: called CC=3 SCAR=11.2
179 14 my ($self, $scope) = @_;
180  
181 14 my $cookie_header = $self->_get_header($scope, 'cookie');
182 14 ▶ return unless $cookie_header;
Branch: 1 branch
BranchTrueFalseTotal
unless $cookie_header 9 5 14
183  
184 5 my $name = $self->{cookie_name};
185 5 ▶ if ($cookie_header =~ /(?:^|;\s*)\Q$name\E=([^;]+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cookie_header =~ /(?:^|;\s*)\Q$name\E=([^;]+)/) 5 0 5
186 5 return $1;
187 }
188 0 return;
189 }
190  
191 6 ▶sub _get_submitted_token {
Subroutine _get_submitted_token: called CC=1 SCAR=0.0
192 6 my ($self, $scope) = @_;
193 6 return $self->_get_header($scope, $self->{token_header});
194 }
195  
196 20 ▶sub _get_header {
Subroutine _get_header: called CC=4 SCAR=13.9
197 20 my ($self, $scope, $name) = @_;
198  
199 20 $name = lc($name);
200 20 ▶ for my $h (@{$scope->{headers} // []}) {
Condition50%1/2
$scope->{"headers"} // []
l!l
200
MC/DC0%0/1
$scope->{"headers"} // []
$scope->{"headers"}
Truth table50%1/2
A
A= $scope->{"headers"}
Aresult
11
00
201 12 ▶ return $h->[1] if lc($h->[0]) eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if lc $h->[0] eq $name 8 4 12
202 }
203 12 return;
204 }
205  
206 4 ▶async sub _send_error {
Subroutine _send_error: called CC=1 SCAR=0.0
207 4 my ($self, $send, $status, $message) = @_;
208  
209 4 await $send->({
210 type => 'http.response.start',
211 status => $status,
212 headers => [
213 ['content-type', 'text/plain'],
214 ['content-length', length($message)],
215 ],
216 });
217 4 await $send->({
218 type => 'http.response.body',
219 body => $message,
220 more => 0,
221 });
222 2 }
223  
224 2 1;
225  
226 __END__
« blib/lib/PAGI/Middleware/ContentNegotiation.pm ↑ Summary lib/PAGI/App/WebSocket/Echo.pm »