OpenIDConnect/Utils/JWT.pm

filter: Statementstmt 92.4% 122 / 132 Branchbran 74.1% 43 / 58 Conditioncond 66.6% 6 / 9 MC/DCmcdc 40.0% 2 / 5 Subroutinesub 86.3% 19 / 22 Podpod 100% 6 / 6 totaltotal 85.3% 198 / 232 CC 36 SCAR 21.3
CC
36
Cov
86%
__ANON__
16.2
sign_token
12.2
create_access_token
6.0
CRAP 8.4
« OpenIDConnect/Context.pm ↑ Summary OpenIDConnect/Utils/Store.pm »
1 package Catalyst::Plugin::OpenIDConnect::Utils::JWT;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 3 ▶use JSON::MaybeXS qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use MIME::Base64 qw(encode_base64 decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use Digest::SHA qw(sha256);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Crypt::OpenSSL::RSA;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 =head1 NAME
16  
17 Catalyst::Plugin::OpenIDConnect::Utils::JWT - JWT handling for OpenID Connect
18  
19 =head1 DESCRIPTION
20  
21 Provides JWT signing and verification functionality using RS256 (RSA SHA-256) algorithm
22 for OpenID Connect token creation and validation.
23  
24 =head1 ATTRIBUTES
25  
26 =head2 private_key
27  
28 The RSA private key for signing tokens.
29  
30 =cut
31  
32 3 has private_key => (
33 is => 'ro',
34 isa => 'Crypt::OpenSSL::RSA',
35 required => 1,
36 );
37  
38 =head2 public_key
39  
40 The RSA public key for verifying tokens.
41  
42 =cut
43  
44 3 has public_key => (
45 is => 'ro',
46 isa => 'Crypt::OpenSSL::RSA',
47 required => 1,
48 );
49  
50 =head2 key_id
51  
52 The key ID (kid) used in JWT headers.
53  
54 =cut
55  
56 3 has key_id => (
57 is => 'ro',
58 isa => 'Str',
59 required => 1,
60 );
61  
62 =head2 issuer
63  
64 The issuer URL/identifier for the iss claim.
65  
66 =cut
67  
68 3 has issuer => (
69 is => 'ro',
70 isa => 'Str',
71 required => 1,
72 );
73  
74 =head2 logger
75  
76 Optional logger instance for debug/info logging.
77  
78 =cut
79  
80 3 has logger => (
81 is => 'ro',
82 isa => 'Maybe[Object]',
83 required => 0,
84 );
85  
86 =head1 METHODS
87  
88 =head2 sign_token(%payload)
89  
90 Signs a JWT token with the configured private key using RS256 algorithm.
91  
92 Returns the complete JWT (header.payload.signature).
93  
94 =cut
95  
96 7 ▶sub sign_token {
Subroutine sign_token: called CC=12 SCAR=25.0
Pod documented
97 7 my ( $self, %payload ) = @_;
98  
99 7 ▶ $self->logger->debug('Signing JWT token') if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 1 6 7
100  
101 # Set standard claims
102 7 ▶ $payload{iss} = $self->issuer unless defined $payload{iss};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload{"iss"} 6 1 7
103 7 ▶ $payload{iat} = time() unless defined $payload{iat};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload{"iat"} 7 0 7
104  
105 # RFC 7519 §4.1.2 requires these claims (and jti, handled elsewhere)
106 # to be a StringOrURI value.
107 7 for my $claim (qw(iss aud sub)) {
108 21 ▶ if ( defined $payload{$claim} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $payload{$claim}) 21 0 21
109 21 $payload{$claim} = "$payload{$claim}";
110 }
111 }
112  
113 # Log only non-sensitive metadata — never log PII-bearing claims (MED-2).
114 7 ▶ if ( $self->logger ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->logger) 1 6 7
115 $self->logger->debug( sprintf(
116 'Signing JWT: sub=%s aud=%s exp=%s',
117 1 ▶ $payload{sub} // '?', $payload{aud} // '?', $payload{exp} // '?',
Condition50%3/6
$payload{"sub"} // "?"
l!l
10
$payload{"aud"} // "?"
l!l
10
$payload{"exp"} // "?"
l!l
10
MC/DC0%0/1
$payload{"sub"} // "?"
$payload{"sub"}
MC/DC0%0/1
$payload{"aud"} // "?"
$payload{"aud"}
MC/DC0%0/1
$payload{"exp"} // "?"
$payload{"exp"}
Truth table50%1/2
A
A= $payload{"sub"}
Aresult
11
00
Truth table50%1/2
A
A= $payload{"aud"}
Aresult
11
00
Truth table50%1/2
A
A= $payload{"exp"}
Aresult
11
00
118 ));
119 }
120  
121 # Prep header
122 7 my %header = (
123 alg => 'RS256',
124 typ => 'JWT',
125 kid => $self->key_id,
126 );
127  
128 # Encode header and payload
129 7 my $header_json = encode_json( \%header );
130  
131 # Perl's JSON serialiser encodes a scalar as a JSON string if the SvPOK
132 # (string) flag is set, even when the value is also numeric. Reading a
133 # number through a string context — e.g. the sprintf() debug statement
134 # above — sets that flag. Explicitly numify all timestamp claims with
135 # int() to clear SvPOK before serialisation so they are always encoded
136 # as JSON integers (e.g. 1746000000, not "1746000000"). Python's authlib and
137 # other compliant RPs reject string-typed exp/iat/nbf values.
138 $payload{$_} = int( $payload{$_} )
139 7 for grep { defined $payload{$_} } qw(exp iat nbf);
140  
141 7 my $payload_json = encode_json( \%payload );
142  
143 7 my $header_b64 = _urlsafe_b64_encode($header_json);
144 7 my $payload_b64 = _urlsafe_b64_encode($payload_json);
145  
146 # Create signature (explicitly use SHA256 for RS256)
147 7 my $signing_input = "$header_b64.$payload_b64";
148 7 my $priv_key = $self->private_key;
149 # Ensure consistent RSA configuration for signing (RFC 3447 PKCS1v15)
150 7 $priv_key->use_pkcs1_padding();
151 7 $priv_key->use_sha256_hash();
152 7 my $signature = $priv_key->sign($signing_input);
153 7 my $signature_b64 = _urlsafe_b64_encode($signature);
154  
155 7 my $token = "$signing_input.$signature_b64";
156
157 7 ▶ if ( $self->logger ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->logger) 1 6 7
158 1 $self->logger->debug( sprintf(
159 'JWT signed: header_b64_len=%d, payload_b64_len=%d, sig_b64_len=%d, total_len=%d',
160 length($header_b64), length($payload_b64), length($signature_b64), length($token),
161 ));
162 1 $self->logger->debug("JWT token (first 80 chars): " . substr($token, 0, 80) . "...");
163 }
164
165 7 return $token;
166 }
167  
168 =head2 verify_token($token, %opts)
169  
170 Verifies a JWT token with the configured public key.
171  
172 Mandatory claims C<exp> and C<iss> are always validated. The C<nbf>
173 claim is validated when present. Pass C<expected_audience> to also
174 validate the C<aud> claim:
175  
176 $jwt->verify_token($token, expected_audience => 'my-client-id');
177  
178 Returns a hashref with decoded claims on success.
179 Raises an exception on verification failure.
180  
181 =cut
182  
183 13 ▶sub verify_token {
Subroutine verify_token: called CC=2 SCAR=7.0
Pod documented
184 13 my ( $self, $token, %opts ) = @_;
185 13 my $expected_audience = $opts{expected_audience};
186  
187 13 ▶ $self->logger->debug('Verifying JWT token') if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 13 13
188  
189 13 ▶ return try {
Subroutine __ANON__: called CC=16 SCAR=27.8
190 13 my @parts = split /\./, $token;
191 13 ▶ die 'Invalid JWT format' unless @parts == 3;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts == 3 0 13 13
192  
193 13 my ( $header_b64, $payload_b64, $signature_b64 ) = @parts;
194  
195 13 ▶ $self->logger->debug('JWT format validated (3 parts)') if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 13 13
196  
197 # Verify signature (explicitly use SHA256 for RS256)
198 13 my $signing_input = "$header_b64.$payload_b64";
199 13 my $signature = _urlsafe_b64_decode($signature_b64);
200  
201 13 my $pub_key = $self->public_key;
202 # Ensure consistent RSA configuration for verification (RFC 3447 PKCS1v15)
203 13 $pub_key->use_pkcs1_padding();
204 13 $pub_key->use_sha256_hash();
205 13 ▶ die 'Invalid signature' unless $pub_key->verify(
Branch: 1 branch
BranchTrueFalseTotal
unless $pub_key->verify($signing_input, $signature) 1 12 13
206 $signing_input,
207 $signature
208 );
209  
210 12 ▶ $self->logger->debug('JWT signature verified') if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 12 12
211  
212 # Decode payload
213 12 my $payload_json = _urlsafe_b64_decode($payload_b64);
214 12 my $payload = decode_json($payload_json);
215  
216 12 ▶ $self->logger->debug('JWT payload decoded successfully') if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 12 12
217  
218 # --- Mandatory claim validation (RFC 7519 §4.1, OIDC Core §2) ---
219 # exp and iss must be present and valid; a token that omits them
220 # must be rejected regardless of its signature.
221 12 ▶ die 'Missing exp claim' unless defined $payload->{exp};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload->{"exp"} 1 11 12
222 11 ▶ die 'Token expired' if $payload->{exp} < time();
Branch: 1 branch
BranchTrueFalseTotal
if $payload->{"exp"} < time 2 9 11
223 9 ▶ die 'Missing iss claim' unless defined $payload->{iss};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload->{"iss"} 1 8 9
224 8 ▶ die 'Invalid issuer' unless $payload->{iss} eq $self->issuer;
Branch: 1 branch
BranchTrueFalseTotal
unless $payload->{"iss"} eq $self->issuer 1 7 8
225  
226 # nbf (not-before) is optional but must be honoured when present
227 die 'Token not yet valid'
228 7 ▶ if defined $payload->{nbf} && $payload->{nbf} > time();
Branch: 1 branch
BranchTrueFalseTotal
if defined $payload->{"nbf"} and $payload->{"nbf"} > time 1 6 7
Condition100%3/3
defined $payload->{"nbf"} and $payload->{"nbf"} > time
!ll&&!rl&&r
511
MC/DC100%2/2
defined $payload->{"nbf"} and $payload->{"nbf"} > time
defined $payload->{"nbf"} $payload->{"nbf"} > time
Truth table100%3/3
A and B
A= defined $payload->{"nbf"}B= $payload->{"nbf"} > time
ABresult
0X0
100
111
229  
230 # aud — validated when the caller supplies an expected value
231 6 ▶ if ( defined $expected_audience ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $expected_audience) 3 3 6
232 3 ▶ die 'Missing aud claim' unless defined $payload->{aud};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload->{"aud"} 1 2 3
233 2 ▶ die 'Invalid audience' unless $payload->{aud} eq $expected_audience;
Branch: 1 branch
BranchTrueFalseTotal
unless $payload->{"aud"} eq $expected_audience 1 1 2
234 }
235  
236 4 ▶ $self->logger->debug('JWT claims validated') if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 4 4
237  
238 4 return $payload;
239 }
240 9 ▶ catch {
Subroutine __ANON__: called CC=2 SCAR=7.2
241 9 ▶ $self->logger->warn("Token verification failed: $_") if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 9 9
242 9 die "Token verification failed: $_";
243 13 };
244 }
245  
246 =head2 create_id_token(%claims)
247  
248 Creates a signed ID token with the specified claims.
249  
250 The following claims are automatically set if not provided:
251 - exp: Expiration time (1 hour from now, required by OIDC/JWT spec)
252 - iat: Issued at time (current time)
253 - iss: Issuer URL
254  
255 =cut
256  
257 4 ▶sub create_id_token {
Subroutine create_id_token: called CC=2 SCAR=6.9
Pod documented
258 4 my ( $self, %claims ) = @_;
259  
260 # Ensure exp is set - this is MANDATORY per RFC 7519 and OIDC spec
261 # If not provided, default to 1 hour from now
262 4 ▶ unless ( defined $claims{exp} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $claims{"exp"}) 1 3 4
263 1 $claims{exp} = time() + 3600;
264 }
265  
266 4 my %payload = (
267 typ => 'JWT',
268 %claims,
269 );
270  
271 4 return $self->sign_token(%payload);
272 }
273  
274 =head2 create_access_token(%claims)
275  
276 Creates a signed access token with the specified claims.
277  
278 The exp (expiration) claim is mandatory and will be set to 1 hour from now
279 if not explicitly provided.
280  
281 =cut
282  
283 0 ▶sub create_access_token {
Subroutine create_access_token: not called CC=2 SCAR=17.9
Pod documented
284 0 my ( $self, %claims ) = @_;
285  
286 # Ensure exp is set - this is MANDATORY per RFC 7519
287 0 ▶ unless ( defined $claims{exp} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $claims{"exp"}) 0 0 0
288 0 $claims{exp} = time() + 3600;
289 }
290  
291 0 return $self->sign_token(%claims);
292 }
293  
294 =head2 create_refresh_token(%claims)
295  
296 Creates a signed refresh token with the specified claims.
297  
298 The exp (expiration) claim is mandatory and will be set to 30 days from now
299 if not explicitly provided.
300  
301 =cut
302  
303 0 ▶sub create_refresh_token {
Subroutine create_refresh_token: not called CC=2 SCAR=17.9
Pod documented
304 0 my ( $self, %claims ) = @_;
305  
306 # Ensure exp is set - this is MANDATORY per RFC 7519
307 # Refresh tokens have a longer lifetime (30 days)
308 0 ▶ unless ( defined $claims{exp} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $claims{"exp"}) 0 0 0
309 0 $claims{exp} = time() + (30 * 24 * 3600);
310 }
311  
312 0 return $self->sign_token(%claims);
313 }
314  
315 =head2 decode_id_token_hint($token)
316  
317 Decodes a JWT passed as an C<id_token_hint> during logout.
318  
319 Verifies the token signature against the configured public key to confirm
320 it was genuinely issued by this server, but deliberately skips expiry
321 validation; hint tokens are frequently expired at logout time by design.
322  
323 Returns a hashref of the token's claims on success, or C<undef> if the
324 token is malformed or the signature cannot be verified.
325  
326 =cut
327  
328 7 ▶sub decode_id_token_hint {
Subroutine decode_id_token_hint: called CC=1 SCAR=0.1
Pod documented
329 7 my ( $self, $token ) = @_;
330  
331 7 ▶ return try {
Subroutine __ANON__: called CC=3 SCAR=11.0
332 7 my @parts = split /\./, $token;
333 7 ▶ return undef unless @parts == 3;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts == 3 3 4 7
334  
335 4 my ( $header_b64, $payload_b64, $signature_b64 ) = @parts;
336  
337 # Verify signature — ensures the token was genuinely issued by us
338 # and was not crafted by an attacker to spoof a client_id.
339 4 my $signing_input = "$header_b64.$payload_b64";
340 4 my $signature = _urlsafe_b64_decode($signature_b64);
341 4 my $pub_key = $self->public_key;
342 # Ensure consistent RSA configuration for verification (RFC 3447 PKCS1v15)
343 4 $pub_key->use_pkcs1_padding();
344 4 $pub_key->use_sha256_hash();
345 4 ▶ return undef unless $pub_key->verify( $signing_input, $signature );
Branch: 1 branch
BranchTrueFalseTotal
unless $pub_key->verify($signing_input, $signature) 2 2 4
346  
347 2 my $payload_json = _urlsafe_b64_decode($payload_b64);
348 2 return decode_json($payload_json);
349 }
350 0 ▶ catch {
Subroutine __ANON__: not called CC=2 SCAR=17.9
351 0 ▶ $self->logger->warn("id_token_hint decode failed: $_") if $self->logger;
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 0 0 0
352 0 return undef;
353 7 };
354 }
355  
356 # Helper: URL-safe base64 encode (RFC 4648 Section 5)
357 21 ▶sub _urlsafe_b64_encode {
Subroutine _urlsafe_b64_encode: called CC=1 SCAR=0.0
358 21 my ($data) = @_;
359 21 my $b64 = encode_base64($data, '');
360 21 $b64 =~ tr|+/|-_|;
361 21 $b64 =~ s/=+$//;
362 21 return $b64;
363 }
364  
365 # Helper: URL-safe base64 decode (RFC 4648 Section 5)
366 31 ▶sub _urlsafe_b64_decode {
Subroutine _urlsafe_b64_decode: called CC=2 SCAR=6.9
367 31 my ($data) = @_;
368 31 $data =~ tr|-_|+/|;
369 31 my $padding = length($data) % 4;
370 31 ▶ $data .= '=' x ( 4 - $padding ) if $padding;
Branch: 1 branch
BranchTrueFalseTotal
if $padding 22 9 31
371 31 return decode_base64($data);
372 }
373  
374 3 __PACKAGE__->meta->make_immutable;
375 3 1;
376  
377 =head1 AUTHOR
378  
379 Tim F. Rayner
380  
381 =head1 LICENSE
382  
383 This library is free software; you can redistribute it and/or modify
384 it under the terms of The Artistic License 2.0.
385  
386 =cut
« OpenIDConnect/Context.pm ↑ Summary OpenIDConnect/Utils/Store.pm »