blib/lib/Lemonldap/NG/Portal/Issuer/OpenIDConnect.pm

filter: Statementstmt 14.8% 182 / 1227 Branchbran 8.2% 57 / 692 Conditioncond 4.0% 9 / 224 MC/DCmcdc 0.7% 1 / 137 Subroutinesub 42.1% 27 / 64 Podpod 15.3% 4 / 26 totaltotal 11.8% 280 / 2370 CC 448 SCAR 70.6
CC
448
Cov
12%
_authorizeEndpoint
5550.0
_checkErrorsInAuthorizeEndpoint
1892.0
registration
870.0
CRAP 1160.6
« blib/lib/Lemonldap/NG/Portal/Lib/Net/LDAP.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Issuer/CAS.pm »
1 package Lemonldap::NG::Portal::Issuer::OpenIDConnect;
2  
3 24 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 24 ▶use JSON qw(from_json to_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 24 ▶use Lemonldap::NG::Common::JWT qw(getJWTPayload);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 24 ▶use Mouse;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 24 ▶use Lemonldap::NG::Common::FormEncode;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 24 use Lemonldap::NG::Portal::Main::Constants qw(
9 portalConsts
10 PE_OK
11 PE_DONE
12 PE_ERROR
13 PE_CONFIRM
14 PE_REDIRECT
15 PE_LOGOUT_OK
16 PE_PASSWORD_OK
17 PE_BADCREDENTIALS
18 PE_UNAUTHORIZEDURL
19 PE_UNAUTHORIZEDPARTNER
20 PE_UNKNOWNPARTNER
21 PE_OIDC_SERVICE_NOT_ALLOWED
22 PE_FIRSTACCESS
23 PE_SENDRESPONSE
24 PE_SLO_ERROR
25 24 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 24 ▶use String::Random qw/random_string/;
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 24 our $VERSION = '2.22.0';
29  
30 24 extends qw(
31 Lemonldap::NG::Portal::Main::Issuer
32 Lemonldap::NG::Common::Conf::AccessLib
33 Lemonldap::NG::Portal::Lib::OpenIDConnect
34 );
35  
36 24 with 'Lemonldap::NG::Portal::Lib::LazyLoadedConfiguration',
37 'Lemonldap::NG::Common::OpenIDConnect::Metadata',
38 'Lemonldap::NG::Portal::Lib::Key';
39  
40 # INTERFACE
41  
42 30 ▶sub beforeAuth { 'exportRequestParameters' }
Subroutine beforeAuth: called CC=1 SCAR=0.0
Pod undocumented
43 24 ▶use constant hook => { updateSessionId => 'updateOidcSecondarySessions' };
Subroutine BEGIN: called CC=1 SCAR=0.0
44  
45 # INITIALIZATION
46  
47 24 ▶use constant sessionKind => 'OIDCI';
Subroutine BEGIN: called CC=1 SCAR=0.0
48  
49 # random_string mask for auto-registration client-id/secret
50 24 ▶use constant RS_MSK => 's' x 30;
Subroutine BEGIN: called CC=1 SCAR=0.0
51  
52 24 has rule => ( is => 'rw' );
53 has configStorage => (
54 is => 'ro',
55 lazy => 1,
56 default => sub {
57 0 ▶ $_[0]->{p}->HANDLER->localConfig->{configStorage};
Subroutine __ANON__: not called CC=1 SCAR=6.9
58 }
59 24 );
60 24 has ssoMatchUrl => ( is => 'rw' );
61  
62 has iss => (
63 is => 'ro',
64 lazy => 1,
65 default => sub {
66 $_[0]->conf->{oidcServiceMetaDataIssuer}
67 1 ▶ || $_[0]->p->HANDLER->tsv->{portal}->();
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$_[0]->conf->{"oidcServiceMetaDataIssuer"} or $_[0]->p->HANDLER->tsv->{"portal"}->() 1 0 1
68 }
69 24 );
70  
71 31 ▶has amrRules => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
72  
73 sub get_issuer {
74 1 ▶ my ( $self, $req ) = @_;
Subroutine get_issuer: called CC=2 SCAR=7.6
Pod undocumented
75 1 ▶ if ( $self->iss ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->iss) { } 1 0 1
76 1 return $self->iss;
77 }
78 else {
79 0 return $req->portal;
80 }
81 }
82  
83 # OIDC has 7 endpoints managed here as PSGI endpoints or in run() [Main/Issuer.pm
84 # manage transparent authentication for run()]:
85 # - authorize : in run()
86 # - logout : in run()
87 # => endSessionDone() for unauth users
88 # - checksession: => checkSession() for all
89 # - token : => token() for unauth users (RP)
90 # - userinfo : => userInfo() for unauth users (RP)
91 # - jwks : => jwks() for unauth users (RP)
92 # - register : => registration() for unauth users (RP)
93 # - introspect : => introspection() for unauth users (RP)
94 #
95 # Other paths will be handle by run() and return PE_ERROR
96 #
97 # .well-known/openid-configuration is handled by metadata()
98  
99 sub init {
100 30 ▶ my ($self) = @_;
Subroutine init: called CC=8 SCAR=22.3
Pod undocumented
101  
102 # Parse activation rule
103 30 my $hd = $self->p->HANDLER;
104 $self->logger->debug(
105 30 "OIDC rule -> " . $self->conf->{issuerDBOpenIDConnectRule} );
106 my $rule =
107 $hd->buildSub(
108 30 $hd->substitute( $self->conf->{issuerDBOpenIDConnectRule} ) );
109 30 ▶ unless ($rule) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rule) 0 30 30
110 0 ▶ my $error = $hd->tsv->{jail}->error || '???';
Condition0%0/2
$hd->tsv->{'jail'}->error || '???'
l!l
00
MC/DC0%0/1
$hd->tsv->{'jail'}->error || '???'
$hd->tsv->{'jail'}->error
Truth table0%0/2
A
A= $hd->tsv->{'jail'}->error
Aresult
11
00
111 0 $self->error("Bad OIDC activation rule -> $error");
112 0 return 0;
113 }
114 30 $self->{rule} = $rule;
115  
116 30 ▶ return 0
Branch: 1 branch
BranchTrueFalseTotal
unless $self->Lemonldap::NG::Portal::Main::Issuer::init 0 30 30
117 unless $self->Lemonldap::NG::Portal::Main::Issuer::init();
118  
119 # Preloading RPs should not be needed thanks to lazy loading, but is
120 # required to make sp:confKey display rules work (#3058)
121 30 $self->loadRPs;
122  
123 # Manage RP requests
124 30 $self->addRouteFromConf(
125 'Unauth',
126 oidcServiceMetaDataEndSessionURI => 'endSessionDone',
127 oidcServiceMetaDataCheckSessionURI => 'checkSession',
128 oidcServiceMetaDataTokenURI => 'token',
129 oidcServiceMetaDataUserInfoURI => 'unauthUserInfo',
130 oidcServiceMetaDataJWKSURI => 'jwks',
131 oidcServiceMetaDataRegistrationURI => 'registration',
132 oidcServiceMetaDataIntrospectionURI => 'introspection',
133 oidcServiceMetaDataRevokeURI => 'unauthRevokeToken',
134 );
135  
136 # Manage user requests
137 30 $self->addRouteFromConf(
138 'Auth',
139 oidcServiceMetaDataCheckSessionURI => 'checkSession',
140 oidcServiceMetaDataTokenURI => 'token',
141 oidcServiceMetaDataUserInfoURI => 'userInfo',
142 oidcServiceMetaDataJWKSURI => 'jwks',
143 oidcServiceMetaDataRegistrationURI => 'registration',
144 oidcServiceMetaDataIntrospectionURI => 'introspection',
145 oidcServiceMetaDataRevokeURI => 'authRevokeToken',
146 );
147  
148 # Metadata (.well-known/openid-configuration)
149 $self->addUnauthRoute(
150 '.well-known' => { 'openid-configuration' => 'metadata' },
151 ['GET']
152 30 ▶ ) unless $self->conf->{oidcServiceHideMetadata};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->conf->{"oidcServiceHideMetadata"} 30 0 30
153 30 $self->addAuthRoute(
154 '.well-known' => { 'openid-configuration' => 'metadata' },
155 ['GET']
156 );
157 my $m =
158 '^/'
159 . $self->path . '/+(?:'
160 . join( '|',
161 $self->conf->{oidcServiceMetaDataAuthorizeURI},
162 $self->conf->{oidcServiceMetaDataEndSessionURI},
163 30 ) . ')';
164 30 $self->ssoMatchUrl(qr/$m/);
165  
166 30 ▶ while ( my ( $amr_value, $rule ) =
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$self->conf->{"oidcServiceMetaDataAmrRules"} or {};}) 121 30 151
167 151 ▶ each %{ $self->conf->{oidcServiceMetaDataAmrRules} || {} } )
Branch: 1 branch
BranchTrueFalseTotal
$self->conf->{"oidcServiceMetaDataAmrRules"} or {} 0 151 151
168 {
169 121 $self->logger->debug("Compiling AMR rule for $amr_value");
170 121 my $compiled_rule =
171 $self->p->buildRule( $rule, "amr rule for $amr_value" );
172 121 ▶ $self->amrRules->{$amr_value} = $compiled_rule if $compiled_rule;
Branch: 1 branch
BranchTrueFalseTotal
if $compiled_rule 121 0 121
173 }
174  
175 30 return 1;
176 }
177  
178 # CONFIGURATION LOADING
179  
180 # Get Relying Party corresponding to a Client ID
181 # This will lazy-load the corresponding config from either LLNG configuration
182 # or from a plugin.
183 # @param client_id Client ID
184 # @return String result
185 sub getRP {
186 7 ▶ my ( $self, $client_id ) = @_;
Subroutine getRP: called CC=1 SCAR=0.0
Pod documented
187 7 my $rp;
188 7 my $result = $self->lazy_load_config($client_id);
189 7 return $result->{confKey};
190 }
191  
192 # Handles configuration loading of RPs
193 # this method is called by the LazyLoadedConfiguration role
194 sub load_config {
195 33 ▶ my ( $self, $client_id ) = @_;
Subroutine load_config: called CC=9 SCAR=35.5
Pod undocumented
196  
197 my @confKeys = grep {
198 $self->conf->{oidcRPMetaDataOptions}->{$_}
199 45 ->{oidcRPMetaDataOptionsClientID} eq $client_id
200 33 ▶ } keys %{ $self->conf->{oidcRPMetaDataOptions} || {} };
Branch: 1 branch
BranchTrueFalseTotal
$self->conf->{"oidcRPMetaDataOptions"} or {} 0 33 33
201  
202 # Found this client_id in configuration,
203 # load it permanently (until next conf reload)
204 33 ▶ if (@confKeys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@confKeys) 33 0 33
205 33 my $confKey = $confKeys[0];
206 33 $self->logger->debug("Loading $client_id from LLNG config $confKey");
207 33 ▶ if ( $self->load_rp_from_llng_conf($confKey) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->load_rp_from_llng_conf($confKey)) { } 33 0 33
208 33 return { info => { confKey => $confKey } };
209 }
210 else {
211 # This marks the RP as permanently not loaded
212 # (until next config reload)
213 0 return {};
214 }
215 }
216  
217 # Not found in config, try to load from hook
218 0 my $config = {};
219 0 my $res =
220 $self->p->processHook( {}, 'getOidcRpConfig', $client_id, $config );
221 0 ▶ if ( $res != PE_OK ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res != 0) 0 0 0
222 0 return;
223 }
224  
225 0 my $info;
226 0 ▶ if ( $config->{confKey} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"confKey"}) 0 0 0
227  
228 0 $self->logger->debug(
229 "Loading $config->{confKey} from getOidcRpConfig hook");
230  
231 # Make sure Client ID is correctly set in options
232 0 $config->{options}->{oidcRPMetaDataOptionsClientID} = $client_id;
233  
234 # Make sure load_rp succeeds before remembering the confKey
235 0 ▶ if ( $self->load_rp(%$config) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->load_rp(%$config)) 0 0 0
236 0 $info = { confKey => $config->{confKey} };
237 }
238  
239 }
240  
241 # You can set a negative TTL in getOidcRpConfig hook even if you don't find
242 # anything to avoid doing too many lookups
243 0 my $ttl = $config->{ttl};
244 0 ▶ return { ( $ttl ? ( ttl => $ttl ) : () ),
Branch: 2 branches
BranchTrueFalseTotal
$ttl ? : 0 0 0
$info ? : 0 0 0
245 ( $info ? ( info => $info ) : () ) };
246 }
247  
248 # Load all OpenID Connect Relying Parties from configuration
249 sub loadRPs {
250 30 ▶ my ($self) = @_;
Subroutine loadRPs: called CC=6 SCAR=18.3
Pod documented
251  
252 # Check presence of at least one relying party in configuration
253 30 ▶ unless ( $self->conf->{oidcRPMetaDataOptions}
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->conf->{"oidcRPMetaDataOptions"} and keys %{$self->conf->{"oidcRPMetaDataOptions"};}) 1 29 30
Condition66%2/3
$self->conf->{"oidcRPMetaDataOptions"} and keys %{$self->conf->{"oidcRPMetaDataOptions"};}
!ll&&!rl&&r
1029
MC/DC50%1/2
$self->conf->{"oidcRPMetaDataOptions"} and keys %{$self->conf->{"oidcRPMetaDataOptions"};}
$self->conf->{"oidcRPMetaDataOptions"} keys %{$self->conf->{"oidcRPMetaDataOptions"};}
Truth table66%2/3
A and B
A= $self->conf->{"oidcRPMetaDataOptions"}B= keys %{$self->conf->{"oidcRPMetaDataOptions"};}
ABresult
0X0
100
111
254 29 and keys %{ $self->conf->{oidcRPMetaDataOptions} } )
255 {
256 1 $self->logger->warn(
257 "No OpenID Connect Relying Party found in configuration");
258 1 return 1;
259 }
260  
261 29 ▶ foreach my $rp ( keys %{ $self->conf->{oidcRPMetaDataOptions} || {} } ) {
Branch: 1 branch
BranchTrueFalseTotal
$self->conf->{"oidcRPMetaDataOptions"} or {} 0 29 29
262 my $client_id = $self->conf->{oidcRPMetaDataOptions}->{$rp}
263 33 ->{oidcRPMetaDataOptionsClientID};
264 33 ▶ if ($client_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_id) { } 33 0 33
265 33 $self->lazy_load_config($client_id);
266 }
267 else {
268 0 $self->logger->warn("RP $rp has no Client ID");
269 }
270 }
271 29 return 1;
272 }
273  
274 # RUNNING METHODS
275  
276 sub ssoMatch {
277 37 ▶ my ( $self, $req ) = @_;
Subroutine ssoMatch: called CC=4 SCAR=15.6
Pod undocumented
278 37 my $lh = $req->param('login_hint');
279 37 ▶ $req->data->{suggestedLogin} ||= $lh if $lh;
Branch: 1 branch
BranchTrueFalseTotal
if $lh 0 37 37
Condition0%0/3
$req->data->{"suggestedLogin"} ||= $lh
l!l&&r!l&&!r
000
MC/DC0%0/2
$req->data->{"suggestedLogin"} ||= $lh
$req->data->{"suggestedLogin"} $lh
Truth table0%0/3
A ||= B
A= $req->data->{"suggestedLogin"}B= $lh
ABresult
1X1
011
000
280 37 ▶ return ( $req->uri =~ $self->ssoMatchUrl ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$req->uri =~ $self->ssoMatchUrl ? : 4 33 37
281 }
282  
283 # Main method (launched only for authenticated users, see Main/Issuer.pm)
284 # run() manages only "authorize" and "logout" endpoints.
285 sub run {
286 0 ▶ my ( $self, $req, $path ) = @_;
Subroutine run: not called CC=7 SCAR=40.3
Pod documented
287 0 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 0 0
288  
289 # Check activation rule
290 0 ▶ unless ( $self->rule->( $req, $req->sessionInfo ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->rule->($req, $req->sessionInfo)) 0 0 0
291 0 $self->userLogger->error('OIDC service not authorized');
292 0 return PE_OIDC_SERVICE_NOT_ALLOWED;
293 }
294  
295 0 ▶ if ($path) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path) 0 0 0
296  
297 # Convert old format OIDC Consents
298 0 my $ConvertedConsents = $self->_convertOldFormatConsents($req);
299 0 $self->logger->debug("$ConvertedConsents consent(s) converted");
300  
301 # AUTHORIZE
302 0 ▶ if ( $path eq $self->conf->{oidcServiceMetaDataAuthorizeURI} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($path eq $self->conf->{'oidcServiceMetaDataAuthorizeURI'}) { } 0 0 0
elsif ($path eq $self->conf->{'oidcServiceMetaDataEndSessionURI'}) { } 0 0 0
303 0 $self->logger->debug(
304 "URL detected as an OpenID Connect AUTHORIZE URL");
305 0 return $self->_authorizeEndpoint($req);
306  
307 }
308 elsif ( $path eq $self->conf->{oidcServiceMetaDataEndSessionURI} ) {
309 0 $self->logger->debug(
310 "URL detected as an OpenID Connect END SESSION URL");
311 0 return $self->_rpInitiatedLogout($req);
312 }
313 }
314  
315 $self->logger->error(
316 0 ▶ $path
Branch: 1 branch
BranchTrueFalseTotal
$path ? : 0 0 0
317 ? "Unknown OIDC endpoint: $path, skipping"
318 : 'No OIDC endpoint found, aborting'
319 );
320 0 return PE_ERROR;
321 }
322  
323 sub _checkErrorsInAuthorizeEndpoint {
324 0 ▶ my ( $self, $req ) = @_;
Subroutine _checkErrorsInAuthorizeEndpoint: not called CC=43 SCAR=75.5
325  
326 # Get and save parameters
327 0 my $oidc_request = {};
328 0 foreach my $param (
329 qw/response_type scope client_id state redirect_uri nonce
330 response_mode display prompt max_age ui_locales id_token_hint
331 login_hint acr_values request request_uri code_challenge code_challenge_method/
332 )
333 {
334 0 ▶ if ( $req->param($param) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->param($param)) 0 0 0
335 0 $oidc_request->{$param} = $req->param($param);
336 $self->logger->debug(
337 0 "OIDC request parameter $param: " . $oidc_request->{$param} );
338 0 $self->p->setHiddenFormValue( $req, $param, $oidc_request->{$param},
339 '', 0 );
340 }
341 }
342  
343 0 my $h = $self->p->processHook( $req, 'oidcGotRequest', $oidc_request );
344 0 ▶ return $self->_failAuthorize(
Branch: 1 branch
BranchTrueFalseTotal
if $h != 0 0 0 0
345 $req,
346 message => "oidcGotRequest hook failed",
347 res => $h
348 ) if ( $h != PE_OK );
349  
350 # Detect requested flow
351 0 my $response_type = $oidc_request->{'response_type'};
352  
353 0 ▶ unless ($response_type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response_type) 0 0 0
354 0 return $self->_failAuthorize( $req,
355 msg => "No response type provided" );
356 }
357  
358 0 my $flow = $self->getFlowType($response_type);
359  
360 0 ▶ unless ($flow) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($flow) 0 0 0
361 0 return $self->_failAuthorize( $req,
362 msg => "Unknown response type: $response_type" );
363 }
364 $self->logger->debug(
365 0 "OIDC $flow flow requested (response type: $response_type)");
366  
367 # Check if response mode is allowed for flow
368 0 my $response_mode = $oidc_request->{'response_mode'};
369 0 ▶ if ( !$self->isResponseModeAllowed( $flow, $response_mode ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->isResponseModeAllowed($flow, $response_mode)) 0 0 0
370 0 return $self->_failAuthorize( $req,
371 msg => "Reponse mode $response_mode is not allowed in $flow Flow" );
372 }
373  
374 # Client ID must be provided and cannot come from
375 # request or request_uri
376 0 ▶ unless ( $oidc_request->{'client_id'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($oidc_request->{"client_id"}) 0 0 0
377 0 return $self->_failAuthorize( $req, msg => "Client ID is required" );
378 }
379  
380 # Check client_id
381 0 my $client_id = $oidc_request->{'client_id'};
382 0 $self->logger->debug("Request from client id $client_id");
383  
384 # Verify that client_id is registered in configuration
385 0 my $rp = $self->getRP($client_id);
386  
387 0 ▶ unless ($rp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rp) { } 0 0 0
388 0 return $self->_failAuthorize(
389 $req,
390 msg => (
391 "No registered Relying Party found with"
392 . " client_id $client_id"
393 ),
394 res => PE_UNKNOWNPARTNER
395 );
396 }
397 else {
398 0 $self->logger->debug("Client id $client_id matches RP $rp");
399 }
400  
401 # Scope must be provided and cannot come from request or request_uri
402 0 ▶ unless ( $oidc_request->{'scope'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($oidc_request->{"scope"}) 0 0 0
403 0 return $self->_failAuthorize( $req, msg => "Scope is required" );
404 }
405  
406 # Extract request_uri/request parameter
407 0 ▶ if ( my $request_uri = $oidc_request->{'request_uri'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $request_uri = $oidc_request->{"request_uri"}) 0 0 0
408 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($self->isUriAllowedForRP($request_uri, $rp, 'oidcRPMetaDataOptionsRequestUris', 1)) { } 0 0 0
409 $self->isUriAllowedForRP(
410 $request_uri, $rp, "oidcRPMetaDataOptionsRequestUris", 1
411 )
412 )
413 {
414 0 my $request = $self->getRequestJWT($request_uri);
415  
416 0 ▶ if ($request) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request) { } 0 0 0
417 0 $oidc_request->{'request'} = $request;
418 }
419 else {
420 0 return $self->_failAuthorize( $req,
421 msg => "Error with Request URI resolution" );
422 }
423 }
424 else {
425 0 return $self->_failAuthorize( $req,
426 msg => "Request URI $request_uri is not allowed for $rp" );
427 }
428 }
429  
430 0 my $authMethod;
431 0 ▶ if ( $oidc_request->{'request'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidc_request->{"request"}) 0 0 0
432 0 ▶ if ( my ( $request, $alg ) =
Branch: 1 branch
BranchTrueFalseTotal
if (() = $self->decodeJWT($oidc_request->{'request'}, undef, $rp)) { } 0 0 0
433 $self->decodeJWT( $oidc_request->{'request'}, undef, $rp ) )
434 {
435 0 $self->logger->debug("JWT signature request verified");
436  
437 0 ▶ $authMethod =
Branch: 1 branch
BranchTrueFalseTotal
$alg =~ /^HS/i ? : 0 0 0
438 $alg =~ /^HS/i
439 ? 'client_secret_jwt'
440 : 'private_key_jwt';
441  
442 # Override OIDC parameters by request content
443 0 foreach ( keys %$request ) {
444 0 $self->logger->debug( "Override $_ OIDC param"
445 . " by value present in request parameter" );
446  
447 0 ▶ if ( $_ eq "client_id" or $_ eq "response_type" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ eq "client_id" or $_ eq "response_type") 0 0 0
Condition0%0/3
$_ eq "client_id" or $_ eq "response_type"
l!l&&r!l&&!r
000
MC/DC0%0/2
$_ eq "client_id" or $_ eq "response_type"
$_ eq "client_id" $_ eq "response_type"
Truth table0%0/3
A or B
A= $_ eq "client_id"B= $_ eq "response_type"
ABresult
1X1
011
000
448 0 ▶ if ( $oidc_request->{$_} ne $request->{$_} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidc_request->{$_} ne $request->{$_}) 0 0 0
449 return $self->_failAuthorize(
450 $req,
451 msg => (
452 "$_ from request JWT ("
453 . $oidc_request->{$_}
454 . ") does not match $_ from request URI ("
455 0 . $request->{$_} . ")"
456 )
457 );
458 }
459 }
460 0 $oidc_request->{$_} = $request->{$_};
461 0 $self->p->setHiddenFormValue( $req, $_, $request->{$_}, '', 0 );
462 }
463 }
464 else {
465 0 return $self->_failAuthorize( $req,
466 msg => "JWT signature request can not be verified" );
467 }
468 }
469  
470 # Check all required parameters
471 0 ▶ unless ( $oidc_request->{'redirect_uri'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($oidc_request->{"redirect_uri"}) 0 0 0
472 0 return $self->_failAuthorize( $req, msg => "Redirect URI is required" );
473 }
474 0 ▶ if ( $flow eq "implicit" and not defined $oidc_request->{'nonce'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flow eq "implicit" and not defined $oidc_request->{"nonce"}) 0 0 0
Condition0%0/3
$flow eq "implicit" and not defined $oidc_request->{"nonce"}
!ll&&!rl&&r
000
MC/DC0%0/2
$flow eq "implicit" and not defined $oidc_request->{"nonce"}
$flow eq "implicit" not defined $oidc_request->{"nonce"}
Truth table0%0/3
A and not(B)
A= $flow eq "implicit"B= not defined $oidc_request->{"nonce"}
ABresult
0X0
100
111
475 0 return $self->_failAuthorize( $req,
476 msg => "Nonce is required for implicit flow" );
477 }
478  
479 # Check if this RP is authorized
480 0 ▶ if ( my $rule = $self->rpRules->{$rp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rule = $self->rpRules->{$rp}) 0 0 0
481 my $ruleVariables =
482 0 ▶ { %{ $req->sessionInfo || {} }, _oidc_grant_type => $flow };
Branch: 1 branch
BranchTrueFalseTotal
$req->sessionInfo or {} 0 0 0
483 0 ▶ unless ( $rule->( $req, $ruleVariables ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$rule($req, $ruleVariables)) 0 0 0
484 return $self->_failAuthorize(
485 $req,
486 msg => (
487 'User '
488 . $req->sessionInfo->{ $self->conf->{whatToTrace} }
489 0 . " is not authorized to access to $rp"
490 ),
491 res => PE_UNAUTHORIZEDPARTNER,
492 userLogger => 1,
493 );
494 }
495 }
496  
497 # Check redirect_uri
498 0 my $redirect_uri = $oidc_request->{'redirect_uri'};
499 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_validateRedirectUri($req, $rp, $redirect_uri, "authorization")) 0 0 0
500 !$self->_validateRedirectUri(
501 $req, $rp, $redirect_uri, "authorization"
502 )
503 )
504 {
505 0 return $self->_failAuthorize(
506 $req,
507 msg => "Redirect URI $redirect_uri not allowed",
508 res => PE_UNAUTHORIZEDURL,
509 userLogger => 1,
510 );
511 }
512  
513 # Check if flow is allowed
514 0 ▶ if ( $flow eq "authorizationcode"
Branch: 1 branch
BranchTrueFalseTotal
if ($flow eq "authorizationcode" and not $self->conf->{"oidcServiceAllowAuthorizationCodeFlow"}) 0 0 0
Condition0%0/3
$flow eq "authorizationcode" and not $self->conf->{"oidcServiceAllowAuthorizationCodeFlow"}
!ll&&!rl&&r
000
MC/DC0%0/2
$flow eq "authorizationcode" and not $self->conf->{"oidcServiceAllowAuthorizationCodeFlow"}
$flow eq "authorizationcode" not $self->conf->{"oidcServiceAllowAuthorizationCodeFlow"}
Truth table0%0/3
A and not(B)
A= $flow eq "authorizationcode"B= not $self->conf->{"oidcServiceAllowAuthorizationCodeFlow"}
ABresult
0X0
100
111
515 and not $self->conf->{oidcServiceAllowAuthorizationCodeFlow} )
516 {
517 return $self->returnRedirectError(
518 $req, $oidc_request->{'redirect_uri'},
519 "server_error", "Authorization code flow not allowed",
520 0 undef, $oidc_request->{'state'}, 0
521 );
522 }
523 0 ▶ if ( $flow eq "implicit"
Branch: 1 branch
BranchTrueFalseTotal
if ($flow eq "implicit" and not $self->conf->{"oidcServiceAllowImplicitFlow"}) 0 0 0
Condition0%0/3
$flow eq "implicit" and not $self->conf->{"oidcServiceAllowImplicitFlow"}
!ll&&!rl&&r
000
MC/DC0%0/2
$flow eq "implicit" and not $self->conf->{"oidcServiceAllowImplicitFlow"}
$flow eq "implicit" not $self->conf->{"oidcServiceAllowImplicitFlow"}
Truth table0%0/3
A and not(B)
A= $flow eq "implicit"B= not $self->conf->{"oidcServiceAllowImplicitFlow"}
ABresult
0X0
100
111
524 and not $self->conf->{oidcServiceAllowImplicitFlow} )
525 {
526 return $self->returnRedirectError(
527 $req, $oidc_request->{'redirect_uri'},
528 "server_error", "Implicit flow not allowed",
529 0 undef, $oidc_request->{'state'}, 1
530 );
531 }
532 0 ▶ if ( $flow eq "hybrid"
Branch: 1 branch
BranchTrueFalseTotal
if ($flow eq "hybrid" and not $self->conf->{"oidcServiceAllowHybridFlow"}) 0 0 0
Condition0%0/3
$flow eq "hybrid" and not $self->conf->{"oidcServiceAllowHybridFlow"}
!ll&&!rl&&r
000
MC/DC0%0/2
$flow eq "hybrid" and not $self->conf->{"oidcServiceAllowHybridFlow"}
$flow eq "hybrid" not $self->conf->{"oidcServiceAllowHybridFlow"}
Truth table0%0/3
A and not(B)
A= $flow eq "hybrid"B= not $self->conf->{"oidcServiceAllowHybridFlow"}
ABresult
0X0
100
111
533 and not $self->conf->{oidcServiceAllowHybridFlow} )
534 {
535 return $self->returnRedirectError(
536 $req, $oidc_request->{'redirect_uri'},
537 "server_error", "Hybrid flow not allowed",
538 0 undef, $oidc_request->{'state'}, 1
539 );
540 }
541  
542 # Check if authentication was required
543 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthRequiredForAuthorize"}) 0 0 0
544 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAuthRequiredForAuthorize}
545 )
546 {
547 0 $self->logger->debug('JWS authentication is required');
548 0 ▶ unless ($authMethod) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($authMethod) 0 0 0
549 return $self->returnRedirectError(
550 $req, $oidc_request->{'redirect_uri'},
551 'server_error', 'JWS authentication required',
552 0 undef, $oidc_request->{'state'}, 1
553 );
554 }
555 my $methodAllowed =
556 0 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAuthMethod};
557 0 ▶ if ( $methodAllowed and $authMethod ne $methodAllowed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($methodAllowed and $authMethod ne $methodAllowed) 0 0 0
Condition0%0/3
$methodAllowed and $authMethod ne $methodAllowed
!ll&&!rl&&r
000
MC/DC0%0/2
$methodAllowed and $authMethod ne $methodAllowed
$methodAllowed $authMethod ne $methodAllowed
Truth table0%0/3
A and B
A= $methodAllowedB= $authMethod ne $methodAllowed
ABresult
0X0
100
111
558 return $self->returnRedirectError(
559 $req, $oidc_request->{'redirect_uri'},
560 'server_error', "Authentication must use $methodAllowed",
561 0 undef, $oidc_request->{'state'},
562 1
563 );
564 }
565 }
566  
567 # Check if state is required
568 0 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAuthnRequireState}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireState"} and not $oidc_request->{"state"}) 0 0 0
Condition0%0/3
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireState"} and not $oidc_request->{"state"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireState"} and not $oidc_request->{"state"}
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireState"} not $oidc_request->{"state"}
Truth table0%0/3
A and not(B)
A= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireState"}B= not $oidc_request->{"state"}
ABresult
0X0
100
111
569 and not( $oidc_request->{'state'} ) )
570 {
571 return $self->returnRedirectError(
572 0 $req, $oidc_request->{'redirect_uri'},
573 "server_error", "State required",
574 undef, undef, 1
575 );
576 }
577  
578 # Check if nonce is required
579 0 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAuthnRequireNonce}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireNonce"} and not $oidc_request->{"nonce"}) 0 0 0
Condition0%0/3
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireNonce"} and not $oidc_request->{"nonce"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireNonce"} and not $oidc_request->{"nonce"}
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireNonce"} not $oidc_request->{"nonce"}
Truth table0%0/3
A and not(B)
A= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnRequireNonce"}B= not $oidc_request->{"nonce"}
ABresult
0X0
100
111
580 and not( $oidc_request->{'nonce'} ) )
581 {
582 return $self->returnRedirectError(
583 0 $req, $oidc_request->{'redirect_uri'},
584 "server_error", "Nonce required",
585 undef, undef, 1
586 );
587 }
588  
589 # Check scope validity
590 # We use a slightly more relaxed version of
591 # https://tools.ietf.org/html/rfc6749#appendix-A.4
592 # To be tolerant of user error (trailing spaces, etc.)
593 # Scope names are restricted to printable ASCII characters,
594 # excluding double quote and backslash
595 0 ▶ unless ( $oidc_request->{'scope'} =~ /^[\x20\x21\x23-\x5B\x5D-\x7E]*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($oidc_request->{"scope"} =~ /^[\x20\x21\x23-\x5B\x5D-\x7E]*$/) 0 0 0
596 0 return $self->_failAuthorize( $req,
597 msg => "Submitted scope is not valid" );
598 }
599  
600 # Check openid scope
601 0 ▶ unless ( $self->_hasScope( 'openid', $oidc_request->{'scope'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_hasScope("openid", $oidc_request->{"scope"})) 0 0 0
602 0 return $self->_failAuthorize( $req, msg => "No openid scope found" );
603 }
604 0 $req->data->{_oidc_request} = $oidc_request;
605 0 $req->data->{_oidc_rp} = $rp;
606 0 $req->data->{_oidc_flow} = $flow;
607 0 return ();
608 }
609  
610 sub _authorizeEndpoint {
611 0 ▶ my ( $self, $req ) = @_;
Subroutine _authorizeEndpoint: not called CC=74 SCAR=86.2
612  
613 0 my $res = $self->_checkErrorsInAuthorizeEndpoint($req);
614 0 ▶ return $res if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 0 0 0
615 0 my $oidc_request = $req->data->{_oidc_request};
616 0 my $rp = $req->data->{_oidc_rp};
617 0 my $flow = $req->data->{_oidc_flow};
618 0 my $client_id = $oidc_request->{client_id};
619 0 my $response_type = $oidc_request->{'response_type'};
620  
621 0 my $spAuthnLevel = $self->rpLevelRules->{$rp}->( $req, $req->sessionInfo );
622 0 ▶ $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAuthnLevel} || 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthnLevel"} or '???' 0 0 0
623  
624 # RP may increase, but not lower, the requirement set in LLNG conf
625 0 ▶ if ( $oidc_request->{'acr_values'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidc_request->{"acr_values"}) 0 0 0
626 my $requested_authn_level =
627 $self->_get_authn_level_from_acr_values(
628 0 $oidc_request->{'acr_values'} );
629 0 ▶ if ( $requested_authn_level > $spAuthnLevel ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($requested_authn_level > $spAuthnLevel) { } 0 0 0
630 0 $spAuthnLevel = $requested_authn_level;
631 }
632 else {
633 0 $self->logger->info( "Ignoring requested authentication level "
634 . $requested_authn_level
635 . " because it is lower than minimum for this RP: $spAuthnLevel"
636 );
637 }
638 }
639  
640 # Check if user needs to be reauthenticated
641 0 my $prompt = $oidc_request->{'prompt'};
642 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($prompt and $prompt =~ /\blogin\b/ and &CORE::GLOBAL::time() - $req->sessionInfo->{"_lastAuthnUTime"} > $self->conf->{"portalForceAuthnInterval"}) 0 0 0
Condition0%0/6
$prompt and $prompt =~ /\blogin\b/ and &CORE::GLOBAL::time() - $req->sessionInfo->{"_lastAuthnUTime"} > $self->conf->{"portalForceAuthnInterval"}
!ll&&!rl&&r
000
$prompt and $prompt =~ /\blogin\b/
!ll&&!rl&&r
000
MC/DC0%0/3
$prompt and $prompt =~ /\blogin\b/ and &CORE::GLOBAL::time() - $req->sessionInfo->{"_lastAuthnUTime"} > $self->conf->{"portalForceAuthnInterval"}
$prompt $prompt =~ /\blogin\b/ &CORE::GLOBAL::time() - $req->sessionInfo->{"_lastAuthnUTime"} > $self->conf->{"portalForceAuthnInterval"}
Truth table0%0/4
A and B and C
A= $promptB= $prompt =~ /\blogin\b/C= &CORE::GLOBAL::time() - $req->sessionInfo->{"_lastAuthnUTime"} > $self->conf->{"portalForceAuthnInterval"}
ABCresult
0XX0
10X0
1100
1111
643 $prompt
644 and $prompt =~ /\blogin\b/
645 and (
646 time - $req->sessionInfo->{_lastAuthnUTime} >
647 $self->conf->{portalForceAuthnInterval} )
648 )
649 {
650 0 $self->logger->debug(
651 "Reauthentication required by Relying Party in prompt parameter");
652 0 $req->pdata->{targetAuthnLevel} = $spAuthnLevel;
653 0 return $self->reAuth($req);
654 }
655  
656 # Check id_token_hint
657 0 my $id_token_hint = $oidc_request->{'id_token_hint'};
658 0 ▶ if ($id_token_hint) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id_token_hint) 0 0 0
659  
660 0 $self->logger->debug("Check sub of ID Token $id_token_hint");
661  
662 # Check that id_token_hint sub match current user
663 0 my $sub = $self->getIDTokenSub($id_token_hint);
664 0 my $user_id = $self->getUserIDForRP( $req, $rp, $req->{sessionInfo} );
665 0 ▶ unless ( $sub eq $user_id ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sub eq $user_id) { } 0 0 0
666 0 $self->logger->error(
667 "ID Token hint sub $sub does not match user $user_id");
668 return $self->returnRedirectError(
669 $req,
670 $oidc_request->{'redirect_uri'},
671 'invalid_request',
672 "Current user does not match id_token_hint sub",
673 undef,
674 0 $oidc_request->{'state'},
675 ( $flow ne "authorizationcode" )
676 );
677 }
678 else {
679 0 $self->logger->debug("ID Token hint sub $sub matches current user");
680 }
681 }
682  
683 0 my $max_age = $oidc_request->{'max_age'};
684 0 my $_lastAuthnUTime = $req->{sessionInfo}->{_lastAuthnUTime};
685 0 ▶ if ( $max_age && time > $_lastAuthnUTime + $max_age ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_age and &CORE::GLOBAL::time() > $_lastAuthnUTime + $max_age) 0 0 0
Condition0%0/3
$max_age and &CORE::GLOBAL::time() > $_lastAuthnUTime + $max_age
!ll&&!rl&&r
000
MC/DC0%0/2
$max_age and &CORE::GLOBAL::time() > $_lastAuthnUTime + $max_age
$max_age &CORE::GLOBAL::time() > $_lastAuthnUTime + $max_age
Truth table0%0/3
A and B
A= $max_ageB= &CORE::GLOBAL::time() > $_lastAuthnUTime + $max_age
ABresult
0X0
100
111
686 0 $self->logger->debug(
687 "Reauthentication forced because authentication time"
688 . " ($_lastAuthnUTime) is too old (>$max_age s)" );
689 0 $req->pdata->{targetAuthnLevel} = $spAuthnLevel;
690 0 return $self->reAuth($req);
691 }
692  
693 # Check if we have sufficient auth level
694 0 ▶ my $authenticationLevel = $req->{sessionInfo}->{authenticationLevel} || 0;
Condition0%0/2
$req->{'sessionInfo'}{'authenticationLevel'} || 0
l!l
00
MC/DC0%0/1
$req->{'sessionInfo'}{'authenticationLevel'} || 0
$req->{'sessionInfo'}{'authenticationLevel'}
Truth table0%0/2
A
A= $req->{'sessionInfo'}{'authenticationLevel'}
Aresult
11
00
695 0 ▶ if ( $authenticationLevel < $spAuthnLevel ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($authenticationLevel < $spAuthnLevel) 0 0 0
696 0 $self->logger->debug(
697 "Insufficient authentication level for service $rp"
698 . " (has: $authenticationLevel, want: $spAuthnLevel)" );
699  
700 # Reauth with sp auth level as target
701 0 $req->pdata->{targetAuthnLevel} = $spAuthnLevel;
702 0 return $self->upgradeAuth($req);
703 }
704  
705 # Compute scopes
706 0 my $req_scope = $oidc_request->{'scope'};
707 0 my $scope = $self->getScope( $req, $rp, $req_scope );
708  
709 # Obtain consent
710 my $bypassConsent =
711 0 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsBypassConsent};
712 0 ▶ if ($bypassConsent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bypassConsent) { } 0 0 0
713 0 $self->logger->debug( "Consent is disabled for Relying Party $rp,"
714 . " user will not be prompted" );
715 }
716 else {
717 0 my $ask_for_consent = 1;
718 0 my $_oidcConsents;
719 0 my @RPoidcConsent = ();
720  
721 # Loading existing oidcConsents
722 0 $self->logger->debug("Looking for OIDC Consents ...");
723  
724 0 ▶ if ( $req->{sessionInfo}->{_oidcConsents} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->{'sessionInfo'}{'_oidcConsents'}) { } 0 0 0
725 0 $_oidcConsents = eval {
726 from_json( $req->{sessionInfo}->{_oidcConsents},
727 0 { allow_nonref => 1 } );
728 };
729 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
730 0 return $self->_failAuthorize( $req,
731 msg => "Corrupted session (_oidcConsents): $@" );
732 }
733 }
734 else {
735 0 $self->logger->debug("No OIDC Consent found");
736 0 $_oidcConsents = [];
737 }
738  
739 # Read existing RP
740 0 @RPoidcConsent = grep { $_->{rp} eq $rp } @$_oidcConsents;
741 0 ▶ unless (@RPoidcConsent) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@RPoidcConsent) 0 0 0
742 0 $self->logger->debug("No Relying Party $rp Consent found");
743  
744 # Set default value
745 0 push @RPoidcConsent, { rp => $rp, epoch => '', scope => '' };
746 }
747  
748 0 ▶ if ( $RPoidcConsent[0]{rp} eq $rp
Branch: 1 branch
BranchTrueFalseTotal
if ($RPoidcConsent[0]{"rp"} eq $rp and $RPoidcConsent[0]{"epoch"} and $RPoidcConsent[0]{"scope"}) 0 0 0
Condition0%0/6
$RPoidcConsent[0]{"rp"} eq $rp and $RPoidcConsent[0]{"epoch"} and $RPoidcConsent[0]{"scope"}
!ll&&!rl&&r
000
$RPoidcConsent[0]{"rp"} eq $rp and $RPoidcConsent[0]{"epoch"}
!ll&&!rl&&r
000
MC/DC0%0/3
$RPoidcConsent[0]{"rp"} eq $rp and $RPoidcConsent[0]{"epoch"} and $RPoidcConsent[0]{"scope"}
$RPoidcConsent[0]{"rp"} eq $rp $RPoidcConsent[0]{"epoch"} $RPoidcConsent[0]{"scope"}
Truth table0%0/4
A and B and C
A= $RPoidcConsent[0]{"rp"} eq $rpB= $RPoidcConsent[0]{"epoch"}C= $RPoidcConsent[0]{"scope"}
ABCresult
0XX0
10X0
1100
1111
749 && $RPoidcConsent[0]{epoch}
750 && $RPoidcConsent[0]{scope} )
751 {
752 0 $ask_for_consent = 0;
753 0 my $consent_time = $RPoidcConsent[0]{epoch};
754 0 my $consent_scope = $RPoidcConsent[0]{scope};
755 0 $self->logger->debug(
756 "Consent already given for Relying Party $rp"
757 . " (time: $consent_time, scope: $consent_scope)" );
758  
759 # Check accepted scope
760 0 foreach my $requested_scope ( split( /\s+/, $scope ) ) {
761 0 ▶ if ( $self->_hasScope( $requested_scope, $consent_scope ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_hasScope($requested_scope, $consent_scope)) { } 0 0 0
762 0 $self->logger->debug(
763 "Scope $requested_scope already accepted");
764 }
765 else {
766 0 $self->logger->debug(
767 "Scope $requested_scope was not previously accepted");
768 0 $ask_for_consent = 1;
769 0 last;
770 }
771 }
772  
773 # Check prompt parameter
774 0 ▶ $ask_for_consent = 1
Branch: 1 branch
BranchTrueFalseTotal
if $prompt and $prompt =~ /\bconsent\b/ 0 0 0
Condition0%0/3
$prompt and $prompt =~ /\bconsent\b/
!ll&&!rl&&r
000
MC/DC0%0/2
$prompt and $prompt =~ /\bconsent\b/
$prompt $prompt =~ /\bconsent\b/
Truth table0%0/3
A and B
A= $promptB= $prompt =~ /\bconsent\b/
ABresult
0X0
100
111
775 if ( $prompt and $prompt =~ /\bconsent\b/ );
776 }
777 0 ▶ if ($ask_for_consent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ask_for_consent) 0 0 0
778 0 ▶ if ( $req->param('confirm')
Branch: 2 branches
BranchTrueFalseTotal
if ($req->param('confirm') and $req->param('confirm') == 1) { } 0 0 0
elsif ($req->param('confirm') and $req->param('confirm') == -1) { } 0 0 0
Condition0%0/3
$req->param("confirm") and $req->param("confirm") == 1
!ll&&!rl&&r
000
MC/DC0%0/2
$req->param("confirm") and $req->param("confirm") == 1
$req->param("confirm") $req->param("confirm") == 1
Truth table0%0/3
A and B
A= $req->param("confirm")B= $req->param("confirm") == 1
ABresult
0X0
100
111
779 and $req->param('confirm') == 1 )
780 {
781 0 $RPoidcConsent[0]{epoch} = time;
782 0 $RPoidcConsent[0]{scope} = $scope;
783  
784 # Build new consent list by removing all references
785 # to the current RP from the old list and appending the
786 # new consent
787 my @newoidcConsents =
788 0 grep { $_->{rp} ne $rp } @$_oidcConsents;
789 0 push @newoidcConsents, $RPoidcConsent[0];
790 0 $self->logger->debug("Append Relying Party $rp Consent");
791 0 $self->p->updatePersistentSession( $req,
792 { _oidcConsents => to_json( \@newoidcConsents ) } );
793  
794 0 $self->logger->debug("Consent given for Relying Party $rp");
795 }
796 ▶ elsif ( $req->param('confirm')
Condition0%0/3
$req->param("confirm") and $req->param("confirm") == -1
!ll&&!rl&&r
000
MC/DC0%0/2
$req->param("confirm") and $req->param("confirm") == -1
$req->param("confirm") $req->param("confirm") == -1
Truth table0%0/3
A and B
A= $req->param("confirm")B= $req->param("confirm") == -1
ABresult
0X0
100
111
797 and $req->param('confirm') == -1 )
798 {
799 0 $self->logger->debug(
800 "User refused consent for Relying party $rp");
801 return $self->returnRedirectError(
802 $req,
803 $oidc_request->{'redirect_uri'},
804 "consent_required",
805 "consent not given",
806 undef,
807 0 $oidc_request->{'state'},
808 ( $flow ne "authorizationcode" )
809 );
810 }
811 else {
812 0 $self->logger->debug(
813 "Request user consent for Relying Party $rp");
814  
815 # Return error if prompt is none
816 0 ▶ if ( $prompt and $prompt =~ /\bnone\b/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prompt and $prompt =~ /\bnone\b/) 0 0 0
Condition0%0/3
$prompt and $prompt =~ /\bnone\b/
!ll&&!rl&&r
000
MC/DC0%0/2
$prompt and $prompt =~ /\bnone\b/
$prompt $prompt =~ /\bnone\b/
Truth table0%0/3
A and B
A= $promptB= $prompt =~ /\bnone\b/
ABresult
0X0
100
111
817 0 $self->logger->debug(
818 "Consent is requiered but prompt is set to none");
819 return $self->returnRedirectError(
820 $req,
821 $oidc_request->{'redirect_uri'},
822 "consent_required",
823 "consent required",
824 undef,
825 0 $oidc_request->{'state'},
826 ( $flow ne "authorizationcode" )
827 );
828 }
829  
830 my $display_name =
831 0 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsDisplayName};
832 0 my $icon = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIcon};
833 0 my $imgSrc;
834  
835 0 ▶ if ($icon) {
Branch: 1 branch
BranchTrueFalseTotal
if ($icon) 0 0 0
836 0 ▶ $imgSrc =
Branch: 1 branch
BranchTrueFalseTotal
$icon =~ m[^https?://] ? : 0 0 0
837 ( $icon =~ m#^https?://# )
838 ? $icon
839 : $self->p->staticPrefix . "/common/" . $icon;
840 }
841  
842 0 my $scope_messages = {
843 openid => 'yourIdentity',
844 profile => 'yourProfile',
845 email => 'yourEmail',
846 address => 'yourAddress',
847 phone => 'yourPhone',
848 offline_access => 'yourOffline',
849 };
850 0 my @list;
851 0 foreach my $requested_scope ( split( /\s+/, $scope ) ) {
852 0 ▶ if ( my $message = $scope_messages->{$requested_scope} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $message = $scope_messages->{$requested_scope}) { } 0 0 0
853 0 push @list, { m => $message };
854 }
855 else {
856 0 push @list,
857 {
858 m => 'anotherInformation',
859 n => $requested_scope
860 };
861 }
862 }
863 $req->info(
864 0 $self->loadTemplate(
865 $req,
866 'oidcGiveConsent',
867 params => {
868 displayName => $display_name,
869 imgUrl => $imgSrc,
870 list => \@list,
871 }
872 )
873 );
874 0 $req->data->{activeTimer} = 0;
875 0 return PE_CONFIRM;
876 }
877 }
878 }
879  
880 # Create session_state
881 0 my $session_state = $self->createSessionState( $req->id, $client_id );
882  
883 # Check if PKCE is required
884 0 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsRequirePKCE}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsRequirePKCE"} and not $oidc_request->{"code_challenge"}) 0 0 0
Condition0%0/3
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsRequirePKCE"} and not $oidc_request->{"code_challenge"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsRequirePKCE"} and not $oidc_request->{"code_challenge"}
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsRequirePKCE"} not $oidc_request->{"code_challenge"}
Truth table0%0/3
A and not(B)
A= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsRequirePKCE"}B= not $oidc_request->{"code_challenge"}
ABresult
0X0
100
111
885 and !$oidc_request->{'code_challenge'} )
886 {
887 return $self->returnRedirectError(
888 $req, $oidc_request->{'redirect_uri'},
889 'invalid_request', "Code challenge is required",
890 0 undef, $oidc_request->{'state'},
891 ( $flow ne "authorizationcode" )
892 );
893 }
894  
895 0 my $offline = 0;
896 0 ▶ if ( $self->_hasScope( 'offline_access', $scope ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_hasScope("offline_access", $scope)) 0 0 0
897 0 $offline = 1;
898  
899 # MUST ensure that the prompt parameter contains consent unless
900 # other conditions for processing the request permitting offline
901 # access to the requested resources are in place; unless one or
902 # both of these conditions are fulfilled, then it MUST ignore
903 # the offline_access request,
904 0 ▶ unless ( $bypassConsent
Branch: 1 branch
BranchTrueFalseTotal
unless ($bypassConsent or $prompt and $prompt =~ /\bconsent\b/) 0 0 0
Condition0%0/6
$bypassConsent or $prompt and $prompt =~ /\bconsent\b/
l!l&&r!l&&!r
000
$prompt and $prompt =~ /\bconsent\b/
!ll&&!rl&&r
000
MC/DC0%0/3
$bypassConsent or $prompt and $prompt =~ /\bconsent\b/
$bypassConsent $prompt $prompt =~ /\bconsent\b/
Truth table0%0/4
A or B and C
A= $bypassConsentB= $promptC= $prompt =~ /\bconsent\b/
ABCresult
1XX1
0111
00X0
0100
905 or ( $prompt and $prompt =~ /\bconsent\b/ ) )
906 {
907 0 $self->logger->warn( "Offline access ignored, "
908 . "prompt parameter must contain \"consent\"" );
909 0 $offline = 0;
910 }
911  
912 # MUST ignore the offline_access request unless the Client is
913 # using a response_type value that would result in an
914 # Authorization Code being returned,
915 0 ▶ if ( $response_type !~ /\bcode\b/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response_type =~ /\bcode\b/) 0 0 0
916 0 $self->logger->warn( "Offline access incompatible "
917 . "with response type $response_type" );
918 0 $offline = 0;
919 }
920  
921 # Ignore offline_access request if not authorized by the RP
922 0 ▶ unless ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAllowOffline} )
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAllowOffline"}) 0 0 0
923 {
924 0 $self->logger->warn("Offline access not authorized for RP $rp");
925 0 $offline = 0;
926 }
927  
928 # Strip offline_access from scopes from now on
929 0 $scope = join " ", grep !/^offline_access$/, split /\s+/, $scope;
930 }
931  
932 # Authorization Code Flow
933 0 ▶ if ( $flow eq "authorizationcode" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flow eq "authorizationcode") 0 0 0
934  
935 # Store data in session
936 my $code_payload = {
937 code_challenge => $oidc_request->{'code_challenge'},
938 code_challenge_method => $oidc_request->{'code_challenge_method'},
939 nonce => $oidc_request->{'nonce'},
940 offline => $offline,
941 0 redirect_uri => $oidc_request->{'redirect_uri'},
942 scope => $scope,
943 req_scope => $req_scope,
944 client_id => $client_id,
945 user_session_id => $req->id,
946 };
947  
948 0 my $h = $self->p->processHook( $req, 'oidcGenerateCode',
949 $oidc_request, $rp, $code_payload );
950 0 ▶ return $self->_failAuthorize(
Branch: 1 branch
BranchTrueFalseTotal
if $h != 0 0 0 0
951 $req,
952 msg => "oidcGenerateCode hook failed",
953 res => $h
954 ) if ( $h != PE_OK );
955  
956 0 my $codeSession = $self->newAuthorizationCode( $rp, $code_payload );
957  
958 # Generate code
959 0 my $code = $codeSession->id();
960  
961 0 $self->logger->debug("Generated code: $code");
962  
963 0 my $state = $oidc_request->{'state'};
964  
965 $self->p->registerProtectedAppAccess( $req,
966 0 $req->sessionInfo->{ $self->conf->{whatToTrace} }, "oidc:$rp" );
967  
968 $self->auditLog(
969 $req,
970 code => "ISSUER_OIDC_LOGIN_SUCCESS",
971 rp => $rp,
972 message => (
973 'User '
974 . $req->sessionInfo->{ $self->conf->{whatToTrace} }
975 . " is authorized to access to $rp"
976 ),
977 user => $req->sessionInfo->{ $self->conf->{whatToTrace} },
978 0 );
979  
980 return $self->sendOidcResponse(
981 $req, $flow,
982 $oidc_request->{'response_mode'},
983 0 ▶ $oidc_request->{'redirect_uri'},
Branch: 3 branches
BranchTrueFalseTotal
$code ? : 0 0 0
$state ? : 0 0 0
$session_state ? : 0 0 0
984 {
985 ( $code ? ( code => $code ) : () ),
986 ( $state ? ( state => $state ) : () ),
987 (
988 $session_state
989 ? ( session_state => $session_state )
990 : ()
991 ),
992 }
993 );
994 }
995  
996 # Implicit Flow
997 0 ▶ if ( $flow eq "implicit" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flow eq "implicit") 0 0 0
998  
999 0 my $access_token;
1000 my $at_hash;
1001  
1002 0 my $release_claims_in_id_token = 1;
1003 0 ▶ if ( $response_type =~ /\btoken\b/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response_type =~ /\btoken\b/) 0 0 0
1004  
1005 0 $release_claims_in_id_token = 0;
1006  
1007 # Store data in access token
1008 # Generate access_token
1009 0 $access_token = $self->newAccessToken(
1010 $req, $rp, $scope,
1011 $req->sessionInfo,
1012 {
1013 scope => $scope,
1014 rp => $rp,
1015 user_session_id => $req->id,
1016 grant_type => $flow,
1017 }
1018 );
1019  
1020 0 ▶ unless ($access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 0 0
1021 $self->returnRedirectError(
1022 $req, $oidc_request->{'redirect_uri'},
1023 "server_error", "Unable to create Access Token",
1024 0 undef, $oidc_request->{'state'},
1025 1
1026 );
1027 }
1028  
1029 0 $self->logger->debug("Generated access token: $access_token");
1030  
1031 # Compute hash to store in at_hash
1032 my $alg =
1033 0 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIDTokenSignAlg};
1034 0 my ($hash_level) = ( $alg =~ /(?:\w{2})(\d{3})/ );
1035 0 ▶ $at_hash = $self->createHash( $access_token, $hash_level )
Branch: 1 branch
BranchTrueFalseTotal
if $hash_level 0 0 0
1036 if $hash_level;
1037 }
1038  
1039 my $id_token =
1040 $self->_generateIDToken( $req, $rp, $scope, $req->sessionInfo,
1041 $release_claims_in_id_token,
1042 0 { at_hash => $at_hash, nonce => $oidc_request->{nonce} } );
1043  
1044 0 ▶ unless ($id_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token) 0 0 0
1045 0 return $self->_failAuthorize( $req,
1046 msg => "Could not generate ID token" );
1047 }
1048  
1049 0 $self->logger->debug("Generated id token: $id_token");
1050  
1051 # Send token response
1052 my $expires_in =
1053 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenExpiration}
1054 0 ▶ || $self->conf->{oidcServiceAccessTokenExpiration};
Condition0%0/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} $self->conf->{'oidcServiceAccessTokenExpiration'}
Truth table0%0/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'}B= $self->conf->{'oidcServiceAccessTokenExpiration'}
ABresult
1X1
011
000
1055  
1056 0 my $state = $oidc_request->{'state'};
1057  
1058 $self->auditLog(
1059 $req,
1060 code => "ISSUER_OIDC_LOGIN_SUCCESS",
1061 rp => $rp,
1062 message => (
1063 'User '
1064 . $req->sessionInfo->{ $self->conf->{whatToTrace} }
1065 . " is authorized to access to $rp"
1066 ),
1067 user => $req->sessionInfo->{ $self->conf->{whatToTrace} },
1068 0 );
1069  
1070 return $self->sendOidcResponse(
1071 $req, $flow,
1072 $oidc_request->{'response_mode'},
1073 0 ▶ $oidc_request->{'redirect_uri'},
Branch: 5 branches
BranchTrueFalseTotal
$access_token ? : 0 0 0
$expires_in ? : 0 0 0
$state ? : 0 0 0
$req_scope ne $scope ? : 0 0 0
$session_state ? : 0 0 0
1074 {
1075 id_token => $id_token,
1076 (
1077 $access_token
1078 ? (
1079 token_type => 'bearer',
1080 access_token => $access_token
1081 )
1082 : ()
1083 ),
1084 ( $expires_in ? ( expires_in => $expires_in ) : () ),
1085 ( $state ? ( state => $state ) : () ),
1086 ( ( $req_scope ne $scope ) ? ( scope => $scope ) : () ),
1087 (
1088 $session_state ? ( session_state => $session_state )
1089 : ()
1090 )
1091 }
1092 );
1093 }
1094  
1095 # Hybrid Flow
1096 0 ▶ if ( $flow eq "hybrid" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flow eq "hybrid") 0 0 0
1097  
1098 0 my $access_token;
1099 my $id_token;
1100 0 my $at_hash;
1101 0 my $c_hash;
1102  
1103 # Hash level
1104 my $alg =
1105 0 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIDTokenSignAlg};
1106 0 my ($hash_level) = ( $alg =~ /(?:\w{2})(\d{3})/ );
1107  
1108 # Store data in session
1109 my $codeSession = $self->newAuthorizationCode(
1110 $rp,
1111 {
1112 nonce => $oidc_request->{'nonce'},
1113 offline => $offline,
1114 0 redirect_uri => $oidc_request->{'redirect_uri'},
1115 client_id => $client_id,
1116 scope => $scope,
1117 user_session_id => $req->id,
1118 }
1119 );
1120  
1121 # Generate code
1122 0 my $code = $codeSession->id();
1123  
1124 0 $self->logger->debug("Generated code: $code");
1125  
1126 # Compute hash to store in c_hash
1127 0 ▶ $c_hash = $self->createHash( $code, $hash_level )
Branch: 1 branch
BranchTrueFalseTotal
if $hash_level 0 0 0
1128 if $hash_level;
1129  
1130 0 my $release_claims_in_id_token = 1;
1131 0 ▶ if ( $response_type =~ /\btoken\b/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response_type =~ /\btoken\b/) 0 0 0
1132  
1133 0 $release_claims_in_id_token = 0;
1134  
1135 # Generate access_token
1136 0 $access_token = $self->newAccessToken(
1137 $req, $rp, $scope,
1138 $req->sessionInfo,
1139 {
1140 scope => $scope,
1141 rp => $rp,
1142 user_session_id => $req->id,
1143 grant_type => $flow,
1144 }
1145 );
1146  
1147 0 ▶ unless ($access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 0 0
1148 return $self->returnRedirectError(
1149 $req, $oidc_request->{'redirect_uri'},
1150 "server_error", "Unable to create Access Token",
1151 0 undef, $oidc_request->{'state'},
1152 1
1153 );
1154 }
1155  
1156 0 $self->logger->debug("Generated access token: $access_token");
1157  
1158 # Compute hash to store in at_hash
1159 0 ▶ $at_hash = $self->createHash( $access_token, $hash_level )
Branch: 1 branch
BranchTrueFalseTotal
if $hash_level 0 0 0
1160 if $hash_level;
1161 }
1162  
1163 0 ▶ if ( $response_type =~ /\bid_token\b/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response_type =~ /\bid_token\b/) 0 0 0
1164  
1165 $id_token = $self->_generateIDToken(
1166 $req, $rp, $scope,
1167 $req->sessionInfo,
1168 $release_claims_in_id_token,
1169 {
1170 at_hash => $at_hash,
1171 c_hash => $c_hash,
1172 nonce => $oidc_request->{nonce},
1173 }
1174 0 );
1175  
1176 0 ▶ unless ($id_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token) 0 0 0
1177 0 return $self->_failAuthorize( $req,
1178 msg => "Could not generate ID token" );
1179 }
1180  
1181 0 $self->logger->debug("Generated id token: $id_token");
1182 }
1183  
1184 my $expires_in =
1185 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenExpiration}
1186 0 ▶ || $self->conf->{oidcServiceAccessTokenExpiration};
Condition0%0/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} $self->conf->{'oidcServiceAccessTokenExpiration'}
Truth table0%0/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'}B= $self->conf->{'oidcServiceAccessTokenExpiration'}
ABresult
1X1
011
000
1187  
1188 0 my $state = $oidc_request->{state};
1189  
1190 $self->auditLog(
1191 $req,
1192 code => "ISSUER_OIDC_LOGIN_SUCCESS",
1193 rp => $rp,
1194 message => (
1195 'User '
1196 . $req->sessionInfo->{ $self->conf->{whatToTrace} }
1197 . " is authorized to access to $rp"
1198 ),
1199 user => $req->sessionInfo->{ $self->conf->{whatToTrace} },
1200 0 );
1201  
1202 return $self->sendOidcResponse(
1203 $req, $flow,
1204 $oidc_request->{'response_mode'},
1205 0 ▶ $oidc_request->{'redirect_uri'},
Branch: 6 branches
BranchTrueFalseTotal
$access_token ? : 0 0 0
$id_token ? : 0 0 0
$expires_in ? : 0 0 0
$state ? : 0 0 0
$req_scope ne $scope ? : 0 0 0
$session_state ? : 0 0 0
1206 {
1207 code => $code,
1208 (
1209 $access_token
1210 ? (
1211 token_type => 'bearer',
1212 access_token => $access_token
1213 )
1214 : ()
1215 ),
1216 (
1217 $id_token ? ( id_token => $id_token )
1218 : ()
1219 ),
1220 ( $expires_in ? ( expires_in => $expires_in ) : () ),
1221 ( $state ? ( state => $state ) : () ),
1222 ( ( $req_scope ne $scope ) ? ( scope => $scope ) : () ),
1223 (
1224 $session_state ? ( session_state => $session_state )
1225 : ()
1226 )
1227 }
1228 );
1229 }
1230  
1231 0 $self->logger->debug("None flow has been selected");
1232 0 return PE_OK;
1233 }
1234  
1235 sub _failAuthorize {
1236 0 ▶ my ( $self, $req, %params ) = @_;
Subroutine _failAuthorize: not called CC=4 SCAR=30.0
1237  
1238 0 ▶ my $reason = $params{'msg'} ? ": $params{'msg'}" : "";
Branch: 1 branch
BranchTrueFalseTotal
$params{'msg'} ? : 0 0 0
1239 0 ▶ my $res = $params{res} || PE_ERROR;
Condition0%0/2
$params{'res'} || 24
l!l
00
MC/DC0%0/1
$params{'res'} || 24
$params{'res'}
Truth table0%0/2
A
A= $params{'res'}
Aresult
11
00
1240  
1241 $self->auditLog(
1242 $req,
1243 code => "ISSUER_OIDC_LOGIN_FAILED",
1244 message => ( "OIDC login failed" . $reason ),
1245 ( $reason ? ( reason => $reason ) : () ),
1246 portal_error => portalConsts->{$res},
1247 user => $req->sessionInfo->{ $self->conf->{whatToTrace} },
1248 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$reason ? : 0 0 0
1249  
1250 0 return $res;
1251 }
1252  
1253 sub _rpInitiatedLogout {
1254 0 ▶ my ( $self, $req ) = @_;
Subroutine _rpInitiatedLogout: not called CC=24 SCAR=64.0
1255  
1256 # Set hidden fields
1257 0 my $oidc_request = {};
1258 0 foreach
1259 my $param (qw/id_token_hint post_logout_redirect_uri state client_id/)
1260 {
1261 0 ▶ if ( $oidc_request->{$param} = $req->param($param) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidc_request->{$param} = $req->param($param)) 0 0 0
1262 $self->logger->debug(
1263 0 "OIDC request parameter $param: " . $oidc_request->{$param} );
1264 }
1265 }
1266  
1267 0 my $post_logout_redirect_uri = $oidc_request->{'post_logout_redirect_uri'};
1268 0 my $id_token_hint = $oidc_request->{'id_token_hint'};
1269 0 my $client_id = $oidc_request->{'client_id'};
1270 0 my $state = $oidc_request->{'state'};
1271 0 my $bypassConfirm = 0;
1272  
1273 0 my $post_logout_redirect_uri_with_state;
1274 my $rp;
1275  
1276 # Check if we can bypass confirm using token_hint
1277 0 ▶ if ($id_token_hint) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id_token_hint) 0 0 0
1278  
1279 # TODO: we should check JWT signature here to avoid DoS by
1280 # logging the user out, however, as long as there is no logout
1281 # confirmation when accessing ?logout=1, such a protection is
1282 # trivial to bypass
1283 0 my $payload = getJWTPayload($id_token_hint);
1284  
1285 0 ▶ if ( my $azp = $payload->{azp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $azp = $payload->{"azp"}) 0 0 0
1286 0 ▶ if ( !$client_id or $client_id eq $azp ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $client_id or $client_id eq $azp) { } 0 0 0
Condition0%0/3
not $client_id or $client_id eq $azp
l!l&&r!l&&!r
000
MC/DC0%0/2
not $client_id or $client_id eq $azp
not $client_id $client_id eq $azp
Truth table0%0/3
not(A) or B
A= not $client_idB= $client_id eq $azp
ABresult
1X1
011
000
1287 0 $rp = $self->getRP( $payload->{azp} );
1288 }
1289 else {
1290 0 $self->logger->error(
1291 "Provided client ID $client_id does not match"
1292 . " id_token_hint azp $azp" );
1293 0 return PE_ERROR;
1294 }
1295 }
1296  
1297 0 $bypassConfirm = $self->_check_bypass_confirm( $req, $rp, $payload );
1298  
1299 }
1300  
1301 0 ▶ if ( not $rp and $client_id ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $rp and $client_id) 0 0 0
Condition0%0/3
not $rp and $client_id
!ll&&!rl&&r
000
MC/DC0%0/2
not $rp and $client_id
not $rp $client_id
Truth table0%0/3
not(A) and B
A= not $rpB= $client_id
ABresult
0X0
100
111
1302 0 $rp = $self->getRP($client_id);
1303 }
1304  
1305 # Validate post_logout_redirect_uri
1306 0 ▶ if ($post_logout_redirect_uri) {
Branch: 1 branch
BranchTrueFalseTotal
if ($post_logout_redirect_uri) 0 0 0
1307  
1308 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_validatePostLogoutRedirectUri($req, $rp, $post_logout_redirect_uri, "end_session")) 0 0 0
1309 $self->_validatePostLogoutRedirectUri(
1310 $req, $rp, $post_logout_redirect_uri, "end_session"
1311 )
1312 )
1313 {
1314 0 $self->logger->error("$post_logout_redirect_uri is not allowed");
1315 0 return PE_UNAUTHORIZEDURL;
1316 }
1317  
1318 # Build Response
1319 $post_logout_redirect_uri_with_state =
1320 0 $self->buildLogoutResponse( $post_logout_redirect_uri, $state );
1321 }
1322  
1323 # Ask consent for logout
1324 0 ▶ if ( $req->param('confirm') or $bypassConfirm ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->param("confirm") or $bypassConfirm) 0 0 0
Condition0%0/3
$req->param("confirm") or $bypassConfirm
l!l&&r!l&&!r
000
MC/DC0%0/2
$req->param("confirm") or $bypassConfirm
$req->param("confirm") $bypassConfirm
Truth table0%0/3
A or B
A= $req->param("confirm")B= $bypassConfirm
ABresult
1X1
011
000
1325 0 my $err;
1326 0 ▶ if ( (
Branch: 1 branch
BranchTrueFalseTotal
if (defined $req->param("confirm") and $req->param("confirm") eq 1 or $bypassConfirm) 0 0 0
Condition0%0/6
defined $req->param("confirm") and $req->param("confirm") eq 1 or $bypassConfirm
l!l&&r!l&&!r
000
defined $req->param("confirm") and $req->param("confirm") eq 1
!ll&&!rl&&r
000
MC/DC0%0/3
defined $req->param("confirm") and $req->param("confirm") eq 1 or $bypassConfirm
defined $req->param("confirm") $req->param("confirm") eq 1 $bypassConfirm
Truth table0%0/5
A and B or C
A= defined $req->param("confirm")B= $req->param("confirm") eq 1C= $bypassConfirm
ABCresult
11X1
0X11
1011
0X00
1000
1327 defined( $req->param('confirm') )
1328 and $req->param('confirm') eq '1'
1329 )
1330 or $bypassConfirm
1331 )
1332 {
1333  
1334 # Save the target URL in case authLogout has external steps
1335 0 ▶ $req->{issuerNextUrl} = $post_logout_redirect_uri_with_state
Branch: 1 branch
BranchTrueFalseTotal
if $post_logout_redirect_uri_with_state 0 0 0
1336 if $post_logout_redirect_uri_with_state;
1337  
1338 $req->steps(
1339 0 [ @{ $self->p->beforeLogout }, 'authLogout', 'deleteSession' ]
1340 );
1341 0 $req->data->{nofail} = 1;
1342 0 $err = $req->error( $self->p->process($req) );
1343 0 ▶ if ( $err and $err != PE_LOGOUT_OK ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err and $err != 47) 0 0 0
Condition0%0/3
$err and $err != 47
!ll&&!rl&&r
000
MC/DC0%0/2
$err and $err != 47
$err $err != 47
Truth table0%0/3
A and B
A= $errB= $err != 47
ABresult
0X0
100
111
1344 0 ▶ if ( $err > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err > 0) 0 0 0
1345 0 $self->logger->error(
1346 "Logout process returns error code $err");
1347 }
1348 0 return $err;
1349 }
1350 }
1351  
1352 0 ▶ if ($post_logout_redirect_uri_with_state) {
Branch: 1 branch
BranchTrueFalseTotal
if ($post_logout_redirect_uri_with_state) 0 0 0
1353 0 return $self->_redirectToUrl( $req,
1354 $post_logout_redirect_uri_with_state );
1355 }
1356  
1357 0 ▶ return $req->param('confirm') == 1
Branch: 2 branches
BranchTrueFalseTotal
$req->param('confirm') == 1 ? : 0 0 0
$err ? : 0 0 0
1358 ? ( $err ? $err : PE_LOGOUT_OK )
1359 : PE_OK;
1360 }
1361  
1362 0 $req->info( $self->loadTemplate( $req, 'oidcLogout' ) );
1363 0 $req->data->{activeTimer} = 0;
1364  
1365 0 ▶ while ( my ( $k, $v ) = each %$oidc_request ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$oidc_request) 0 0 0
1366 0 $self->p->setHiddenFormValue( $req, $k, $v, '', 0 );
1367 }
1368  
1369 0 return PE_CONFIRM;
1370 }
1371  
1372 sub _check_bypass_confirm {
1373 0 ▶ my ( $self, $req, $rp, $payload ) = @_;
Subroutine _check_bypass_confirm: not called CC=5 SCAR=34.0
1374  
1375 0 ▶ unless ($rp) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rp) 0 0 0
1376 0 $self->userLogger->info(
1377 "ID Token hint azp doesn't match any known RP,"
1378 . " forcing confirmation" );
1379 0 return 0;
1380 }
1381  
1382 0 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsLogoutBypassConfirm} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsLogoutBypassConfirm"}) 0 0 0
1383  
1384 0 my $sub = $payload->{sub};
1385 0 my $user_id = $self->getUserIDForRP( $req, $rp, $req->{sessionInfo} );
1386 0 ▶ if ( $sub ne $user_id ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sub ne $user_id) 0 0 0
1387 0 $self->userLogger->info(
1388 "ID Token hint sub $sub does not match user $user_id,"
1389 . " forcing confirmation" );
1390 0 return 0;
1391 }
1392  
1393 0 my $sid = $payload->{sid};
1394 0 ▶ if ( $self->getSidFromSession( $rp, $req->{sessionInfo} ) ne $sid ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->getSidFromSession($rp, $req->{"sessionInfo"}) ne $sid) 0 0 0
1395 0 $self->userLogger->info(
1396 "ID Token hint `sid` does not match user session,"
1397 . " forcing confirmation" );
1398 0 return 0;
1399 }
1400 0 $self->logger->debug("Bypass logout confirm for RP $rp");
1401 0 return 1;
1402  
1403 }
1404 0 return 0;
1405  
1406 }
1407  
1408 sub _validateRedirectUri {
1409 0 ▶ my ( $self, $req, $rp, $uri, $current_endpoint ) = @_;
Subroutine _validateRedirectUri: not called CC=3 SCAR=24.8
1410  
1411 0 ▶ return unless $rp;
Branch: 1 branch
BranchTrueFalseTotal
unless $rp 0 0 0
1412  
1413 0 my $state = {};
1414 0 my $h = $self->p->processHook( $req, 'oidcValidateRedirectUri',
1415 $rp, $uri, $current_endpoint, $state );
1416 0 ▶ return $state->{result} if ( $h == PE_DONE );
Branch: 1 branch
BranchTrueFalseTotal
if $h == -1 0 0 0
1417  
1418 0 return $self->isUriAllowedForRP( $uri, $rp,
1419 'oidcRPMetaDataOptionsRedirectUris' );
1420 }
1421  
1422 sub _validatePostLogoutRedirectUri {
1423 0 ▶ my ( $self, $req, $rp, $uri, $current_endpoint ) = @_;
Subroutine _validatePostLogoutRedirectUri: not called CC=4 SCAR=30.0
1424  
1425 0 ▶ if ($rp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rp) { } 0 0 0
1426  
1427 0 my $state = {};
1428 0 my $h = $self->p->processHook( $req, 'oidcValidateRedirectUri',
1429 $rp, $uri, $current_endpoint, $state );
1430 0 ▶ return $state->{result} if ( $h == PE_DONE );
Branch: 1 branch
BranchTrueFalseTotal
if $h == -1 0 0 0
1431  
1432 0 return $self->isUriAllowedForRP( $uri, $rp,
1433 'oidcRPMetaDataOptionsPostLogoutRedirectUris' );
1434 }
1435 else {
1436 return (
1437 0 ▶ $self->findRPFromUri( $uri,
Branch: 1 branch
BranchTrueFalseTotal
$self->findRPFromUri($uri, 'oidcRPMetaDataOptionsPostLogoutRedirectUris') ? : 0 0 0
1438 'oidcRPMetaDataOptionsPostLogoutRedirectUris' ) ? 1 : 0
1439 );
1440 }
1441 }
1442  
1443 sub findRPFromUri {
1444 0 ▶ my ( $self, $uri, $option ) = @_;
Subroutine findRPFromUri: not called CC=3 SCAR=24.8
Pod undocumented
1445  
1446 0 my $found_rp;
1447 0 foreach my $rp ( keys %{ $self->rpOptions } ) {
1448 0 ▶ $found_rp = $rp if $self->isUriAllowedForRP( $uri, $rp, $option );
Branch: 1 branch
BranchTrueFalseTotal
if $self->isUriAllowedForRP($uri, $rp, $option) 0 0 0
1449 }
1450 0 return $found_rp;
1451 }
1452  
1453 sub isUriAllowedForRP {
1454 0 ▶ my ( $self, $uri, $rp, $option, $wildcard_allowed ) = @_;
Subroutine isUriAllowedForRP: not called CC=3 SCAR=24.8
Pod undocumented
1455 0 ▶ my $allowed_uris = $self->rpOptions->{$rp}->{$option} // "";
Condition0%0/2
$self->rpOptions->{$rp}{$option} // ""
l!l
00
MC/DC0%0/1
$self->rpOptions->{$rp}{$option} // ""
$self->rpOptions->{$rp}{$option}
Truth table0%0/2
A
A= $self->rpOptions->{$rp}{$option}
Aresult
11
00
1456 0 $self->logger->debug("Allowed URIs for $rp: $allowed_uris");
1457  
1458 0 my $is_uri_allowed;
1459 0 ▶ if ($wildcard_allowed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wildcard_allowed) { } 0 0 0
1460 $is_uri_allowed =
1461 0 grep { _wildcard_match( $_, $uri ) } split( /\s+/, $allowed_uris );
1462 }
1463 else {
1464 0 $is_uri_allowed = grep { $_ eq $uri } split( /\s+/, $allowed_uris );
1465 }
1466 0 return $is_uri_allowed;
1467 }
1468  
1469 # Picks the first ACR value from the list that matches a known Authn Context
1470 sub _get_authn_level_from_acr_values {
1471 0 ▶ my ( $self, $acr_values ) = @_;
Subroutine _get_authn_level_from_acr_values: not called CC=3 SCAR=24.8
1472 0 my @acr_values = split( /\s+/, $acr_values );
1473 0 for my $acr_value (@acr_values) {
1474 0 ▶ if ( my $level =
Branch: 1 branch
BranchTrueFalseTotal
if (my $level = $self->conf->{"oidcServiceMetaDataAuthnContext"}{$acr_value}) 0 0 0
1475 $self->conf->{oidcServiceMetaDataAuthnContext}->{$acr_value} )
1476 {
1477 0 $self->logger->debug(
1478 "Authentication level $level selected from ACR value $acr_value"
1479 );
1480  
1481 0 return $level;
1482 }
1483 }
1484 0 return 0;
1485 }
1486  
1487 sub _wildcard_match {
1488 0 ▶ my ( $config_url, $candidate ) = @_;
Subroutine _wildcard_match: not called CC=2 SCAR=17.9
1489  
1490 # Quote everything
1491 0 my $config_re = $config_url =~ s/(.)/\Q$1/gr;
1492  
1493 # Replace \* by .*
1494 0 $config_re =~ s/\\\*/.*/g;
1495  
1496 0 ▶ return ( $candidate =~ qr/^$config_re$/ ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$candidate =~ qr/^$config_re$/ ? : 0 0 0
1497 }
1498  
1499 # Handle token endpoint
1500 sub token {
1501 4 ▶ my ( $self, $req ) = @_;
Subroutine token: called CC=12 SCAR=32.3
Pod undocumented
1502 4 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 4 4
1503 4 $self->logger->debug("URL detected as an OpenID Connect TOKEN URL");
1504  
1505 4 my ($rp) = $self->checkEndPointAuthenticationCredentials($req);
1506 4 ▶ return $self->invalidClientResponse($req) unless ($rp);
Branch: 1 branch
BranchTrueFalseTotal
unless $rp 0 4 4
1507  
1508 4 ▶ my $grant_type = $req->param('grant_type') || '';
Condition50%1/2
$req->param('grant_type') || ''
l!l
40
MC/DC0%0/1
$req->param('grant_type') || ''
$req->param('grant_type')
Truth table50%1/2
A
A= $req->param('grant_type')
Aresult
11
00
1509  
1510 # Autorization Code grant
1511 4 ▶ if ( $grant_type eq 'authorization_code' ) {
Branch: 5 branches
BranchTrueFalseTotal
if ($grant_type eq 'authorization_code') { } 0 4 4
elsif ($grant_type eq 'refresh_token') { } 2 2 4
elsif ($grant_type eq 'password') { } 1 1 2
elsif ($grant_type eq 'client_credentials') { } 1 0 1
elsif ($grant_type eq 'urn:ietf:params:oauth:grant-type:token-exchange') { } 0 0 0
1512 0 return $self->_handleAuthorizationCodeGrant( $req, $rp );
1513 }
1514  
1515 # Refresh token
1516 elsif ( $grant_type eq 'refresh_token' ) {
1517 2 return $self->_handleRefreshTokenGrant( $req, $rp );
1518 }
1519  
1520 # Resource Owner Password Credenials
1521 elsif ( $grant_type eq 'password' ) {
1522 1 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAllowPasswordGrant"}) 0 1 1
1523 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAllowPasswordGrant} )
1524 {
1525 0 $self->logger->warn(
1526 "Access to grant_type=password, is not allowed for RP $rp");
1527 0 return $self->sendOIDCError( $req, 'unauthorized_client', 400 );
1528 }
1529 1 return $self->_handlePasswordGrant( $req, $rp );
1530 }
1531  
1532 # Resource Owner Password Credenials
1533 elsif ( $grant_type eq 'client_credentials' ) {
1534 1 ▶ unless ( $self->rpOptions->{$rp}
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAllowClientCredentialsGrant"}) 0 1 1
1535 ->{oidcRPMetaDataOptionsAllowClientCredentialsGrant} )
1536 {
1537 0 $self->logger->warn(
1538 "Access to Client Credentials grant is not allowed for RP $rp");
1539 0 return $self->sendOIDCError( $req, 'unauthorized_client', 400 );
1540 }
1541 1 return $self->_handleClientCredentialsGrant( $req, $rp );
1542 }
1543  
1544 # OAuth2.0 Token Exchange
1545 elsif ( $grant_type eq 'urn:ietf:params:oauth:grant-type:token-exchange' ) {
1546 0 return $self->_handleTokenExchange( $req, $rp );
1547 }
1548  
1549 # Unknown or unspecified grant type
1550 else {
1551 0 ▶ $self->userLogger->error(
Branch: 1 branch
BranchTrueFalseTotal
$grant_type ? : 0 0 0
1552 $grant_type
1553 ? "Unknown grant type: $grant_type"
1554 : "Missing grant_type parameter"
1555 );
1556 0 return $self->sendOIDCError( $req, 'unsupported_grant_type', 400 );
1557 }
1558  
1559 }
1560  
1561 # RFC6749 section 4.4
1562 sub _handleClientCredentialsGrant {
1563 1 ▶ my ( $self, $req, $rp ) = @_;
Subroutine _handleClientCredentialsGrant: called CC=12 SCAR=33.7
1564  
1565 # The client credentials grant type MUST only be used by confidential
1566 # clients.
1567 1 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsPublic} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsPublic"}) 0 1 1
1568 0 $self->logger->error(
1569 "Client Credentials grant cannot be used on public clients");
1570 0 return $self->sendOIDCError( $req, 'unauthorized_client', 400 );
1571 }
1572 1 my $client_id = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
1573  
1574 # Populate minimal session info
1575 1 ▶ my $req_scope = $req->param('scope') || '';
Condition50%1/2
$req->param('scope') || ''
l!l
10
MC/DC0%0/1
$req->param('scope') || ''
$req->param('scope')
Truth table50%1/2
A
A= $req->param('scope')
Aresult
11
00
1576 1 my $scope = $self->getScope( $req, $rp, $req_scope );
1577  
1578 1 ▶ unless ($scope) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($scope) 0 1 1
1579 0 $self->userLogger->warn( 'Client '
1580 . $client_id
1581 . " was not granted any requested scopes ($req_scope) for $rp" );
1582 0 return $self->sendOIDCError( $req, 'invalid_scope', 400 );
1583 }
1584  
1585 my $infos = {
1586 1 $self->conf->{whatToTrace} => $client_id,
1587 _clientId => $client_id,
1588 _clientConfKey => $rp,
1589 _scope => $scope,
1590 _utime => time,
1591 };
1592  
1593 1 my $h = $self->p->processHook( $req, 'oidcGotClientCredentialsGrant',
1594 $infos, $rp );
1595 1 ▶ return $self->sendOIDCError( $req, 'server_error', 500 ) if ( $h != PE_OK );
Branch: 1 branch
BranchTrueFalseTotal
if $h != 0 0 1 1
1596  
1597 # Update scope in case hook changed it
1598 1 $scope = $infos->{_scope};
1599  
1600 # Run rule against session info
1601 1 ▶ if ( my $rule = $self->rpRules->{$rp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rule = $self->rpRules->{$rp}) 0 1 1
1602 my $ruleVariables =
1603 0 ▶ { %{ $infos || {} }, _oidc_grant_type => "clientcredentials", };
Branch: 1 branch
BranchTrueFalseTotal
$infos or {} 0 0 0
1604 0 ▶ unless ( $rule->( $req, $ruleVariables ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$rule($req, $ruleVariables)) 0 0 0
1605 0 $self->userLogger->warn(
1606 "Relying party $rp did not validate the provided "
1607 . "Access Rule during Client Credentials Grant" );
1608 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
1609 }
1610 }
1611  
1612 # Create access token
1613 1 my $session = $self->p->getApacheSession( undef, info => $infos );
1614 1 ▶ unless ($session) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($session) 0 1 1
1615 0 $self->logger->error("Unable to create session");
1616 0 return $self->sendOIDCError( $req, 'server_error', 500 );
1617 }
1618  
1619 1 my $access_token = $self->newAccessToken(
1620 $req, $rp, $scope,
1621 $session->data,
1622 {
1623 scope => $scope,
1624 rp => $rp,
1625 user_session_id => $session->id,
1626 grant_type => "clientcredentials",
1627 }
1628 );
1629 1 ▶ unless ($access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 1 1
1630 0 $self->userLogger->error("Unable to create Access Token");
1631 0 return $self->sendOIDCError( $req,
1632 'Unable to create Access Token', 500 );
1633 }
1634  
1635 my $expires_in =
1636 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenExpiration}
1637 1 ▶ || $self->conf->{oidcServiceAccessTokenExpiration};
Condition33%1/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
l!l&&r!l&&!r
100
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} $self->conf->{'oidcServiceAccessTokenExpiration'}
Truth table33%1/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'}B= $self->conf->{'oidcServiceAccessTokenExpiration'}
ABresult
1X1
011
000
1638  
1639 1 ▶ my $token_response = {
Branch: 1 branch
BranchTrueFalseTotal
$req_scope ne $scope ? : 0 1 1
1640 access_token => "$access_token",
1641 token_type => 'Bearer',
1642 expires_in => $expires_in + 0,
1643 ( ( $req_scope ne $scope ) ? ( scope => "$scope" ) : () ),
1644 };
1645  
1646 1 $self->logger->debug("Send token response");
1647 1 return $self->p->sendJSONresponse( $req, $token_response );
1648 }
1649  
1650 # OAuth 2.0 Token Exchange - RFC8693
1651 sub _handleTokenExchange {
1652 0 ▶ my ( $self, $req, $rp ) = @_;
Subroutine _handleTokenExchange: not called CC=2 SCAR=17.9
1653  
1654 0 my $h = $self->p->processHook( $req, 'oidcGotTokenExchange', $rp );
1655 0 ▶ if ( $h == PE_SENDRESPONSE ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h == -4) 0 0 0
1656 0 return $req->response;
1657 }
1658  
1659 0 $self->logger->error("Unsupported OAuth 2.0 Token Exchange request");
1660 0 return $self->sendOIDCError( $req, 'invalid_request', 400 );
1661 }
1662  
1663 sub _handlePasswordGrant {
1664 1 ▶ my ( $self, $req, $rp ) = @_;
Subroutine _handlePasswordGrant: called CC=26 SCAR=60.5
1665 1 my $client_id = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
1666 1 ▶ my $req_scope = $req->param('scope') || '';
Condition50%1/2
$req->param('scope') || ''
l!l
10
MC/DC0%0/1
$req->param('scope') || ''
$req->param('scope')
Truth table50%1/2
A
A= $req->param('scope')
Aresult
11
00
1667 1 my $username = $req->param('username');
1668 1 my $password = $req->param('password');
1669  
1670 1 ▶ unless ( $username and $password ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($username and $password) 0 1 1
Condition33%1/3
$username and $password
!ll&&!rl&&r
001
MC/DC0%0/2
$username and $password
$username $password
Truth table33%1/3
A and B
A= $usernameB= $password
ABresult
0X0
100
111
1671 0 $self->logger->error("Missing username or password");
1672 0 return $self->sendOIDCError( $req, 'invalid_request', 400 );
1673 }
1674  
1675 ####
1676 # Authenticate user by running through the regular login process
1677 # minus the buildCookie step
1678 1 $req->parameters->{user} = ($username);
1679 1 $req->parameters->{password} = $password;
1680 1 $req->data->{skipToken} = 1;
1681  
1682 # This makes Auth::Choice use authChoiceAuthBasic if defined
1683 1 $req->data->{_pwdCheck} = 1;
1684  
1685 $req->steps( [
1686 1 @{ $self->p->beforeAuth },
1687 $self->p->authProcess,
1688 1 @{ $self->p->betweenAuthAndData },
1689 $self->p->sessionData,
1690 1 @{ $self->p->afterData },
1691 'storeHistory',
1692 1 @{ $self->p->endAuth },
1693 ]
1694 );
1695 1 my $result = $self->p->process($req);
1696  
1697 0 ▶ if ( ( $result == PE_FIRSTACCESS )
Branch: 1 branch
BranchTrueFalseTotal
if ($result == 9 and $self->conf->{"authentication"} eq "Choice") 0 0 0
Condition0%0/3
$result == 9 and $self->conf->{"authentication"} eq "Choice"
!ll&&!rl&&r
000
MC/DC0%0/2
$result == 9 and $self->conf->{"authentication"} eq "Choice"
$result == 9 $self->conf->{"authentication"} eq "Choice"
Truth table0%0/3
A and B
A= $result == 9B= $self->conf->{"authentication"} eq "Choice"
ABresult
0X0
100
111
1698 and ( $self->conf->{authentication} eq "Choice" ) )
1699 {
1700 0 $self->logger->warn(
1701 "Choice module did not know which module to choose. "
1702 . "You should define authChoiceAuthBasic or specify desired module in the URL"
1703 );
1704 }
1705  
1706 0 ▶ $self->logger->debug( "Credentials check returned "
Branch: 1 branch
BranchTrueFalseTotal
if $result 0 0 0
1707 . $self->p->_formatProcessResult($result) )
1708 if $result;
1709  
1710 ## Make sure we returned successfuly from the process AND we were able to create a session
1711 0 ▶ return $self->sendOIDCError( $req, 'invalid_grant', 400 )
Branch: 1 branch
BranchTrueFalseTotal
unless $result == 0 and $req->id and $req->user 0 0 0
Condition0%0/6
$result == 0 and $req->id and $req->user
!ll&&!rl&&r
000
$result == 0 and $req->id
!ll&&!rl&&r
000
MC/DC0%0/3
$result == 0 and $req->id and $req->user
$result == 0 $req->id $req->user
Truth table0%0/4
A and B and C
A= $result == 0B= $req->idC= $req->user
ABCresult
0XX0
10X0
1100
1111
1712 unless ( $result == PE_OK and $req->id and $req->user );
1713  
1714 ## Make sure the current user is allowed to use this RP
1715 0 ▶ if ( my $rule = $self->rpRules->{$rp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rule = $self->rpRules->{$rp}) 0 0 0
1716 my $ruleVariables =
1717 0 ▶ { %{ $req->sessionInfo || {} }, _oidc_grant_type => "password", };
Branch: 1 branch
BranchTrueFalseTotal
$req->sessionInfo or {} 0 0 0
1718 0 ▶ unless ( $rule->( $req, $ruleVariables ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$rule($req, $ruleVariables)) 0 0 0
1719 $self->userLogger->warn( 'User '
1720 . $req->sessionInfo->{ $self->conf->{whatToTrace} }
1721 0 . " is not authorized to access to $rp" );
1722 0 $self->p->deleteSession($req);
1723 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
1724 }
1725 }
1726  
1727 0 my $user = $req->sessionInfo->{ $self->conf->{whatToTrace} };
1728  
1729 # Resolve scopes
1730 0 my $scope = $self->getScope( $req, $rp, $req_scope );
1731 0 ▶ unless ($scope) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($scope) 0 0 0
1732 0 $self->userLogger->warn( "User $user was not granted"
1733 . " any requested scopes ($req_scope) for $rp" );
1734 0 return $self->sendOIDCError( $req, 'invalid_scope', 400 );
1735 }
1736  
1737 0 my $user_id = $self->getUserIDForRP( $req, $rp, $req->sessionInfo );
1738  
1739 0 ▶ $self->logger->debug(
Branch: 1 branch
BranchTrueFalseTotal
$user_id ? : 0 0 0
1740 $user_id
1741 ? "Found corresponding user: $user_id"
1742 : 'Corresponding user not found'
1743 );
1744  
1745 # Generate access_token
1746 0 my $access_token = $self->newAccessToken(
1747 $req, $rp, $scope,
1748 $req->sessionInfo,
1749 {
1750 grant_type => "password",
1751 user_session_id => $req->id,
1752 }
1753 );
1754  
1755 0 ▶ unless ($access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 0 0
1756 0 $self->userLogger->error("Unable to create Access Token");
1757 0 return $self->sendOIDCError( $req, 'server_error', 500 );
1758 }
1759  
1760 0 $self->logger->debug("Generated access token: $access_token");
1761  
1762 # Generate refresh_token
1763 0 my $refresh_token = undef;
1764  
1765 0 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsRefreshToken} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsRefreshToken"}) 0 0 0
1766 my $refreshTokenSession = $self->_generateRefreshToken(
1767 $req, $rp,
1768 {
1769 scope => $scope,
1770 client_id => $client_id,
1771 user_session_id => $req->id,
1772 grant_type => "password",
1773 0 $self->conf->{whatToTrace} => $user,
1774 },
1775 0,
1776 );
1777  
1778 0 ▶ unless ($refreshTokenSession) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($refreshTokenSession) 0 0 0
1779 0 $self->userLogger->error(
1780 "Unable to create OIDC session for refresh_token");
1781 0 return $self->sendOIDCError( $req,
1782 'Could not create refresh token session', 500 );
1783 }
1784  
1785 0 $refresh_token = $refreshTokenSession->id;
1786  
1787 0 $self->logger->debug("Generated refresh token: $refresh_token");
1788 }
1789  
1790 # Generate ID token
1791 0 my $id_token = undef;
1792 0 ▶ if ( $self->_hasScope( "openid", $scope ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_hasScope("openid", $scope)) 0 0 0
1793  
1794 # Compute hash to store in at_hash
1795 my $alg =
1796 0 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIDTokenSignAlg};
1797 0 my ($hash_level) = ( $alg =~ /(?:\w{2})(\d{3})/ );
1798 0 ▶ my $at_hash = $self->createHash( $access_token, $hash_level )
Branch: 1 branch
BranchTrueFalseTotal
if $hash_level 0 0 0
1799 if $hash_level;
1800  
1801 0 ▶ $id_token =
Branch: 1 branch
BranchTrueFalseTotal
$at_hash ? : 0 0 0
1802 $self->_generateIDToken( $req, $rp, $scope, $req->sessionInfo, 0,
1803 { ( $at_hash ? ( at_hash => $at_hash ) : () ), } );
1804  
1805 0 ▶ unless ($id_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token) 0 0 0
1806 0 $self->logger->error(
1807 "Failed to generate ID Token for service: $client_id");
1808 0 return $self->sendOIDCError( $req, 'server_error', 500 );
1809 }
1810 }
1811  
1812 # Send token response
1813 my $expires_in =
1814 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenExpiration}
1815 0 ▶ || $self->conf->{oidcServiceAccessTokenExpiration};
Condition0%0/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} $self->conf->{'oidcServiceAccessTokenExpiration'}
Truth table0%0/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'}B= $self->conf->{'oidcServiceAccessTokenExpiration'}
ABresult
1X1
011
000
1816  
1817 0 ▶ my $token_response = {
Branch: 3 branches
BranchTrueFalseTotal
$scope ne $req_scope ? : 0 0 0
$refresh_token ? : 0 0 0
$id_token ? : 0 0 0
1818 access_token => "$access_token",
1819 token_type => 'Bearer',
1820 expires_in => $expires_in + 0,
1821 ( ( $scope ne $req_scope ) ? ( scope => "$scope" ) : () ),
1822 ( $refresh_token ? ( refresh_token => "$refresh_token" ) : () ),
1823 ( $id_token ? ( id_token => "$id_token" ) : () ),
1824 };
1825  
1826 0 $self->logger->debug("Send token response");
1827  
1828 0 return $self->p->sendJSONresponse( $req, $token_response );
1829 }
1830  
1831 sub _handleAuthorizationCodeGrant {
1832 0 ▶ my ( $self, $req, $rp ) = @_;
Subroutine _handleAuthorizationCodeGrant: not called CC=25 SCAR=64.8
1833 0 my $client_id = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
1834 0 my $code = $req->param('code');
1835  
1836 0 ▶ unless ($code) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($code) 0 0 0
1837 0 $self->logger->error("No code found on token endpoint");
1838 0 return $self->sendOIDCError( $req, 'invalid_request', 400 );
1839 }
1840  
1841 0 my $codeSession = $self->getAuthorizationCode($code);
1842 0 ▶ unless ($codeSession) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($codeSession) 0 0 0
1843 0 $self->logger->warn("Unable to find OIDC session $code");
1844 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
1845 }
1846  
1847 0 $codeSession->remove();
1848  
1849 # Check PKCE
1850 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->validatePKCEChallenge($req->param("code_verifier"), $codeSession->data->{"code_challenge"}, $codeSession->data->{"code_challenge_method"})) 0 0 0
1851 $self->validatePKCEChallenge(
1852 $req->param('code_verifier'),
1853 $codeSession->data->{'code_challenge'},
1854 $codeSession->data->{'code_challenge_method'}
1855 )
1856 )
1857 {
1858 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
1859 }
1860  
1861 # Check we have the same client_id value
1862 0 ▶ unless ( $client_id eq $codeSession->data->{client_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client_id eq $codeSession->data->{"client_id"}) 0 0 0
1863 $self->userLogger->error( "Provided client_id does not match "
1864 0 . $codeSession->data->{client_id} );
1865 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
1866 }
1867  
1868 # Check we have the same redirect_uri value
1869 0 ▶ unless ( $req->param("redirect_uri") eq $codeSession->data->{redirect_uri} )
Branch: 1 branch
BranchTrueFalseTotal
unless ($req->param("redirect_uri") eq $codeSession->data->{"redirect_uri"}) 0 0 0
1870 {
1871 $self->userLogger->error( "Provided redirect_uri does not match: "
1872 0 . $codeSession->data->{redirect_uri} . ' != '
1873 . $req->param("redirect_uri") );
1874 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
1875 }
1876  
1877 # Get user identifier
1878 my $apacheSession =
1879 0 $self->p->getApacheSession( $codeSession->data->{user_session_id} );
1880  
1881 0 ▶ unless ($apacheSession) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($apacheSession) 0 0 0
1882 0 $self->userLogger->warn("Unable to find user session");
1883 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
1884 }
1885  
1886 0 my $user_id = $self->getUserIDForRP( $req, $rp, $apacheSession->data );
1887  
1888 0 $self->logger->debug("Found corresponding user: $user_id");
1889  
1890 0 my $req_scope = $codeSession->{data}->{req_scope};
1891 0 my $scope = $codeSession->{data}->{scope};
1892  
1893 # Generate access_token
1894 0 my $access_token = $self->newAccessToken(
1895 $req, $rp, $scope,
1896 $apacheSession->data,
1897 {
1898 grant_type => "authorizationcode",
1899 user_session_id => $apacheSession->id,
1900 }
1901 );
1902  
1903 0 ▶ unless ($access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 0 0
1904 0 $self->userLogger->error("Unable to create Access Token");
1905 0 return $self->sendOIDCError( $req, 'server_error', 500 );
1906 }
1907  
1908 0 $self->logger->debug("Generated access token: $access_token");
1909  
1910 # Generate refresh_token
1911 0 my $refresh_token = undef;
1912  
1913 0 my $sid = $self->getSidFromSession( $rp, $apacheSession->data );
1914 0 my $user = $apacheSession->data->{ $self->conf->{whatToTrace} };
1915  
1916 # For offline access, the refresh token isn't tied to the session ID
1917 0 ▶ if ( $codeSession->{data}->{offline} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($codeSession->{'data'}{'offline'}) { } 0 0 0
elsif ($self->rpOptions->{$rp}{'oidcRPMetaDataOptionsRefreshToken'}) { } 0 0 0
1918  
1919 # We need to remove _sessionType, _sessionid , _utime and _lastSeen
1920 # from the session data before storing session data in the refresh
1921 # token
1922 0 my %userInfo;
1923 0 for my $userKey (
1924 grep !/^(_session|_utime$|_lastSeen$)/,
1925 0 keys %{ $apacheSession->data }
1926 )
1927 {
1928 0 $userInfo{$userKey} = $apacheSession->data->{$userKey};
1929 }
1930 my $refreshTokenSession = $self->_generateRefreshToken(
1931 $req, $rp,
1932 {
1933 %userInfo,
1934 redirect_uri => $codeSession->data->{redirect_uri},
1935 scope => $scope,
1936 client_id => $client_id,
1937 _session_uid => $user,
1938 auth_time => $apacheSession->data->{_lastAuthnUTime},
1939 0 grant_type => "authorizationcode",
1940 _oidc_sid => $sid,
1941 },
1942 1,
1943 );
1944  
1945 0 ▶ unless ($refreshTokenSession) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($refreshTokenSession) 0 0 0
1946 0 $self->userLogger->error(
1947 "Unable to create OIDC session for refresh_token");
1948 0 return $self->sendOIDCError( $req, 'server_error', 500 );
1949 }
1950  
1951 0 $refresh_token = $refreshTokenSession->id;
1952  
1953 0 $self->logger->debug("Generated offline refresh token: $refresh_token");
1954 }
1955  
1956 # For online access, if configured
1957 elsif ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsRefreshToken} ) {
1958 my $refreshTokenSession = $self->_generateRefreshToken(
1959 $req,
1960  
1961 $rp,
1962 {
1963 redirect_uri => $codeSession->data->{redirect_uri},
1964 scope => $scope,
1965 client_id => $client_id,
1966 _session_uid =>
1967 $apacheSession->data->{ $self->conf->{whatToTrace} },
1968 user_session_id => $codeSession->data->{user_session_id},
1969 grant_type => "authorizationcode",
1970 _oidc_sid => $sid,
1971 0 $self->conf->{whatToTrace} => $user,
1972 },
1973 0,
1974 );
1975  
1976 0 ▶ unless ($refreshTokenSession) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($refreshTokenSession) 0 0 0
1977 0 $self->userLogger->error(
1978 "Unable to create OIDC session for refresh_token");
1979 0 return $self->sendOIDCError( $req, 'server_error', 500 );
1980 }
1981  
1982 0 $refresh_token = $refreshTokenSession->id;
1983  
1984 0 $self->logger->debug("Generated online refresh token: $refresh_token");
1985 }
1986  
1987 # Compute hash to store in at_hash
1988 0 my $alg = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIDTokenSignAlg};
1989 0 my ($hash_level) = ( $alg =~ /(?:\w{2})(\d{3})/ );
1990 0 ▶ my $at_hash = $self->createHash( $access_token, $hash_level )
Branch: 1 branch
BranchTrueFalseTotal
if $hash_level 0 0 0
1991 if $hash_level;
1992  
1993 # Create ID Token
1994 0 my $nonce = $codeSession->data->{nonce};
1995 0 ▶ my $id_token = $self->_generateIDToken(
Branch: 2 branches
BranchTrueFalseTotal
$nonce ? : 0 0 0
$at_hash ? : 0 0 0
1996 $req, $rp, $scope,
1997 $apacheSession->data,
1998 0,
1999 {
2000 ( $nonce ? ( nonce => $nonce ) : () ),
2001 ( $at_hash ? ( at_hash => $at_hash ) : () ),
2002 },
2003 );
2004  
2005 0 ▶ unless ($id_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token) 0 0 0
2006 0 $self->logger->error(
2007 "Failed to generate ID Token for service: $client_id");
2008 0 return $self->sendOIDCError( $req, 'server_error', 500 );
2009 }
2010  
2011 0 $self->logger->debug("Generated id token: $id_token");
2012  
2013 # Send token response
2014 my $expires_in =
2015 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenExpiration}
2016 0 ▶ || $self->conf->{oidcServiceAccessTokenExpiration};
Condition0%0/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} $self->conf->{'oidcServiceAccessTokenExpiration'}
Truth table0%0/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'}B= $self->conf->{'oidcServiceAccessTokenExpiration'}
ABresult
1X1
011
000
2017  
2018 0 ▶ my $token_response = {
Branch: 2 branches
BranchTrueFalseTotal
$refresh_token ? : 0 0 0
$req_scope ne $scope ? : 0 0 0
2019 access_token => "$access_token",
2020 token_type => 'Bearer',
2021 expires_in => $expires_in + 0,
2022 id_token => "$id_token",
2023 ( $refresh_token ? ( refresh_token => "$refresh_token" ) : () ),
2024 ( ( $req_scope ne $scope ) ? ( scope => "$scope" ) : () ),
2025 };
2026  
2027 0 $self->p->processHook( $req, 'oidcGenerateTokenResponse', $rp,
2028 $token_response, $codeSession->data, $apacheSession->data );
2029  
2030 0 my %update;
2031  
2032 # This is kept for compatibility in case some plugins use it
2033 0 ▶ my $cRP = $apacheSession->data->{_oidcConnectedRP} || '';
Condition0%0/2
$apacheSession->data->{'_oidcConnectedRP'} || ''
l!l
00
MC/DC0%0/1
$apacheSession->data->{'_oidcConnectedRP'} || ''
$apacheSession->data->{'_oidcConnectedRP'}
Truth table0%0/2
A
A= $apacheSession->data->{'_oidcConnectedRP'}
Aresult
11
00
2034 0 ▶ unless ( grep { $_ eq $rp } split( ",", $cRP ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $rp;} split(/,/, $cRP, 0)) 0 0 0
2035 0 %update = ( %update, _oidcConnectedRP => "$rp,$cRP" );
2036 }
2037  
2038 0 ▶ my $cRPID = $apacheSession->data->{_oidcConnectedRPIDs} || '';
Condition0%0/2
$apacheSession->data->{'_oidcConnectedRPIDs'} || ''
l!l
00
MC/DC0%0/1
$apacheSession->data->{'_oidcConnectedRPIDs'} || ''
$apacheSession->data->{'_oidcConnectedRPIDs'}
Truth table0%0/2
A
A= $apacheSession->data->{'_oidcConnectedRPIDs'}
Aresult
11
00
2039 0 ▶ unless ( grep { $_ eq $client_id } split( ",", $cRPID ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $client_id;} split(/,/, $cRPID, 0)) 0 0 0
2040 0 %update = ( %update, _oidcConnectedRPIDs => "$client_id,$cRPID" );
2041 }
2042  
2043 0 ▶ if (%update) {
Branch: 1 branch
BranchTrueFalseTotal
if (%update) 0 0 0
2044 0 $self->p->updateSession( $req, \%update, $apacheSession->id );
2045 }
2046  
2047 0 $self->logger->debug("Send token response");
2048  
2049 0 return $self->p->sendJSONresponse( $req, $token_response );
2050 }
2051  
2052 sub _handleRefreshTokenGrant {
2053 2 ▶ my ( $self, $req, $rp, $refresh_token, $client_id ) = @_;
Subroutine _handleRefreshTokenGrant: called CC=26 SCAR=63.4
2054 2 ▶ $client_id ||= $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
Condition33%1/3
$client_id ||= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientID"}
l!l&&r!l&&!r
020
MC/DC0%0/2
$client_id ||= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientID"}
$client_id $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientID"}
Truth table33%1/3
A ||= B
A= $client_idB= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientID"}
ABresult
1X1
011
000
2055 2 ▶ $refresh_token ||= $req->param('refresh_token');
Condition33%1/3
$refresh_token ||= $req->param("refresh_token")
l!l&&r!l&&!r
002
MC/DC0%0/2
$refresh_token ||= $req->param("refresh_token")
$refresh_token $req->param("refresh_token")
Truth table33%1/3
A ||= B
A= $refresh_tokenB= $req->param("refresh_token")
ABresult
1X1
011
000
2056  
2057 2 ▶ unless ($refresh_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($refresh_token) 2 0 2
2058 2 $self->logger->error("Missing refresh_token parameter");
2059 2 return $self->sendOIDCError( $req, 'invalid_request', 400 );
2060 }
2061  
2062 0 $self->logger->debug("OpenID Refresh Token: $refresh_token");
2063  
2064 0 my $refreshSession = $self->getRefreshToken($refresh_token);
2065  
2066 0 ▶ unless ($refreshSession) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($refreshSession) 0 0 0
2067 0 $self->logger->warn("Unable to find OIDC session $refresh_token");
2068 0 return $self->sendOIDCError( $req, 'invalid_request', 400 );
2069 }
2070  
2071 $refreshSession =
2072 0 $self->_rotateRefreshSession( $req, $rp, $refreshSession );
2073  
2074 # Check we have the same client_id value
2075 0 ▶ unless ( $client_id eq $refreshSession->data->{client_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client_id eq $refreshSession->data->{"client_id"}) 0 0 0
2076 $self->userLogger->error( "Provided client_id does not match "
2077 0 . $refreshSession->data->{client_id} );
2078 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
2079 }
2080 0 ▶ if ( my $delay =
Branch: 1 branch
BranchTrueFalseTotal
if (my $delay = $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsRtActivity"}) 0 0 0
2081 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsRtActivity} )
2082 {
2083 0 my $user = $refreshSession->data->{_whatToTrace};
2084 0 ▶ if ( defined $refreshSession->data->{_oidcRtUpdate} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $refreshSession->data->{'_oidcRtUpdate'}) { } 0 0 0
2085 0 ▶ if ( ( $refreshSession->data->{_oidcRtUpdate} + $delay ) < time ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($refreshSession->data->{"_oidcRtUpdate"} + $delay < &CORE::GLOBAL::time()) 0 0 0
2086 0 $self->auditLog(
2087 $req,
2088 code => 'ISSUER_OIDC_INACTIVE_REFRESH_TOKEN',
2089 rp => $rp,
2090 message =>
2091 "User $user tried to use an inactive refresh_token",
2092 user => $user,
2093 );
2094 0 $refreshSession->remove;
2095 0 return $self->sendOIDCError( $req, 'invalid_grant', 401 );
2096 }
2097 }
2098 else {
2099 0 $self->logger->info(
2100 "$user use a refresh_token without previous _oidcRtUpdate ($refresh_token), considered as active"
2101 );
2102 }
2103 }
2104  
2105 0 my $access_token;
2106 my $userData;
2107  
2108 # If this refresh token is tied to a SSO session
2109 0 ▶ if ( $refreshSession->data->{user_session_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($refreshSession->data->{'user_session_id'}) { } 0 0 0
2110 0 my $user_session_id = $refreshSession->data->{user_session_id};
2111 0 $userData =
2112 $self->p->HANDLER->retrieveSession( $req, $user_session_id );
2113  
2114 0 ▶ unless ($userData) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($userData) 0 0 0
2115 0 $self->logger->error(
2116 "Unable to find user session tied to Refresh Token");
2117 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
2118 }
2119  
2120 0 my $h = $self->p->processHook( $req, 'oidcGotOnlineRefresh', $rp,
2121 $refreshSession->data, $userData );
2122 0 ▶ if ( $h != PE_OK ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h != 0) 0 0 0
2123 0 return $self->sendOIDCError( $req, 'server_error', 500 );
2124 }
2125  
2126 # Generate access_token
2127 $access_token = $self->newAccessToken(
2128 $req, $rp,
2129 $refreshSession->data->{scope},
2130 $userData,
2131 {
2132 user_session_id => $user_session_id,
2133 grant_type => $refreshSession->data->{grant_type},
2134 }
2135 0 );
2136  
2137 0 ▶ unless ($access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 0 0
2138 0 $self->userLogger->error("Unable to create Access Token");
2139 0 return $self->sendOIDCError( $req, 'server_error', 500 );
2140 }
2141  
2142 0 $self->logger->debug("Generated access token: $access_token");
2143 }
2144  
2145 # Else, we are in an offline session
2146 else {
2147  
2148 0 ▶ unless ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAllowOffline} )
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAllowOffline"}) 0 0 0
2149 {
2150 0 $self->logger->error(
2151 'Got a offline refresh_token for an application no more allowed'
2152 );
2153 0 return $self->sendOIDCError( $req, 'invalid_grant', 400 );
2154 }
2155  
2156 # Lookup attributes and macros for user
2157 0 ▶ $self->getAttributesForUser( $req, $refreshSession )
Branch: 1 branch
BranchTrueFalseTotal
$self->getAttributesForUser($req, $refreshSession) or return $self->sendOIDCError($req, "invalid_grant", 400) 0 0 0
2158 or return $self->sendOIDCError( $req, 'invalid_grant', 400 );
2159  
2160 # Cleanup sessionInfo
2161 0 delete $req->sessionInfo->{_utime};
2162 0 delete $req->sessionInfo->{_startTime};
2163 0 delete $req->sessionInfo->{_lastSeen};
2164  
2165 # Update refresh session
2166 0 $self->updateRefreshToken( $refreshSession->id, $req->sessionInfo );
2167 0 $userData = $refreshSession->data;
2168 0 for ( keys %{ $req->sessionInfo } ) {
2169 0 $refreshSession->data->{$_} = $req->sessionInfo->{$_};
2170 }
2171  
2172 0 my $h = $self->p->processHook( $req, 'oidcGotOfflineRefresh', $rp,
2173 $refreshSession->data );
2174 0 ▶ if ( $h != PE_OK ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h != 0) 0 0 0
2175 0 return $self->sendOIDCError( $req, 'server_error', 500 );
2176 }
2177  
2178 # Generate access_token
2179 $access_token = $self->newAccessToken(
2180 $req, $rp,
2181 $refreshSession->data->{scope},
2182 $refreshSession->data,
2183 {
2184 offline_session_id => $refreshSession->id,
2185 grant_type => $refreshSession->data->{grant_type},
2186 }
2187 0 );
2188  
2189 0 ▶ unless ($access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 0 0
2190 0 $self->userLogger->error("Unable to create Access Token");
2191 0 return $self->sendOIDCError( $req, 'server_error', 500 );
2192 }
2193  
2194 0 $self->logger->debug("Generated access token: $access_token");
2195 }
2196  
2197 # Compute hash to store in at_hash
2198 0 my $alg = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIDTokenSignAlg};
2199 0 my ($hash_level) = ( $alg =~ /(?:\w{2})(\d{3})/ );
2200 0 ▶ my $at_hash = $self->createHash( $access_token, $hash_level )
Branch: 1 branch
BranchTrueFalseTotal
if $hash_level 0 0 0
2201 if $hash_level;
2202  
2203 # Create ID Token
2204 0 my $id_token = undef;
2205 0 ▶ if ( $self->_hasScope( 'openid', $refreshSession->data->{scope} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_hasScope("openid", $refreshSession->data->{"scope"})) 0 0 0
2206 0 my $nonce = $refreshSession->data->{nonce};
2207 $id_token = $self->_generateIDToken(
2208 $req, $rp,
2209 $refreshSession->data->{scope},
2210 0 ▶ $userData,
Branch: 2 branches
BranchTrueFalseTotal
$nonce ? : 0 0 0
$at_hash ? : 0 0 0
2211 0,
2212 {
2213 ( $nonce ? ( nonce => $nonce ) : () ),
2214 ( $at_hash ? ( at_hash => $at_hash ) : () ),
2215 }
2216 );
2217  
2218 0 ▶ unless ($id_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token) 0 0 0
2219 0 $self->logger->error(
2220 "Failed to generate ID Token for service: $rp");
2221 0 return $self->sendOIDCError( $req, 'server_error', 500 );
2222 }
2223  
2224 0 $self->logger->debug("Generated id token: $id_token");
2225 }
2226  
2227 # Send token response
2228 my $expires_in =
2229 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenExpiration}
2230 0 ▶ || $self->conf->{oidcServiceAccessTokenExpiration};
Condition0%0/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} $self->conf->{'oidcServiceAccessTokenExpiration'}
Truth table0%0/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'}B= $self->conf->{'oidcServiceAccessTokenExpiration'}
ABresult
1X1
011
000
2231  
2232 0 my $need_to_update_refresh_token =
2233 ( $refresh_token ne $refreshSession->id );
2234  
2235 0 ▶ my $token_response = {
Branch: 2 branches
BranchTrueFalseTotal
$need_to_update_refresh_token ? : 0 0 0
$id_token ? : 0 0 0
2236 access_token => "$access_token",
2237 token_type => 'Bearer',
2238 expires_in => $expires_in + 0,
2239 (
2240 $need_to_update_refresh_token
2241 ? ( refresh_token => $refreshSession->id )
2242 : ()
2243 ),
2244 ( $id_token ? ( id_token => "$id_token" ) : () ),
2245 };
2246  
2247 0 $self->logger->debug("Send token response");
2248  
2249 0 return $self->p->sendJSONresponse( $req, $token_response );
2250 }
2251  
2252 sub _rotateRefreshSession {
2253 0 ▶ my ( $self, $req, $rp, $refreshSession ) = @_;
Subroutine _rotateRefreshSession: not called CC=4 SCAR=30.0
2254  
2255 0 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsRefreshTokenRotation} )
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsRefreshTokenRotation"}) 0 0 0
2256 {
2257 0 $self->logger->debug("Creating new refresh token for $rp");
2258  
2259 0 my $newRefreshSession =
2260 $self->_generateRefreshToken( $req, $rp, $refreshSession->data );
2261  
2262 0 ▶ if ($newRefreshSession) {
Branch: 1 branch
BranchTrueFalseTotal
if ($newRefreshSession) { } 0 0 0
2263 0 $self->logger->debug(
2264 "Generated new refresh token: " . $newRefreshSession->id );
2265  
2266 0 my $old_refresh_token = $refreshSession->id;
2267 0 ▶ if ( $refreshSession->remove ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($refreshSession->remove) { } 0 0 0
2268 0 $self->logger->debug(
2269 "Removed old refresh token: $old_refresh_token");
2270 }
2271 else {
2272 0 $self->logger->error(
2273 "Failed to remove old refresh token $old_refresh_token: "
2274 . $refreshSession->error );
2275 }
2276  
2277 0 return $newRefreshSession;
2278  
2279 }
2280 else {
2281 0 $self->logger->error(
2282 "Unable to create OIDC session for refresh_token");
2283 0 return $refreshSession;
2284 }
2285 }
2286 0 return $refreshSession;
2287 }
2288  
2289 sub unauthUserInfo {
2290 0 ▶ my ( $self, $req ) = @_;
Subroutine unauthUserInfo: not called CC=1 SCAR=6.9
Pod undocumented
2291 0 return $self->userInfo( $req, 1 );
2292 }
2293  
2294 # Handle userinfo endpoint
2295 sub userInfo {
2296 0 ▶ my ( $self, $req, $setUser ) = @_;
Subroutine userInfo: not called CC=11 SCAR=48.8
Pod undocumented
2297 0 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 0 0
2298 0 $self->logger->debug("URL detected as an OpenID Connect USERINFO URL");
2299  
2300 0 my ( $access_token, $authMethod ) = $self->getEndPointAccessToken($req);
2301  
2302 0 ▶ unless ($access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 0 0
2303 0 $self->auditLog(
2304 $req,
2305 code => 'ISSUER_OIDC_USERINFO_FAILED',
2306 message => 'Missing access_token',
2307 );
2308 0 return $self->returnBearerError( 'invalid_request',
2309 "Access token not found in request", 401 );
2310 }
2311  
2312 0 $self->logger->debug("Received Access Token $access_token");
2313  
2314 0 my $accessTokenSession = $self->getAccessToken($access_token);
2315  
2316 0 ▶ unless ($accessTokenSession) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($accessTokenSession) 0 0 0
2317 0 $self->auditLog(
2318 $req,
2319 code => 'ISSUER_OIDC_USERINFO_FAILED',
2320 message => 'Invalid or expired access_token',
2321 );
2322 0 return $self->returnBearerError( 'invalid_request',
2323 'Invalid request', 401 );
2324 }
2325  
2326 # Get access token session data
2327 0 my $scope = $accessTokenSession->data->{scope};
2328 0 my $rp = $accessTokenSession->data->{rp};
2329 0 my $user_session_id = $accessTokenSession->data->{user_session_id};
2330  
2331 $self->p->HANDLER->set_user( $req,
2332 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID} )
2333 0 ▶ if $setUser;
Branch: 1 branch
BranchTrueFalseTotal
if $setUser 0 0 0
2334  
2335 0 ▶ if ( $self->rpOptions->{$rp}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsUserinfoRequireHeaderToken"} and $authMethod ne "header") 0 0 0
Condition0%0/3
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsUserinfoRequireHeaderToken"} and $authMethod ne "header"
!ll&&!rl&&r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsUserinfoRequireHeaderToken"} and $authMethod ne "header"
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsUserinfoRequireHeaderToken"} $authMethod ne "header"
Truth table0%0/3
A and B
A= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsUserinfoRequireHeaderToken"}B= $authMethod ne "header"
ABresult
0X0
100
111
2336 ->{oidcRPMetaDataOptionsUserinfoRequireHeaderToken}
2337 and $authMethod ne 'header' )
2338 {
2339 0 $self->auditLog(
2340 $req,
2341 code => 'ISSUER_OIDC_USERINFO_FAILED',
2342 message => 'Missing required authentication header',
2343 );
2344 0 return $self->returnBearerError( 'invalid_request',
2345 'Invalid request', 400 );
2346 }
2347  
2348 # Make sure $rp has been lazy loaded
2349 0 ▶ if ( $accessTokenSession->data->{client_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($accessTokenSession->data->{"client_id"}) 0 0 0
2350 0 $self->getRP( $accessTokenSession->data->{client_id} );
2351 }
2352  
2353 0 my $session =
2354 $self->_getSessionFromAccessTokenData( $accessTokenSession->data );
2355 0 ▶ unless ($session) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($session) 0 0 0
2356 0 $self->auditLog(
2357 $req,
2358 code => 'ISSUER_OIDC_USERINFO_FAILED',
2359 message => 'Unable to get session corresponding to access-token',
2360 );
2361 0 return $self->returnBearerError( 'invalid_request',
2362 'Invalid request', 401 );
2363 }
2364  
2365 0 my $userinfo_response =
2366 $self->buildUserInfoResponse( $req, $scope, $rp, $session );
2367 0 ▶ return $self->returnBearerError( 'invalid_request', 'Invalid request', 401 )
Branch: 1 branch
BranchTrueFalseTotal
unless $userinfo_response 0 0 0
2368 unless ($userinfo_response);
2369  
2370 0 my $attr_str = join( ',', sort( keys(%$userinfo_response) ) );
2371 0 my $sub = $userinfo_response->{sub};
2372 0 my $user = $session->data->{ $self->conf->{whatToTrace} };
2373 0 $self->auditLog(
2374 $req,
2375 code => "ISSUER_OIDC_USERINFO",
2376 rp => $rp,
2377 message => (
2378 "User information for $user transmitted to $rp as $sub with attributes $attr_str"
2379 ),
2380 user => $user,
2381 oidc_sub => $sub,
2382 attributes => $userinfo_response,
2383 );
2384  
2385 my $userinfo_sign_alg =
2386 0 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsUserInfoSignAlg};
2387  
2388 0 ▶ unless ($userinfo_sign_alg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($userinfo_sign_alg) { } 0 0 0
2389 0 my $debug_response = to_json($userinfo_response);
2390 0 utf8::downgrade($debug_response);
2391 0 $self->logger->debug( "Return UserInfo as JSON: " . $debug_response );
2392 0 return $self->p->sendJSONresponse( $req, $userinfo_response );
2393  
2394 }
2395 else {
2396 my $userinfo_jwt = $self->encryptToken(
2397 $rp,
2398 $self->createJWT( $userinfo_response, $userinfo_sign_alg, $rp ),
2399 $self->rpOptions->{$rp}
2400 ->{oidcRPMetaDataOptionsUserInfoEncKeyMgtAlg},
2401 $self->rpOptions->{$rp}
2402 ->{oidcRPMetaDataOptionsUserInfoEncContentEncAlg},
2403 0 );
2404 0 $self->logger->debug("Return UserInfo as JWT: $userinfo_jwt");
2405 return [
2406 0 200,
2407 [
2408 'Content-Type' => 'application/jwt',
2409 'Content-Length' => length($userinfo_jwt)
2410 ],
2411 [$userinfo_jwt]
2412 ];
2413 }
2414 }
2415  
2416 sub _getSessionFromAccessTokenData {
2417 0 ▶ my ( $self, $tokenData ) = @_;
Subroutine _getSessionFromAccessTokenData: not called CC=5 SCAR=34.0
2418 0 my $session;
2419  
2420 # If using a refreshed access token
2421 0 ▶ if ( $tokenData->{user_session_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tokenData->{'user_session_id'}) { } 0 0 0
2422  
2423 # Get user identifier
2424 0 $session = $self->p->getApacheSession( $tokenData->{user_session_id} );
2425 0 ▶ $self->logger->warn("Unable to find user session") unless ($session);
Branch: 1 branch
BranchTrueFalseTotal
unless $session 0 0 0
2426 }
2427 else {
2428 0 my $offline_session_id = $tokenData->{offline_session_id};
2429 0 ▶ if ($offline_session_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offline_session_id) 0 0 0
2430 0 $session = $self->getRefreshToken($offline_session_id);
2431 0 ▶ $self->logger->warn("Unable to find refresh session")
Branch: 1 branch
BranchTrueFalseTotal
unless $session 0 0 0
2432 unless ($session);
2433 }
2434 }
2435 0 return $session;
2436 }
2437  
2438 sub introspection {
2439 0 ▶ my ( $self, $req ) = @_;
Subroutine introspection: not called CC=12 SCAR=50.5
Pod undocumented
2440 0 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 0 0
2441 0 $self->logger->debug("URL detected as an Oauth2 INTROSPECTION URL");
2442  
2443 0 my ( $rp, $authMethod ) =
2444 $self->checkEndPointAuthenticationCredentials($req);
2445 0 ▶ return $self->invalidClientResponse($req) unless ($rp);
Branch: 1 branch
BranchTrueFalseTotal
unless $rp 0 0 0
2446  
2447 0 ▶ if ( !$authMethod or $authMethod eq 'none' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $authMethod or $authMethod eq "none") 0 0 0
Condition0%0/3
not $authMethod or $authMethod eq "none"
l!l&&r!l&&!r
000
MC/DC0%0/2
not $authMethod or $authMethod eq "none"
not $authMethod $authMethod eq "none"
Truth table0%0/3
not(A) or B
A= not $authMethodB= $authMethod eq "none"
ABresult
1X1
011
000
2448 0 $self->logger->error(
2449 "Unauthenticated clients are not allowed to access the introspection endpoint"
2450 );
2451 0 return $self->sendOIDCError( $req, 'unauthorized_client', 401 );
2452 }
2453  
2454 0 my $token = $req->param('token');
2455 0 ▶ return $self->sendOIDCError( $req, 'invalid_request', 400 ) unless ($token);
Branch: 1 branch
BranchTrueFalseTotal
unless $token 0 0 0
2456  
2457 0 my $response = { active => JSON::false };
2458 0 my $oidcSession = $self->getAccessToken($token);
2459 0 ▶ if ($oidcSession) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidcSession) 0 0 0
2460 my $apacheSession =
2461 0 $self->_getSessionFromAccessTokenData( $oidcSession->{data} );
2462 0 ▶ if ($apacheSession) {
Branch: 1 branch
BranchTrueFalseTotal
if ($apacheSession) { } 0 0 0
2463 $response = {
2464 active => JSON::true,
2465 aud => $self->getAudiences( $oidcSession->data->{rp} ),
2466 client_id => $oidcSession->{data}->{client_id},
2467 exp =>
2468 int( $oidcSession->data->{_utime} + $self->conf->{timeout} ),
2469 iat => int( $oidcSession->data->{iat} ),
2470 iss => $self->get_issuer($req),
2471 nbf => int( $oidcSession->data->{nbf} ),
2472 scope => $oidcSession->{data}->{scope},
2473 0 token_type => 'bearer',
2474  
2475 # The ID attribute we choose is the one of the calling
2476 # webservice, which might be different from the OIDC client the
2477 # token was issued to.
2478 sub => $self->getUserIDForRP( $req, $rp, $apacheSession->data ),
2479 };
2480 0 foreach ( keys %$response ) {
2481 delete $response->{$_}
2482 unless defined $response->{$_}
2483 0 ▶ and $response->{$_} || length( $response->{$_} ) > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $response->{$_} and $response->{$_} || length $response->{$_} > 0 0 0 0
Condition0%0/6
defined $response->{$_} and $response->{$_} || length $response->{$_} > 0
!ll&&!rl&&r
000
$response->{$_} or length $response->{$_} > 0
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $response->{$_} and $response->{$_} || length $response->{$_} > 0
defined $response->{$_} $response->{$_} length $response->{$_} > 0
Truth table0%0/4
A and B or C
A= defined $response->{$_}B= $response->{$_}C= length $response->{$_} > 0
ABCresult
0XX0
1000
11X1
1011
2484 }
2485 }
2486 else {
2487 0 $self->logger->warn("Count not find session tied to Access Token");
2488 }
2489 }
2490 0 return $self->p->sendJSONresponse( $req, $response );
2491 }
2492  
2493 sub unauthRevokeToken {
2494 1 ▶ my ( $self, $req ) = @_;
Subroutine unauthRevokeToken: called CC=3 SCAR=17.6
Pod undocumented
2495 1 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 1 1
2496 1 $self->logger->debug("URL detected as an Oauth2 TOKEN REVOCATION URL");
2497  
2498 1 my ( $rp, $authMethod ) =
2499 $self->checkEndPointAuthenticationCredentials($req);
2500 1 ▶ return $self->invalidClientResponse($req) unless ($rp);
Branch: 1 branch
BranchTrueFalseTotal
unless $rp 0 1 1
2501  
2502 return $self->_revokeToken(
2503 $req,
2504 sub {
2505 0 ▶ my ($session) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
2506 0 my $_rp = $self->getRP( $session->data->{client_id} );
2507 my $rpClientId =
2508 0 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
2509 0 ▶ unless ( $session->data->{client_id} eq $rpClientId ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($session->data->{"client_id"} eq $rpClientId) 0 0 0
2510 0 my @aud = $self->getAudiences($_rp);
2511 0 ▶ unless ( grep { $_ eq $rpClientId } $self->getAudiences($_rp) )
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $rpClientId;} $self->getAudiences($_rp)) 0 0 0
2512 {
2513 0 $self->auditLog(
2514 $req,
2515 code => 'ISSUER_OIDC_UNAUTHORIZED_REVOKE_REQUEST',
2516 rp => $rp,
2517 message =>
2518 "RP $rp tried to remove a token issued from $_rp",
2519 );
2520 0 return ();
2521 }
2522 }
2523 0 my $_uid = $session->data->{ $self->conf->{whatToTrace} };
2524 0 return ( $_rp, $_uid );
2525 },
2526 1 $rp
2527 );
2528 }
2529  
2530 sub authRevokeToken {
2531 0 ▶ my ( $self, $req ) = @_;
Subroutine authRevokeToken: not called CC=1 SCAR=6.9
Pod undocumented
2532 0 my $uid = $req->sessionInfo->{ $self->conf->{whatToTrace} };
2533 return $self->_revokeToken(
2534 $req,
2535 sub {
2536 0 ▶ my ( $session, $rp ) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
2537 0 my $_uid = $session->data->{ $self->conf->{whatToTrace} };
2538 0 ▶ unless ( $uid eq $_uid ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($uid eq $_uid) 0 0 0
2539 0 $self->auditLog(
2540 $req,
2541 code => 'ISSUER_OIDC_UNAUTHORIZED_REVOKE_REQUEST',
2542 user => $uid,
2543 message =>
2544 "User $uid tried to remove a token issued for $_uid",
2545 );
2546 0 return ();
2547 }
2548 0 return ( $rp, $uid );
2549 }
2550 0 );
2551 }
2552  
2553 sub _revokeToken {
2554 1 ▶ my ( $self, $req, $checkRight, $rp, $raw ) = @_;
Subroutine _revokeToken: called CC=18 SCAR=54.8
2555 my $userReq =
2556 1 ▶ $rp ? undef : $req->sessionInfo->{ $self->conf->{whatToTrace} };
Branch: 1 branch
BranchTrueFalseTotal
$rp ? : 1 0 1
2557  
2558 1 ▶ return $self->sendOIDCError( $req, 'invalid_request', 400 )
Branch: 1 branch
BranchTrueFalseTotal
unless $req->method =~ /^POST$/i 0 1 1
2559 unless ( $req->method =~ /^POST$/i );
2560  
2561 1 my $token = $req->param('token');
2562 1 ▶ return $self->sendOIDCError( $req, 'invalid_request', 400 ) unless ($token);
Branch: 1 branch
BranchTrueFalseTotal
unless $token 1 0 1
2563  
2564 0 my $tokenHint = $req->param('token_hint');
2565 0 my $oidcSession;
2566 0 ▶ if ( !$tokenHint or $tokenHint eq 'access_token' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $tokenHint or $tokenHint eq "access_token") 0 0 0
Condition0%0/3
not $tokenHint or $tokenHint eq "access_token"
l!l&&r!l&&!r
000
MC/DC0%0/2
not $tokenHint or $tokenHint eq "access_token"
not $tokenHint $tokenHint eq "access_token"
Truth table0%0/3
not(A) or B
A= not $tokenHintB= $tokenHint eq "access_token"
ABresult
1X1
011
000
2567 0 $self->logger->debug('Try to find an access_token to revoke');
2568 0 $oidcSession = $self->getAccessToken($token);
2569 0 ▶ $tokenHint = 'access_token' if $oidcSession;
Branch: 1 branch
BranchTrueFalseTotal
if $oidcSession 0 0 0
2570 }
2571 0 ▶ if ( !$oidcSession and ( !$tokenHint or $tokenHint eq 'refresh_token' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $oidcSession and !$tokenHint || $tokenHint eq "refresh_token") 0 0 0
Condition0%0/6
not $oidcSession and !$tokenHint || $tokenHint eq "refresh_token"
!ll&&!rl&&r
000
not $tokenHint or $tokenHint eq "refresh_token"
l!l&&r!l&&!r
000
MC/DC0%0/3
not $oidcSession and !$tokenHint || $tokenHint eq "refresh_token"
not $oidcSession not $tokenHint $tokenHint eq "refresh_token"
Truth table0%0/4
not(A) and not(B) or C
A= not $oidcSessionB= not $tokenHintC= $tokenHint eq "refresh_token"
ABCresult
0XX0
1000
11X1
1011
2572 0 $self->logger->debug('Try to find a refresh_token to revoke');
2573 0 $oidcSession = $self->getRefreshToken( $token, $raw );
2574 0 $tokenHint = 'refresh_token';
2575 }
2576 0 ▶ if ($oidcSession) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidcSession) { } 0 0 0
2577 0 $self->logger->debug("token found");
2578 0 ▶ if ( my ( $_rp, $_uid ) = $checkRight->( $oidcSession, $rp ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$checkRight($oidcSession, $rp)) 0 0 0
2579 my $bck =
2580 0 $self->rpOptions->{$_rp}->{oidcRPMetaDataOptionsLogoutType};
2581 0 ▶ if ( $bck and $bck eq 'back' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bck and $bck eq "back") 0 0 0
Condition0%0/3
$bck and $bck eq "back"
!ll&&!rl&&r
000
MC/DC0%0/2
$bck and $bck eq "back"
$bck $bck eq "back"
Truth table0%0/3
A and B
A= $bckB= $bck eq "back"
ABresult
0X0
100
111
2582 0 $self->_backChannelLogout( $req, $_rp, $oidcSession->data );
2583 }
2584 $self->auditLog(
2585 0 ▶ $req,
Branch: 1 branch
BranchTrueFalseTotal
$userReq ? : 0 0 0
Condition0%0/3
$userReq || $rp
l!l&&r!l&&!r
000
MC/DC0%0/2
$userReq || $rp
$userReq $rp
Truth table0%0/3
A || B
A= $userReqB= $rp
ABresult
1X1
011
000
2586 code => 'ISSUER_OIDC_' . uc($tokenHint) . '_REVOKE',
2587 rp => $_rp,
2588 message => ( $userReq ? "User $userReq" : "OIDC RP $rp" )
2589 . " dropped a $tokenHint owned by $_uid",
2590 user => ( $userReq || $rp ),
2591 $tokenHint => $token
2592 );
2593 0 $self->logger->debug(
2594 "$tokenHint dropped was " . $oidcSession->id );
2595 0 $oidcSession->remove;
2596 }
2597 0 return [ 200, [], [] ];
2598 }
2599 else {
2600 0 ▶ $self->auditLog(
Branch: 1 branch
BranchTrueFalseTotal
$userReq ? : 0 0 0
Condition0%0/3
$userReq || $rp
l!l&&r!l&&!r
000
MC/DC0%0/2
$userReq || $rp
$userReq $rp
Truth table0%0/3
A || B
A= $userReqB= $rp
ABresult
1X1
011
000
2601 $req,
2602 code => 'ISSUER_OIDC_' . uc($tokenHint) . '_REVOKE_NOT_FOUND',
2603 rp => $rp,
2604 message => ( $userReq ? "User $userReq" : "OIDC RP $rp" )
2605 . " tried to drop an unexistent $tokenHint",
2606 user => ( $userReq || $rp ),
2607 $tokenHint => $token
2608 );
2609 }
2610 0 return [ 200, [], [] ];
2611 }
2612  
2613 # Endpoint JWKS is implemented in Lib/OpenIDConnect
2614  
2615 # Handle register endpoint
2616 sub registration {
2617 0 ▶ my ( $self, $req ) = @_;
Subroutine registration: not called CC=29 SCAR=67.7
Pod undocumented
2618 0 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 0 0
2619 0 $self->logger->debug("URL detected as an OpenID Connect REGISTRATION URL");
2620  
2621 # TODO: check Initial Access Token
2622  
2623 # Specific message to allow DOS detection
2624 0 my $source_ip = $req->address;
2625 0 $self->logger->notice(
2626 "OpenID Connect Registration request from $source_ip");
2627  
2628 # Check dynamic registration is allowed
2629 0 ▶ unless ( $self->conf->{oidcServiceAllowDynamicRegistration} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->conf->{"oidcServiceAllowDynamicRegistration"}) 0 0 0
2630 0 $self->logger->error("Dynamic registration is not allowed");
2631 0 return $self->p->sendError( $req, 'server_error' );
2632 }
2633  
2634 # Get client metadata
2635 0 my $client_metadata_json = $req->content;
2636 0 ▶ return $self->p->sendError( $req, 'Missing POST data', 400 )
Branch: 1 branch
BranchTrueFalseTotal
unless $client_metadata_json 0 0 0
2637 unless ($client_metadata_json);
2638  
2639 0 $self->logger->debug("Client metadata received: $client_metadata_json");
2640  
2641 0 ▶ my $client_metadata = $self->decodeClientMetadata($client_metadata_json)
Branch: 1 branch
BranchTrueFalseTotal
my $client_metadata = $self->decodeClientMetadata($client_metadata_json) or return $self->p->sendError($req, "invalid_client_metadata", 400) 0 0 0
2642 or return $self->p->sendError( $req, 'invalid_client_metadata', 400 );
2643 0 my $registration_response = {};
2644  
2645 # Check redirect_uris
2646 0 my $redirect_uris = $client_metadata->{redirect_uris};
2647 0 ▶ unless ( $redirect_uris and ref($redirect_uris) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($redirect_uris and ref $redirect_uris eq 'ARRAY') { } 0 0 0
Condition0%0/3
$redirect_uris and ref $redirect_uris eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$redirect_uris and ref $redirect_uris eq "ARRAY"
$redirect_uris ref $redirect_uris eq "ARRAY"
Truth table0%0/3
A and B
A= $redirect_urisB= ref $redirect_uris eq "ARRAY"
ABresult
0X0
100
111
2648 0 $self->logger->error("Field redirect_uris (array) is mandatory");
2649 0 return $self->p->sendError( $req, 'invalid_client_metadata', 400 );
2650 }
2651 else {
2652 0 foreach (@$redirect_uris) {
2653 0 ▶ if ( /^\s*((?:java|vb)script|data):/i
Branch: 1 branch
BranchTrueFalseTotal
if (/^\s*((?:java|vb)script|data):/i or $self->p->checkXSSAttack("redirect_uri", $_)) 0 0 0
Condition0%0/3
/^\s*((?:java|vb)script|data):/i or $self->p->checkXSSAttack("redirect_uri", $_)
l!l&&r!l&&!r
000
MC/DC0%0/2
/^\s*((?:java|vb)script|data):/i or $self->p->checkXSSAttack("redirect_uri", $_)
/^\s*((?:java|vb)script|data):/i $self->p->checkXSSAttack("redirect_uri", $_)
Truth table0%0/3
A or B
A= /^\s*((?:java|vb)script|data):/iB= $self->p->checkXSSAttack("redirect_uri", $_)
ABresult
1X1
011
000
2654 or $self->p->checkXSSAttack( 'redirect_uri', $_ ) )
2655 {
2656 0 $self->userLogger->error(
2657 "Registration tried with a forbidden redirect_uri: $_");
2658 0 return $self->p->sendError( $req, 'invalid_client_metadata',
2659 400 );
2660 }
2661 }
2662 }
2663  
2664 # RP identifier
2665 0 my $registration_time = time;
2666 0 my $rp = "register-$registration_time";
2667  
2668 # Generate Client ID and Client Password
2669 0 my $client_id = random_string(RS_MSK);
2670 0 my $client_secret = random_string(RS_MSK);
2671  
2672 0 my $default_signing_key_type =
2673 $self->_getKeyType( $self->get_public_key("default-oidc-sig") );
2674  
2675 # Register known parameters
2676 my $client_name =
2677 0 ▶ $client_metadata->{client_name} || "Self registered client";
Condition0%0/2
$client_metadata->{'client_name'} || 'Self registered client'
l!l
00
MC/DC0%0/1
$client_metadata->{'client_name'} || 'Self registered client'
$client_metadata->{'client_name'}
Truth table0%0/2
A
A= $client_metadata->{'client_name'}
Aresult
11
00
2678 0 my $logo_uri = $client_metadata->{logo_uri};
2679 my $id_token_signed_response_alg =
2680 $client_metadata->{id_token_signed_response_alg}
2681 0 ▶ || ( $default_signing_key_type eq 'EC' ? 'ES256' : 'RS256' );
Branch: 1 branch
BranchTrueFalseTotal
$default_signing_key_type eq 'EC' ? : 0 0 0
Condition0%0/3
$client_metadata->{'id_token_signed_response_alg'} || ($default_signing_key_type eq 'EC' ? 'ES256' : 'RS256')
l!l&&r!l&&!r
000
MC/DC0%0/2
$client_metadata->{'id_token_signed_response_alg'} || ($default_signing_key_type eq 'EC' ? 'ES256' : 'RS256')
$client_metadata->{'id_token_signed_response_alg'} ($default_signing_key_type eq 'EC' ? 'ES256' : 'RS256')
Truth table0%0/3
A || B
A= $client_metadata->{'id_token_signed_response_alg'}B= ($default_signing_key_type eq 'EC' ? 'ES256' : 'RS256')
ABresult
1X1
011
000
2682 my $userinfo_signed_response_alg =
2683 0 $client_metadata->{userinfo_signed_response_alg};
2684 0 my $request_uris = $client_metadata->{request_uris};
2685 0 my $backchannel_logout_uri = $client_metadata->{backchannel_logout_uri};
2686 my $backchannel_logout_session_required =
2687 0 $client_metadata->{backchannel_logout_session_required};
2688 0 my $frontchannel_logout_uri = $client_metadata->{frontchannel_logout_uri};
2689 my $frontchannel_logout_session_required =
2690 0 $client_metadata->{frontchannel_logout_session_required};
2691 0 my $jwksUri = $client_metadata->{jwks_uri};
2692 my $encryptedResponseAlg =
2693 0 $client_metadata->{id_token_encrypted_response_alg};
2694 my $encryptedResponseEnc =
2695 0 $client_metadata->{id_token_encrypted_response_enc};
2696 0 my $userInfoEncAlg = $client_metadata->{userinfo_encrypted_response_alg};
2697 0 my $userInfoEncEnc = $client_metadata->{userinfo_encrypted_response_enc};
2698  
2699 # Register RP in global configuration
2700 0 my $conf = $self->confAcc->getConf( { raw => 1, noCache => 1 } );
2701  
2702 0 $conf->{cfgAuthor} = "OpenID Connect Registration ($client_name)";
2703 0 $conf->{cfgAuthorIP} = $source_ip;
2704 0 $conf->{cfgVersion} = $VERSION;
2705  
2706 0 $conf->{oidcRPMetaDataExportedVars}->{$rp} = {};
2707 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsClientID} =
2708 0 $client_id;
2709 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsClientSecret}
2710 0 = $client_secret;
2711 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsDisplayName} =
2712 0 $client_name;
2713 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsIcon} =
2714 0 $logo_uri;
2715 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsIDTokenSignAlg}
2716 0 = $id_token_signed_response_alg;
2717 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsRedirectUris}
2718 0 = join( ' ', @$redirect_uris );
2719 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsRequestUris} =
2720 0 ▶ join( ' ', @$request_uris )
Branch: 1 branch
BranchTrueFalseTotal
if $request_uris and @$request_uris 0 0 0
Condition0%0/3
$request_uris and @$request_uris
!ll&&!rl&&r
000
MC/DC0%0/2
$request_uris and @$request_uris
$request_uris @$request_uris
Truth table0%0/3
A and B
A= $request_urisB= @$request_uris
ABresult
0X0
100
111
2721 if $request_uris and @$request_uris;
2722 $conf->{oidcRPMetaDataOptions}->{$rp}
2723 0 ▶ ->{oidcRPMetaDataOptionsUserInfoSignAlg} = $userinfo_signed_response_alg
Branch: 1 branch
BranchTrueFalseTotal
if defined $userinfo_signed_response_alg 0 0 0
2724 if defined $userinfo_signed_response_alg;
2725  
2726 0 ▶ if ($frontchannel_logout_uri) {
Branch: 2 branches
BranchTrueFalseTotal
if ($frontchannel_logout_uri) { } 0 0 0
elsif ($backchannel_logout_uri) { } 0 0 0
2727 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsLogoutType}
2728 0 = 'front';
2729 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsLogoutUrl}
2730 0 = $frontchannel_logout_uri;
2731 $conf->{oidcRPMetaDataOptions}->{$rp}
2732 ->{oidcRPMetaDataOptionsLogoutSessionRequired} =
2733 0 $frontchannel_logout_session_required;
2734 }
2735 elsif ($backchannel_logout_uri) {
2736 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsLogoutType}
2737 0 = 'back';
2738 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsLogoutUrl}
2739 0 = $backchannel_logout_uri;
2740 $conf->{oidcRPMetaDataOptions}->{$rp}
2741 ->{oidcRPMetaDataOptionsLogoutSessionRequired} =
2742 0 $backchannel_logout_session_required;
2743 }
2744 $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsJwksUri} =
2745 0 ▶ $jwksUri
Branch: 1 branch
BranchTrueFalseTotal
if $jwksUri 0 0 0
2746 if $jwksUri;
2747 $conf->{oidcRPMetaDataOptions}->{$rp}
2748 0 ▶ ->{oidcRPMetaDataOptionsIdTokenEncKeyMgtAlg} = $encryptedResponseAlg
Branch: 1 branch
BranchTrueFalseTotal
if $encryptedResponseAlg 0 0 0
2749 if $encryptedResponseAlg;
2750 $conf->{oidcRPMetaDataOptions}->{$rp}
2751 0 ▶ ->{oidcRPMetaDataOptionsIdTokenEncContentEncAlg} = $encryptedResponseEnc
Branch: 1 branch
BranchTrueFalseTotal
if $encryptedResponseEnc 0 0 0
2752 if $encryptedResponseEnc;
2753 $conf->{oidcRPMetaDataOptions}->{$rp}
2754 0 ▶ ->{oidcRPMetaDataOptionsUserInfoEncKeyMgtAlg} = $userInfoEncAlg
Branch: 1 branch
BranchTrueFalseTotal
if $userInfoEncAlg 0 0 0
2755 if $userInfoEncAlg;
2756 $conf->{oidcRPMetaDataOptions}->{$rp}
2757 0 ▶ ->{oidcRPMetaDataOptionsUserInfoEncContentEncAlg} = $userInfoEncEnc
Branch: 1 branch
BranchTrueFalseTotal
if $userInfoEncEnc 0 0 0
2758 if $userInfoEncEnc;
2759  
2760 # TODO "jwks" support (when jwks_uri isn't available
2761  
2762 # Exported Vars
2763 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->conf->{"oidcServiceDynamicRegistrationExportedVars"} eq "HASH") 0 0 0
2764 ref( $self->conf->{oidcServiceDynamicRegistrationExportedVars} ) eq
2765 'HASH' )
2766 {
2767 $conf->{oidcRPMetaDataExportedVars}->{$rp} =
2768 0 $self->conf->{oidcServiceDynamicRegistrationExportedVars};
2769 }
2770  
2771 # Extra claims
2772 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->conf->{"oidcServiceDynamicRegistrationExtraClaims"} eq "HASH") 0 0 0
2773 ref( $self->conf->{oidcServiceDynamicRegistrationExtraClaims} ) eq
2774 'HASH' )
2775 {
2776 $conf->{oidcRPMetaDataOptionsExtraClaims}->{$rp} =
2777 0 $self->conf->{oidcServiceDynamicRegistrationExtraClaims};
2778 }
2779  
2780 0 ▶ if ( $self->confAcc->saveConf($conf) > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->confAcc->saveConf($conf) > 0) { } 0 0 0
2781  
2782 # Send registration response
2783 0 $registration_response->{'client_id'} = $client_id;
2784 0 $registration_response->{'client_secret'} = $client_secret;
2785 0 $registration_response->{'client_id_issued_at'} = $registration_time;
2786 0 $registration_response->{'client_id_expires_at'} = 0;
2787 0 $registration_response->{'client_name'} = $client_name;
2788 0 $registration_response->{'logo_uri'} = $logo_uri;
2789 0 $registration_response->{'id_token_signed_response_alg'} =
2790 $id_token_signed_response_alg;
2791 0 $registration_response->{'redirect_uris'} = $redirect_uris;
2792 0 ▶ $registration_response->{'request_uris'} = $request_uris
Branch: 1 branch
BranchTrueFalseTotal
if $request_uris and @$request_uris 0 0 0
Condition0%0/3
$request_uris and @$request_uris
!ll&&!rl&&r
000
MC/DC0%0/2
$request_uris and @$request_uris
$request_uris @$request_uris
Truth table0%0/3
A and B
A= $request_urisB= @$request_uris
ABresult
0X0
100
111
2793 if $request_uris and @$request_uris;
2794 0 ▶ $registration_response->{'userinfo_signed_response_alg'} =
Branch: 1 branch
BranchTrueFalseTotal
if defined $userinfo_signed_response_alg 0 0 0
2795 $userinfo_signed_response_alg
2796 if defined $userinfo_signed_response_alg;
2797 }
2798 else {
2799 0 $self->logger->error(
2800 "Configuration not saved: $Lemonldap::NG::Common::Conf::msg");
2801 0 return $self->p->sendError( $req, 'server_error', 500 );
2802 }
2803  
2804 0 $self->logger->debug("Registration response sent");
2805 0 return $self->p->sendJSONresponse( $req, $registration_response,
2806 code => 201 );
2807 }
2808  
2809 # Handle logout endpoint for unauthenticated users
2810 sub endSessionDone {
2811 0 ▶ my ( $self, $req ) = @_;
Subroutine endSessionDone: not called CC=10 SCAR=47.0
Pod undocumented
2812 0 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 0 0
2813 0 $self->logger->debug("URL detected as an OpenID Connect END SESSION URL");
2814 0 $self->logger->debug("User is already logged out");
2815  
2816 0 my $post_logout_redirect_uri = $req->param('post_logout_redirect_uri');
2817 0 my $state = $req->param('state');
2818 0 my $client_id = $req->param('client_id');
2819 0 my $id_token_hint = $req->param('id_token_hint');
2820 0 my $rp;
2821  
2822 0 ▶ if ($id_token_hint) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id_token_hint) 0 0 0
2823 0 my $payload = getJWTPayload($id_token_hint);
2824  
2825 0 ▶ if ( my $azp = $payload->{azp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $azp = $payload->{"azp"}) 0 0 0
2826 0 ▶ if ( !$client_id or $client_id eq $azp ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $client_id or $client_id eq $azp) { } 0 0 0
Condition0%0/3
not $client_id or $client_id eq $azp
l!l&&r!l&&!r
000
MC/DC0%0/2
not $client_id or $client_id eq $azp
not $client_id $client_id eq $azp
Truth table0%0/3
not(A) or B
A= not $client_idB= $client_id eq $azp
ABresult
1X1
011
000
2827 0 $rp = $self->getRP( $payload->{azp} );
2828 }
2829 else {
2830 0 $self->logger->error(
2831 "Provided client ID $client_id does not match"
2832 . " id_token_hint azp $azp" );
2833 0 return $self->p->login($req);
2834 }
2835 }
2836 }
2837  
2838 0 ▶ if ( not $rp and $client_id ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $rp and $client_id) 0 0 0
Condition0%0/3
not $rp and $client_id
!ll&&!rl&&r
000
MC/DC0%0/2
not $rp and $client_id
not $rp $client_id
Truth table0%0/3
not(A) and B
A= not $rpB= $client_id
ABresult
0X0
100
111
2839 0 $rp = $self->getRP($client_id);
2840 }
2841  
2842 0 ▶ if ($post_logout_redirect_uri) {
Branch: 1 branch
BranchTrueFalseTotal
if ($post_logout_redirect_uri) 0 0 0
2843  
2844 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_validatePostLogoutRedirectUri($req, $rp, $post_logout_redirect_uri, "end_session")) 0 0 0
2845 $self->_validatePostLogoutRedirectUri(
2846 $req, $rp, $post_logout_redirect_uri, "end_session"
2847 )
2848 )
2849 {
2850 0 $self->logger->error("$post_logout_redirect_uri is not allowed");
2851 0 return $self->p->login($req);
2852 }
2853  
2854 # Build Response
2855 0 my $response_url =
2856 $self->buildLogoutResponse( $post_logout_redirect_uri, $state );
2857  
2858 0 $self->logger->debug("Redirect user to $response_url");
2859 0 return [ 302, [ Location => $response_url ], [] ];
2860 }
2861  
2862 # Else, normal login process
2863 0 return $self->p->login($req);
2864 }
2865  
2866 # Handle checksession endpoint
2867 sub checkSession {
2868 0 ▶ my ( $self, $req ) = @_;
Subroutine checkSession: not called CC=2 SCAR=17.9
Pod undocumented
2869 0 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 0 0
2870 0 $self->logger->debug("URL detected as an OpenID Connect CHECK SESSION URL");
2871  
2872 # TODO: access_control_allow_origin => '*'
2873 0 $req->frame(1);
2874 return $self->p->sendHtml(
2875 $req,
2876 '../common/oidc_checksession',
2877 params => {
2878 COOKIENAME => $self->conf->{cookieName},
2879 }
2880 0 );
2881 }
2882  
2883 sub logout {
2884 0 ▶ my ( $self, $req ) = @_;
Subroutine logout: not called CC=12 SCAR=50.5
Pod documented
2885 0 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 0 0
2886 0 my $code = PE_OK;
2887 0 ▶ if ( my $s = $req->userData->{_oidcConnectedRPIDs} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $s = $req->userData->{"_oidcConnectedRPIDs"}) 0 0 0
2888 0 my @rps = grep /\w/, split( ',', $s );
2889 0 foreach my $client_id (@rps) {
2890 0 my $rp = $self->getRP($client_id);
2891 0 ▶ if ( !$rp ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rp) 0 0 0
2892 0 $self->logger->warn(
2893 "Cannot find RP configuration for $client_id");
2894 0 $code = PE_SLO_ERROR;
2895 0 next;
2896 }
2897 0 my $rpConf = $self->rpOptions->{$rp};
2898 0 ▶ if ( !$rpConf ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rpConf) 0 0 0
2899 0 $self->logger->warn("Cannot find RP options for $client_id");
2900 0 $code = PE_SLO_ERROR;
2901 0 next;
2902 }
2903 0 ▶ if ( my $url = $rpConf->{oidcRPMetaDataOptionsLogoutUrl} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $url = $rpConf->{"oidcRPMetaDataOptionsLogoutUrl"}) 0 0 0
2904  
2905 # FRONT CHANNEL
2906 0 ▶ if ( $rpConf->{oidcRPMetaDataOptionsLogoutType} eq 'front' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rpConf->{'oidcRPMetaDataOptionsLogoutType'} eq 'front') { } 0 0 0
elsif ($rpConf->{'oidcRPMetaDataOptionsLogoutType'} eq 'back') { } 0 0 0
2907 0 ▶ if ( $rpConf->{oidcRPMetaDataOptionsLogoutSessionRequired} )
Branch: 1 branch
BranchTrueFalseTotal
if ($rpConf->{"oidcRPMetaDataOptionsLogoutSessionRequired"}) 0 0 0
2908 {
2909 $url .= ( $url =~ /\?/ ? '&' : '?' )
2910 . build_urlencoded(
2911 iss => $self->get_issuer($req),
2912 sid => $self->getSidFromSession(
2913 $rp, $req->{sessionInfo}
2914 )
2915 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$url =~ /\?/ ? : 0 0 0
2916 }
2917 0 $req->info( qq'<iframe src="$url" class="noborder">'
2918 . '</iframe>' );
2919 }
2920  
2921 # BACK CHANNEL
2922 elsif ( $rpConf->{oidcRPMetaDataOptionsLogoutType} eq 'back' ) {
2923 0 my $c =
2924 $self->_backChannelLogout( $req, $rp, $req->userData );
2925 0 ▶ $code = $c if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 0 0 0
2926 }
2927 }
2928 }
2929 }
2930 0 return $code;
2931 }
2932  
2933 # Internal methods
2934 sub _backChannelLogout {
2935 0 ▶ my ( $self, $req, $rp, $sessionInfo ) = @_;
Subroutine _backChannelLogout: not called CC=4 SCAR=30.0
2936  
2937 # Logout token must contain:
2938 # - iss: issuer identifier
2939 # - sub: subject id (user id)
2940 # OR/AND
2941 # - sid: OP session id given to the RP
2942 # - aud: audience
2943 # - iat: issue at time
2944 # - jti: JWT token id
2945 # - events: should be :
2946 # { 'http://schemas.openid.net/event/backchannel-logout"
2947 # => {} } # or a JSON object
2948 #
2949 # Logout token should be send using a POST request:
2950 #
2951 # POST /backChannelUri HTTP/1.1
2952 # Host: rp
2953 # Content-Type: application/x-www-form-urlencoded
2954 #
2955 # logout_token=<JWT value>
2956 #
2957 # RP response should be 200 (204 accepted) or 400 for errors
2958 0 my $alg = $self->getSignAlg($rp);
2959 0 my $userId = $self->getUserIDForRP( $req, $rp, $sessionInfo );
2960 my $logoutToken = {
2961 iss => $self->get_issuer($req),
2962 sub => $userId,
2963 aud => $self->getAudiences($rp),
2964 iat => time,
2965  
2966 # Random string: no response expected from RP
2967 jti =>
2968 0 join( "", map { [ "0" .. "9", 'A' .. 'Z' ]->[ rand 36 ] } 1 .. 8 ),
2969 events => { $self->BACKCHANNEL_EVENTSKEY => {} },
2970 };
2971 0 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsLogoutSessionRequired} )
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsLogoutSessionRequired"}) 0 0 0
2972 {
2973 0 $logoutToken->{sid} = $self->getSidFromSession( $rp, $sessionInfo );
2974 }
2975 $self->logger->debug(
2976 0 "Logout token content: " . JSON::to_json($logoutToken) );
2977 my $jwt = $self->encryptToken(
2978 $rp,
2979 $self->createJWT( $logoutToken, $alg, $rp ),
2980 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsLogoutEncKeyMgtAlg},
2981 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsLogoutEncContentEncAlg},
2982 0 );
2983 my $resp = $self->ua->post(
2984 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsLogoutUrl},
2985 0 { logout_token => $jwt },
2986 'Content-Type' => 'application/x-www-form-urlencoded',
2987 );
2988 0 ▶ if ( $resp->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->is_error) { } 0 0 0
2989 0 $self->logger->warn( "OIDC back channel: unable to unlog"
2990 . " $userId from $rp: "
2991 . $resp->message );
2992 0 $self->logger->debug("Logout token: $jwt");
2993 0 $self->logger->debug( 'Upstream status: ' . $resp->status_line );
2994 0 ▶ $self->logger->debug(
Condition0%0/2
$resp->content // ""
l!l
00
MC/DC0%0/1
$resp->content // ""
$resp->content
Truth table0%0/2
A
A= $resp->content
Aresult
11
00
2995 'Upstream response: ' . ( $resp->content // '' ) );
2996 0 return PE_SLO_ERROR;
2997 }
2998 else {
2999 0 $self->logger->info(
3000 "OIDC back channel: user $userId unlogged from $rp");
3001 }
3002 0 return PE_OK;
3003 }
3004  
3005 sub metadata {
3006 1 ▶ my ( $self, $req ) = @_;
Subroutine metadata: called CC=3 SCAR=11.3
Pod undocumented
3007 1 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 1 1
3008 1 my %args;
3009 $args{ttl} = $self->conf->{oidcServiceMetadataTtl}
3010 1 ▶ if $self->conf->{oidcServiceMetadataTtl};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcServiceMetadataTtl"} 0 1 1
3011 1 return $self->p->sendJSONresponse( $req,
3012 $self->metadataDoc( $self->get_issuer($req) ), %args );
3013 }
3014  
3015 # Store request parameters in %ENV
3016 sub exportRequestParameters {
3017 35 ▶ my ( $self, $req ) = @_;
Subroutine exportRequestParameters: called CC=16 SCAR=35.5
Pod undocumented
3018  
3019 35 ▶ unless ( $self->ssoMatch($req) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->ssoMatch($req)) 33 2 35
3020 33 return PE_OK;
3021 }
3022  
3023 2 ▶ if ( my $p = $req->param('prompt') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = $req->param("prompt")) 0 2 2
3024 0 ▶ if ( $p eq 'none' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p eq "none") 0 0 0
3025 0 return $self->_unauthPromptNone($req);
3026 }
3027 }
3028  
3029 2 foreach my $param (
3030 qw/response_type scope client_id state redirect_uri nonce
3031 response_mode display prompt max_age ui_locales id_token_hint
3032 login_hint acr_values request request_uri/
3033 )
3034 {
3035 32 ▶ if ( $req->param($param) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->param($param)) 11 21 32
3036 11 $req->env->{ "llng_oidc_" . $param } = $req->param($param);
3037 }
3038 }
3039  
3040 2 my $rp;
3041 2 ▶ if ( $req->param('client_id') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->param("client_id")) 2 0 2
3042 2 $rp = $self->getRP( $req->param('client_id') );
3043 2 ▶ if ($rp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rp) 2 0 2
3044 2 $req->env->{"llng_oidc_rp"} = $rp;
3045 }
3046 }
3047  
3048 # Extract request_uri/request parameter
3049 2 my $request = $req->param('request');
3050 2 ▶ if ( my $request_uri = $req->param('request_uri') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $request_uri = $req->param("request_uri")) 0 2 2
3051 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($rp and $self->isUriAllowedForRP($request_uri, $rp, "oidcRPMetaDataOptionsRequestUris", 1)) 0 0 0
Condition0%0/3
$rp and $self->isUriAllowedForRP($request_uri, $rp, "oidcRPMetaDataOptionsRequestUris", 1)
!ll&&!rl&&r
000
MC/DC0%0/2
$rp and $self->isUriAllowedForRP($request_uri, $rp, "oidcRPMetaDataOptionsRequestUris", 1)
$rp $self->isUriAllowedForRP($request_uri, $rp, "oidcRPMetaDataOptionsRequestUris", 1)
Truth table0%0/3
A and B
A= $rpB= $self->isUriAllowedForRP($request_uri, $rp, "oidcRPMetaDataOptionsRequestUris", 1)
ABresult
0X0
100
111
3052 $rp
3053 and $self->isUriAllowedForRP(
3054 $request_uri, $rp, 'oidcRPMetaDataOptionsRequestUris', 1
3055 )
3056 )
3057 {
3058 0 $request = $self->getRequestJWT($request_uri);
3059 }
3060 }
3061  
3062 2 ▶ if ($request) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request) 0 2 2
3063 0 my $request_data = getJWTPayload($request);
3064 0 foreach ( keys %$request_data ) {
3065 0 $req->env->{ "llng_oidc_" . $_ } = $request_data->{$_};
3066 }
3067 }
3068  
3069 # Store target authentication level in pdata
3070 2 ▶ if ($rp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rp) 2 0 2
3071 2 my $targetAuthnLevel = $self->rpLevelRules->{$rp}->( $req, {} );
3072  
3073 2 ▶ if ( my $acr_values = $req->env->{'llng_oidc_acr_values'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $acr_values = $req->env->{"llng_oidc_acr_values"}) 0 2 2
3074 0 $targetAuthnLevel =
3075 $self->_get_authn_level_from_acr_values($acr_values);
3076 }
3077  
3078 2 ▶ $req->pdata->{targetAuthnLevel} = $targetAuthnLevel
Branch: 1 branch
BranchTrueFalseTotal
if $targetAuthnLevel 0 2 2
3079 if $targetAuthnLevel;
3080 }
3081  
3082 2 return PE_OK;
3083 }
3084  
3085 sub _unauthPromptNone {
3086 0 ▶ my ( $self, $req ) = @_;
Subroutine _unauthPromptNone: not called CC=4 SCAR=30.0
3087 0 my $res = $self->_checkErrorsInAuthorizeEndpoint($req);
3088 0 ▶ return $res if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 0 0 0
3089  
3090 0 my $oidc_request = $req->data->{_oidc_request};
3091 0 my $uri = $oidc_request->{redirect_uri};
3092 $uri =
3093 $uri
3094 . ( $uri =~ /\?/ ? '&' : '?' )
3095 . build_urlencoded(
3096 error => 'login_required',
3097 0 ▶ ( $oidc_request->{state} ? ( state => $oidc_request->{state} ) : () ),
Branch: 2 branches
BranchTrueFalseTotal
$uri =~ /\?/ ? : 0 0 0
$oidc_request->{'state'} ? : 0 0 0
3098 );
3099 0 return $self->_redirectToUrl( $req, $uri );
3100 }
3101  
3102 sub _hasScope {
3103 0 ▶ my ( $self, $scope, $scopelist ) = @_;
Subroutine _hasScope: not called CC=1 SCAR=6.9
3104 0 return scalar grep { $_ eq $scope } ( split /\s+/, $scopelist );
3105 }
3106  
3107 sub _convertOldFormatConsents {
3108 0 ▶ my ( $self, $req ) = @_;
Subroutine _convertOldFormatConsents: not called CC=9 SCAR=45.0
3109 0 my @oidcConsents = ();
3110 0 my @rps = ();
3111 0 my $scope = '';
3112 0 my $epoch = '';
3113 0 my $rp = '';
3114 0 ▶ unless ( $req->{sessionInfo} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($req->{"sessionInfo"}) 0 0 0
3115 0 $self->logger->error("Corrupted session");
3116 0 return PE_ERROR;
3117 }
3118  
3119 # Search Relying Parties
3120 $self->logger->debug(
3121 0 "Searching for previously registered Relying Parties...");
3122 0 foreach ( keys %{ $req->{sessionInfo} } ) {
3123 0 ▶ if ( $_ =~ /^_oidc_consent_scope_([\w-]+)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ =~ /^_oidc_consent_scope_([\w-]+)$/) 0 0 0
3124 0 push @rps, $1;
3125 0 $self->logger->debug("Found RP $1");
3126 }
3127 }
3128  
3129 # Convert OIDC Consents format
3130 0 $self->logger->debug("Convert Relying Party Consent(s)...");
3131 0 my $count = 0;
3132 0 foreach (@rps) {
3133 0 $scope = $req->{sessionInfo}->{ "_oidc_consent_scope_" . $_ };
3134 0 $epoch = $req->{sessionInfo}->{ "_oidc_consent_time_" . $_ };
3135 0 $rp = $_;
3136  
3137 0 ▶ if ( $scope and $epoch and $rp ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($scope and $epoch and $rp) { } 0 0 0
Condition0%0/6
$scope and $epoch and $rp
!ll&&!rl&&r
000
$scope and $epoch
!ll&&!rl&&r
000
MC/DC0%0/3
$scope and $epoch and $rp
$scope $epoch $rp
Truth table0%0/4
A and B and C
A= $scopeB= $epochC= $rp
ABCresult
0XX0
10X0
1100
1111
3138 0 $self->logger->debug("Append RP $rp Consent");
3139 0 push @oidcConsents, { rp => $rp, scope => $scope, epoch => $epoch };
3140 0 $count++;
3141 0 $self->logger->debug("Delete Key -> _oidc_consent_scope_$_");
3142 0 $self->p->updatePersistentSession( $req,
3143 { "_oidc_consent_scope_" . $_ => undef } );
3144 0 $self->logger->debug("Delete Key -> _oidc_consent_time_$_");
3145 0 $self->p->updatePersistentSession( $req,
3146 { "_oidc_consent_time_" . $_ => undef } );
3147 }
3148 else {
3149 0 $self->logger->debug( "Corrupted Consent / Session -> "
3150 . "RP=$rp, Scope=$scope, Epoch=$epoch" );
3151 0 return PE_ERROR;
3152 }
3153 }
3154  
3155 # Update persistent session
3156 0 ▶ $self->p->updatePersistentSession( $req,
Branch: 1 branch
BranchTrueFalseTotal
if $count 0 0 0
3157 { _oidcConsents => to_json( \@oidcConsents ) } )
3158 if $count;
3159 0 return $count;
3160 }
3161  
3162 sub _generateRefreshToken {
3163 0 ▶ my ( $self, $req, $rp, $info, $offline ) = @_;
Subroutine _generateRefreshToken: not called CC=4 SCAR=30.0
3164  
3165 0 my $user = $info->{_session_uid};
3166 0 my $token = $self->newRefreshToken( $rp, $info, $offline );
3167 0 ▶ if ($token) {
Branch: 1 branch
BranchTrueFalseTotal
if ($token) 0 0 0
3168 0 ▶ my $offline_str = ( $offline ? 'Offline ' : '' );
Branch: 1 branch
BranchTrueFalseTotal
$offline ? : 0 0 0
3169 0 ▶ $self->auditLog(
Branch: 1 branch
BranchTrueFalseTotal
$offline ? : 0 0 0
3170 $req,
3171 code => "ISSUER_OIDC_REFRESH_TOKEN",
3172 rp => $rp,
3173 message =>
3174 ( "${offline_str}Refresh Token for $user generated for $rp", ),
3175 user => $user,
3176 offline => ( $offline ? 1 : 0 ),
3177 );
3178 }
3179 0 return $token;
3180 }
3181  
3182 sub _generateIDToken {
3183 0 ▶ my ( $self, $req, $rp, $scope, $sessionInfo, $release_user_claims,
Subroutine _generateIDToken: not called CC=16 SCAR=56.1
3184 $extra_claims, $sid )
3185 = @_;
3186  
3187 0 ▶ $sid ||= $self->getSidFromSession( $rp, $sessionInfo );
Condition0%0/3
$sid ||= $self->getSidFromSession($rp, $sessionInfo)
l!l&&r!l&&!r
000
MC/DC0%0/2
$sid ||= $self->getSidFromSession($rp, $sessionInfo)
$sid $self->getSidFromSession($rp, $sessionInfo)
Truth table0%0/3
A ||= B
A= $sidB= $self->getSidFromSession($rp, $sessionInfo)
ABresult
1X1
011
000
3188 0 my $client_id = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
3189  
3190 my $id_token_exp =
3191 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIDTokenExpiration}
3192 0 ▶ || $self->conf->{oidcServiceIDTokenExpiration};
Condition0%0/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsIDTokenExpiration'} || $self->conf->{'oidcServiceIDTokenExpiration'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsIDTokenExpiration'} || $self->conf->{'oidcServiceIDTokenExpiration'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsIDTokenExpiration'} $self->conf->{'oidcServiceIDTokenExpiration'}
Truth table0%0/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsIDTokenExpiration'}B= $self->conf->{'oidcServiceIDTokenExpiration'}
ABresult
1X1
011
000
3193 0 $id_token_exp += time;
3194  
3195 0 ▶ my $authenticationLevel = $sessionInfo->{authenticationLevel} || 0;
Condition0%0/2
$sessionInfo->{'authenticationLevel'} || 0
l!l
00
MC/DC0%0/1
$sessionInfo->{'authenticationLevel'} || 0
$sessionInfo->{'authenticationLevel'}
Truth table0%0/2
A
A= $sessionInfo->{'authenticationLevel'}
Aresult
11
00
3196  
3197 0 my $id_token_acr = "loa-$authenticationLevel";
3198 0 foreach ( keys %{ $self->conf->{oidcServiceMetaDataAuthnContext} } ) {
3199 0 ▶ if ( $self->conf->{oidcServiceMetaDataAuthnContext}->{$_} eq
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{"oidcServiceMetaDataAuthnContext"}{$_} eq $authenticationLevel) 0 0 0
3200 $authenticationLevel )
3201 {
3202 0 $id_token_acr = $_;
3203 0 last;
3204 }
3205 }
3206  
3207 0 my $sub = $self->getUserIDForRP( $req, $rp, $sessionInfo );
3208  
3209 0 my $amr = $self->getAmr( $req, $rp, $sessionInfo );
3210  
3211 my $id_token_payload_hash = {
3212 iss => $self->get_issuer($req), # Issuer Identifier
3213 sub => $sub, # Subject Identifier
3214 aud => $self->getAudiences($rp), # Audience
3215 exp => $id_token_exp, # expiration
3216 iat => time, # Issued time
3217 auth_time => $sessionInfo->{_lastAuthnUTime}, # Authentication time
3218 0 ▶ acr => $id_token_acr, # Authentication Context Class Reference
Branch: 1 branch
BranchTrueFalseTotal
@$amr ? : 0 0 0
3219 azp => $client_id, # Authorized party, this is used for logout
3220 ( @$amr ? ( amr => $amr ) : () ),
3221 sid => $sid,
3222 };
3223  
3224 0 for ( keys %{$extra_claims} ) {
3225 $id_token_payload_hash->{$_} = $extra_claims->{$_}
3226 0 ▶ if $extra_claims->{$_} and not $id_token_payload_hash->{$_};
Branch: 1 branch
BranchTrueFalseTotal
if $extra_claims->{$_} and not $id_token_payload_hash->{$_} 0 0 0
Condition0%0/3
$extra_claims->{$_} and not $id_token_payload_hash->{$_}
!ll&&!rl&&r
000
MC/DC0%0/2
$extra_claims->{$_} and not $id_token_payload_hash->{$_}
$extra_claims->{$_} not $id_token_payload_hash->{$_}
Truth table0%0/3
A and not(B)
A= $extra_claims->{$_}B= not $id_token_payload_hash->{$_}
ABresult
0X0
100
111
3227 }
3228  
3229 # Decided by response_type or forced in RP config
3230 0 my $attribute_claims = {};
3231 0 ▶ if ( $release_user_claims || $self->force_id_claims($rp) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($release_user_claims or $self->force_id_claims($rp)) 0 0 0
Condition0%0/3
$release_user_claims or $self->force_id_claims($rp)
l!l&&r!l&&!r
000
MC/DC0%0/2
$release_user_claims or $self->force_id_claims($rp)
$release_user_claims $self->force_id_claims($rp)
Truth table0%0/3
A or B
A= $release_user_claimsB= $self->force_id_claims($rp)
ABresult
1X1
011
000
3232  
3233 0 $attribute_claims =
3234 $self->buildUserInfoResponseFromData( $req, $scope, $rp,
3235 $sessionInfo );
3236  
3237 0 foreach ( keys %$attribute_claims ) {
3238 0 ▶ $id_token_payload_hash->{$_} = $attribute_claims->{$_}
Branch: 1 branch
BranchTrueFalseTotal
unless $_ eq "sub" or $_ eq "sid" 0 0 0
Condition0%0/3
$_ eq "sub" or $_ eq "sid"
l!l&&r!l&&!r
000
MC/DC0%0/2
$_ eq "sub" or $_ eq "sid"
$_ eq "sub" $_ eq "sid"
Truth table0%0/3
A or B
A= $_ eq "sub"B= $_ eq "sid"
ABresult
1X1
011
000
3239 unless ( $_ eq "sub" or $_ eq "sid" );
3240 }
3241 }
3242  
3243 0 ▶ my $attr_str = (
Branch: 1 branch
BranchTrueFalseTotal
keys %$attribute_claims ? : 0 0 0
3244 keys %$attribute_claims
3245 ? ( " with attributes "
3246 . join( ',', sort( keys(%$attribute_claims) ) ) )
3247 : ''
3248 );
3249 0 my $user = $sessionInfo->{ $self->conf->{whatToTrace} };
3250 0 $self->auditLog(
3251 $req,
3252 code => "ISSUER_OIDC_ID_TOKEN",
3253 rp => $rp,
3254 message => ("ID Token for $user generated for $rp as $sub$attr_str"),
3255 user => $user,
3256 oidc_sub => $sub,
3257 attributes => $attribute_claims,
3258 );
3259  
3260 # Create ID Token
3261 0 return $self->createIDToken( $req, $id_token_payload_hash, $rp,
3262 $sessionInfo );
3263 }
3264  
3265 sub getAmr {
3266 0 ▶ my ( $self, $req, $rp, $sessionInfo ) = @_;
Subroutine getAmr: not called CC=5 SCAR=34.0
Pod undocumented
3267 0 my $result = [];
3268  
3269 0 my $client_id = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
3270  
3271 0 for my $amr_value ( sort keys %{ $self->amrRules } ) {
3272 my $richSessionInfo = {
3273 0 ▶ %{ $sessionInfo || {} },
Branch: 1 branch
BranchTrueFalseTotal
$sessionInfo or {} 0 0 0
3274 _clientId => $client_id,
3275 _clientConfKey => $rp,
3276 };
3277  
3278 0 ▶ if ( $self->amrRules->{$amr_value}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->amrRules->{$amr_value} and $self->amrRules->{$amr_value}->($req, $richSessionInfo)) 0 0 0
Condition0%0/3
$self->amrRules->{$amr_value} and $self->amrRules->{$amr_value}->($req, $richSessionInfo)
!ll&&!rl&&r
000
MC/DC0%0/2
$self->amrRules->{$amr_value} and $self->amrRules->{$amr_value}->($req, $richSessionInfo)
$self->amrRules->{$amr_value} $self->amrRules->{$amr_value}->($req, $richSessionInfo)
Truth table0%0/3
A and B
A= $self->amrRules->{$amr_value}B= $self->amrRules->{$amr_value}->($req, $richSessionInfo)
ABresult
0X0
100
111
3279 and $self->amrRules->{$amr_value}->( $req, $richSessionInfo ) )
3280 {
3281 0 push @$result, $amr_value;
3282 }
3283 }
3284  
3285 0 return $result;
3286 }
3287  
3288 sub encryptToken {
3289 0 ▶ my ( $self, $rp, $token, $alg, $enc ) = @_;
Subroutine encryptToken: not called CC=6 SCAR=37.4
Pod undocumented
3290 0 ▶ return $token unless $alg;
Branch: 1 branch
BranchTrueFalseTotal
unless $alg 0 0 0
3291 0 my $keys = $self->rpEncKey->{$rp};
3292 0 ▶ unless ($keys) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($keys) 0 0 0
3293 0 $self->logger->error(
3294 "No key defined for $rp, unable to encrypt tokens");
3295 0 return $token;
3296 }
3297 0 my $key = $keys->{$alg};
3298 0 ▶ unless ($key) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($key) 0 0 0
3299 0 $self->logger->error(
3300 "No compatible key found for $rp with algorithm $alg");
3301 0 return $token;
3302 }
3303 0 $self->logger->debug('Encrypt JWT token');
3304 0 my $tmp = eval {
3305 0 ▶ Crypt::JWT::encode_jwt(
Condition0%0/2
$enc || 'A128CBC-HS256'
l!l
00
MC/DC0%0/1
$enc || 'A128CBC-HS256'
$enc
Truth table0%0/2
A
A= $enc
Aresult
11
00
3306 payload => $token,
3307 alg => $alg,
3308 key => $key,
3309 enc => $enc || 'A128CBC-HS256',
3310 );
3311 };
3312 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
3313 0 $self->logger->error("Unable to encrypt token: $@");
3314 0 return undef;
3315 }
3316 0 return $token;
3317 }
3318  
3319 # Used to build refresh_token
3320 sub getAttributesForUser {
3321 0 ▶ my ( $self, $req, $session ) = @_;
Subroutine getAttributesForUser: not called CC=3 SCAR=24.8
Pod undocumented
3322 0 $req->userData( $session->data );
3323 0 $req->{error} = $self->p->processRefreshSession($req);
3324  
3325 0 ▶ return 1 unless $req->error > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $req->error > 0 0 0 0
3326  
3327 # PE_BADCREDENTIAL is returned by UserDB modules when the user was
3328 # explicitly not found. And not in case of temporary failures
3329 0 ▶ if ( $req->error == PE_BADCREDENTIALS ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->error == 5) { } 0 0 0
3330 0 $self->logger->error( "User: "
3331 . $req->user
3332 . " no longer exists, removing offline session" );
3333 0 $session->remove;
3334 }
3335 else {
3336 0 $self->logger->error( "Could not resolve user: " . $req->user );
3337 }
3338 0 return 0;
3339 }
3340  
3341 # Change the ID of secondary sessions (during upgrade)
3342 sub updateOidcSecondarySessions {
3343 0 ▶ my ( $self, $req, $old_session_id, $new_session_id ) = @_;
Subroutine updateOidcSecondarySessions: not called CC=4 SCAR=30.0
Pod undocumented
3344  
3345 0 my $module = "Lemonldap::NG::Common::Apache::Session";
3346  
3347 0 my %opts = $self->_storeOpts;
3348 0 my $options = $opts{storageModuleOptions};
3349 0 $options->{backend} = $opts{storageModule};
3350  
3351 0 my $oidc_sessions =
3352 $module->searchOn( $options, "user_session_id", $old_session_id );
3353  
3354 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (my(@oidc_sessions_keys) = grep({$oidc_sessions->{$_}{"_session_kind"} eq $self->sessionKind;} keys %$oidc_sessions)) 0 0 0
3355 my @oidc_sessions_keys =
3356 0 grep { $oidc_sessions->{$_}->{_session_kind} eq $self->sessionKind }
3357 keys %$oidc_sessions
3358 )
3359 {
3360  
3361 0 foreach my $oidc_session (@oidc_sessions_keys) {
3362  
3363 # Get session
3364 0 $self->logger->debug("Retrieve OIDC session $oidc_session");
3365  
3366 0 my $oidcSession = $self->getOpenIDConnectSession( $oidc_session, '',
3367 hashStore => 0 );
3368  
3369 0 ▶ if ($oidcSession) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidcSession) 0 0 0
3370  
3371 # Delete session
3372 0 $oidcSession->update( { user_session_id => $new_session_id } );
3373 }
3374 }
3375 }
3376  
3377 0 return;
3378 }
3379  
3380 24 1;
« blib/lib/Lemonldap/NG/Portal/Lib/Net/LDAP.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Issuer/CAS.pm »