lib/PAGI/Middleware/Auth/Bearer.pm

filter: Statementstmt 87.9% 109 / 124 Branchbran 51.8% 28 / 54 Conditioncond 57.1% 8 / 14 MC/DCmcdc 25.0% 2 / 8 Subroutinesub 100% 18 / 18 Podpod 100% 1 / 1 totaltotal 75.8% 166 / 219 CC 37 SCAR 22.6
CC
37
Cov
76%
_requires_auth
25.3
_validate_jwt
16.9
__ANON__
6.8
CRAP 9.6
« blib/lib/PAGI/SSE.pm ↑ Summary blib/lib/PAGI/Request/MultiPartHandler.pm »
1 package PAGI::Middleware::Auth::Bearer;
2 2 $PAGI::Middleware::Auth::Bearer::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 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 5 ▶sub _init {
Subroutine _init: called CC=5 SCAR=17.5
69 5 my ($self, $config) = @_;
70  
71 5 $self->{secret} = $config->{secret};
72 5 ▶ $self->{algorithms} = $config->{algorithms} // ['HS256'];
Condition50%1/2
$config->{"algorithms"} // ["HS256"]
l!l
05
MC/DC0%0/1
$config->{"algorithms"} // ["HS256"]
$config->{"algorithms"}
Truth table50%1/2
A
A= $config->{"algorithms"}
Aresult
11
00
73 5 $self->{validator} = $config->{validator};
74 5 ▶ $self->{realm} = $config->{realm} // 'Bearer';
Condition50%1/2
$config->{"realm"} // "Bearer"
l!l
05
MC/DC0%0/1
$config->{"realm"} // "Bearer"
$config->{"realm"}
Truth table50%1/2
A
A= $config->{"realm"}
Aresult
11
00
75 5 $self->{paths} = $config->{paths};
76  
77 die "Auth::Bearer requires 'secret' or 'validator' option"
78 5 ▶ unless $self->{secret} || $self->{validator};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"secret"} or $self->{"validator"} 0 5 5
Condition33%1/3
$self->{"secret"} or $self->{"validator"}
l!l&&r!l&&!r
500
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 4 ▶sub wrap {
Subroutine wrap: called CC=1 SCAR=0.2
Pod documented
82 4 my ($self, $app) = @_;
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 4 ▶sub _requires_auth {
Subroutine _requires_auth: called CC=6 SCAR=32.3
136 4 my ($self, $path) = @_;
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 3 ▶sub _parse_bearer_token {
Subroutine _parse_bearer_token: called CC=2 SCAR=7.1
151 3 my ($self, $header) = @_;
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 3 ▶sub _validate_token {
Subroutine _validate_token: called CC=2 SCAR=7.6
158 3 my ($self, $token) = @_;
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 3 ▶sub _validate_jwt {
Subroutine _validate_jwt: called CC=14 SCAR=28.3
170 3 my ($self, $token) = @_;
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 3 ▶sub _base64url_encode {
Subroutine _base64url_encode: called CC=1 SCAR=0.0
221 3 my ($self, $data) = @_;
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 8 ▶sub _secure_compare {
Subroutine _secure_compare: called CC=5 SCAR=16.1
230 8 my ($self, $a, $b) = @_;
231  
232 8 ▶ return 0 unless defined $a && defined $b;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $a and defined $b 5 3 8
Condition100%3/3
defined $a and defined $b
!ll&&!rl&&r
323
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
233 3 ▶ return 0 unless length($a) == length($b);
Branch: 1 branch
BranchTrueFalseTotal
unless length $a == length $b 0 3 3
234 3 my $result = 0;
235 3 for my $i (0 .. length($a) - 1) {
236 129 $result |= ord(substr($a, $i, 1)) ^ ord(substr($b, $i, 1));
237 }
238 3 return $result == 0;
239 }
240  
241 3 ▶async sub _send_unauthorized {
Subroutine _send_unauthorized: called CC=1 SCAR=0.0
242 3 my ($self, $send, $error) = @_;
243  
244 3 my $body = $error;
245  
246 3 await $send->({
247 type => 'http.response.start',
248 status => 401,
249 headers => [
250 ['Content-Type', 'text/plain'],
251 ['Content-Length', length($body)],
252 ['WWW-Authenticate', qq{Bearer realm="$self->{realm}"}],
253 ],
254 });
255 3 await $send->({
256 type => 'http.response.body',
257 body => $body,
258 more => 0,
259 });
260 2 }
261  
262 4 ▶sub _get_header {
Subroutine _get_header: called CC=4 SCAR=14.2
263 4 my ($self, $scope, $name) = @_;
264  
265 4 $name = lc($name);
266 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
267 3 ▶ return $h->[1] if lc($h->[0]) eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if lc $h->[0] eq $name 3 0 3
268 }
269 1 return;
270 }
271  
272 2 1;
273  
274 __END__
« blib/lib/PAGI/SSE.pm ↑ Summary blib/lib/PAGI/Request/MultiPartHandler.pm »