OpenIDConnect/Controller/Root.pm

filter: Statementstmt 18.0% 73 / 405 Branchbran 4.1% 8 / 192 Conditioncond 3.7% 3 / 80 MC/DCmcdc 4.0% 2 / 49 Subroutinesub 53.6% 22 / 41 Podpod 100% 7 / 7 totaltotal 14.8% 115 / 774 CC 127 SCAR 63.2
CC
127
Cov
12%
authorize
1482.0
_handle_authorization_code_grant
756.0
logout
506.0
CRAP 554.3
↑ Summary OpenIDConnect.pm »
1 package Catalyst::Plugin::OpenIDConnect::Controller::Root;
2  
3 3 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 ▶BEGIN { extends 'Catalyst::Controller'; }
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 encode_base64url);
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::PK::RSA;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Crypt::Misc qw(slow_eq);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 3 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 3 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use Data::UUID;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 # Set the namespace for OpenIDConnect routes
19 3 __PACKAGE__->config(namespace => 'openidconnect');
20  
21 # Module-level UUID generator for refresh token JTI claims (MED-1).
22 3 my $_uuid = Data::UUID->new();
23  
24 =head1 NAME
25  
26 Catalyst::Plugin::OpenIDConnect::Controller::Root - OIDC Protocol Endpoints
27  
28 =head1 SYNOPSIS
29  
30 Handles OpenID Connect protocol endpoints:
31  
32 /.well-known/openid-configuration - Discovery endpoint
33 /openidconnect/authorize - Authorization endpoint
34 /openidconnect/token - Token endpoint
35 /openidconnect/userinfo - UserInfo endpoint
36 /openidconnect/logout - Logout endpoint
37 /openidconnect/jwks - JWKS endpoint for key discovery
38  
39 =cut
40  
41 =head1 DESCRIPTION
42  
43 This controller implements the core OpenID Connect protocol endpoints. To use it in your application, create a controller that extends this one:
44  
45 package MyApp::Controller::Auth;
46 use Moose;
47 use namespace::autoclean;
48  
49 BEGIN { extends 'Catalyst::Plugin::OpenIDConnect::Controller::Root'; }
50  
51 __PACKAGE__->meta->make_immutable;
52  
53 =head1 METHODS
54  
55 =head2 begin
56  
57 Called automatically before every action in this controller. Sets HTTP
58 security headers that must be present on all OIDC endpoint responses.
59  
60 =cut
61  
62 1 ▶sub begin : Private {
Subroutine begin: called CC=1 SCAR=0.0
Pod documented
63 1 my ( $self, $c ) = @_;
64  
65 # RFC 6749 §5.1 requires Cache-Control: no-store on token responses;
66 # applied globally so new endpoints can't accidentally omit it.
67 # Pragma: no-cache is the HTTP/1.0 equivalent.
68 1 $c->response->header( 'Cache-Control' => 'no-store' );
69 1 $c->response->header( 'Pragma' => 'no-cache' );
70  
71 # Prevent MIME sniffing.
72 1 $c->response->header( 'X-Content-Type-Options' => 'nosniff' );
73  
74 # Clickjacking protection on the authorize endpoint HTML page.
75 # Both headers are set for broadest browser compatibility (MED-6).
76 1 $c->response->header( 'X-Frame-Options' => 'DENY' );
77 1 $c->response->header( 'Content-Security-Policy' => "frame-ancestors 'none'" );
78 3 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
79  
80 =head2 discovery
81  
82 GET /.well-known/openid-configuration
83  
84 Returns the OpenID Connect provider configuration.
85  
86 =cut
87  
88 0 ▶sub discovery : Path('/.well-known/openid-configuration') {
Subroutine discovery: not called CC=2 SCAR=17.9
Pod documented
89 0 my ( $self, $c ) = @_;
90  
91 0 my $config = $c->openidconnect->config;
92  
93 0 ▶ $c->log->debug('OpenID Connect discovery endpoint accessed') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
94 0 $self->_json_response( $c, $c->openidconnect->get_discovery() );
95 3 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
96  
97 =head2 authorize
98  
99 GET /openidconnect/authorize
100  
101 OpenID Connect authorization endpoint.
102  
103 Query parameters:
104  
105 - response_type (REQUIRED): "code"
106 - client_id (REQUIRED): The client ID
107 - redirect_uri (REQUIRED): Where to redirect after authorization
108 - scope (RECOMMENDED): Space-separated scopes (default: "openid")
109 - state (RECOMMENDED): CSRF protection state parameter
110 - nonce (OPTIONAL): String to bind to the ID token
111  
112 =cut
113  
114 0 ▶sub authorize : Local {
Subroutine authorize: not called CC=38 SCAR=73.0
Pod documented
115 0 my ( $self, $c ) = @_;
116  
117 0 my $config = $c->openidconnect->config;
118  
119 0 ▶ $c->log->debug('Authorization endpoint accessed') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
120  
121 0 my $response_type = $c->request->params->{response_type};
122 0 my $client_id = $c->request->params->{client_id};
123 0 my $redirect_uri = $c->request->params->{redirect_uri};
124 0 my $scope = $c->request->params->{scope};
125 0 my $state = $c->request->params->{state};
126 0 my $nonce = $c->request->params->{nonce};
127 0 my $code_challenge = $c->request->params->{code_challenge};
128 0 my $code_challenge_method = $c->request->params->{code_challenge_method};
129  
130 0 ▶ $c->log->debug("Authorization request - client_id: $client_id, response_type: $response_type, redirect_uri: $redirect_uri") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
131  
132 0 ▶ my $stored_auth_request = $c->session->{oidc_auth_request} || {};
Condition0%0/2
$c->session->{'oidc_auth_request'} || {}
l!l
00
MC/DC0%0/1
$c->session->{'oidc_auth_request'} || {}
$c->session->{'oidc_auth_request'}
Truth table0%0/2
A
A= $c->session->{'oidc_auth_request'}
Aresult
11
00
133 0 ▶ $response_type //= $stored_auth_request->{response_type};
Condition0%0/3
$response_type //= $stored_auth_request->{"response_type"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$response_type //= $stored_auth_request->{"response_type"}
$response_type $stored_auth_request->{"response_type"}
Truth table0%0/3
A //= B
A= $response_typeB= $stored_auth_request->{"response_type"}
ABresult
1X1
011
000
134 0 ▶ $client_id //= $stored_auth_request->{client_id};
Condition0%0/3
$client_id //= $stored_auth_request->{"client_id"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$client_id //= $stored_auth_request->{"client_id"}
$client_id $stored_auth_request->{"client_id"}
Truth table0%0/3
A //= B
A= $client_idB= $stored_auth_request->{"client_id"}
ABresult
1X1
011
000
135 0 ▶ $redirect_uri //= $stored_auth_request->{redirect_uri};
Condition0%0/3
$redirect_uri //= $stored_auth_request->{"redirect_uri"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$redirect_uri //= $stored_auth_request->{"redirect_uri"}
$redirect_uri $stored_auth_request->{"redirect_uri"}
Truth table0%0/3
A //= B
A= $redirect_uriB= $stored_auth_request->{"redirect_uri"}
ABresult
1X1
011
000
136 0 ▶ $scope ||= $stored_auth_request->{scope} || 'openid';
Condition0%0/5
$scope ||= $stored_auth_request->{"scope"} || "openid"
l!l&&r!l&&!r
000
$stored_auth_request->{'scope'} || 'openid'
l!l
00
MC/DC0%0/2
$scope ||= $stored_auth_request->{"scope"} || "openid"
$scope $stored_auth_request->{'scope'}
Truth table0%0/3
A ||= B
A= $scopeB= $stored_auth_request->{'scope'}
ABresult
1X1
011
000
137 0 ▶ $state //= $stored_auth_request->{state};
Condition0%0/3
$state //= $stored_auth_request->{"state"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$state //= $stored_auth_request->{"state"}
$state $stored_auth_request->{"state"}
Truth table0%0/3
A //= B
A= $stateB= $stored_auth_request->{"state"}
ABresult
1X1
011
000
138 0 ▶ $nonce //= $stored_auth_request->{nonce};
Condition0%0/3
$nonce //= $stored_auth_request->{"nonce"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$nonce //= $stored_auth_request->{"nonce"}
$nonce $stored_auth_request->{"nonce"}
Truth table0%0/3
A //= B
A= $nonceB= $stored_auth_request->{"nonce"}
ABresult
1X1
011
000
139 0 ▶ $code_challenge //= $stored_auth_request->{code_challenge};
Condition0%0/3
$code_challenge //= $stored_auth_request->{"code_challenge"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$code_challenge //= $stored_auth_request->{"code_challenge"}
$code_challenge $stored_auth_request->{"code_challenge"}
Truth table0%0/3
A //= B
A= $code_challengeB= $stored_auth_request->{"code_challenge"}
ABresult
1X1
011
000
140 0 ▶ $code_challenge_method //= $stored_auth_request->{code_challenge_method};
Condition0%0/3
$code_challenge_method //= $stored_auth_request->{"code_challenge_method"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$code_challenge_method //= $stored_auth_request->{"code_challenge_method"}
$code_challenge_method $stored_auth_request->{"code_challenge_method"}
Truth table0%0/3
A //= B
A= $code_challenge_methodB= $stored_auth_request->{"code_challenge_method"}
ABresult
1X1
011
000
141  
142 # --- Phase 1: validate client_id and redirect_uri BEFORE using either in a
143 # redirect-based error response (NEW-HIGH-1 / RFC 6749 §4.1.2.1).
144 # Any error raised here returns a direct HTTP 400; we must never redirect
145 # to a URI that has not yet been confirmed as registered for the client.
146  
147 0 ▶ unless ($client_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client_id) 0 0 0
148 0 $c->log->warn('Missing client_id parameter');
149 0 return $self->_json_error( $c, 'invalid_request', 'client_id is required' );
150 }
151  
152 0 ▶ unless ($redirect_uri) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($redirect_uri) 0 0 0
153 0 $c->log->warn('Missing redirect_uri parameter');
154 0 return $self->_json_error( $c, 'invalid_request', 'redirect_uri is required' );
155 }
156  
157 # Resolve client — must succeed before redirect_uri can be validated.
158 0 my $client = $c->openidconnect->get_client($client_id);
159 0 ▶ unless ($client) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client) 0 0 0
160 0 $c->log->error("Unknown client: $client_id");
161 0 return $self->_json_error( $c, 'invalid_client', 'Unknown client' );
162 }
163  
164 # Validate redirect_uri against the registered list.
165 # Only after this check is it safe to use $redirect_uri in _error_response.
166 0 my @allowed_uris = _normalize_uri_list( $client->{redirect_uris} );
167 0 ▶ unless ( grep { $_ eq $redirect_uri } @allowed_uris ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $redirect_uri;} @allowed_uris) 0 0 0
168 0 $c->log->error("Redirect URI mismatch for client $client_id: $redirect_uri");
169 0 return $self->_json_error( $c, 'invalid_request',
170 'Redirect URI not registered' );
171 }
172  
173 # --- Phase 2: remaining parameter validation — redirect_uri is now
174 # confirmed registered so _error_response redirects are safe from here on.
175  
176 0 ▶ unless ( $response_type && $response_type eq 'code' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response_type and $response_type eq "code") 0 0 0
Condition0%0/3
$response_type and $response_type eq "code"
!ll&&!rl&&r
000
MC/DC0%0/2
$response_type and $response_type eq "code"
$response_type $response_type eq "code"
Truth table0%0/3
A and B
A= $response_typeB= $response_type eq "code"
ABresult
0X0
100
111
177 0 $c->log->warn("Invalid response_type: $response_type");
178 0 return $self->_error_response(
179 $c, $redirect_uri, 'invalid_request',
180 'response_type must be "code"', $state
181 );
182 }
183  
184 # Restrict scope to the intersection of what was requested and what this
185 # client is registered for (NEW-MED-2 / RFC 6749 §3.3).
186 # Accepting arbitrary scope strings allows clients to obtain tokens
187 # bearing scopes they were never granted (e.g. "admin").
188 {
189 0 ▶ my @registered = split /\s+/, ( $client->{scope} // 'openid' );
Condition0%0/2
$client->{"scope"} // "openid"
l!l
00
MC/DC0%0/1
$client->{"scope"} // "openid"
$client->{"scope"}
Truth table0%0/2
A
A= $client->{"scope"}
Aresult
11
00
190 0 my @requested = split /\s+/, $scope;
191 0 my %allowed = map { $_ => 1 } @registered;
192 0 my @effective = grep { $allowed{$_} } @requested;
193 0 ▶ unless (@effective) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@effective) 0 0 0
194 0 $c->log->warn(
195 "No permitted scopes in request for client $client_id: $scope"
196 );
197 0 return $self->_error_response(
198 $c, $redirect_uri, 'invalid_scope',
199 'None of the requested scopes are registered for this client',
200 $state
201 );
202 }
203 # OIDC Core §3.1.2.1 — openid scope is mandatory for OIDC requests.
204 0 ▶ unless ( grep { $_ eq 'openid' } @effective ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq "openid";} @effective) 0 0 0
205 0 $c->log->warn("Missing openid scope for client $client_id");
206 0 return $self->_error_response(
207 $c, $redirect_uri, 'invalid_scope',
208 'openid scope is required', $state
209 );
210 }
211 0 $scope = join ' ', @effective;
212 $c->log->debug("Effective scope for client $client_id: $scope")
213 0 ▶ if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
214 }
215  
216 # Apply the custom scope handler if one has been registered. It runs
217 # after the built-in intersection so the handler only ever sees scopes
218 # that are already permitted for the client. If the handler throws, the
219 # request is rejected with an invalid_scope error.
220 0 ▶ if ( my $handler = $c->openidconnect->scope_handler ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $handler = $c->openidconnect->scope_handler) 0 0 0
221 0 my @processed;
222 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
223 0 @processed = $handler->( $c, $scope );
224 }
225 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
226 0 ( my $msg = $_ ) =~ s/\s+at\s+\S.*//s; # strip file/line from die message
227 0 $c->log->warn("Scope handler rejected request: $msg");
228 0 return $self->_error_response(
229 $c, $redirect_uri, 'invalid_scope',
230 "Scope validation failed: $msg", $state
231 );
232 0 };
233 0 ▶ if (@processed) {
Branch: 1 branch
BranchTrueFalseTotal
if (@processed) 0 0 0
234 0 ▶ $scope = join ' ', grep { defined $_ && length $_ } @processed;
Condition0%0/3
defined $_ && length $_
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table0%0/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
235 }
236 }
237  
238 # Check if user is authenticated
239 0 ▶ unless ( $c->user ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($c->user) 0 0 0
240 0 ▶ $c->log->debug('User not authenticated, redirecting to login') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
241 $c->session->{oidc_auth_request} = {
242 0 response_type => $response_type,
243 client_id => $client_id,
244 redirect_uri => $redirect_uri,
245 scope => $scope,
246 state => $state,
247 nonce => $nonce,
248 code_challenge => $code_challenge,
249 code_challenge_method => $code_challenge_method,
250 };
251  
252 0 return $c->response->redirect( $c->uri_for('/login', { back => '/openidconnect/authorize' }) );
253 }
254  
255 0 $c->log->info("Authorization granted for user: " . $c->user->id . " to client: $client_id");
256  
257 # PKCE validation (RFC 7636, OAuth 2.1).
258 # Public clients (no client_secret) MUST supply a code_challenge.
259 # Confidential clients MAY supply one; if they do, it is validated.
260 # Only S256 is accepted — 'plain' provides no meaningful security.
261 0 ▶ my $is_public_client = !( $client->{client_secret} && length $client->{client_secret} );
Condition0%0/3
$client->{'client_secret'} && length $client->{'client_secret'}
!ll&&!rl&&r
000
MC/DC0%0/2
$client->{'client_secret'} && length $client->{'client_secret'}
$client->{'client_secret'} length $client->{'client_secret'}
Truth table0%0/3
A && B
A= $client->{'client_secret'}B= length $client->{'client_secret'}
ABresult
0X0
100
111
262 0 ▶ if ( $is_public_client && !$code_challenge ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_public_client and not $code_challenge) 0 0 0
Condition0%0/3
$is_public_client and not $code_challenge
!ll&&!rl&&r
000
MC/DC0%0/2
$is_public_client and not $code_challenge
$is_public_client not $code_challenge
Truth table0%0/3
A and not(B)
A= $is_public_clientB= not $code_challenge
ABresult
0X0
100
111
263 0 $c->log->warn("PKCE code_challenge required for public client: $client_id");
264 0 return $self->_error_response(
265 $c, $redirect_uri, 'invalid_request',
266 'code_challenge is required for public clients', $state
267 );
268 }
269 0 ▶ if ( $code_challenge ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code_challenge) 0 0 0
270 0 ▶ my $method = $code_challenge_method // 'plain';
Condition0%0/2
$code_challenge_method // "plain"
l!l
00
MC/DC0%0/1
$code_challenge_method // "plain"
$code_challenge_method
Truth table0%0/2
A
A= $code_challenge_method
Aresult
11
00
271 0 ▶ unless ( $method eq 'S256' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($method eq "S256") 0 0 0
272 0 $c->log->warn("Unsupported code_challenge_method '$method' for client: $client_id");
273 0 return $self->_error_response(
274 $c, $redirect_uri, 'invalid_request',
275 'code_challenge_method must be S256', $state
276 );
277 }
278 # Validate the challenge value format (NEW-LOW-1 / RFC 7636 §4.2).
279 # An S256 challenge is BASE64URL(SHA256(verifier)) — exactly 43 chars
280 # from the BASE64URL alphabet with no padding. Reject malformed values
281 # before they reach the store or any downstream comparison.
282 0 ▶ unless ( $code_challenge =~ /\A[A-Za-z0-9\-_]{43}\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($code_challenge =~ /\A[A-Za-z0-9\-_]{43}\z/) 0 0 0
283 0 $c->log->warn("Malformed code_challenge for client $client_id");
284 0 return $self->_error_response(
285 $c, $redirect_uri, 'invalid_request',
286 'code_challenge must be a 43-character BASE64URL-encoded string',
287 $state
288 );
289 }
290 }
291  
292 # Extract user claims now, while the live user object is available.
293 # Storing the plain claims hashref (rather than the user object itself)
294 # means the store never needs to serialise application-specific objects
295 # such as DBIx::Class rows or LDAP entries — it always receives and
296 # returns plain data.
297 0 my $user_claims = $c->openidconnect->get_user_claims( $c->user );
298  
299 # Create authorization code, passing any PKCE challenge so it is stored
300 # alongside the code and can be verified at the token endpoint.
301 0 ▶ my $pkce = $code_challenge
Branch: 1 branch
BranchTrueFalseTotal
$code_challenge ? : 0 0 0
302 ? { code_challenge => $code_challenge, code_challenge_method => 'S256' }
303 : undef;
304 0 my $code = $c->openidconnect->store->create_authorization_code(
305 $client_id, $user_claims, $scope, $redirect_uri, $nonce, $pkce
306 );
307  
308 # Store authorization in session for later token request
309 0 ▶ $c->session->{oidc_code}->{$code} = {
Branch: 1 branch
BranchTrueFalseTotal
$code_challenge ? : 0 0 0
310 client_id => $client_id,
311 user => $user_claims,
312 scope => $scope,
313 redirect_uri => $redirect_uri,
314 nonce => $nonce,
315 code_challenge => $code_challenge,
316 code_challenge_method => $code_challenge ? 'S256' : undef,
317 };
318  
319 # Clear the stored authorization request after resuming the flow.
320 0 delete $c->session->{oidc_auth_request};
321  
322 # Build redirect URI with code and state
323 0 my $callback_uri = URI->new($redirect_uri);
324 0 $callback_uri->query_form(
325 code => $code,
326 state => $state,
327 );
328  
329 0 ▶ $c->log->debug("Redirecting to: " . $callback_uri->as_string) if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
330 0 $c->response->redirect( $callback_uri->as_string );
331 3 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
332  
333 =head2 token
334  
335 POST /openidconnect/token
336  
337 Token endpoint for exchanging authorization code for tokens.
338  
339 Parameters (form-encoded):
340  
341 - grant_type (REQUIRED): "authorization_code" or "refresh_token"
342 - code (REQUIRED for authorization_code): The authorization code
343 - redirect_uri (REQUIRED): Must match authorization request
344 - client_id (OPTIONAL): The client ID (extracted from code if not provided)
345 - client_secret (OPTIONAL): The client secret (required for confidential clients, optional for public clients)
346  
347 Returns:
348  
349 - access_token: The access token
350 - token_type: "Bearer"
351 - id_token: The ID token
352 - expires_in: Token expiration in seconds
353 - refresh_token: (optional) Refresh token
354  
355 =cut
356  
357 # Disable CSRF for compatibility with apps using Catalyst::Plugin::CSRF and auto_check => 1,
358 # which would otherwise reject POST requests to this endpoint without a valid CSRF token.
359 # The token endpoint is protected by client authentication and does not use cookies or sessions,
360 # so CSRF protection is not applicable.
361 0 ▶sub token : Local DisableCSRF {
Subroutine token: not called CC=6 SCAR=37.4
Pod documented
362 0 my ( $self, $c ) = @_;
363  
364 0 my $config = $c->openidconnect->config;
365  
366 0 $c->response->content_type('application/json');
367 0 ▶ $c->log->debug('Token endpoint accessed') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
368  
369 0 my $grant_type = $c->request->params->{grant_type};
370  
371 0 ▶ unless ($grant_type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($grant_type) 0 0 0
372 0 $c->log->warn('Missing grant_type parameter');
373 0 return $self->_json_error( $c, 'invalid_request', 'grant_type is required' );
374 }
375  
376 0 ▶ $c->log->debug("Token request with grant_type: $grant_type") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
377  
378 0 ▶ if ( $grant_type eq 'authorization_code' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($grant_type eq 'authorization_code') { } 0 0 0
elsif ($grant_type eq 'refresh_token') { } 0 0 0
379 0 return $self->_handle_authorization_code_grant($c);
380 } elsif ( $grant_type eq 'refresh_token' ) {
381 0 return $self->_handle_refresh_token_grant($c);
382 } else {
383 0 $c->log->warn("Unsupported grant_type: $grant_type");
384 0 return $self->_json_error( $c, 'unsupported_grant_type', "Unsupported grant_type: $grant_type" );
385 }
386 3 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
387  
388 =head2 userinfo
389  
390 GET /openidconnect/userinfo
391 Authorization: Bearer <access_token>
392  
393 UserInfo endpoint returning authenticated user's claims.
394  
395 =cut
396  
397 0 ▶sub userinfo : Local {
Subroutine userinfo: not called CC=12 SCAR=50.5
Pod documented
398 0 my ( $self, $c ) = @_;
399  
400 0 my $config = $c->openidconnect->config;
401 0 ▶ $c->log->debug('UserInfo endpoint accessed') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
402  
403 # Get bearer token
404 0 ▶ my $auth_header = $c->request->header('Authorization') || '';
Condition0%0/2
$c->request->header('Authorization') || ''
l!l
00
MC/DC0%0/1
$c->request->header('Authorization') || ''
$c->request->header('Authorization')
Truth table0%0/2
A
A= $c->request->header('Authorization')
Aresult
11
00
405 0 my ($token) = $auth_header =~ /^Bearer\s+(\S+)$/;
406  
407 0 ▶ unless ($token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($token) 0 0 0
408 0 $c->log->warn('Missing or invalid Authorization header');
409 0 return $self->_json_error( $c, 'invalid_token', 'Missing or invalid Authorization header' );
410 }
411  
412 # Verify token
413 0 my $payload;
414 0 ▶ try {
Subroutine __ANON__: not called CC=2 SCAR=17.9
415 0 $payload = $c->openidconnect->jwt->verify_token($token);
416 0 ▶ $c->log->debug('Access token verified successfully') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
417 }
418 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
419 0 $c->log->warn("Token verification failed: $_");
420 0 return $self->_json_error( $c, 'invalid_token', "Token verification failed: $_" );
421 0 };
422  
423 # Reject ID tokens and refresh tokens presented as access tokens (NEW-MED-1).
424 # Access tokens carry typ=at+JWT (RFC 9068); all other token types must be refused.
425 0 ▶ unless ( ( $payload->{typ} // '' ) eq 'at+JWT' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (($payload->{"typ"} // "") eq "at+JWT") 0 0 0
Condition0%0/2
$payload->{"typ"} // ""
l!l
00
MC/DC0%0/1
$payload->{"typ"} // ""
$payload->{"typ"}
Truth table0%0/2
A
A= $payload->{"typ"}
Aresult
11
00
426 0 ▶ $c->log->warn('Presented token is not an access token (typ=' . ($payload->{typ} // 'missing') . ')');
Condition0%0/2
$payload->{"typ"} // "missing"
l!l
00
MC/DC0%0/1
$payload->{"typ"} // "missing"
$payload->{"typ"}
Truth table0%0/2
A
A= $payload->{"typ"}
Aresult
11
00
427 0 return $self->_json_error( $c, 'invalid_token', 'Presented token is not an access token' );
428 }
429  
430 # Get user and claims
431 0 my $user_id = $payload->{sub};
432 0 ▶ unless ($user_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($user_id) 0 0 0
433 0 $c->log->error('Token missing sub claim');
434 0 return $self->_json_error( $c, 'invalid_token', 'Token missing sub claim' );
435 }
436  
437 0 ▶ $c->log->debug("UserInfo requested for user: $user_id") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
438  
439 # Build claims from token using standard list. String context
440 # is required for correct JSON encoding of these attributes. Other
441 # registered claims which must be strings are: iss, aud, jti (RFC7519 §4.1).
442 0 my %claims = map { $_ => "$payload->{$_}" } qw(sub);
443  
444 # Include remaining claims which are not as tightly specified.
445 0 for my $claim (qw(name email email_verified picture phone_number phone_number_verified)) {
446 0 ▶ $claims{$claim} = $payload->{$claim} if exists $payload->{$claim};
Branch: 1 branch
BranchTrueFalseTotal
if exists $payload->{$claim} 0 0 0
447 }
448  
449 0 ▶ $c->log->debug('UserInfo response prepared') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
450 0 $self->_json_response( $c, \%claims );
451 3 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
452  
453 =head2 logout
454  
455 POST /openidconnect/logout
456  
457 Logout endpoint to invalidate tokens and clear sessions.
458  
459 Implements OpenID Connect RP-Initiated Logout 1.0.
460  
461 Parameters:
462  
463 - id_token_hint (REQUIRED when post_logout_redirect_uri is supplied): A
464 previously issued ID Token identifying the client requesting logout.
465 The token's signature is verified to confirm it was issued by this server.
466 Expiry is intentionally not checked; hint tokens are often expired.
467 - post_logout_redirect_uri (OPTIONAL): URL to redirect to after logout.
468 Must be registered in the client's C<post_logout_redirect_uris> list.
469 Providing this parameter without a valid C<id_token_hint> is rejected
470 with an C<invalid_request> error to prevent open-redirect attacks.
471 - state (OPTIONAL): Opaque value returned verbatim in the redirect query
472 string (only when post_logout_redirect_uri is also provided).
473  
474 =cut
475  
476 0 ▶sub logout : Local {
Subroutine logout: not called CC=22 SCAR=62.3
Pod documented
477 0 my ( $self, $c ) = @_;
478  
479 0 my $config = $c->openidconnect->config;
480  
481 0 ▶ $c->log->debug('Logout endpoint accessed') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
482  
483 0 my $redirect_uri = $c->request->params->{post_logout_redirect_uri};
484 0 my $id_token_hint = $c->request->params->{id_token_hint};
485 0 my $state = $c->request->params->{state};
486  
487 # Decode the hint early — before the session is destroyed — so that we
488 # have the subject identifier available for refresh token revocation (MED-1).
489 0 my $hint_claims;
490 0 ▶ if ($id_token_hint) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id_token_hint) 0 0 0
491 0 $hint_claims = $c->openidconnect->jwt->decode_id_token_hint($id_token_hint);
492 }
493  
494 # Determine the subject identifier for refresh token revocation. Prefer
495 # the hint (authoritative); fall back to the live session so that
496 # logout-without-hint still revokes tokens when the session is present.
497 0 my $logout_sub = do {
498 0 ▶ if ( $hint_claims && $hint_claims->{sub} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hint_claims and $hint_claims->{'sub'}) { } 0 0 0
Condition0%0/3
$hint_claims and $hint_claims->{"sub"}
!ll&&!rl&&r
000
MC/DC0%0/2
$hint_claims and $hint_claims->{"sub"}
$hint_claims $hint_claims->{"sub"}
Truth table0%0/3
A and B
A= $hint_claimsB= $hint_claims->{"sub"}
ABresult
0X0
100
111
499 0 $hint_claims->{sub};
500 }
501 else {
502 0 my $sess_user = eval { $c->session->{user} };
503 0 ▶ $sess_user ? ( $sess_user->{sub} || $sess_user->{id} ) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$sess_user ? : 0 0 0
Condition0%0/3
$sess_user->{"sub"} or $sess_user->{"id"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$sess_user->{"sub"} or $sess_user->{"id"}
$sess_user->{"sub"} $sess_user->{"id"}
Truth table0%0/3
A or B
A= $sess_user->{"sub"}B= $sess_user->{"id"}
ABresult
1X1
011
000
504 }
505 };
506  
507 # Clear user session
508 0 ▶ if ( $c->user ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->user) 0 0 0
509 0 $c->log->info('Logging out user: ' . $c->user->id);
510 0 $c->user->logout();
511 }
512  
513 # Destroy session
514 0 ▶ if ( $c->sessionid ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->sessionid) 0 0 0
515 0 ▶ $c->log->debug('Destroying session: ' . $c->sessionid) if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
516 0 $c->delete_session('User session destroyed');
517 }
518  
519 # Revoke all outstanding refresh tokens for this user (MED-1).
520 0 ▶ if ($logout_sub) {
Branch: 1 branch
BranchTrueFalseTotal
if ($logout_sub) 0 0 0
521 0 $c->openidconnect->store->revoke_refresh_tokens_for_user($logout_sub);
522 $c->log->debug("Refresh tokens revoked for user: $logout_sub")
523 0 ▶ if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
524 }
525  
526 0 ▶ if ($redirect_uri) {
Branch: 1 branch
BranchTrueFalseTotal
if ($redirect_uri) 0 0 0
527 # id_token_hint is required when a redirect is requested so that we
528 # can identify the client and verify the URI is registered for it.
529 # Without this check an attacker could redirect to any arbitrary URL.
530 0 ▶ unless ($id_token_hint) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token_hint) 0 0 0
531 0 $c->log->warn('post_logout_redirect_uri provided without id_token_hint');
532 0 return $self->_json_error( $c, 'invalid_request',
533 'id_token_hint is required when post_logout_redirect_uri is provided' );
534 }
535  
536 # $hint_claims was decoded above; reject if invalid.
537 0 ▶ unless ($hint_claims) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hint_claims) 0 0 0
538 0 $c->log->warn('Invalid id_token_hint provided at logout');
539 0 return $self->_json_error( $c, 'invalid_request', 'Invalid id_token_hint' );
540 }
541  
542 # aud may be a string or an array per RFC 7519 §4.1.3.
543 0 my $aud = $hint_claims->{aud};
544 0 ▶ my $client_id = ref $aud eq 'ARRAY' ? $aud->[0] : $aud;
Branch: 1 branch
BranchTrueFalseTotal
ref $aud eq 'ARRAY' ? : 0 0 0
545  
546 0 ▶ unless ($client_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client_id) 0 0 0
547 0 $c->log->warn('id_token_hint is missing the aud claim');
548 0 return $self->_json_error( $c, 'invalid_request',
549 'id_token_hint does not contain an aud claim' );
550 }
551  
552 # Look up the client and validate the redirect URI against its
553 # registered post_logout_redirect_uris list.
554 0 my $client = $c->openidconnect->get_client($client_id);
555 0 ▶ unless ($client) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client) 0 0 0
556 0 $c->log->warn("Unknown client in id_token_hint aud claim: $client_id");
557 0 return $self->_json_error( $c, 'invalid_request',
558 'Unknown client in id_token_hint' );
559 }
560  
561 0 my @allowed = _normalize_uri_list( $client->{post_logout_redirect_uris} );
562 0 ▶ unless ( grep { $_ eq $redirect_uri } @allowed ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $redirect_uri;} @allowed) 0 0 0
563 0 $c->log->warn(
564 "Unregistered post_logout_redirect_uri for client $client_id: $redirect_uri"
565 );
566 0 return $self->_json_error( $c, 'invalid_request',
567 'post_logout_redirect_uri is not registered for this client' );
568 }
569  
570 # Build the final redirect URI, appending state if supplied.
571 0 my $final_uri = URI->new($redirect_uri);
572 0 ▶ $final_uri->query_form( $final_uri->query_form, state => $state )
Branch: 1 branch
BranchTrueFalseTotal
if defined $state and $state ne "" 0 0 0
Condition0%0/3
defined $state and $state ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $state and $state ne ""
defined $state $state ne ""
Truth table0%0/3
A and B
A= defined $stateB= $state ne ""
ABresult
0X0
100
111
573 if defined $state && $state ne '';
574  
575 $c->log->debug( 'Redirecting to post-logout URI: ' . $final_uri->as_string )
576 0 ▶ if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
577 0 return $c->response->redirect( $final_uri->as_string );
578 }
579  
580 # Return success JSON response
581 0 $c->log->info('Logout completed successfully');
582 0 $self->_json_response( $c, {
583 message => 'Logged out successfully',
584 });
585 3 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
586  
587 # Verify a PKCE code_verifier against a stored code_challenge.
588 # Only S256 (SHA-256) is supported; 'plain' is intentionally rejected.
589 # Returns a true value on success, false on failure.
590 11 ▶sub _verify_pkce {
Subroutine _verify_pkce: called CC=4 SCAR=13.9
591 11 my ( $code_verifier, $code_challenge ) = @_;
592 11 ▶ return 0 unless defined $code_verifier && defined $code_challenge;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code_verifier and defined $code_challenge 2 9 11
Condition100%3/3
defined $code_verifier and defined $code_challenge
!ll&&!rl&&r
119
MC/DC100%2/2
defined $code_verifier and defined $code_challenge
defined $code_verifier defined $code_challenge
Truth table100%3/3
A and B
A= defined $code_verifierB= defined $code_challenge
ABresult
0X0
100
111
593 # Verifier must contain only unreserved URI chars and be 43-128 chars (RFC 7636 §4.1)
594 9 ▶ return 0 unless $code_verifier =~ /\A[A-Za-z0-9\-._~]{43,128}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $code_verifier =~ /\A[A-Za-z0-9\-._~]{43,128}\z/ 3 6 9
595 # S256: BASE64URL( SHA256( ASCII( code_verifier ) ) )
596 6 my $computed = encode_base64url( sha256($code_verifier) );
597 6 return slow_eq( $computed, $code_challenge );
598 }
599  
600 # Normalise a redirect-URI config field.
601 # Accepts either an arrayref (YAML / JSON / Perl hash config) or a
602 # whitespace-delimited string (Config::General / Apache-style config).
603 # Returns a flat list of URI strings.
604 # Used for both redirect_uris and post_logout_redirect_uris so that both
605 # fields behave identically regardless of config format.
606 5 ▶sub _normalize_uri_list {
Subroutine _normalize_uri_list: called CC=3 SCAR=11.0
607 5 my ($field) = @_;
608 5 ▶ return () unless defined $field;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $field 1 4 5
609 4 ▶ return ref $field eq 'ARRAY' ? @$field : split /\s+/, $field;
Branch: 1 branch
BranchTrueFalseTotal
ref $field eq 'ARRAY' ? : 2 2 4
610 }
611  
612 =head2 jwks
613  
614 GET /openidconnect/jwks
615  
616 JSON Web Key Set endpoint for key discovery.
617  
618 Returns the public key(s) for verifying signatures.
619  
620 =cut
621  
622 0 ▶sub jwks : Local {
Subroutine jwks: not called CC=4 SCAR=30.0
Pod documented
623 0 my ( $self, $c ) = @_;
624  
625 0 my $config = $c->openidconnect->config;
626  
627 0 ▶ $c->log->debug('JWKS endpoint accessed') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
628  
629 # Get JWT handler and public key
630 0 my $jwt = $c->openidconnect->jwt;
631 0 my $public_key = $jwt->public_key;
632  
633 0 ▶ $c->log->debug('Extracting public key parameters for JWKS') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
634  
635 # Convert OpenSSL public key to Crypt::PK::RSA for easier parameter extraction
636 0 my $public_key_pem = $public_key->get_public_key_string();
637 0 my $pk = Crypt::PK::RSA->new(\$public_key_pem);
638  
639 # Get key parameters for JWK generation
640 0 my $keydata = $pk->key2hash();
641  
642 # Convert modulus and exponent to base64url
643 # Note: key2hash() returns lowercase keys (e, N, etc.)
644 0 my $n = $self->_bigint_to_base64url($keydata->{N});
645 0 my $e = $self->_bigint_to_base64url($keydata->{e});
646  
647 # Create JWK with all required fields
648 0 my %jwk = (
649 kty => 'RSA',
650 use => 'sig',
651 kid => $jwt->key_id,
652 alg => 'RS256',
653 n => $n,
654 e => $e,
655 );
656  
657 0 ▶ $c->log->debug('JWKS response prepared with key ID: ' . $jwt->key_id) if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
658 0 $self->_json_response( $c, { keys => [ \%jwk ] } );
659 3 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
660  
661 # Private helper methods
662  
663 0 ▶sub _handle_authorization_code_grant {
Subroutine _handle_authorization_code_grant: not called CC=27 SCAR=66.3
664 0 my ( $self, $c ) = @_;
665  
666 0 my $config = $c->openidconnect->config;
667  
668 0 ▶ $c->log->debug('Processing authorization_code grant') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
669  
670 0 my $code = $c->request->params->{code};
671 0 my $redirect_uri = $c->request->params->{redirect_uri};
672 0 my $client_id = $c->request->params->{client_id};
673 0 my $client_secret = $c->request->params->{client_secret};
674 0 my $code_verifier = $c->request->params->{code_verifier};
675  
676 0 ▶ unless ( $code && $redirect_uri ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($code and $redirect_uri) 0 0 0
Condition0%0/3
$code and $redirect_uri
!ll&&!rl&&r
000
MC/DC0%0/2
$code and $redirect_uri
$code $redirect_uri
Truth table0%0/3
A and B
A= $codeB= $redirect_uri
ABresult
0X0
100
111
677 0 $c->log->warn('Missing code or redirect_uri in token request');
678 0 return $self->_json_error( $c, 'invalid_request', 'code and redirect_uri are required' );
679 }
680  
681 0 ▶ $c->log->debug("Token request - code: $code, client_id: $client_id") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
682  
683 # Atomically consume (fetch + delete) the authorization code.
684 # Using consume_authorization_code rather than a separate get + delete
685 # eliminates the TOCTOU race that would otherwise allow two concurrent
686 # requests carrying the same code to both succeed (HIGH-4).
687 # Per RFC 6749 §4.1.2 any code that fails subsequent validation must
688 # also be treated as used, which this pattern naturally enforces.
689 0 my $code_data = $c->openidconnect->store->consume_authorization_code($code);
690 0 ▶ unless ($code_data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($code_data) 0 0 0
691 0 $c->log->warn("Authorization code not found, expired, or already used: $code");
692 0 return $self->_json_error( $c, 'invalid_grant', 'Authorization code not found or expired' );
693 }
694 0 ▶ $c->log->debug("Authorization code consumed: $code") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
695  
696 # Remove session copy of this code so stale claims/scope/nonce do not
697 # accumulate in the session store beyond the code's 10-minute lifetime (MED-5).
698 0 delete $c->session->{oidc_code}->{$code};
699  
700 # Use client_id from authorization code if not provided in request (public client flow)
701 0 ▶ $client_id ||= $code_data->{client_id};
Condition0%0/3
$client_id ||= $code_data->{"client_id"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$client_id ||= $code_data->{"client_id"}
$client_id $code_data->{"client_id"}
Truth table0%0/3
A ||= B
A= $client_idB= $code_data->{"client_id"}
ABresult
1X1
011
000
702  
703 # Enforce that the client presenting the token request is the same client
704 # the authorization code was issued to (RFC 6749 §4.1.3, NEW-HIGH-2).
705 # Without this check a confidential client that obtains another client's
706 # code could redeem it by authenticating with its own valid secret.
707 0 ▶ if ( $client_id ne $code_data->{client_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_id ne $code_data->{"client_id"}) 0 0 0
708 0 $c->log->warn(
709 "client_id mismatch at token endpoint: "
710 . "request=$client_id stored=$code_data->{client_id}"
711 );
712 0 return $self->_json_error( $c, 'invalid_grant',
713 'client_id does not match the authorization code' );
714 }
715  
716 # Verify redirect URI matches
717 0 ▶ unless ( $code_data->{redirect_uri} eq $redirect_uri ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($code_data->{"redirect_uri"} eq $redirect_uri) 0 0 0
718 0 $c->log->error("Redirect URI mismatch for code: $code (expected: " . $code_data->{redirect_uri} . ", got: $redirect_uri)");
719 0 return $self->_json_error( $c, 'invalid_grant', 'Redirect URI mismatch' );
720 }
721  
722 # PKCE verification (RFC 7636)
723 0 ▶ if ( $code_data->{code_challenge} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code_data->{"code_challenge"}) 0 0 0
724 0 ▶ unless ( defined $code_verifier ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $code_verifier) 0 0 0
725 0 $c->log->warn("PKCE code_verifier missing for client: $client_id");
726 0 return $self->_json_error( $c, 'invalid_grant', 'code_verifier is required' );
727 }
728 0 ▶ unless ( _verify_pkce( $code_verifier, $code_data->{code_challenge} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_verify_pkce($code_verifier, $code_data->{"code_challenge"})) 0 0 0
729 0 $c->log->warn("PKCE verification failed for client: $client_id");
730 0 return $self->_json_error( $c, 'invalid_grant', 'code_verifier is invalid' );
731 }
732 0 ▶ $c->log->debug('PKCE verification passed') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
733 }
734  
735 # If client_secret is provided, verify client credentials (confidential client)
736 0 ▶ if ($client_secret) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_secret) { } 0 0 0
737 0 ▶ $c->log->debug("Verifying client credentials for: $client_id") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
738 0 my $client = $c->openidconnect->get_client($client_id);
739 0 ▶ unless ( $client && slow_eq( $client->{client_secret}, $client_secret ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client and slow_eq($client->{"client_secret"}, $client_secret)) 0 0 0
Condition0%0/3
$client and slow_eq($client->{"client_secret"}, $client_secret)
!ll&&!rl&&r
000
MC/DC0%0/2
$client and slow_eq($client->{"client_secret"}, $client_secret)
$client slow_eq($client->{"client_secret"}, $client_secret)
Truth table0%0/3
A and B
A= $clientB= slow_eq($client->{"client_secret"}, $client_secret)
ABresult
0X0
100
111
740 0 $c->log->warn("Client authentication failed for: $client_id");
741 0 return $self->_json_error( $c, 'invalid_client', 'Client authentication failed' );
742 }
743 } else {
744 # For public clients (no secret provided), at least verify client exists
745 0 my $client = $c->openidconnect->get_client($client_id);
746 0 ▶ unless ($client) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client) 0 0 0
747 0 $c->log->warn("Unknown client: $client_id");
748 0 return $self->_json_error( $c, 'invalid_client', 'Unknown client' );
749 }
750 }
751  
752 # User claims were extracted and stored at authorization time, so
753 # $code_data->{user} is already the mapped claims hashref.
754 0 my $user_claims = $code_data->{user};
755  
756 # Create tokens
757 0 my $now = time();
758 0 my %id_token_payload = (
759 %$user_claims,
760 aud => $client_id,
761 exp => $now + 3600, # 1 hour
762 );
763  
764 0 ▶ $id_token_payload{nonce} = $code_data->{nonce} if $code_data->{nonce};
Branch: 1 branch
BranchTrueFalseTotal
if $code_data->{"nonce"} 0 0 0
765  
766 0 my $id_token = $c->openidconnect->jwt->create_id_token(%id_token_payload);
767 0 ▶ $c->log->debug('ID token created') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
768  
769 my %access_token_payload = (
770 sub => $user_claims->{sub},
771 aud => $client_id,
772 scp => $code_data->{scope},
773 0 typ => 'at+JWT', # RFC 9068 — distinguishes access tokens from ID/refresh tokens (NEW-MED-1)
774 exp => $now + 3600,
775 );
776  
777 0 my $access_token = $c->openidconnect->jwt->create_access_token(%access_token_payload);
778 0 ▶ $c->log->debug('Access token created') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
779  
780 # Issue a refresh token with a unique JTI and register the JTI in the
781 # store so the token endpoint can enforce single-use semantics (MED-1).
782 0 my $rt_jti = $_uuid->create_str();
783 0 my $rt_ttl = 30 * 24 * 3600; # 30 days
784 my %refresh_token_payload = (
785 sub => $user_claims->{sub},
786 0 aud => $client_id,
787 jti => $rt_jti,
788 exp => $now + $rt_ttl,
789 );
790  
791 0 my $refresh_token = $c->openidconnect->jwt->create_refresh_token(%refresh_token_payload);
792 $c->openidconnect->store->store_refresh_token(
793 0 $rt_jti, $user_claims->{sub}, $client_id, $rt_ttl,
794 );
795 0 ▶ $c->log->debug('Refresh token created and JTI registered') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
796  
797 0 $c->log->info("Tokens issued for client: $client_id, user: " . $user_claims->{sub});
798
799 # Log token lengths for debugging signature issues
800 0 ▶ $c->log->debug("ID token length: " . length($id_token) . " bytes") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
801 0 ▶ $c->log->debug("Access token length: " . length($access_token) . " bytes") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
802 0 ▶ $c->log->debug("Refresh token length: " . length($refresh_token) . " bytes") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
803 0 ▶ $c->log->debug("ID token (first 80 chars): " . substr($id_token, 0, 80) . "...") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
804  
805 # Return tokens
806 0 $self->_json_response( $c, {
807 access_token => $access_token,
808 token_type => 'Bearer',
809 id_token => $id_token,
810 expires_in => 3600,
811 refresh_token => $refresh_token,
812 });
813 }
814  
815 0 ▶sub _handle_refresh_token_grant {
Subroutine _handle_refresh_token_grant: not called CC=13 SCAR=52.0
816 0 my ( $self, $c ) = @_;
817  
818 0 my $config = $c->openidconnect->config;
819  
820 0 ▶ $c->log->debug('Processing refresh_token grant') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
821  
822 0 my $refresh_token = $c->request->params->{refresh_token};
823 0 my $client_id = $c->request->params->{client_id};
824 0 my $client_secret = $c->request->params->{client_secret};
825  
826 0 ▶ unless ( $refresh_token && $client_id && $client_secret ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($refresh_token and $client_id and $client_secret) 0 0 0
Condition0%0/6
$refresh_token and $client_id and $client_secret
!ll&&!rl&&r
000
$refresh_token and $client_id
!ll&&!rl&&r
000
MC/DC0%0/3
$refresh_token and $client_id and $client_secret
$refresh_token $client_id $client_secret
Truth table0%0/4
A and B and C
A= $refresh_tokenB= $client_idC= $client_secret
ABCresult
0XX0
10X0
1100
1111
827 0 $c->log->warn('Missing required parameters for refresh token grant');
828 0 return $self->_json_error( $c, 'invalid_request', 'Missing required parameters' );
829 }
830  
831 0 ▶ $c->log->debug("Refresh token request for client: $client_id") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
832  
833 # Verify client
834 0 my $client = $c->openidconnect->get_client($client_id);
835 0 ▶ unless ( $client && slow_eq( $client->{client_secret}, $client_secret ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client and slow_eq($client->{"client_secret"}, $client_secret)) 0 0 0
Condition0%0/3
$client and slow_eq($client->{"client_secret"}, $client_secret)
!ll&&!rl&&r
000
MC/DC0%0/2
$client and slow_eq($client->{"client_secret"}, $client_secret)
$client slow_eq($client->{"client_secret"}, $client_secret)
Truth table0%0/3
A and B
A= $clientB= slow_eq($client->{"client_secret"}, $client_secret)
ABresult
0X0
100
111
836 0 $c->log->warn("Client authentication failed for: $client_id");
837 0 return $self->_json_error( $c, 'invalid_client', 'Client authentication failed' );
838 }
839  
840 # Verify refresh token
841 0 my $payload;
842 0 ▶ try {
Subroutine __ANON__: not called CC=2 SCAR=17.9
843 0 $payload = $c->openidconnect->jwt->verify_token($refresh_token);
844 0 ▶ $c->log->debug('Refresh token verified') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
845 }
846 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
847 0 $c->log->warn("Invalid refresh token: $_");
848 0 return $self->_json_error( $c, 'invalid_grant', 'Invalid refresh token' );
849 0 };
850  
851 # Enforce single-use via JTI (MED-1). All tokens issued after this fix
852 # carry a jti registered in the store. Tokens without a jti (issued before
853 # the fix) are rejected to prevent indefinite re-use of old long-lived tokens.
854 0 my $jti = $payload->{jti};
855 0 ▶ unless ( defined $jti ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $jti) 0 0 0
856 0 $c->log->warn("Refresh token missing jti claim for client: $client_id");
857 0 return $self->_json_error( $c, 'invalid_grant',
858 'Refresh token is not valid (missing jti)' );
859 }
860  
861 0 ▶ unless ( $c->openidconnect->store->consume_refresh_token($jti) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($c->openidconnect->store->consume_refresh_token($jti)) 0 0 0
862 0 $c->log->warn("Refresh token jti already used or revoked: $jti");
863 0 return $self->_json_error( $c, 'invalid_grant',
864 'Refresh token has already been used or revoked' );
865 }
866 0 ▶ $c->log->debug("Refresh token jti consumed: $jti") if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
867  
868 # Create new access token
869 0 my $now = time();
870 my %new_payload = (
871 sub => $payload->{sub},
872 0 aud => $client_id,
873 typ => 'at+JWT', # RFC 9068 — distinguishes access tokens from ID/refresh tokens (NEW-MED-1)
874 exp => $now + 3600,
875 );
876  
877 0 my $access_token = $c->openidconnect->jwt->create_access_token(%new_payload);
878 0 ▶ $c->log->debug('New access token created from refresh token') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
879  
880 # Rotate refresh token: issue a new one with a fresh JTI (MED-1).
881 0 my $new_rt_jti = $_uuid->create_str();
882 0 my $rt_ttl = 30 * 24 * 3600;
883 my %new_rt_payload = (
884 sub => $payload->{sub},
885 0 aud => $client_id,
886 jti => $new_rt_jti,
887 exp => $now + $rt_ttl,
888 );
889 0 my $new_refresh_token = $c->openidconnect->jwt->create_refresh_token(%new_rt_payload);
890 $c->openidconnect->store->store_refresh_token(
891 0 $new_rt_jti, $payload->{sub}, $client_id, $rt_ttl,
892 );
893 0 ▶ $c->log->debug('Refresh token rotated') if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
894  
895 0 $c->log->info("Access token refreshed for client: $client_id, user: " . $payload->{sub});
896  
897 0 $self->_json_response( $c, {
898 access_token => $access_token,
899 token_type => 'Bearer',
900 expires_in => 3600,
901 refresh_token => $new_refresh_token,
902 });
903 }
904  
905 0 ▶sub _error_response {
Subroutine _error_response: not called CC=3 SCAR=24.8
906 0 my ( $self, $c, $redirect_uri, $error, $error_description, $state ) = @_;
907  
908 0 my $config = $c->openidconnect->config;
909  
910 0 $c->log->warn("OAuth error: $error - $error_description");
911  
912 0 ▶ if ($redirect_uri) {
Branch: 1 branch
BranchTrueFalseTotal
if ($redirect_uri) { } 0 0 0
913 0 my $callback_uri = URI->new($redirect_uri);
914 0 $callback_uri->query_form(
915 error => $error,
916 error_description => $error_description,
917 state => $state,
918 );
919 0 ▶ $c->log->debug("Redirecting error response to: " . $callback_uri->as_string) if $config->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"debug"} 0 0 0
920 0 return $c->response->redirect( $callback_uri->as_string );
921 } else {
922 0 return $self->_json_response( $c, {
923 error => $error,
924 error_description => $error_description,
925 });
926 }
927 }
928  
929 0 ▶sub _json_error {
Subroutine _json_error: not called CC=1 SCAR=6.9
930 0 my ( $self, $c, $error, $error_description ) = @_;
931  
932 0 $c->log->warn("JSON error response: $error - $error_description");
933 0 $c->response->status(400);
934 0 return $self->_json_response( $c, {
935 error => $error,
936 error_description => $error_description,
937 });
938 }
939  
940 0 ▶sub _json_response {
Subroutine _json_response: not called CC=1 SCAR=6.9
941 0 my ( $self, $c, $data ) = @_;
942  
943 0 $c->response->content_type('application/json');
944 0 $c->response->body( encode_json($data) );
945 }
946  
947 0 ▶sub _hex_to_base64url {
Subroutine _hex_to_base64url: not called CC=1 SCAR=6.9
948 0 my ( $self, $hex_string ) = @_;
949  
950 # Remove any spaces or newlines
951 0 $hex_string =~ s/\s+//g;
952  
953 # Convert hex to binary
954 0 my $binary = pack('H*', $hex_string);
955  
956 # Encode to base64
957 0 my $base64 = encode_base64($binary, '');
958  
959 # Convert to base64url (- instead of +, _ instead of /)
960 0 $base64 =~ tr/+\//\-_/;
961  
962 # Remove padding
963 0 $base64 =~ s/=+$//;
964  
965 0 return $base64;
966 }
967  
968 0 ▶sub _bigint_to_base64url {
Subroutine _bigint_to_base64url: not called CC=2 SCAR=17.9
969 0 my ( $self, $hex_str ) = @_;
970  
971 0 ▶ return '' unless $hex_str; # Handle empty/undef
Branch: 1 branch
BranchTrueFalseTotal
unless $hex_str 0 0 0
972  
973 # Crypt::PK::RSA returns big integers as hex strings (lowercase)
974 # Convert directly using the hex-to-base64url method
975 0 return $self->_hex_to_base64url($hex_str);
976 }
977  
978 3 __PACKAGE__->meta->make_immutable;
979  
980 3 1;
981  
982 =head1 AUTHOR
983  
984 Tim F. Rayner
985  
986 =head1 LICENSE
987  
988 This library is free software; you can redistribute it and/or modify
989 it under the terms of The Artistic License 2.0.
990  
991 =cut
↑ Summary OpenIDConnect.pm »