lib/PAGI/Middleware/Auth/Bearer.pm

filter: Statementstmt 87.8% 108 / 123 Branchbran 50.0% 26 / 52 Conditioncond 45.4% 5 / 11 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 100% 18 / 18 Podpod 100% 1 / 1 totaltotal 74.8% 158 / 211 CC 35 SCAR 22.7
CC
35
Cov
75%
_requires_auth
25.3
_validate_jwt
16.9
__ANON__
6.8
CRAP 9.7
« lib/PAGI/Middleware/SecurityHeaders.pm ↑ Summary blib/lib/PAGI/Request/MultiPartHandler.pm »
1 package PAGI::Middleware::Auth::Bearer;
2 2 $PAGI::Middleware::Auth::Bearer::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 JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use MIME::Base64 qw(decode_base64url);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use Digest::SHA qw(hmac_sha256);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =head1 NAME
12  
13 PAGI::Middleware::Auth::Bearer - Bearer token authentication middleware
14  
15 =head1 SYNOPSIS
16  
17 use PAGI::Middleware::Builder;
18  
19 my $app = builder {
20 enable 'Auth::Bearer',
21 secret => 'your-jwt-secret',
22 algorithms => ['HS256'];
23 $my_app;
24 };
25  
26 # In your app:
27 async sub app {
28 my ($scope, $receive, $send) = @_;
29  
30 my $auth = $scope->{'pagi.auth'};
31 my $user_id = $auth->{claims}{sub};
32 }
33  
34 =head1 DESCRIPTION
35  
36 PAGI::Middleware::Auth::Bearer validates Bearer tokens in the Authorization
37 header. It supports JWT (JSON Web Tokens) with HMAC-SHA256 signatures.
38  
39 =head1 CONFIGURATION
40  
41 =over 4
42  
43 =item * secret (required for JWT)
44  
45 Secret key for JWT signature verification.
46  
47 =item * algorithms (default: ['HS256'])
48  
49 Allowed JWT algorithms.
50  
51 =item * validator (optional)
52  
53 Custom token validator coderef. Receives ($token) and returns claims hashref or undef.
54 If provided, bypasses built-in JWT validation.
55  
56 =item * realm (default: 'Bearer')
57  
58 The authentication realm for WWW-Authenticate header.
59  
60 =item * paths (optional)
61  
62 Arrayref of path patterns to protect.
63  
64 =back
65  
66 =cut
67  
68 sub _init {
69 4 ▶ my ($self, $config) = @_;
Subroutine _init: called CC=5 SCAR=17.5
70  
71 4 $self->{secret} = $config->{secret};
72 4 ▶ $self->{algorithms} = $config->{algorithms} // ['HS256'];
Condition50%1/2
$config->{"algorithms"} // ["HS256"]
l!l
04
MC/DC0%0/1
$config->{"algorithms"} // ["HS256"]
$config->{"algorithms"}
Truth table50%1/2
A
A= $config->{"algorithms"}
Aresult
11
00
73 4 $self->{validator} = $config->{validator};
74 4 ▶ $self->{realm} = $config->{realm} // 'Bearer';
Condition50%1/2
$config->{"realm"} // "Bearer"
l!l
04
MC/DC0%0/1
$config->{"realm"} // "Bearer"
$config->{"realm"}
Truth table50%1/2
A
A= $config->{"realm"}
Aresult
11
00
75 4 $self->{paths} = $config->{paths};
76  
77 die "Auth::Bearer requires 'secret' or 'validator' option"
78 4 ▶ unless $self->{secret} || $self->{validator};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"secret"} or $self->{"validator"} 0 4 4
Condition33%1/3
$self->{"secret"} or $self->{"validator"}
l!l&&r!l&&!r
400
MC/DC0%0/2
$self->{"secret"} or $self->{"validator"}
$self->{"secret"} $self->{"validator"}
Truth table33%1/3
A or B
A= $self->{"secret"}B= $self->{"validator"}
ABresult
1X1
011
000
79 }
80  
81 sub wrap {
82 4 ▶ my ($self, $app) = @_;
Subroutine wrap: called CC=1 SCAR=0.2
Pod documented
83  
84 4 ▶ return async sub {
Subroutine __ANON__: called CC=6 SCAR=19.2
85 4 my ($scope, $receive, $send) = @_;
86 4 ▶ if ($scope->{type} ne 'http') {
Branch: 1 branch
BranchTrueFalseTotal
if ($scope->{"type"} ne "http") 0 4 4
87 0 await $app->($scope, $receive, $send);
88 0 return;
89 }
90  
91 # Check if path requires authentication
92 4 ▶ unless ($self->_requires_auth($scope->{path})) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_requires_auth($scope->{"path"})) 0 4 4
93 0 await $app->($scope, $receive, $send);
94 0 return;
95 }
96  
97 # Get Authorization header
98 4 my $auth_header = $self->_get_header($scope, 'authorization');
99  
100 4 ▶ unless ($auth_header) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($auth_header) 1 3 4
101 1 await $self->_send_unauthorized($send, 'Token required');
102 1 return;
103 }
104  
105 # Parse Bearer token
106 3 my $token = $self->_parse_bearer_token($auth_header);
107  
108 3 ▶ unless ($token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($token) 0 3 3
109 0 await $self->_send_unauthorized($send, 'Invalid authorization header');
110 0 return;
111 }
112  
113 # Validate token
114 3 my $claims = $self->_validate_token($token);
115  
116 3 ▶ unless ($claims) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($claims) 2 1 3
117 2 await $self->_send_unauthorized($send, 'Invalid token');
118 2 return;
119 }
120  
121 # Add auth info to scope
122 1 my $new_scope = {
123 %$scope,
124 'pagi.auth' => {
125 type => 'bearer',
126 token => $token,
127 claims => $claims,
128 },
129 };
130  
131 1 await $app->($new_scope, $receive, $send);
132 4 };
133 }
134  
135 sub _requires_auth {
136 4 ▶ my ($self, $path) = @_;
Subroutine _requires_auth: called CC=6 SCAR=32.3
137  
138 4 ▶ return 1 unless $self->{paths};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"paths"} 4 0 4
139  
140 0 for my $pattern (@{$self->{paths}}) {
141 0 ▶ if (ref $pattern eq 'Regexp') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pattern eq 'Regexp') { } 0 0 0
142 0 ▶ return 1 if $path =~ $pattern;
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ /$pattern/ 0 0 0
143 } else {
144 0 ▶ return 1 if index($path, $pattern) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($path, $pattern) == 0 0 0 0
145 }
146 }
147 0 return 0;
148 }
149  
150 sub _parse_bearer_token {
151 3 ▶ my ($self, $header) = @_;
Subroutine _parse_bearer_token: called CC=2 SCAR=7.1
152  
153 3 ▶ return unless $header =~ /^Bearer\s+(.+)$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $header =~ /^Bearer\s+(.+)$/i 0 3 3
154 3 return $1;
155 }
156  
157 sub _validate_token {
158 3 ▶ my ($self, $token) = @_;
Subroutine _validate_token: called CC=2 SCAR=7.6
159  
160 # Use custom validator if provided
161 3 ▶ if ($self->{validator}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"validator"}) 0 3 3
162 0 return $self->{validator}->($token);
163 }
164  
165 # Validate as JWT
166 3 return $self->_validate_jwt($token);
167 }
168  
169 sub _validate_jwt {
170 3 ▶ my ($self, $token) = @_;
Subroutine _validate_jwt: called CC=14 SCAR=28.3
171  
172 3 my @parts = split /\./, $token;
173 3 ▶ return unless @parts == 3;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts == 3 0 3 3
174  
175 3 my ($header_b64, $payload_b64, $signature_b64) = @parts;
176  
177 # Decode and parse header
178 3 my $header_json = eval { decode_base64url($header_b64) };
179 3 ▶ return unless $header_json;
Branch: 1 branch
BranchTrueFalseTotal
unless $header_json 0 3 3
180 3 my $header = eval { JSON::MaybeXS::decode_json($header_json) };
181 3 ▶ return unless $header;
Branch: 1 branch
BranchTrueFalseTotal
unless $header 0 3 3
182  
183 # Check algorithm
184 3 ▶ my $alg = $header->{alg} // '';
Condition50%1/2
$header->{"alg"} // ""
l!l
30
MC/DC0%0/1
$header->{"alg"} // ""
$header->{"alg"}
Truth table50%1/2
A
A= $header->{"alg"}
Aresult
11
00
185 3 ▶ return unless grep { $_ eq $alg } @{$self->{algorithms}};
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $alg;} @{$$self{"algorithms"};} 0 3 3
186  
187 # Verify signature
188 3 my $signature_input = "$header_b64.$payload_b64";
189 3 my $expected_signature;
190  
191 3 ▶ if ($alg eq 'HS256') {
Branch: 1 branch
BranchTrueFalseTotal
if ($alg eq 'HS256') { } 3 0 3
192 $expected_signature = $self->_base64url_encode(
193 hmac_sha256($signature_input, $self->{secret})
194 3 );
195 } else {
196 0 return; # Unsupported algorithm
197 }
198  
199 3 ▶ return unless $self->_secure_compare($signature_b64, $expected_signature);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_secure_compare($signature_b64, $expected_signature) 1 2 3
200  
201 # Decode payload
202 2 my $payload_json = eval { decode_base64url($payload_b64) };
203 2 ▶ return unless $payload_json;
Branch: 1 branch
BranchTrueFalseTotal
unless $payload_json 0 2 2
204 2 my $claims = eval { JSON::MaybeXS::decode_json($payload_json) };
205 2 ▶ return unless $claims;
Branch: 1 branch
BranchTrueFalseTotal
unless $claims 0 2 2
206  
207 # Check expiration
208 2 ▶ if (exists $claims->{exp}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $claims->{"exp"}) 2 0 2
209 2 ▶ return if time() > $claims->{exp};
Branch: 1 branch
BranchTrueFalseTotal
if time > $claims->{"exp"} 1 1 2
210 }
211  
212 # Check not-before
213 1 ▶ if (exists $claims->{nbf}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $claims->{"nbf"}) 0 1 1
214 0 ▶ return if time() < $claims->{nbf};
Branch: 1 branch
BranchTrueFalseTotal
if time < $claims->{"nbf"} 0 0 0
215 }
216  
217 1 return $claims;
218 }
219  
220 sub _base64url_encode {
221 3 ▶ my ($self, $data) = @_;
Subroutine _base64url_encode: called CC=1 SCAR=0.0
222  
223 3 my $encoded = MIME::Base64::encode_base64($data, '');
224 3 $encoded =~ tr{+/}{-_};
225 3 $encoded =~ s/=+$//;
226 3 return $encoded;
227 }
228  
229 sub _secure_compare {
230 3 ▶ my ($self, $a, $b) = @_;
Subroutine _secure_compare: called CC=3 SCAR=11.0
231  
232 3 ▶ return 0 unless length($a) == length($b);
Branch: 1 branch
BranchTrueFalseTotal
unless length $a == length $b 0 3 3
233 3 my $result = 0;
234 3 for my $i (0 .. length($a) - 1) {
235 129 $result |= ord(substr($a, $i, 1)) ^ ord(substr($b, $i, 1));
236 }
237 3 return $result == 0;
238 }
239  
240 3 ▶async sub _send_unauthorized {
Subroutine _send_unauthorized: called CC=1 SCAR=0.0
241 3 my ($self, $send, $error) = @_;
242  
243 3 my $body = $error;
244  
245 3 await $send->({
246 type => 'http.response.start',
247 status => 401,
248 headers => [
249 ['Content-Type', 'text/plain'],
250 ['Content-Length', length($body)],
251 ['WWW-Authenticate', qq{Bearer realm="$self->{realm}"}],
252 ],
253 });
254 3 await $send->({
255 type => 'http.response.body',
256 body => $body,
257 more => 0,
258 });
259 2 }
260  
261 sub _get_header {
262 4 ▶ my ($self, $scope, $name) = @_;
Subroutine _get_header: called CC=4 SCAR=14.2
263  
264 4 $name = lc($name);
265 4 ▶ for my $h (@{$scope->{headers} // []}) {
Condition50%1/2
$scope->{"headers"} // []
l!l
40
MC/DC0%0/1
$scope->{"headers"} // []
$scope->{"headers"}
Truth table50%1/2
A
A= $scope->{"headers"}
Aresult
11
00
266 3 ▶ return $h->[1] if lc($h->[0]) eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if lc $h->[0] eq $name 3 0 3
267 }
268 1 return;
269 }
270  
271 2 1;
272  
273 __END__
« lib/PAGI/Middleware/SecurityHeaders.pm ↑ Summary blib/lib/PAGI/Request/MultiPartHandler.pm »