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

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