blib/lib/Mojo/JWT.pm

filter: Statementstmt 88.6% 117 / 132 Branchbran 64.2% 45 / 70 Conditioncond 76.1% 16 / 21 MC/DCmcdc 36.3% 4 / 11 Subroutinesub 90.9% 20 / 22 Podpod 100% 7 / 7 totaltotal 79.4% 209 / 263 CC 44 SCAR 20.0
CC
44
Cov
80%
decode
19.0
encode
7.3
_try_jwks
6.3
CRAP 7.4
↑ Summary
1 package Mojo::JWT;
2  
3 1 ▶use Mojo::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 our $VERSION = '1.02';
6 1 $VERSION = eval $VERSION;
7  
8 1 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use List::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Mojo::JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 1 ▶use CryptX;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Crypt::Misc ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 1 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 13 ▶my $isa = sub { Scalar::Util::blessed $_[0] && $_[0]->isa($_[1]) };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_[0]) and $_[0]->isa($_[1]) 5 8 13
18  
19 10 ▶has header => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
20 1 has algorithm => 'HS256';
21 1 has [qw/allow_none set_iat/] => 0;
22 0 ▶has claims => sub { {} };
Subroutine __ANON__: not called CC=1 SCAR=1.2
23 14 ▶has jwks => sub { [] };
Subroutine __ANON__: called CC=1 SCAR=0.0
24 1 has [qw/expires not_before/];
25 1 has [qw/public secret/] => '';
26  
27 1 my $re_hs = qr/^HS(\d+)$/;
28 1 my $re_rs = qr/^RS(\d+)$/;
29  
30 2 ▶sub add_jwkset {
Subroutine add_jwkset: called CC=3 SCAR=12.3
Pod documented
31 2 my ($self, $jwkset) = @_;
32 2 ▶ if (ref $jwkset eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $jwkset eq "HASH") 2 0 2
33 2 push @{ $self->jwks }, @{ $jwkset->{keys} };
34 }
35 2 ▶ if (ref $jwkset eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $jwkset eq "ARRAY") 0 2 2
36 0 push @{ $self->jwks }, @{ $jwkset };
37 }
38 2 return $self;
39 }
40  
41 17 ▶sub decode {
Subroutine decode: called CC=14 SCAR=29.4
Pod documented
42 17 my ($self, $token, $peek) = @_;
43 17 $self->{token} = $token;
44  
45 # reset
46 17 $self->algorithm(undef);
47 17 delete $self->{$_} for qw/claims expires not_before header/;
48  
49 17 my ($hstring, $cstring, $signature) = split /\./, $token;
50 17 my $header = Mojo::JSON::decode_json Crypt::Misc::decode_b64u($hstring);
51 17 my $claims = Mojo::JSON::decode_json Crypt::Misc::decode_b64u($cstring);
52 17 $signature = Crypt::Misc::decode_b64u $signature;
53  
54 # typ header is only recommended and is ignored
55 # https://tools.ietf.org/html/rfc7519#section-5.1
56 17 delete $header->{typ};
57 Carp::croak 'Required header field "alg" not specified'
58 17 ▶ unless my $algo = $self->algorithm(delete $header->{alg})->algorithm;
Branch: 1 branch
BranchTrueFalseTotal
unless my $algo = $self->algorithm(delete $header->{"alg"})->algorithm 0 17 17
59 17 $self->header($header);
60  
61 17 $self->_try_jwks($algo, $header);
62  
63 17 ▶ $self->$peek($claims) if $peek;
Branch: 1 branch
BranchTrueFalseTotal
if $peek 0 17 17
64  
65 # check signature
66 17 my $payload = "$hstring.$cstring";
67 17 ▶ if ($algo eq 'none') {
Branch: 3 branches
BranchTrueFalseTotal
if ($algo eq 'none') { } 1 16 17
elsif ($algo =~ /$re_rs/u) { } 8 8 16
elsif ($algo =~ /$re_hs/u) { } 8 0 8
68 1 ▶ Carp::croak 'Algorithm "none" is prohibited'
Branch: 1 branch
BranchTrueFalseTotal
unless $self->allow_none 0 1 1
69 unless $self->allow_none;
70 } elsif ($algo =~ $re_rs) {
71 8 ▶ Carp::croak 'Failed RS validation'
Branch: 1 branch
BranchTrueFalseTotal
unless $self->verify_rsa($1, $payload, $signature) 1 5 6
72 unless $self->verify_rsa($1, $payload, $signature);
73 } elsif ($algo =~ $re_hs) {
74 8 ▶ Carp::croak 'Failed HS validation'
Branch: 1 branch
BranchTrueFalseTotal
unless Mojo::Util::secure_compare($signature, $self->sign_hmac($1, $payload)) 1 6 7
75 unless Mojo::Util::secure_compare($signature, $self->sign_hmac($1, $payload));
76 } else {
77 0 Carp::croak 'Unsupported signing algorithm';
78 }
79  
80 # check timing
81 12 my $now = $self->now;
82 12 ▶ if (defined(my $exp = $claims->{exp})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $exp = $claims->{"exp"})) 0 12 12
83 0 ▶ Carp::croak 'JWT has expired' if $now > $exp;
Branch: 1 branch
BranchTrueFalseTotal
if $now > $exp 0 0 0
84 0 $self->expires($exp);
85 }
86 12 ▶ if (defined(my $nbf = $claims->{nbf})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $nbf = $claims->{"nbf"})) 0 12 12
87 0 ▶ Carp::croak 'JWT is not yet valid' if $now < $nbf;
Branch: 1 branch
BranchTrueFalseTotal
if $now < $nbf 0 0 0
88 0 $self->not_before($nbf);
89 }
90  
91 12 return $self->claims($claims)->claims;
92 }
93  
94 17 ▶sub _try_jwks {
Subroutine _try_jwks: called CC=6 SCAR=18.4
95 17 my ($self, $algo, $header) = @_;
96 17 ▶ return unless @{$self->jwks} && $header->{kid};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->jwks;} and $header->{"kid"} 13 4 17
Condition100%3/3
@{$self->jwks;} and $header->{"kid"}
!ll&&!rl&&r
1214
MC/DC100%2/2
@{$self->jwks;} and $header->{"kid"}
@{$self->jwks;} $header->{"kid"}
Truth table100%3/3
A and B
A= @{$self->jwks;}B= $header->{"kid"}
ABresult
0X0
100
111
97  
98 # Check we have the JWK for this JWT
99 4 ▶ my $jwk = List::Util::first { exists $header->{kid} && $_->{kid} eq $header->{kid} } @{$self->jwks};
Subroutine __ANON__: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
exists $header->{"kid"} and $_->{"kid"} eq $header->{"kid"} 4 0 4
100 4 ▶ return unless $jwk;
Branch: 1 branch
BranchTrueFalseTotal
unless $jwk 1 3 4
101  
102 3 ▶ if ($algo =~ $re_rs) {
Branch: 2 branches
BranchTrueFalseTotal
if ($algo =~ /$re_rs/u) { } 3 0 3
elsif ($algo =~ /$re_hs/u) { } 0 0 0
103 3 require Crypt::PK::RSA;
104 3 my $pubkey = Crypt::PK::RSA->new($jwk);
105 3 $self->public($pubkey);
106 } elsif ($algo =~ $re_hs) {
107 $self->secret( Crypt::Misc::decode_b64u $jwk->{k} )
108 0 }
109 }
110  
111 12 ▶sub encode {
Subroutine encode: called CC=7 SCAR=19.8
Pod documented
112 12 my $self = shift;
113 12 delete $self->{token};
114  
115 12 my $claims = $self->claims;
116 12 ▶ if ($self->set_iat) { $claims->{iat} = $self->now }
Branch: 1 branch
BranchTrueFalseTotal
if ($self->set_iat) 1 11 12
117 0 ▶ if (defined(my $exp = $self->expires)) { $claims->{exp} = $exp }
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $exp = $self->expires)) 0 12 12
118 0 ▶ if (defined(my $nbf = $self->not_before)) { $claims->{nbf} = $nbf }
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $nbf = $self->not_before)) 0 12 12
119  
120 12 my $header = { %{ $self->header }, typ => 'JWT', alg => $self->algorithm };
121 12 my $hstring = Crypt::Misc::encode_b64u Mojo::JSON::encode_json($header);
122 12 my $cstring = Crypt::Misc::encode_b64u Mojo::JSON::encode_json($claims);
123 12 my $payload = "$hstring.$cstring";
124 12 my $signature;
125 12 my $algo = $self->algorithm;
126 12 ▶ if ($algo eq 'none') {
Branch: 3 branches
BranchTrueFalseTotal
if ($algo eq 'none') { } 1 11 12
elsif ($algo =~ /$re_rs/u) { } 3 8 11
elsif ($algo =~ /$re_hs/u) { } 8 0 8
127 1 $signature = '';
128 } elsif ($algo =~ $re_rs) {
129 3 $signature = $self->sign_rsa($1, $payload);
130 } elsif ($algo =~ $re_hs) {
131 8 $signature = $self->sign_hmac($1, $payload);
132 } else {
133 0 Carp::croak 'Unknown algorithm';
134 }
135  
136 11 return $self->{token} = "$payload." . Crypt::Misc::encode_b64u $signature;
137 }
138  
139 11 ▶sub now { time }
Subroutine now: called CC=1 SCAR=0.0
140  
141 16 ▶sub sign_hmac {
Subroutine sign_hmac: called CC=5 SCAR=16.1
Pod documented
142 16 my ($self, $size, $payload) = @_;
143 16 ▶ Carp::croak 'symmetric secret not specified' unless my $secret = $self->secret;
Branch: 1 branch
BranchTrueFalseTotal
unless my $secret = $self->secret 1 15 16
144 15 ▶ Carp::croak 'Unsupported HS signing algorithm' unless $size == 256 || $size == 384 || $size == 512;
Branch: 1 branch
BranchTrueFalseTotal
unless $size == 256 or $size == 384 or $size == 512 1 14 15
Condition83%5/6
$size == 256 or $size == 384 or $size == 512
l!l&&r!l&&!r
1221
$size == 256 or $size == 384
l!l&&r!l&&!r
1203
MC/DC66%2/3
$size == 256 or $size == 384 or $size == 512
$size == 256 $size == 384 $size == 512
Truth table75%3/4
A or B or C
A= $size == 256B= $size == 384C= $size == 512
ABCresult
1XX1
01X1
0011
0000
145 14 require Crypt::Mac::HMAC;
146 14 return Crypt::Mac::HMAC::hmac("SHA$size", $secret, $payload);
147 }
148  
149 3 ▶sub sign_rsa {
Subroutine sign_rsa: called CC=5 SCAR=17.0
Pod documented
150 3 my ($self, $size, $payload) = @_;
151 3 ▶ Carp::croak 'Unsupported RS signing algorithm' unless $size == 256 || $size == 384 || $size == 512;
Branch: 1 branch
BranchTrueFalseTotal
unless $size == 256 or $size == 384 or $size == 512 0 3 3
Condition66%4/6
$size == 256 or $size == 384 or $size == 512
l!l&&r!l&&!r
120
$size == 256 or $size == 384
l!l&&r!l&&!r
102
MC/DC0%0/3
$size == 256 or $size == 384 or $size == 512
$size == 256 $size == 384 $size == 512
Truth table50%2/4
A or B or C
A= $size == 256B= $size == 384C= $size == 512
ABCresult
1XX1
01X1
0011
0000
152 3 ▶ Carp::croak 'secret key not specified' unless my $secret = $self->secret;
Branch: 1 branch
BranchTrueFalseTotal
unless my $secret = $self->secret 0 3 3
153 3 my $crypt = _inflate_rsa_key($secret);
154 3 return $crypt->sign_message($payload, "SHA$size", 'v1.5');
155 }
156  
157 0 ▶sub token { shift->{token} }
Subroutine token: not called CC=1 SCAR=6.9
Pod documented
158  
159 8 ▶sub verify_rsa {
Subroutine verify_rsa: called CC=5 SCAR=16.5
Pod documented
160 8 my ($self, $size, $payload, $signature) = @_;
161 8 ▶ Carp::croak 'Unsupported RS verification algorithm' unless $size == 256 || $size == 384 || $size == 512;
Branch: 1 branch
BranchTrueFalseTotal
unless $size == 256 or $size == 384 or $size == 512 0 8 8
Condition66%4/6
$size == 256 or $size == 384 or $size == 512
l!l&&r!l&&!r
620
$size == 256 or $size == 384
l!l&&r!l&&!r
602
MC/DC0%0/3
$size == 256 or $size == 384 or $size == 512
$size == 256 $size == 384 $size == 512
Truth table50%2/4
A or B or C
A= $size == 256B= $size == 384C= $size == 512
ABCresult
1XX1
01X1
0011
0000
162 8 ▶ Carp::croak 'public key not specified' unless my $public = $self->public;
Branch: 1 branch
BranchTrueFalseTotal
unless my $public = $self->public 2 6 8
163 6 my $crypt = _inflate_rsa_key($public);
164 6 return $crypt->verify_message($signature, $payload, "SHA$size", 'v1.5');
165 }
166  
167 9 ▶sub _inflate_rsa_key {
Subroutine _inflate_rsa_key: called CC=4 SCAR=15.2
168 9 my ($key) = @_;
169 9 require Crypt::PK::RSA;
170 9 ▶ return $key if $key->$isa('Crypt::PK::RSA');
Branch: 1 branch
BranchTrueFalseTotal
if $key->$isa("Crypt::PK::RSA") 5 4 9
171 4 ▶ if ($key->$isa('Crypt::OpenSSL::RSA')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key->$isa("Crypt::OpenSSL::RSA")) 0 4 4
172 0 ▶ $key = $key->is_private ? $key->get_private_key_string : $key->get_public_key_string;
Branch: 1 branch
BranchTrueFalseTotal
$key->is_private ? : 0 0 0
173 }
174 4 return Crypt::PK::RSA->new(\$key);
175 }
176  
177 1 1;
178  
179 =head1 NAME
180  
181 Mojo::JWT - JSON Web Token the Mojo way
182  
183 =head1 SYNOPSIS
184  
185 my $jwt = Mojo::JWT->new(claims => {...}, secret => 's3cr3t')->encode;
186 my $claims = Mojo::JWT->new(secret => 's3cr3t')->decode($jwt);
187  
188 =head1 DESCRIPTION
189  
190 JSON Web Token is described in L<https://tools.ietf.org/html/rfc7519>.
191 L<Mojo::JWT> implements that standard with an API that should feel familiar to L<Mojolicious> users (though of course it is useful elsewhere).
192 Indeed, JWT is much like L<Mojolicious::Sessions> except that the result is a url-safe text string rather than a cookie.
193  
194 In JWT, the primary payload is called the C<claims>, and a few claims are reserved, as seen in the IETF document.
195 The header and the claims are signed when stringified to guard against tampering.
196 Note that while signed, the data is not encrypted, so don't use it to send secrets over clear channels.
197  
198 =head1 ATTRIBUTES
199  
200 L<Mojo::JWT> inherits all of the attributes from L<Mojo::Base> and implements the following new ones.
201  
202 =head2 algorithm
203  
204 The algorithm to be used to sign a JWT during encoding or else the algorithm that was used for the most recent decoding.
205 Defaults to C<HS256> until a decode is performed.
206  
207 C<none> is an acceptable encoding algorithm, however for it to be used to decode, L</allow_none> must be set.
208  
209 =head2 allow_none
210  
211 To prevent spoofing attacks, C<allow_none> must be explicitly set to a true value otherwise decoding a JWT which specifies the C<none> algorithm will result in an exception.
212 The default is of course false.
213  
214 =head2 claims
215  
216 The payload to be encoded or else the claims from the most recent decoding.
217 This must be a hash reference, array references are not allowed as the top-level JWT claims.
218  
219 =head2 expires
220  
221 The epoch time value after which the JWT value should not be considered valid.
222 This value (if set and not undefined) will be used as the C<exp> key in the claims or was extracted from the claims during the most recent decoding.
223  
224 =head2 header
225  
226 You may set your own headers when encoding the JWT bypassing a hash reference to the L</header> attribute. Please note that there are two default headers set. B<alg> is set to the value of L</algorithm> or 'HS256' and B<typ> is set to 'JWT'. These cannot be overridden.
227  
228 =head2 not_before
229  
230 The epoch time value before which the JWT value should not be considered valid.
231 This value (if set and not undefined) will be used as the C<nbf> key in the claims or was extracted from the claims during the most recent decoding.
232  
233 =head2 public
234  
235 The public key to be used in decoding an asymmetrically signed JWT (eg. RSA).
236 This can be any public key in a string format accepted by L<Crypt::PK::RSA> or a L<Crypt::PK::RSA> object (if used a L<Crypt::OpenSSL::RSA> object will be converted).
237  
238 =head2 secret
239  
240 The symmetric secret (eg. HMAC) or else the private key used in encoding an asymmetrically signed JWT (eg. RSA).
241 Symmetric secrets should be a string.
242 A private key can be in a string format accepted by L<Crypt::PK::RSA> or a L<Crypt::PK::RSA> object (if used a L<Crypt::OpenSSL::RSA> object will be converted).
243  
244 =head2 set_iat
245  
246 If true (false by default), then the C<iat> claim will be set to the value of L</now> during L</encode>.
247  
248 =head2 jwks
249  
250 An arrayref of JWK objects used by C<decode> to verify the input token when matching with the JWTs C<kid> field.
251  
252 my $jwks = Mojo::UserAgent->new->get('https://example.com/oidc/jwks.json')->result->json('/keys');
253 my $jwt = Mojo::JWT->new(jwks => $jwks);
254 $jwk->decode($token);
255  
256 =head1 METHODS
257  
258 L<Mojo::JWT> inherits all of the methods from L<Mojo::Base> and implements the following new ones.
259  
260 =head2 add_jwkset
261  
262 my $jwkset = Mojo::UserAgent->new->get('https://example.com/oidc/jwks.json')->result->json;
263 my $jwt = Mojo::JWT->new->add_jwkset($jwksset);
264 $jwk->decode($token);
265  
266 Helper for appending a jwkset to the L</jwks>.
267 Accepts a hashref with a C<keys> field that is an arrayref of jwks and also an arrayref directly.
268 Appends the JWKs to L</jwks>.
269 Returns the instance.
270  
271 =head2 decode
272  
273 my $claims = $jwt->decode($token);
274  
275 my $peek = sub { my ($jwt, $claims) = @_; ... };
276 my $claims = $jwt->decode($token, $peek);
277  
278 Decode and parse a JSON Web Token string and return the claims hashref.
279 Calling this function immediately sets the L</token> to the passed in token.
280 It also sets L</algorithm> to C<undef> and unsets L</claims>, L</expires> and L</not_before>.
281 These values are then set as part of the parsing process.
282  
283 Parsing occurs as follows
284  
285 =over
286  
287 =item *
288  
289 The L</algorithm> is extracted from the header and set, if not present or permissible an exception is thrown
290  
291 =item *
292  
293 Any JWKs in C</jwks> are checked against the headers and if one is found then it is set in L</public> or L</secret> as appropriate to the L</algorithm>
294  
295 =item *
296  
297 If a C<$peek> callback is provided, it is called with the instance and claims as arguments
298  
299 =item *
300  
301 The signature is verified or an exception is thrown
302  
303 =item *
304  
305 The timing claims (L</expires> and L</not_before>), if present, are evaluated, failures result in exceptions. On success the values are set in the relevant attributes
306  
307 =item *
308  
309 The L</claims> attribute is set and the claims are returned.
310  
311 =back
312  
313 Note that when the C<$peek> callback is invoked, the claims have not yet been verified.
314 This callback is most likely to be used to inspect the C<iss> or issuer claim to determine a secret or key for decoding.
315 The return value is ignored, changes should be made to the instances attributes directly.
316 Since the L</algorithm> has already been parsed, it is available via the instance attribute as well.
317  
318 =head2 encode
319  
320 my $token = $jwt->encode;
321  
322 Encode the data expressed in the instance attributes: L</algorithm>, L</claims>, L</expires>, L</not_before>.
323 Note that if the timing attributes are given, they override existing keys in the L</claims>.
324 Calling C<encode> immediately clears the L</token> and upon completion sets it to the result as well as returning it.
325  
326 Note also that due to Perl's hash randomization, repeated encoding is not guaranteed to result in the same encoded string.
327 However any encoded string will survive an encode/decode roundtrip.
328  
329 =head2 header
330  
331 my $header = $jwt->header;
332  
333 Returns a hash reference representing the JWT header, constructed from instance attributes (see L</algorithm>).
334  
335 =head2 now
336  
337 my $time = $jwt->now;
338  
339 Returns the current time, currently implemented as the core C<time> function.
340  
341 =head2 sign_hmac
342  
343 my $signature = $jwt->sign_hmac($size, $payload);
344  
345 Returns the HMAC SHA signature for the given size and payload.
346 The L</secret> attribute is used as the symmetric key.
347 The result is not yet base64 encoded.
348 This method is provided mostly for the purposes of subclassing.
349  
350 =head2 sign_rsa
351  
352 my $signature = $jwt->sign_rsa($size, $payload);
353  
354 Returns the RSA signature for the given size and payload.
355 The L</secret> attribute is used as the private key.
356 The result is not yet base64 encoded.
357 This method is provided mostly for the purposes of subclassing.
358  
359 =head2 token
360  
361 The most recently encoded or decoded token.
362 Note that any attribute modifications are not taken into account until L</encode> is called again.
363  
364 =head2 verify_rsa
365  
366 my $bool = $jwt->verify_rsa($size, $payload, $signature);
367  
368 Returns true if the given RSA size algorithm validates the given payload and signature.
369 The L</public> attribute is used as the public key.
370 This method is provided mostly for the purposes of subclassing.
371  
372 =head1 SEE ALSO
373  
374 =over
375  
376 =item L<Acme::JWT>
377  
378 =item L<JSON::WebToken>
379  
380 =item L<http://jwt.io/>
381  
382 =back
383  
384 =head1 SOURCE REPOSITORY
385  
386 L<http://github.com/jberger/Mojo-JWT>
387  
388 =head1 AUTHOR
389  
390 Joel Berger, E<lt>joel.a.berger@gmail.comE<gt>
391  
392 =head1 CONTRIBUTORS
393  
394 Christopher Raa (mishanti1)
395  
396 Cameron Daniel (ccakes)
397  
398 Olaf Alders (oalders)
399  
400 =head1 COPYRIGHT AND LICENSE
401  
402 Copyright (C) 2015 by L</AUTHOR> and L</CONTRIBTORS>.
403  
404 This library is free software; you can redistribute it and/or modify
405 it under the same terms as Perl itself.
406  
↑ Summary