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

filter: Statementstmt 68.3% 858 / 1255 Branchbran 45.4% 279 / 614 Conditioncond 43.2% 106 / 245 MC/DCmcdc 16.6% 23 / 138 Subroutinesub 86.8% 112 / 129 Podpod 46.8% 37 / 79 totaltotal 57.5% 1415 / 2460 CC 423 SCAR 39.2
CC
423
Cov
59%
getEndPointAuthenticationCredentials
335.5
refreshAccessToken
132.0
checkEndPointAuthenticationCredentials
128.2
CRAP 50.6
« blib/lib/Lemonldap/NG/Portal/Password/Base.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Plugins/CheckHIBP.pm »
1 ## @file
2 # Common OpenID Connect functions
3  
4 ## @class
5 # Common OpenID Connect functions
6 package Lemonldap::NG::Portal::Lib::OpenIDConnect;
7  
8 55 ▶use Mouse;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 55 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 55 ▶use Crypt::URandom;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 55 ▶use Crypt::OpenSSL::RSA;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 55 ▶use Crypt::OpenSSL::X509;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 55 ▶use Crypt::JWT qw(encode_jwt decode_jwt);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 55 ▶use Digest::SHA qw/sha1 hmac_sha256_base64 sha256 sha384 sha512 sha256_base64/;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 55 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 55 ▶use Lemonldap::NG::Common::FormEncode;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 55 ▶use Lemonldap::NG::Common::OpenIDConnect::Constants;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 55 ▶use Lemonldap::NG::Common::Session 'id2storage';
Subroutine BEGIN: called CC=1 SCAR=0.0
19 55 ▶use Lemonldap::NG::Common::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 use Lemonldap::NG::Common::JWT
21 55 ▶ qw(getAccessTokenSessionId getJWTPayload getJWTHeader getJWTSignature getJWTSignedData);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 use MIME::Base64
23 55 ▶ qw/encode_base64 decode_base64 encode_base64url decode_base64url/;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 55 ▶use Scalar::Util qw/looks_like_number/;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 55 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 55 ▶use URI::Escape qw(uri_unescape);
Subroutine BEGIN: called CC=1 SCAR=0.0
27 55 ▶use URI::QueryParam;
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 use Lemonldap::NG::Portal::Main::Constants
30 55 ▶ qw(PE_OK PE_REDIRECT PE_ERROR portalConsts);
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 55 our $VERSION = '2.23.4';
33  
34 55 ▶use constant oidcErrorLevel => {
Subroutine BEGIN: called CC=1 SCAR=0.0
35 server_error => 'error',
36 invalid_request => 'warn',
37 consent_required => 'notice',
38 55 };
39  
40 # PROPERTIES
41  
42 160 ▶has opAttributes => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
43 160 ▶has opMetadata => ( is => 'rw', default => sub { {} }, );
Subroutine __ANON__: called CC=1 SCAR=0.0
44 160 ▶has opOptions => ( is => 'rw', default => sub { {} }, );
Subroutine __ANON__: called CC=1 SCAR=0.0
45 160 ▶has opRules => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
46 160 ▶has rpAttributes => ( is => 'rw', default => sub { {} }, );
Subroutine __ANON__: called CC=1 SCAR=0.0
47 160 ▶has rpMacros => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
48 160 ▶has rpOptions => ( is => 'rw', default => sub { {} }, );
Subroutine __ANON__: called CC=1 SCAR=0.0
49 160 ▶has rpRules => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
50 160 ▶has rpLevelRules => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
51 160 ▶has rpScopes => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
52 160 ▶has rpScopeRules => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
53 160 ▶has rpEncKey => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
54 160 ▶has rpSigKey => ( is => 'rw', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
55  
56 # Deprecated names, remove in 3.0
57 55 *oidcOPList = \&opMetadata;
58 55 *oidcRPList = \&rpOptions;
59 55 *spMacros = \&rpMacros;
60 55 *spRules = \&rpRules;
61 55 *spScopeRules = \&rpScopeRules;
62  
63 # return LWP::UserAgent object
64 has ua => (
65 is => 'rw',
66 lazy => 1,
67 16 ▶ builder => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
68 16 my $ua = Lemonldap::NG::Common::UserAgent->new( $_[0]->{conf} );
69 16 $ua->env_proxy();
70 16 return $ua;
71 }
72 55 );
73  
74 has state_ott => (
75 is => 'rw',
76 lazy => 1,
77 46 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
78 46 my $ott = $_[0]->{p}->loadModule('::Lib::OneTimeToken');
79 $ott->timeout( $_[0]->conf->{oidcRPStateTimeout}
80 46 ▶ || $_[0]->conf->{timeout} );
Condition33%1/3
$_[0]->conf->{'oidcRPStateTimeout'} || $_[0]->conf->{'timeout'}
l!l&&r!l&&!r
4600
MC/DC0%0/2
$_[0]->conf->{'oidcRPStateTimeout'} || $_[0]->conf->{'timeout'}
$_[0]->conf->{'oidcRPStateTimeout'} $_[0]->conf->{'timeout'}
Truth table33%1/3
A || B
A= $_[0]->conf->{'oidcRPStateTimeout'}B= $_[0]->conf->{'timeout'}
ABresult
1X1
011
000
81 46 return $ott;
82 }
83 55 );
84  
85 # Calculate conditional plugins to be loaded if required by a dynamic RP
86 has _rpConditionalPlugins => (
87 is => 'ro',
88 lazy => 1,
89 54 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
90 54 my %map;
91 54 ▶ for ( my $i = 0 ; $i < @Lemonldap::NG::Portal::Main::pList ; $i += 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @Lemonldap::NG::Portal::Main::pList) 2214 54 2268
92 2214 ▶ if ( $Lemonldap::NG::Portal::Main::pList[$i] =~
Branch: 1 branch
BranchTrueFalseTotal
if ($Lemonldap::NG::Portal::Main::pList[$i] =~ m[^or::oidcRPMetaDataOptions/\*/(.+)$]) 216 1998 2214
93 m{^or::oidcRPMetaDataOptions/\*/(.+)$} )
94 {
95 216 $map{$1} = $Lemonldap::NG::Portal::Main::pList[ $i + 1 ];
96 }
97 }
98 54 return \%map;
99 }
100 55 );
101  
102 # METHODS
103  
104 # Load OpenID Connect Providers and JWKS data
105 # @param no_cache Disable cache use
106 # @return boolean result
107 97 ▶sub loadOPs {
Subroutine loadOPs: called CC=8 SCAR=24.8
Pod documented
108 97 my ($self) = @_;
109  
110 # Check cache
111 # Check presence of at least one identity provider in configuration
112 97 ▶ unless ( $self->conf->{oidcOPMetaDataJSON}
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->conf->{"oidcOPMetaDataJSON"} and keys %{$self->conf->{"oidcOPMetaDataJSON"};}) 0 97 97
Condition33%1/3
$self->conf->{"oidcOPMetaDataJSON"} and keys %{$self->conf->{"oidcOPMetaDataJSON"};}
!ll&&!rl&&r
0097
MC/DC0%0/2
$self->conf->{"oidcOPMetaDataJSON"} and keys %{$self->conf->{"oidcOPMetaDataJSON"};}
$self->conf->{"oidcOPMetaDataJSON"} keys %{$self->conf->{"oidcOPMetaDataJSON"};}
Truth table33%1/3
A and B
A= $self->conf->{"oidcOPMetaDataJSON"}B= keys %{$self->conf->{"oidcOPMetaDataJSON"};}
ABresult
0X0
100
111
113 97 and keys %{ $self->conf->{oidcOPMetaDataJSON} } )
114 {
115 0 $self->logger->warn(
116 "No OpenID Connect Provider found in configuration");
117 0 return 1;
118 }
119  
120 # Extract JSON data
121 97 foreach ( keys %{ $self->conf->{oidcOPMetaDataJSON} } ) {
122 my $op_conf =
123 101 $self->decodeJSON( $self->conf->{oidcOPMetaDataJSON}->{$_} );
124 101 ▶ if ($op_conf) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op_conf) { } 101 0 101
125 101 $self->opMetadata->{$_}->{conf} = $op_conf;
126 $self->opMetadata->{$_}->{jwks} =
127 101 $self->decodeJSON( $self->conf->{oidcOPMetaDataJWKS}->{$_} );
128 }
129 else {
130 0 $self->logger->warn("Could not parse OIDC metadata for $_");
131 }
132 }
133  
134 # Set rule
135 97 foreach ( keys %{ $self->conf->{oidcOPMetaDataOptions} } ) {
136 $self->opAttributes->{$_} =
137 101 $self->conf->{oidcOPMetaDataExportedVars}->{$_};
138 101 $self->opOptions->{$_} = $self->conf->{oidcOPMetaDataOptions}->{$_};
139 my $cond =
140 101 $self->opOptions->{$_}->{oidcOPMetaDataOptionsResolutionRule};
141 101 ▶ if ( length $cond ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $cond) 0 101 101
142 0 my $rule_sub =
143 $self->p->buildRule( $cond, "OIDC provider resolution" );
144 0 ▶ if ($rule_sub) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rule_sub) 0 0 0
145 0 $self->opRules->{$_} = $rule_sub;
146 }
147 }
148 }
149  
150 97 return 1;
151 }
152  
153 # Load a single RP from LLNG configuration
154 65 ▶sub load_rp_from_llng_conf {
Subroutine load_rp_from_llng_conf: called CC=1 SCAR=0.0
Pod undocumented
155 65 my ( $self, $rp ) = @_;
156  
157 return $self->load_rp(
158 confKey => $rp,
159 extraClaims => $self->conf->{oidcRPMetaDataOptionsExtraClaims}->{$rp},
160 options => $self->conf->{oidcRPMetaDataOptions}->{$rp},
161 macros => $self->conf->{oidcRPMetaDataMacros}->{$rp},
162 scopeRules => $self->conf->{oidcRPMetaDataScopeRules}->{$rp},
163 65 attributes => $self->conf->{oidcRPMetaDataExportedVars}->{$rp},
164 );
165 }
166  
167 65 ▶sub load_rp {
Subroutine load_rp: called CC=46 SCAR=45.6
Pod undocumented
168 65 my ( $self, %config ) = @_;
169 65 my $rp = $config{confKey};
170  
171 # Check if RP is activated
172 65 ▶ unless ( $config{options}->{oidcRPMetaDataOptionsActivation} // 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($config{"options"}{"oidcRPMetaDataOptionsActivation"} // 1) 1 64 65
Condition100%2/2
$config{"options"}{"oidcRPMetaDataOptionsActivation"} // 1
l!l
263
MC/DC100%1/1
$config{"options"}{"oidcRPMetaDataOptionsActivation"} // 1
$config{"options"}{"oidcRPMetaDataOptionsActivation"}
Truth table100%2/2
A
A= $config{"options"}{"oidcRPMetaDataOptionsActivation"}
Aresult
11
00
173 1 $self->logger->debug("Processing $rp: RP Deactivated");
174 1 return 0;
175 }
176  
177 64 my $valid = 1;
178  
179 # Handle scopes
180 # this HAS to be a deep copy of the DEFAULT_SCOPES hashref!
181 64 my $scope_values = { %{ DEFAULT_SCOPES() } };
182  
183 # Additional claims
184 64 my $extraClaims = $config{extraClaims};
185 64 ▶ if ($extraClaims) {
Branch: 1 branch
BranchTrueFalseTotal
if ($extraClaims) 2 62 64
186 2 $self->logger->debug("Processing extra claims for RP $rp...");
187 2 foreach my $scope ( keys %$extraClaims ) {
188 2 $self->logger->debug("Processing scope value $scope for RP $rp...");
189 2 my @extraAttributes = split( /\s/, $extraClaims->{$scope} );
190 2 $scope_values->{$scope} = \@extraAttributes;
191 }
192 }
193  
194 # Access rule
195 64 my $rule = $config{options}->{oidcRPMetaDataOptionsRule};
196 64 ▶ if ( length $rule ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $rule) 3 61 64
197 3 $self->logger->debug("Processing access rule for RP $rp...");
198 3 $rule = $self->p->buildRule( $rule, "access rule for RP $rp" );
199 3 ▶ unless ($rule) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rule) 0 3 3
200 0 $valid = 0;
201 }
202 }
203  
204 # Required authentication level rule
205 my $levelrule =
206 $config{options}->{oidcRPMetaDataOptionsAuthnLevel}
207 || $self->conf->{defaultAuthnLevel}
208 64 ▶ || 0;
Condition40%2/5
$config{'options'}{'oidcRPMetaDataOptionsAuthnLevel'} || $self->conf->{'defaultAuthnLevel'} || 0
l!l
064
$config{"options"}{"oidcRPMetaDataOptionsAuthnLevel"} or $self->conf->{"defaultAuthnLevel"}
l!l&&r!l&&!r
0064
MC/DC0%0/2
$config{'options'}{'oidcRPMetaDataOptionsAuthnLevel'} || $self->conf->{'defaultAuthnLevel'} || 0
$config{"options"}{"oidcRPMetaDataOptionsAuthnLevel"} $self->conf->{"defaultAuthnLevel"}
Truth table33%1/3
A or B
A= $config{"options"}{"oidcRPMetaDataOptionsAuthnLevel"}B= $self->conf->{"defaultAuthnLevel"}
ABresult
1X1
011
000
209 64 $levelrule = $self->p->buildRule( $levelrule,
210 "Required authentication level rule for RP $rp" );
211 64 ▶ unless ($levelrule) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($levelrule) 0 64 64
212 0 $valid = 0;
213 }
214  
215 # Load per-RP macros
216 64 my $macros = $config{macros};
217 64 my $compiledMacros = {};
218 64 for my $macroAttr ( keys %{$macros} ) {
219 12 my $macroRule = $macros->{$macroAttr};
220 12 ▶ if ( length $macroRule ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $macroRule) 12 0 12
221 12 $self->logger->debug("Processing macros for RP $rp...");
222 12 $macroRule = $self->p->HANDLER->substitute($macroRule);
223 12 ▶ if ( $macroRule = $self->p->HANDLER->buildSub($macroRule) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($macroRule = $self->p->HANDLER->buildSub($macroRule)) { } 12 0 12
224 12 $compiledMacros->{$macroAttr} = $macroRule;
225 }
226 else {
227 $self->logger->error(
228 "Unable to build macro $macroAttr for RP $rp:"
229 0 . $self->p->HANDLER->tsv->{jail}->error );
230 0 $valid = 0;
231 }
232 }
233 }
234  
235 # Load per-RP dynamic scopes
236 64 my $scope_rules = $config{scopeRules};
237 64 my $compiled_scope_rules = {};
238 64 for my $scopeName ( keys %{$scope_rules} ) {
239 0 my $scopeRule = $scope_rules->{$scopeName};
240 0 ▶ if ( length $scopeRule ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $scopeRule) 0 0 0
241 0 $self->logger->debug("Processing dynamic scopes for RP $rp...");
242 0 $scopeRule = $self->p->HANDLER->substitute($scopeRule);
243 0 ▶ if ( $scopeRule = $self->p->HANDLER->buildSub($scopeRule) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($scopeRule = $self->p->HANDLER->buildSub($scopeRule)) { } 0 0 0
244 0 $compiled_scope_rules->{$scopeName} = $scopeRule;
245 }
246 else {
247 $self->logger->error(
248 "Unable to build scope $scopeName for RP $rp:"
249 0 . $self->p->HANDLER->tsv->{jail}->error );
250 0 $valid = 0;
251 }
252 }
253 }
254 64 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($valid and $config{"options"}{"oidcRPMetaDataOptionsJwksUri"} || $config{"options"}{"oidcRPMetaDataOptionsJwks"}) 12 52 64
Condition66%4/6
$valid and $config{"options"}{"oidcRPMetaDataOptionsJwksUri"} || $config{"options"}{"oidcRPMetaDataOptionsJwks"}
!ll&&!rl&&r
05212
$config{"options"}{"oidcRPMetaDataOptionsJwksUri"} or $config{"options"}{"oidcRPMetaDataOptionsJwks"}
l!l&&r!l&&!r
12052
MC/DC33%1/3
$valid and $config{"options"}{"oidcRPMetaDataOptionsJwksUri"} || $config{"options"}{"oidcRPMetaDataOptionsJwks"}
$valid $config{"options"}{"oidcRPMetaDataOptionsJwksUri"} $config{"options"}{"oidcRPMetaDataOptionsJwks"}
Truth table50%2/4
A and B or C
A= $validB= $config{"options"}{"oidcRPMetaDataOptionsJwksUri"}C= $config{"options"}{"oidcRPMetaDataOptionsJwks"}
ABCresult
0XX0
1000
11X1
1011
255 $valid
256 and ( $config{options}->{oidcRPMetaDataOptionsJwksUri}
257 or $config{options}->{oidcRPMetaDataOptionsJwks} )
258 )
259 {
260 12 $self->logger->debug("Processing JWKS options for RP $rp");
261 12 my $jwks = $config{options}->{oidcRPMetaDataOptionsJwks};
262 12 ▶ $jwks = $self->decodeJSON($jwks) if $jwks and not ref $jwks;
Branch: 1 branch
BranchTrueFalseTotal
if $jwks and not ref $jwks 2 10 12
Condition66%2/3
$jwks and not ref $jwks
!ll&&!rl&&r
1002
MC/DC50%1/2
$jwks and not ref $jwks
$jwks not ref $jwks
Truth table66%2/3
A and not(B)
A= $jwksB= not ref $jwks
ABresult
0X0
100
111
263  
264 12 ▶ if ( !$jwks
Branch: 1 branch
BranchTrueFalseTotal
if (not $jwks and my $url = $config{"options"}{"oidcRPMetaDataOptionsJwksUri"}) 10 2 12
Condition66%2/3
not $jwks and my $url = $config{"options"}{"oidcRPMetaDataOptionsJwksUri"}
!ll&&!rl&&r
2010
MC/DC50%1/2
not $jwks and my $url = $config{"options"}{"oidcRPMetaDataOptionsJwksUri"}
not $jwks my $url = $config{"options"}{"oidcRPMetaDataOptionsJwksUri"}
Truth table66%2/3
not(A) and B
A= not $jwksB= my $url = $config{"options"}{"oidcRPMetaDataOptionsJwksUri"}
ABresult
0X0
100
111
265 and my $url = $config{options}->{oidcRPMetaDataOptionsJwksUri} )
266 {
267 10 $self->logger->debug("Fetching JWKS URL: $url for RP $rp");
268 10 my $resp = $self->ua->get($url);
269 10 ▶ if ( $resp->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->is_success) { } 10 0 10
270 10 my $content = $self->decodeJSON( $resp->decoded_content );
271 10 ▶ if ( $content and ref($content) eq 'HASH' and $content->{keys} )
Branch: 1 branch
BranchTrueFalseTotal
if ($content and ref $content eq 'HASH' and $content->{'keys'}) { } 10 0 10
Condition33%2/6
$content and ref $content eq "HASH" and $content->{"keys"}
!ll&&!rl&&r
0010
$content and ref $content eq "HASH"
!ll&&!rl&&r
0010
MC/DC0%0/3
$content and ref $content eq "HASH" and $content->{"keys"}
$content ref $content eq "HASH" $content->{"keys"}
Truth table25%1/4
A and B and C
A= $contentB= ref $content eq "HASH"C= $content->{"keys"}
ABCresult
0XX0
10X0
1100
1111
272 {
273 10 $jwks = $content;
274 }
275 else {
276 0 $self->logger->error("Invalid response from $url");
277 0 $valid = 0;
278 }
279 }
280 else {
281 0 $self->logger->error( "Unable to fetch RP keys from $url: "
282 . $resp->status_line );
283 0 $valid = 0;
284 }
285 }
286 12 ▶ if ( $jwks and ref($jwks) eq 'HASH' and $jwks->{keys} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($jwks and ref $jwks eq 'HASH' and $jwks->{'keys'}) { } 12 0 12
Condition33%2/6
$jwks and ref $jwks eq "HASH" and $jwks->{"keys"}
!ll&&!rl&&r
0012
$jwks and ref $jwks eq "HASH"
!ll&&!rl&&r
0012
MC/DC0%0/3
$jwks and ref $jwks eq "HASH" and $jwks->{"keys"}
$jwks ref $jwks eq "HASH" $jwks->{"keys"}
Truth table25%1/4
A and B and C
A= $jwksB= ref $jwks eq "HASH"C= $jwks->{"keys"}
ABCresult
0XX0
10X0
1100
1111
287 12 $self->logger->debug("Processing JWKS document for RP $rp");
288 12 my %keys;
289 my %validKeys;
290 12 foreach my $key ( sort @{ $jwks->{keys} } ) {
291 14 my $type = lc( $key->{use} );
292 14 ▶ next unless $type =~ /^(?:enc|sig)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $type =~ /^(?:enc|sig)$/ 0 14 14
293 $key->{alg} = 'RSA-OAEP'
294 14 ▶ if !$key->{alg} and $key->{kty} eq 'RSA';
Branch: 1 branch
BranchTrueFalseTotal
if not $key->{"alg"} and $key->{"kty"} eq "RSA" 8 6 14
Condition100%3/3
not $key->{"alg"} and $key->{"kty"} eq "RSA"
!ll&&!rl&&r
428
MC/DC100%2/2
not $key->{"alg"} and $key->{"kty"} eq "RSA"
not $key->{"alg"} $key->{"kty"} eq "RSA"
Truth table100%3/3
not(A) and B
A= not $key->{"alg"}B= $key->{"kty"} eq "RSA"
ABresult
0X0
100
111
295 $key->{alg} = 'ES256'
296 14 ▶ if !$key->{alg} and $key->{kty} eq 'EC';
Branch: 1 branch
BranchTrueFalseTotal
if not $key->{"alg"} and $key->{"kty"} eq "EC" 2 12 14
Condition66%2/3
not $key->{"alg"} and $key->{"kty"} eq "EC"
!ll&&!rl&&r
1202
MC/DC50%1/2
not $key->{"alg"} and $key->{"kty"} eq "EC"
not $key->{"alg"} $key->{"kty"} eq "EC"
Truth table66%2/3
not(A) and B
A= not $key->{"alg"}B= $key->{"kty"} eq "EC"
ABresult
0X0
100
111
297 14 ▶ if ( $type eq 'sig' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "sig") 10 4 14
298 10 push @{ $validKeys{sig} }, $key;
299 }
300 14 ▶ if ( $key->{alg} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key->{'alg'}) { } 14 0 14
301 14 ▶ $keys{ $key->{alg} } ||= $key;
Condition33%1/3
$keys{$key->{"alg"}} ||= $key
l!l&&r!l&&!r
0140
MC/DC0%0/2
$keys{$key->{"alg"}} ||= $key
$keys{$key->{"alg"}} $key
Truth table33%1/3
A ||= B
A= $keys{$key->{"alg"}}B= $key
ABresult
1X1
011
000
302 }
303 else {
304 0 $self->logger->warn('Unable to find "alg" field in RP key');
305 }
306 }
307 12 foreach my $alg ( @{&ENC_ALG_SUPPORTED} ) {
308 60 ▶ if ( $keys{$alg} and $keys{$alg}->{use} eq 'enc' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keys{$alg} and $keys{$alg}{"use"} eq "enc") 4 56 60
Condition100%3/3
$keys{$alg} and $keys{$alg}{"use"} eq "enc"
!ll&&!rl&&r
4884
MC/DC100%2/2
$keys{$alg} and $keys{$alg}{"use"} eq "enc"
$keys{$alg} $keys{$alg}{"use"} eq "enc"
Truth table100%3/3
A and B
A= $keys{$alg}B= $keys{$alg}{"use"} eq "enc"
ABresult
0X0
100
111
309 4 $self->logger->debug(
310 "Found encryption key with algorith $alg");
311 4 $validKeys{enc}{$alg} = $keys{$alg};
312 4 last;
313 }
314 }
315 12 ▶ unless (%validKeys) {
Branch: 1 branch
BranchTrueFalseTotal
if (%validKeys) { } 12 0 12
316 0 $self->logger->error(
317 "Unable to find a supported key for RP $rp");
318 0 $valid = 0;
319 }
320 else {
321 $self->rpEncKey->{$rp} = { keys => $validKeys{enc} }
322 12 ▶ if $validKeys{enc};
Branch: 1 branch
BranchTrueFalseTotal
if $validKeys{"enc"} 4 8 12
323 $self->rpSigKey->{$rp} = { keys => $validKeys{sig} }
324 12 ▶ if $validKeys{sig};
Branch: 1 branch
BranchTrueFalseTotal
if $validKeys{"sig"} 8 4 12
325 }
326 }
327 else {
328 0 $self->logger->error('Malformed JWKS document');
329 0 $valid = 0;
330 }
331 }
332 64 ▶ if ($valid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($valid) { } 64 0 64
333 64 $self->logger->debug(" -> RP $rp is valid");
334  
335 # Register RP
336 64 $self->rpOptions->{$rp} = $config{options};
337 64 $self->rpAttributes->{$rp} = $config{attributes};
338 64 $self->rpScopes->{$rp} = $scope_values;
339 64 $self->rpMacros->{$rp} = $compiledMacros;
340 64 $self->rpScopeRules->{$rp} = $compiled_scope_rules;
341 64 $self->rpRules->{$rp} = $rule;
342 64 $self->rpLevelRules->{$rp} = $levelrule;
343  
344 # Ensure plugins required by this RP's options are loaded (#3587)
345 64 $self->_loadConditionalPlugins( $config{options} );
346  
347 64 return 1;
348 }
349 else {
350 0 $self->logger->debug(" -> RP $rp is NOT valid");
351 0 $self->logger->error(
352 "Relying Party $rp has errors and will be ignored");
353 }
354 0 return 0;
355 }
356  
357 # Plugins that must be loaded when specific RP options are enabled (#3587)
358 # Built from @Lemonldap::NG::Portal::Main::pList entries matching
359 # or::oidcRPMetaDataOptions/*/...
360 64 ▶sub _loadConditionalPlugins {
Subroutine _loadConditionalPlugins: called CC=5 SCAR=16.2
361 64 my ( $self, $options ) = @_;
362  
363 64 ▶ while ( my ( $opt, $plugin ) = each %{ $self->_rpConditionalPlugins } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$self->_rpConditionalPlugins;}) 256 64 320
364 256 ▶ next unless $options->{$opt};
Branch: 1 branch
BranchTrueFalseTotal
unless $options->{$opt} 249 7 256
365 7 ▶ my $full =
Branch: 1 branch
BranchTrueFalseTotal
$plugin =~ /^::/ ? : 7 0 7
366 ( $plugin =~ /^::/ ) ? "Lemonldap::NG::Portal$plugin" : $plugin;
367 7 ▶ next if $self->p->loadedModules->{$full};
Branch: 1 branch
BranchTrueFalseTotal
if $self->p->loadedModules->{$full} 0 7 7
368 7 $self->logger->info(
369 "Dynamically loading plugin $plugin for RP option $opt");
370 7 $self->p->loadPlugin($plugin);
371 }
372 }
373  
374 # Refresh JWKS data if needed
375 # @param no_cache Disable cache update
376 # @return boolean result
377 49 ▶sub refreshJWKSdata {
Subroutine refreshJWKSdata: called CC=4 SCAR=15.5
Pod documented
378 49 my ($self) = @_;
379  
380 49 ▶ unless ( $self->conf->{oidcOPMetaDataJSON}
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->conf->{"oidcOPMetaDataJSON"} and keys %{$self->conf->{"oidcOPMetaDataJSON"};}) 0 49 49
Condition33%1/3
$self->conf->{"oidcOPMetaDataJSON"} and keys %{$self->conf->{"oidcOPMetaDataJSON"};}
!ll&&!rl&&r
0049
MC/DC0%0/2
$self->conf->{"oidcOPMetaDataJSON"} and keys %{$self->conf->{"oidcOPMetaDataJSON"};}
$self->conf->{"oidcOPMetaDataJSON"} keys %{$self->conf->{"oidcOPMetaDataJSON"};}
Truth table33%1/3
A and B
A= $self->conf->{"oidcOPMetaDataJSON"}B= keys %{$self->conf->{"oidcOPMetaDataJSON"};}
ABresult
0X0
100
111
381 49 and keys %{ $self->conf->{oidcOPMetaDataJSON} } )
382 {
383 0 $self->logger->debug(
384 "No OpenID Provider configured, JWKS data will not be refreshed");
385 0 return 1;
386 }
387  
388 49 foreach ( keys %{ $self->conf->{oidcOPMetaDataJSON} } ) {
389 51 $self->refreshJWKSdataForOp($_);
390 }
391 49 return 1;
392 }
393  
394 53 ▶sub refreshJWKSdataForOp {
Subroutine refreshJWKSdataForOp: called CC=7 SCAR=19.8
Pod undocumented
395 53 my ( $self, $op, $force ) = @_;
396  
397 53 $self->logger->debug("Attempting to refresh JWKS data for $op");
398  
399 # Refresh JWKS data if
400 # 1/ oidcOPMetaDataOptionsJWKSTimeout > 0
401 # 2/ jwks_uri defined in metadata
402  
403 my $jwksTimeout =
404 53 $self->opOptions->{$op}->{oidcOPMetaDataOptionsJWKSTimeout};
405 53 my $jwksUri = $self->opMetadata->{$op}->{conf}->{jwks_uri};
406  
407 53 ▶ unless ($jwksUri) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($jwksUri) 45 8 53
408 45 $self->logger->debug("No JWKS URI defined for $op, skipping...");
409 45 return;
410 }
411  
412 8 ▶ if ( !$force ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($force) 8 0 8
413 8 ▶ unless ($jwksTimeout) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($jwksTimeout) 6 2 8
414 6 $self->logger->debug(
415 "No JWKS refresh timeout defined for $op, skipping...");
416 6 return;
417 }
418  
419 2 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($self->opMetadata->{$op}{"jwks"}{"time"} and $self->opMetadata->{$op}{"jwks"}{"time"} + $jwksTimeout > &CORE::GLOBAL::time()) 0 2 2
Condition33%1/3
$self->opMetadata->{$op}{"jwks"}{"time"} and $self->opMetadata->{$op}{"jwks"}{"time"} + $jwksTimeout > &CORE::GLOBAL::time()
!ll&&!rl&&r
200
MC/DC0%0/2
$self->opMetadata->{$op}{"jwks"}{"time"} and $self->opMetadata->{$op}{"jwks"}{"time"} + $jwksTimeout > &CORE::GLOBAL::time()
$self->opMetadata->{$op}{"jwks"}{"time"} $self->opMetadata->{$op}{"jwks"}{"time"} + $jwksTimeout > &CORE::GLOBAL::time()
Truth table33%1/3
A and B
A= $self->opMetadata->{$op}{"jwks"}{"time"}B= $self->opMetadata->{$op}{"jwks"}{"time"} + $jwksTimeout > &CORE::GLOBAL::time()
ABresult
0X0
100
111
420 $self->opMetadata->{$op}->{jwks}->{time}
421 && (
422 $self->opMetadata->{$op}->{jwks}->{time} + $jwksTimeout > time )
423 )
424 {
425 0 $self->logger->debug("JWKS data still valid for $op, skipping...");
426 0 return;
427 }
428 }
429  
430 2 $self->logger->debug("Refresh JWKS data for $op from $jwksUri");
431  
432 2 my $response = $self->ua->get($jwksUri);
433  
434 2 ▶ if ( $response->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_error) 1 1 2
435 1 $self->logger->warn(
436 "Unable to get JWKS data for $op from $jwksUri: "
437 . $response->message );
438 1 $self->logger->debug(
439 "JWKS response received: " . $response->as_string );
440 1 return;
441 }
442  
443 1 my $content = $self->decodeJSON( $response->decoded_content );
444  
445 1 $self->opMetadata->{$op}->{jwks} = $content;
446 1 $self->opMetadata->{$op}->{jwks}->{time} = time;
447  
448 1 return 1;
449 }
450  
451 # Compute callback URI
452 # @return String Callback URI
453 10 ▶sub getCallbackUri {
Subroutine getCallbackUri: called CC=1 SCAR=0.0
Pod documented
454 10 my ( $self, $req ) = @_;
455  
456 10 my $callback_get_param = $self->conf->{oidcRPCallbackGetParam};
457 10 my $callback_uri =
458 $self->p->buildUrl( $req->portal, { $callback_get_param => 1 } );
459  
460 10 $self->logger->debug("OpenIDConnect Callback URI: $callback_uri");
461 10 return $callback_uri;
462 }
463  
464 # Build Authentication Request URI for Authorization Code Flow
465 # @param op OpenIP Provider configuration key
466 # @param state State
467 # return String Authentication Request URI
468 134 ▶sub buildAuthorizationCodeAuthnRequest {
Subroutine buildAuthorizationCodeAuthnRequest: called CC=28 SCAR=37.2
Pod documented
469 134 my ( $self, $req, $op, $state, $nonce ) = @_;
470 my $authMode =
471 134 $self->opOptions->{$op}->{oidcOPMetaDataOptionsAuthnEndpointAuthMethod};
472  
473 my $authorize_uri =
474 134 $self->opMetadata->{$op}->{conf}->{authorization_endpoint};
475  
476 134 ▶ unless ($authorize_uri) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($authorize_uri) 125 9 134
477 125 $self->logger->error(
478 "Could not build Authorize request: no
479 'authorization_endpoint'" . " in JSON metadata for OP $op"
480 );
481 125 return undef;
482 }
483 9 my $client_id = $self->opOptions->{$op}->{oidcOPMetaDataOptionsClientID};
484 9 my $scope = $self->opOptions->{$op}->{oidcOPMetaDataOptionsScope};
485 9 my $response_type = "code";
486 9 my $redirect_uri = $self->getCallbackUri($req);
487 9 my $display = $self->opOptions->{$op}->{oidcOPMetaDataOptionsDisplay};
488 9 my $prompt = $self->opOptions->{$op}->{oidcOPMetaDataOptionsPrompt};
489 9 my $max_age = $self->opOptions->{$op}->{oidcOPMetaDataOptionsMaxAge};
490 9 my $ui_locales = $self->opOptions->{$op}->{oidcOPMetaDataOptionsUiLocales};
491 9 my $acr_values = $self->opOptions->{$op}->{oidcOPMetaDataOptionsAcrValues};
492 9 my $login_hint = $req->data->{suggestedLogin};
493  
494 9 ▶ my $authorize_request_oauth2_params = {
Branch: 3 branches
BranchTrueFalseTotal
defined $state ? : 9 0 9
defined $nonce ? : 6 3 9
defined $login_hint ? : 0 9 9
495 response_type => $response_type,
496 client_id => $client_id,
497 scope => $scope,
498 redirect_uri => $redirect_uri,
499 ( defined $state ? ( state => $state ) : () ),
500 ( defined $nonce ? ( nonce => $nonce ) : () ),
501 ( defined $login_hint ? ( login_hint => $login_hint ) : () ),
502 };
503  
504 9 my %custom_request_params;
505 9 ▶ while (
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$self->opOptions->{$op}{"oidcOPMetaDataOptionsAuthEndpointExtraParams"} or {};}) 2 9 11
506 my ( $key, $value ) = each %{
507 $self->opOptions->{$op}
508 ->{oidcOPMetaDataOptionsAuthEndpointExtraParams} || {}
509 11 ▶ }
Condition100%2/2
$self->opOptions->{$op}{'oidcOPMetaDataOptionsAuthEndpointExtraParams'} || {}
l!l
38
MC/DC100%1/1
$self->opOptions->{$op}{'oidcOPMetaDataOptionsAuthEndpointExtraParams'} || {}
$self->opOptions->{$op}{'oidcOPMetaDataOptionsAuthEndpointExtraParams'}
Truth table100%2/2
A
A= $self->opOptions->{$op}{'oidcOPMetaDataOptionsAuthEndpointExtraParams'}
Aresult
11
00
510 )
511 {
512  
513 # If the value looks like JSON, decode it
514 2 ▶ if ( $value =~ /^[\[\{]/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /^[\[\{]/) 1 1 2
515 1 my $try_json = eval { from_json($value) };
516 1 ▶ if ( defined($try_json) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $try_json) { } 1 0 1
517 1 $value = $try_json;
518 }
519 else {
520 0 $self->logger->debug(
521 "Unable to decode value for request parameter $key"
522 . " as JSON: $@" );
523 }
524 }
525 2 $custom_request_params{$key} = $value;
526 }
527  
528 9 ▶ my $authorize_request_params = {
Branch: 5 branches
BranchTrueFalseTotal
$display ? : 1 8 9
$prompt ? : 1 8 9
$max_age ? : 3 6 9
defined $ui_locales && length $ui_locales ? : 1 8 9
defined $acr_values && length $acr_values ? : 3 6 9
Condition100%6/6
defined $ui_locales and length $ui_locales
!ll&&!rl&&r
711
defined $acr_values and length $acr_values
!ll&&!rl&&r
513
MC/DC100%2/2
defined $ui_locales and length $ui_locales
defined $ui_locales length $ui_locales
MC/DC100%2/2
defined $acr_values and length $acr_values
defined $acr_values length $acr_values
Truth table100%3/3
A and B
A= defined $ui_localesB= length $ui_locales
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= defined $acr_valuesB= length $acr_values
ABresult
0X0
100
111
529 %$authorize_request_oauth2_params,
530 ( $display ? ( display => $display ) : () ),
531 ( $prompt ? ( prompt => $prompt ) : () ),
532  
533 # MaxAge is defined as an int type in LLNG config,
534 # so 0 means undefined
535 ( $max_age ? ( max_age => $max_age ) : () ),
536 (
537 defined($ui_locales)
538 && length($ui_locales) ? ( ui_locales => $ui_locales ) : ()
539 ),
540 (
541 defined($acr_values)
542 && length($acr_values) ? ( acr_values => $acr_values ) : ()
543 ),
544 %custom_request_params,
545 };
546  
547 # Call oidcGenerateAuthenticationRequest
548 9 my $h = $self->p->processHook(
549 $req, 'oidcGenerateAuthenticationRequest',
550 $op, $authorize_request_params,
551 );
552 9 ▶ return if ( $h != PE_OK );
Branch: 1 branch
BranchTrueFalseTotal
if $h != 0 0 9 9
553  
554 9 ▶ if ( $authMode and $authMode =~ /^jw(?:s|e)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($authMode and $authMode =~ /^jw(?:s|e)$/) 0 9 9
Condition33%1/3
$authMode and $authMode =~ /^jw(?:s|e)$/
!ll&&!rl&&r
900
MC/DC0%0/2
$authMode and $authMode =~ /^jw(?:s|e)$/
$authMode $authMode =~ /^jw(?:s|e)$/
Truth table33%1/3
A and B
A= $authModeB= $authMode =~ /^jw(?:s|e)$/
ABresult
0X0
100
111
555  
556 # Save hook changes if any
557 $authorize_request_oauth2_params->{$_} = $authorize_request_params->{$_}
558 0 foreach ( keys %$authorize_request_oauth2_params );
559 0 my $aud = $authorize_uri;
560 0 $aud =~ s#^(https://[^/]*).*?$#$1#;
561 my $jwt = $self->createJWTForOP( {
562 iss => $client_id,
563 aud => $aud,
564 jti => $self->generateNonce,
565 exp => time + $self->conf->{shortTokenTTL},
566 iat => time,
567 %$authorize_request_params,
568 },
569 $self->opOptions->{$op}
570 0 ▶ ->{oidcOPMetaDataOptionsAuthnEndpointAuthSigAlg} || 'RS256',
Condition0%0/2
$self->opOptions->{$op}{'oidcOPMetaDataOptionsAuthnEndpointAuthSigAlg'} || 'RS256'
l!l
00
MC/DC0%0/1
$self->opOptions->{$op}{'oidcOPMetaDataOptionsAuthnEndpointAuthSigAlg'} || 'RS256'
$self->opOptions->{$op}{'oidcOPMetaDataOptionsAuthnEndpointAuthSigAlg'}
Truth table0%0/2
A
A= $self->opOptions->{$op}{'oidcOPMetaDataOptionsAuthnEndpointAuthSigAlg'}
Aresult
11
00
571 $op
572 );
573 0 ▶ if ($jwt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($jwt) { } 0 0 0
574 0 $authorize_request_params =
575 { %$authorize_request_oauth2_params, request => $jwt };
576 0 ▶ if ( $authMode eq 'jwe' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($authMode eq "jwe") 0 0 0
577 0 $self->logger->error('jwe mode not yet implemented');
578 }
579 }
580 else {
581 0 $self->logger->error(
582 'Unable to generate JWT, continue with unauthenticated query');
583 }
584 }
585  
586 # Make sure request params all contain string data, since hooks or extra
587 # claims may have inserted a complex object
588  
589 9 my %flat_authorize_request_params;
590 9 ▶ while ( my ( $key, $value ) = each %$authorize_request_params ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$authorize_request_params) 62 9 71
591 62 ▶ if ( ref($value) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value) 1 61 62
592 1 my $try_value = eval { to_json($value) };
593 1 my $eval_error = $@;
594 1 ▶ if ( defined($try_value) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $try_value) { } 1 0 1
595 1 $value = $try_value;
596 }
597 else {
598 0 $value = undef;
599 0 $self->logger->warn(
600 "Could not add $key to Authorization request: $eval_error");
601 }
602 }
603  
604 62 ▶ $flat_authorize_request_params{$key} = $value if defined($value);
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 62 0 62
605 }
606  
607 9 ▶ my $authn_uri =
Branch: 1 branch
BranchTrueFalseTotal
$authorize_uri =~ /\?/ ? : 0 9 9
608 $authorize_uri
609 . ( $authorize_uri =~ /\?/ ? '&' : '?' )
610 . build_urlencoded(%flat_authorize_request_params);
611  
612 9 $self->logger->debug(
613 "OpenIDConnect Authorization Code Flow Authn Request: $authn_uri");
614  
615 9 return $authn_uri;
616 }
617  
618 16 ▶sub isResponseModeAllowed {
Subroutine isResponseModeAllowed: called CC=3 SCAR=13.3
Pod undocumented
619 16 my ( $self, $flow, $response_mode ) = @_;
620  
621 # Query encoding can only be used for authorization code flow
622 # cf oauth-v2-multiple-response-types-1_0.html
623 16 ▶ if ( $response_mode and $response_mode eq "query" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response_mode and $response_mode eq "query") 0 16 16
Condition33%1/3
$response_mode and $response_mode eq "query"
!ll&&!rl&&r
1600
MC/DC0%0/2
$response_mode and $response_mode eq "query"
$response_mode $response_mode eq "query"
Truth table33%1/3
A and B
A= $response_modeB= $response_mode eq "query"
ABresult
0X0
100
111
624 0 return ( $flow eq "authorizationcode" );
625 }
626  
627 # Fragment or Form Post are OK for all types
628 # cf oauth-v2-form-post-response-mode-1_0.html
629 16 return 1;
630 }
631  
632 # Build OpenID Connect response
633 # This method does not check if the response mode is allowed for the current
634 # grant type. Use isResponseModeAllowed for that
635 14 ▶sub sendOidcResponse {
Subroutine sendOidcResponse: called CC=5 SCAR=19.7
Pod undocumented
636 14 my ( $self, $req, $flow, $response_mode, $redirect_uri, $response_params )
637 = @_;
638  
639 # RFC 9207: Add iss parameter to prevent mix-up attacks
640 14 $response_params->{iss} = $self->get_issuer($req);
641  
642 14 ▶ $response_mode //= $self->getDefaultResponseModeForFlow($flow);
Condition33%1/3
$response_mode //= $self->getDefaultResponseModeForFlow($flow)
l!l&&r!l&&!r
0140
MC/DC0%0/2
$response_mode //= $self->getDefaultResponseModeForFlow($flow)
$response_mode $self->getDefaultResponseModeForFlow($flow)
Truth table33%1/3
A //= B
A= $response_modeB= $self->getDefaultResponseModeForFlow($flow)
ABresult
1X1
011
000
643  
644 14 ▶ if ( $response_mode eq "query" ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($response_mode eq 'query') { } 13 1 14
elsif ($response_mode eq 'fragment') { } 1 0 1
elsif ($response_mode eq 'form_post') { } 0 0 0
645 13 return $self->sendQueryResponse( $req, $redirect_uri,
646 $response_params );
647 }
648 elsif ( $response_mode eq "fragment" ) {
649 1 return $self->sendFragmentResponse( $req, $redirect_uri,
650 $response_params );
651 }
652 elsif ( $response_mode eq "form_post" ) {
653 0 return $self->sendFormPostResponse( $req, $redirect_uri,
654 $response_params );
655 }
656 else {
657 0 $self->logger->error("Unknown response_mode $response_mode");
658 0 return PE_ERROR;
659 }
660 }
661  
662 14 ▶sub getDefaultResponseModeForFlow {
Subroutine getDefaultResponseModeForFlow: called CC=1 SCAR=0.0
Pod undocumented
663 14 my ( $self, $flow ) = @_;
664 14 my %def_flows = (
665 authorizationcode => "query",
666 implicit => "fragment",
667 hybrid => "fragment",
668 );
669 14 return $def_flows{$flow};
670 }
671  
672 13 ▶sub sendQueryResponse {
Subroutine sendQueryResponse: called CC=1 SCAR=0.0
Pod undocumented
673 13 my ( $self, $req, $redirect_uri, $response_params ) = @_;
674 13 my $response_uri =
675 $self->getQueryResponse( $redirect_uri, $response_params );
676 13 return $self->_redirectToUrl( $req, $response_uri );
677 }
678  
679 1 ▶sub sendFragmentResponse {
Subroutine sendFragmentResponse: called CC=1 SCAR=0.0
Pod undocumented
680 1 my ( $self, $req, $redirect_uri, $response_params ) = @_;
681 1 my $response_uri =
682 $self->getFragmentResponse( $redirect_uri, $response_params );
683 1 return $self->_redirectToUrl( $req, $response_uri );
684 }
685  
686 # Add parameters to the query string of an URI object
687 #
688 # URI::QueryParam::query_param() silently drops the existing query string
689 # when it does not contain any "=" (URI treats it as an "isindex" query).
690 # Keep such parameters, they are part of the registered redirect URI (#3707)
691 # @param uri URI object, modified in place
692 # @param response_params Hashref of parameters to add
693 14 ▶sub _addQueryParams {
Subroutine _addQueryParams: called CC=5 SCAR=17.2
694 14 my ( $self, $uri, $response_params ) = @_;
695  
696 14 my $query = $uri->query;
697 14 ▶ if ( defined $query and length $query and $query !~ /=/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query and length $query and not $query =~ /=/) { } 0 14 14
Condition66%4/6
defined $query and length $query and not $query =~ /=/
!ll&&!rl&&r
1220
defined $query and length $query
!ll&&!rl&&r
1202
MC/DC0%0/3
defined $query and length $query and not $query =~ /=/
defined $query length $query not $query =~ /=/
Truth table50%2/4
A and B and not(C)
A= defined $queryB= length $queryC= not $query =~ /=/
ABCresult
0XX0
10X0
1100
1111
698 0 $uri->query( $query . '&' . build_urlencoded(%$response_params) );
699 }
700 else {
701 $uri->query_param( $_, $response_params->{$_} )
702 14 for ( keys %$response_params );
703 }
704  
705 14 return $uri;
706 }
707  
708 13 ▶sub getQueryResponse {
Subroutine getQueryResponse: called CC=1 SCAR=0.0
Pod undocumented
709 13 my ( $self, $redirect_uri, $response_params ) = @_;
710 13 my $uri = URI->new($redirect_uri);
711 13 $self->_addQueryParams( $uri, $response_params );
712 13 return $uri;
713 }
714  
715 1 ▶sub getFragmentResponse {
Subroutine getFragmentResponse: called CC=1 SCAR=0.0
Pod undocumented
716 1 my ( $self, $redirect_uri, $response_params ) = @_;
717 1 my $uri = URI->new($redirect_uri);
718  
719 # Use a temporary URL so we can use QueryParam features to build the fragment
720 1 my $tmp = URI->new;
721 1 $tmp->query( $uri->fragment );
722 1 $self->_addQueryParams( $tmp, $response_params );
723  
724 1 $uri->fragment( $tmp->query );
725  
726 1 return $uri;
727 }
728  
729 0 ▶sub sendFormPostResponse {
Subroutine sendFormPostResponse: not called CC=1 SCAR=6.9
Pod undocumented
730 0 my ( $self, $req, $redirect_uri, $response_params ) = @_;
731  
732 0 $self->p->clearHiddenFormValue($req);
733 0 $req->postUrl($redirect_uri);
734 0 $req->postFields($response_params);
735 0 $req->steps( ['autoPost'] );
736 0 return PE_OK;
737 }
738  
739 14 ▶sub _redirectToUrl {
Subroutine _redirectToUrl: called CC=1 SCAR=0.0
740 14 my ( $self, $req, $response_url ) = @_;
741  
742 # We must clear hidden form fields saved from the request (#2085)
743 14 $self->p->clearHiddenFormValue($req);
744 14 $self->logger->debug("Redirect user to $response_url");
745 14 $req->urldc($response_url);
746  
747 14 return PE_REDIRECT;
748 }
749  
750 # Build Authentication Response URI for Authorization Code Flow
751 # DEPRECATED, remove in 3.0, use sendOidcResponse instead
752 # @param redirect_uri Redirect URI
753 # @param code Code
754 # @param state State
755 # @param session_state Session state
756 # return String Authentication Response URI
757 0 ▶sub buildAuthorizationCodeAuthnResponse {
Subroutine buildAuthorizationCodeAuthnResponse: not called CC=3 SCAR=24.8
Pod documented
758 0 my ( $self, $redirect_uri, $code, $state, $session_state ) = @_;
759  
760 0 ▶ return $self->getQueryResponse(
Branch: 2 branches
BranchTrueFalseTotal
$state ? : 0 0 0
$session_state ? : 0 0 0
761 $redirect_uri,
762 {
763 code => $code,
764 ( $state ? ( state => $state ) : () ),
765 ( $session_state ? ( session_state => $session_state ) : () )
766 }
767 );
768 }
769  
770 # Build Authentication Response URI for Implicit Flow
771 # DEPRECATED, remove in 3.0, use sendOidcResponse instead
772 # @param redirect_uri Redirect URI
773 # @param access_token Access token
774 # @param id_token ID token
775 # @param expires_in Expiration of access token
776 # @param state State
777 # @param session_state Session state
778 # return String Authentication Response URI
779 0 ▶sub buildImplicitAuthnResponse {
Subroutine buildImplicitAuthnResponse: not called CC=6 SCAR=37.4
Pod documented
780 0 my ( $self, $redirect_uri, $access_token, $id_token, $expires_in,
781 $state, $session_state, $scope )
782 = @_;
783  
784 0 ▶ return $self->getFragmentResponse(
Branch: 5 branches
BranchTrueFalseTotal
$access_token ? : 0 0 0
$expires_in ? : 0 0 0
$state ? : 0 0 0
$scope ? : 0 0 0
$session_state ? : 0 0 0
785 $redirect_uri,
786 {
787 id_token => $id_token,
788 (
789 $access_token
790 ? ( token_type => 'bearer', access_token => $access_token )
791 : ()
792 ),
793 ( $expires_in ? ( expires_in => $expires_in ) : () ),
794 ( $state ? ( state => $state ) : () ),
795 ( $scope ? ( scope => $scope ) : () ),
796 ( $session_state ? ( session_state => $session_state ) : () )
797 }
798 );
799 }
800  
801 # Build Authentication Response URI for Hybrid Flow
802 # DEPRECATED, remove in 3.0, use sendOidcResponse instead
803 # @param redirect_uri Redirect URI
804 # @param code Code
805 # @param access_token Access token
806 # @param id_token ID token
807 # @param expires_in Expiration of access token
808 # @param state State
809 # @param session_state Session state
810 # return String Authentication Response URI
811 0 ▶sub buildHybridAuthnResponse {
Subroutine buildHybridAuthnResponse: not called CC=7 SCAR=40.3
Pod documented
812 my (
813 0 $self, $redirect_uri, $code, $access_token, $id_token,
814 $expires_in, $state, $session_state, $scope
815 ) = @_;
816  
817 0 ▶ return $self->getFragmentResponse(
Branch: 6 branches
BranchTrueFalseTotal
$access_token ? : 0 0 0
$id_token ? : 0 0 0
$expires_in ? : 0 0 0
$state ? : 0 0 0
$scope ? : 0 0 0
$session_state ? : 0 0 0
818 $redirect_uri,
819 {
820 code => $code,
821 (
822 $access_token
823 ? ( token_type => 'bearer', access_token => $access_token )
824 : ()
825 ),
826 (
827 $id_token ? ( id_token => $id_token )
828 : ()
829 ),
830 ( $expires_in ? ( expires_in => $expires_in ) : () ),
831 ( $state ? ( state => $state ) : () ),
832 ( $scope ? ( scope => $scope ) : () ),
833 ( $session_state ? ( session_state => $session_state ) : () )
834 }
835 );
836 }
837  
838 1 ▶sub getAccessTokenFromTokenEndpoint {
Subroutine getAccessTokenFromTokenEndpoint: called CC=13 SCAR=36.5
Pod undocumented
839 1 my ( $self, $req, $op, $grant_type, $grant_options ) = @_;
840  
841 1 ▶ $grant_options ||= {};
Condition50%1/2
$grant_options ||= {}
l!l
10
MC/DC0%0/1
$grant_options ||= {}
$grant_options
Truth table50%1/2
A
A= $grant_options
Aresult
11
00
842  
843 1 my $client_id = $self->opOptions->{$op}->{oidcOPMetaDataOptionsClientID};
844 my $client_secret =
845 1 $self->opOptions->{$op}->{oidcOPMetaDataOptionsClientSecret};
846 my $access_token_uri =
847 1 $self->opMetadata->{$op}->{conf}->{token_endpoint};
848  
849 1 ▶ unless ($access_token_uri) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token_uri) 0 1 1
850 0 $self->logger->error(
851 "Could not build Token request: no
852 'token_endpoint'" . " in JSON metadata for OP $op"
853 );
854 0 return 0;
855 }
856  
857 my $auth_method =
858 $self->opOptions->{$op}->{oidcOPMetaDataOptionsTokenEndpointAuthMethod}
859 1 ▶ || 'client_secret_post';
Condition50%1/2
$self->opOptions->{$op}{'oidcOPMetaDataOptionsTokenEndpointAuthMethod'} || 'client_secret_post'
l!l
01
MC/DC0%0/1
$self->opOptions->{$op}{'oidcOPMetaDataOptionsTokenEndpointAuthMethod'} || 'client_secret_post'
$self->opOptions->{$op}{'oidcOPMetaDataOptionsTokenEndpointAuthMethod'}
Truth table50%1/2
A
A= $self->opOptions->{$op}{'oidcOPMetaDataOptionsTokenEndpointAuthMethod'}
Aresult
11
00
860  
861 1 ▶ unless ( $auth_method =~
Branch: 1 branch
BranchTrueFalseTotal
unless ($auth_method =~ /^(?:client_secret_(?:(?:pos|jw)t|basic)|private_key_jwt)$/) 0 1 1
862 /^(?:client_secret_(?:(?:pos|jw)t|basic)|private_key_jwt)$/ )
863 {
864 0 $self->logger->error(
865 "Bad authentication method on token endpoint for OP $op");
866 0 return 0;
867 }
868  
869 $self->logger->debug(
870 1 "Using auth method $auth_method to token endpoint $access_token_uri");
871  
872 1 my $response;
873 my $token_request_params = {
874 grant_type => $grant_type,
875 1 %{$grant_options}
876 };
877  
878 # Call oidcGenerateTokenRequest
879 1 my $h = $self->p->processHook( $req, 'oidcGenerateTokenRequest',
880 $op, $token_request_params );
881 1 ▶ return 0 if ( $h != PE_OK );
Branch: 1 branch
BranchTrueFalseTotal
if $h != 0 0 1 1
882  
883 1 ▶ if ( $auth_method eq "client_secret_basic" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($auth_method eq 'client_secret_basic') { } 0 1 1
884 0 $response = $self->ua->post(
885 $access_token_uri, $token_request_params,
886 "Authorization" => "Basic "
887 . encode_base64( "$client_id:$client_secret", '' ),
888 "Content-Type" => 'application/x-www-form-urlencoded',
889 );
890 }
891 else {
892 1 ▶ if ( $auth_method eq "client_secret_post" ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($auth_method eq 'client_secret_post') { } 1 0 1
elsif ($auth_method =~ /^(?:client_secret|private_key)_jwt$/) { } 0 0 0
893 1 $token_request_params->{client_id} = $client_id;
894 1 $token_request_params->{client_secret} = $client_secret;
895 }
896 elsif ( $auth_method =~ /^(?:client_secret|private_key)_jwt$/ ) {
897  
898 my $alg = $self->opOptions->{$op}
899 0 ->{oidcOPMetaDataOptionsTokenEndpointAuthSigAlg};
900 0 ▶ if ( !$alg ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($alg) 0 0 0
901 0 my $default_signing_key_type =
902 $self->_getKeyType(
903 $self->get_public_key("default-oidc-sig") );
904  
905 0 ▶ $alg =
Branch: 2 branches
BranchTrueFalseTotal
$auth_method eq 'client_secret_jwt' ? : 0 0 0
$default_signing_key_type eq 'EC' ? : 0 0 0
906 $auth_method eq 'client_secret_jwt' ? 'HS256'
907 : $default_signing_key_type eq 'EC' ? 'ES256'
908 : 'RS256';
909 }
910 0 my $time = time;
911 my $jws = $self->createJWTForOP( {
912 iss => $client_id,
913 sub => $client_id,
914 aud => $access_token_uri,
915 jti => $self->generateNonce,
916 exp => $time + $self->conf->{shortTokenTTL},
917 0 iat => $time,
918 },
919 $alg, $op
920 );
921 0 $token_request_params->{client_id} = $client_id;
922 $token_request_params->{client_assertion_type} =
923 0 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
924 0 $token_request_params->{client_assertion} = $jws;
925 }
926 else {
927 0 $self->logger->error("Unknown auth method $auth_method");
928 }
929 1 $response = $self->ua->post( $access_token_uri, $token_request_params,
930 "Content-Type" => 'application/x-www-form-urlencoded' );
931 }
932  
933 1 $self->logger->debug(
934 "Token request sent: " . $response->request()->as_string );
935  
936 1 ▶ if ( $response->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_error) 0 1 1
937 0 $self->logger->error(
938 "Bad token response from $op, grant_type: $grant_type, error: "
939 . $response->message );
940 0 $self->logger->debug(
941 "Token response received: " . $response->as_string );
942 0 return 0;
943 }
944 1 return $response->decoded_content;
945 }
946  
947 # Get Token response with authorization code
948 # @param op OpenIP Provider configuration key
949 # @param code Code
950 # @param auth_method Authentication Method (optional)
951 # return String Token response decoded content
952 1 ▶sub getAuthorizationCodeAccessToken {
Subroutine getAuthorizationCodeAccessToken: called CC=1 SCAR=0.0
Pod documented
953 1 my ( $self, $req, $op, $code ) = @_;
954  
955 1 my $redirect_uri = $self->getCallbackUri($req);
956  
957 1 return $self->getAccessTokenFromTokenEndpoint( $req, $op,
958 "authorization_code",
959 { code => $code, redirect_uri => $redirect_uri } );
960 }
961  
962 # Check validity of Token Response
963 # return boolean 1 if the response is valid, 0 else
964 1 ▶sub checkTokenResponseValidity {
Subroutine checkTokenResponseValidity: called CC=3 SCAR=14.2
Pod documented
965 1 my ( $self, $json ) = @_;
966  
967 # token_type MUST be Bearer
968 1 ▶ unless ( $json->{token_type} =~ /^Bearer$/i ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($json->{"token_type"} =~ /^Bearer$/i) 0 1 1
969 $self->logger->error(
970 0 "Token type is " . $json->{token_type} . " but must be Bearer" );
971 0 return 0;
972 }
973  
974 # id_token MUST be present
975 1 ▶ unless ( $json->{id_token} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($json->{"id_token"}) 0 1 1
976 0 $self->logger->error("No id_token");
977 0 return 0;
978 }
979  
980 1 return 1;
981 }
982  
983 # Check validity of ID Token
984 # return boolean 1 if the token is valid, 0 else
985 1 ▶sub checkIDTokenValidity {
Subroutine checkIDTokenValidity: called CC=19 SCAR=48.4
Pod undocumented
986 1 my ( $self, $op, $id_token, $state_nonce ) = @_;
987  
988 1 my $client_id = $self->opOptions->{$op}->{oidcOPMetaDataOptionsClientID};
989 1 my $acr_values = $self->opOptions->{$op}->{oidcOPMetaDataOptionsAcrValues};
990 1 my $max_age = $self->opOptions->{$op}->{oidcOPMetaDataOptionsMaxAge};
991 my $id_token_max_age =
992 1 $self->opOptions->{$op}->{oidcOPMetaDataOptionsIDTokenMaxAge};
993 1 my $use_nonce = $self->opOptions->{$op}->{oidcOPMetaDataOptionsUseNonce};
994  
995 # Check issuer
996 1 ▶ unless ( $id_token->{iss} eq $self->opMetadata->{$op}->{conf}->{issuer} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token->{"iss"} eq $self->opMetadata->{$op}{"conf"}{"issuer"}) 0 1 1
997 0 $self->logger->error("Issuer mismatch");
998 0 return 0;
999 }
1000  
1001 # Check audience
1002 1 ▶ if ( ref $id_token->{aud} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $id_token->{'aud'}) { } 1 0 1
1003 1 my @audience = @{ $id_token->{aud} };
1004 1 ▶ unless ( grep { $_ eq $client_id } @audience ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $client_id;} @audience) 0 1 1
1005 0 $self->logger->error("Client ID not found in audience array");
1006 0 return 0;
1007 }
1008  
1009 1 ▶ if ( $#audience > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($#audience > 1) 0 1 1
1010 0 ▶ unless ( $id_token->{azp} eq $client_id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token->{"azp"} eq $client_id) 0 0 0
1011 0 $self->logger->error(
1012 "More than one audience, and azp not equal to client ID");
1013 0 return 0;
1014 }
1015 }
1016 }
1017 else {
1018 0 ▶ unless ( $id_token->{aud} eq $client_id ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token->{"aud"} eq $client_id) 0 0 0
1019 0 $self->logger->error("Audience mismatch");
1020 0 return 0;
1021 }
1022 }
1023  
1024 # Check time
1025 1 ▶ unless ( time < $id_token->{exp} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&CORE::GLOBAL::time() < $id_token->{"exp"}) 0 1 1
1026 0 $self->logger->error("ID token expired");
1027 0 return 0;
1028 }
1029  
1030 # Check iat
1031 1 my $iat = $id_token->{iat};
1032 1 ▶ if ($id_token_max_age) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id_token_max_age) 0 1 1
1033 0 ▶ unless ( $iat + $id_token_max_age > time ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($iat + $id_token_max_age > &CORE::GLOBAL::time()) 0 0 0
1034 0 $self->logger->error(
1035 "ID token too old (Max age: $id_token_max_age)");
1036 0 return 0;
1037 }
1038 }
1039  
1040 # Check nonce
1041 1 ▶ if ($use_nonce) {
Branch: 1 branch
BranchTrueFalseTotal
if ($use_nonce) 0 1 1
1042 0 my $id_token_nonce = $id_token->{nonce};
1043 0 ▶ unless ($id_token_nonce) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id_token_nonce) { } 0 0 0
1044 0 $self->logger->error("Nonce was not returned by OP $op");
1045 0 return 0;
1046 }
1047 else {
1048 # Get nonce session
1049 0 ▶ unless ( $id_token_nonce eq $state_nonce ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($id_token_nonce eq $state_nonce) 0 0 0
1050 0 $self->logger->error(
1051 "Nonce $id_token_nonce verification failed, expected $state_nonce"
1052 );
1053 0 return 0;
1054 }
1055 }
1056 }
1057  
1058 # Check acr
1059 1 my $acr = $id_token->{acr};
1060 1 ▶ if ($acr_values) {
Branch: 1 branch
BranchTrueFalseTotal
if ($acr_values) 0 1 1
1061 0 ▶ unless ($acr) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($acr) 0 0 0
1062 0 $self->logger->error("ACR was not returned by OP $op");
1063 0 return 0;
1064 }
1065 0 ▶ unless ( grep { $_ eq $acr } split( /[\s,]+/, $acr_values ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $acr;} split(/[\s,]+/, $acr_values, 0)) 0 0 0
1066 0 $self->logger->error(
1067 "ACR $acr not listed in request ACR values ($acr_values)");
1068 0 return 0;
1069 }
1070 }
1071  
1072 # Check auth_time
1073 1 my $auth_time = $id_token->{auth_time};
1074 1 ▶ if ($max_age) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_age) 0 1 1
1075 0 ▶ unless ($auth_time) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($auth_time) 0 0 0
1076 0 $self->logger->error("Auth time was not returned by OP $op");
1077 0 return 0;
1078 }
1079 0 ▶ if ( time > $auth_time + $max_age ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CORE::GLOBAL::time() > $auth_time + $max_age) 0 0 0
1080 0 $self->userLogger->error(
1081 "Authentication time ($auth_time) is too old (Max age: $max_age)"
1082 );
1083 0 return 0;
1084 }
1085 }
1086  
1087 1 return 1;
1088 }
1089  
1090 # Returns the current OP and a valid Access token
1091 1 ▶sub getUserInfoParams {
Subroutine getUserInfoParams: called CC=2 SCAR=7.2
Pod undocumented
1092 1 my ( $self, $req ) = @_;
1093  
1094 1 my $op = $req->data->{_oidcOPCurrent};
1095  
1096 1 ▶ if ($op) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op) { } 1 0 1
1097  
1098 # We are in the middle of an auth process,
1099 # access token has just been fetched already
1100 1 my $access_token = $req->data->{access_token};
1101 1 return ( $op, $access_token );
1102 }
1103 else {
1104 # Get OP and access token from existing session (refresh)
1105 0 return $self->getUserInfoParamsFromSession($req);
1106 }
1107 }
1108  
1109 0 ▶sub getUserInfoParamsFromSession {
Subroutine getUserInfoParamsFromSession: not called CC=3 SCAR=24.8
Pod undocumented
1110 0 my ( $self, $req ) = @_;
1111 0 my $op = $req->userData->{_oidc_OP};
1112  
1113 # Save current OP, we will need it for setSessionInfo & friends
1114 0 $req->data->{_oidcOPCurrent} = $op;
1115  
1116 0 ▶ if ($op) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op) { } 0 0 0
1117 0 my $access_token = $req->userData->{_oidc_access_token};
1118 0 my $access_token_eol = $req->userData->{_oidc_access_token_eol};
1119 0 ▶ if ($access_token_eol) {
Branch: 1 branch
BranchTrueFalseTotal
if ($access_token_eol) { } 0 0 0
1120 0 return $self->refreshAccessTokenIfExpired( $req, $op );
1121 }
1122 else {
1123 # We don't know the TTL for this access token,
1124 # so we can only hope that it works
1125 0 return ( $op, $access_token );
1126 }
1127 }
1128 else {
1129 0 $self->logger->warn("No OP found in session");
1130 0 return ( $op, undef );
1131 }
1132 }
1133  
1134 0 ▶sub refreshAccessTokenIfExpired {
Subroutine refreshAccessTokenIfExpired: not called CC=3 SCAR=24.8
Pod undocumented
1135 0 my ( $self, $req, $op, $session ) = @_;
1136  
1137 # Handle unauthenticated OIDC calls
1138 0 ▶ my $data = $session ? $session->data : $req->userData;
Branch: 1 branch
BranchTrueFalseTotal
$session ? : 0 0 0
1139  
1140 0 my $access_token = $data->{_oidc_access_token};
1141 0 my $access_token_eol = $data->{_oidc_access_token_eol};
1142 0 ▶ if ( time < $access_token_eol ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CORE::GLOBAL::time() < $access_token_eol) { } 0 0 0
1143  
1144 # Access Token is still valid, return it
1145 0 return ( $op, $access_token );
1146 }
1147 else {
1148 # Refresh Access Token
1149 0 return ( $op, $self->refreshAccessToken( $req, $op, $session ) );
1150 }
1151 }
1152  
1153 0 ▶sub refreshAccessToken {
Subroutine refreshAccessToken: not called CC=11 SCAR=48.8
Pod undocumented
1154 0 my ( $self, $req, $op, $session ) = @_;
1155  
1156 # Handle unauthenticated OIDC calls
1157 0 ▶ my $data = $session ? $session->data : $req->userData;
Branch: 1 branch
BranchTrueFalseTotal
$session ? : 0 0 0
1158 0 ▶ my $session_id = $session ? $session->id : $req->id;
Branch: 1 branch
BranchTrueFalseTotal
$session ? : 0 0 0
1159 0 my $refresh_token = $data->{_oidc_refresh_token};
1160  
1161 0 ▶ if ($refresh_token) {
Branch: 1 branch
BranchTrueFalseTotal
if ($refresh_token) { } 0 0 0
1162  
1163 0 my $content =
1164 $self->getAccessTokenFromTokenEndpoint( $req, $op, 'refresh_token',
1165 { refresh_token => $refresh_token } );
1166  
1167 0 ▶ if ($content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content) { } 0 0 0
1168 0 my $token_response = $self->decodeTokenResponse($content);
1169 0 ▶ if ($token_response) {
Branch: 1 branch
BranchTrueFalseTotal
if ($token_response) { } 0 0 0
1170  
1171 0 my $access_token = $token_response->{access_token};
1172 0 my $expires_in = $token_response->{expires_in};
1173 0 my $refresh_token = $token_response->{refresh_token};
1174  
1175 0 ▶ undef $expires_in unless looks_like_number($expires_in);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($expires_in) 0 0 0
1176  
1177 0 $self->logger->debug("Access token: $access_token");
1178 0 ▶ $self->logger->debug( "Access token expires in: "
Condition0%0/2
$expires_in || '<unknown>'
l!l
00
MC/DC0%0/1
$expires_in || '<unknown>'
$expires_in
Truth table0%0/2
A
A= $expires_in
Aresult
11
00
1179 . ( $expires_in || "<unknown>" ) );
1180 0 ▶ $self->logger->debug(
Condition0%0/2
$refresh_token || '<none>'
l!l
00
MC/DC0%0/1
$refresh_token || '<none>'
$refresh_token
Truth table0%0/2
A
A= $refresh_token
Aresult
11
00
1181 "Refresh token: " . ( $refresh_token || "<none>" ) );
1182  
1183 0 my $updateSession;
1184  
1185 # Remember tokens
1186 0 $updateSession->{_oidc_access_token} = $access_token;
1187 0 ▶ $updateSession->{_oidc_refresh_token} = $refresh_token
Branch: 1 branch
BranchTrueFalseTotal
if $refresh_token 0 0 0
1188 if $refresh_token;
1189  
1190 # If access token TTL is given save expiration date
1191 # (with security margin)
1192 0 ▶ if ($expires_in) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expires_in) 0 0 0
1193 $updateSession->{_oidc_access_token_eol} =
1194 0 time + ( $expires_in * 0.9 );
1195 }
1196  
1197 0 $self->p->updateSession( $req, $updateSession, $session_id );
1198  
1199 0 return ($access_token);
1200 }
1201 else {
1202 0 $self->logger->warn("Could not decode Token Response for $op");
1203 0 return undef;
1204 }
1205 }
1206 else {
1207 0 $self->logger->warn("Could not fetch new Access Token for $op");
1208 0 return undef;
1209 }
1210 }
1211 else {
1212 0 $self->logger->warn("No Refresh Token was found for $op");
1213 0 return undef;
1214 }
1215 }
1216  
1217 # Get UserInfo response
1218 # return String UserInfo response decoded content
1219 2 ▶sub getUserInfo {
Subroutine getUserInfo: called CC=5 SCAR=21.4
Pod documented
1220 2 my ( $self, $op, $access_token ) = @_;
1221  
1222 my $userinfo_uri =
1223 2 $self->opMetadata->{$op}->{conf}->{userinfo_endpoint};
1224  
1225 2 ▶ unless ($userinfo_uri) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($userinfo_uri) 0 2 2
1226 0 $self->logger->error("UserInfo URI not found in $op configuration");
1227 0 return 0;
1228 }
1229  
1230 $self->logger->debug(
1231 2 "Request UserInfo on $userinfo_uri with access token $access_token");
1232  
1233 2 my $response = $self->ua->get( $userinfo_uri,
1234 "Authorization" => "Bearer $access_token" );
1235  
1236 2 ▶ if ( $response->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_error) 0 2 2
1237 0 $self->logger->error( "Bad UserInfo response: " . $response->message );
1238 0 $self->logger->debug(
1239 "UserInfo response received: " . $response->as_string );
1240 0 return 0;
1241 }
1242  
1243 2 my $userinfo_content = $response->decoded_content;
1244  
1245 2 $self->logger->debug("UserInfo received: $userinfo_content");
1246  
1247 2 my $content_type = $response->header('Content-Type');
1248 2 ▶ if ( $content_type =~ /json/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($content_type =~ /json/) { } 2 0 2
elsif ($content_type =~ /jwt/) { } 0 0 0
1249 2 return $self->decodeUserInfo($userinfo_content);
1250 }
1251 elsif ( $content_type =~ /jwt/ ) {
1252 0 my $jwt = $self->decryptJwt($userinfo_content);
1253 0 return $self->decodeJWT( $jwt, $op );
1254 }
1255 else {
1256 0 $self->logger->error('Bad UserInfo Content-Type');
1257 0 $self->logger->debug( "UserInfo response received with"
1258 . " invalid Content-Type ($content_type)" );
1259 0 return 0;
1260 }
1261 }
1262  
1263 # Convert JSON to HashRef
1264 # @return HashRef JSON decoded content
1265 222 ▶sub decodeJSON {
Subroutine decodeJSON: called CC=3 SCAR=11.3
Pod documented
1266 222 my ( $self, $json ) = @_;
1267 222 my $json_hash;
1268  
1269 222 eval { $json_hash = from_json( $json, { allow_nonref => 1 } ); };
1270 222 ▶ return undef if ($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 4 218 222
1271 218 ▶ unless ( ref $json_hash ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $json_hash) 0 218 218
1272 0 $self->logger->error("Wanted a JSON object, got: $json_hash");
1273 0 return undef;
1274 }
1275  
1276 218 return $json_hash;
1277 }
1278  
1279 1 ▶sub decodeTokenResponse {
Subroutine decodeTokenResponse: called CC=1 SCAR=0.0
Pod undocumented
1280 1 return decodeJSON(@_);
1281 }
1282  
1283 2 ▶sub decodeUserInfo {
Subroutine decodeUserInfo: called CC=1 SCAR=0.0
Pod undocumented
1284 2 return decodeJSON(@_);
1285 }
1286  
1287 # Create a new Authorization Code
1288 # @param info hashref of session info
1289 # @return new Lemonldap::NG::Common::Session object
1290  
1291 14 ▶sub newAuthorizationCode {
Subroutine newAuthorizationCode: called CC=2 SCAR=8.1
Pod documented
1292 14 my ( $self, $rp, $info ) = @_;
1293  
1294 return $self->getOpenIDConnectSession(
1295 undef,
1296 "authorization_code",
1297 ttl => $self->rpOptions->{$rp}
1298 ->{oidcRPMetaDataOptionsAuthorizationCodeExpiration}
1299 || $self->conf->{oidcServiceAuthorizationCodeExpiration},
1300 14 ▶ info => $info
Condition33%1/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAuthorizationCodeExpiration'} || $self->conf->{'oidcServiceAuthorizationCodeExpiration'}
l!l&&r!l&&!r
0140
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAuthorizationCodeExpiration'} || $self->conf->{'oidcServiceAuthorizationCodeExpiration'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAuthorizationCodeExpiration'} $self->conf->{'oidcServiceAuthorizationCodeExpiration'}
Truth table33%1/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAuthorizationCodeExpiration'}B= $self->conf->{'oidcServiceAuthorizationCodeExpiration'}
ABresult
1X1
011
000
1301 );
1302 }
1303  
1304 # Get existing Authorization Code
1305 # @param id
1306 # @return new Lemonldap::NG::Common::Session object
1307  
1308 12 ▶sub getAuthorizationCode {
Subroutine getAuthorizationCode: called CC=1 SCAR=0.0
Pod documented
1309 12 my ( $self, $id ) = @_;
1310  
1311 12 return $self->getOpenIDConnectSession( $id, "authorization_code" );
1312 }
1313  
1314 # Create a new Access Token
1315 # @param req current request
1316 # @param scope access token scope
1317 # @param rp configuration key of the RP this token is being made for
1318 # @param sessionInfo. Hashref of session info OR session ID for lazy fetching
1319 # @param info hashref of access token session info (offline vs online)
1320 # @return new Lemonldap::NG::Common::Session object
1321  
1322 17 ▶sub newAccessToken {
Subroutine newAccessToken: called CC=5 SCAR=16.3
Pod documented
1323 17 my ( $self, $req, $rp, $scope, $sessionInfo, $info ) = @_;
1324 17 my $client_id = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
1325 my $at_info = {
1326 scope => $scope,
1327 rp => $rp,
1328 client_id => $client_id,
1329 iat => time,
1330 nbf => time,
1331 aud => $self->getAudiences($rp),
1332 17 %{$info},
1333 };
1334 my $ttl =
1335 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenExpiration}
1336 17 ▶ || $self->conf->{oidcServiceAccessTokenExpiration};
Condition66%2/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAccessTokenExpiration'} || $self->conf->{'oidcServiceAccessTokenExpiration'}
l!l&&r!l&&!r
1070
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
1337 17 my $session = $self->getOpenIDConnectSession(
1338 undef, "access_token",
1339 ttl => $ttl,
1340 info => $at_info,
1341 );
1342  
1343 17 ▶ if ($session) {
Branch: 1 branch
BranchTrueFalseTotal
if ($session) { } 17 0 17
1344 17 ▶ if ( $self->_wantJWT($rp) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_wantJWT($rp)) { } 4 13 17
1345 4 my $at_jwt =
1346 $self->makeJWT( $req, $session->id, $sessionInfo, $at_info,
1347 $ttl );
1348 4 ▶ return undef unless $at_jwt;
Branch: 1 branch
BranchTrueFalseTotal
unless $at_jwt 0 4 4
1349 $at_jwt = $self->encryptToken(
1350 $rp,
1351 $at_jwt,
1352 $self->rpOptions->{$rp}
1353 ->{oidcRPMetaDataOptionsIdTokenEncKeyMgtAlg},
1354 $self->rpOptions->{$rp}
1355 ->{oidcRPMetaDataOptionsIdTokenEncContentEncAlg},
1356 4 );
1357 4 $at_info->{sha256_hash} = $self->createHash( $at_jwt, 256 );
1358 4 $self->updateToken( $session->id, $at_info );
1359 4 return $at_jwt;
1360 }
1361 else {
1362 13 my $user = $sessionInfo->{ $self->conf->{whatToTrace} };
1363 13 $self->auditLog(
1364 $req,
1365 code => "ISSUER_OIDC_ACCESS_TOKEN",
1366 rp => $rp,
1367 message =>
1368 ("Access Token for $user generated for $rp with TTL $ttl"),
1369 user => $user,
1370 ttl => $ttl,
1371 );
1372 13 return $session->id;
1373 }
1374 }
1375 else {
1376 0 return undef;
1377 }
1378 }
1379  
1380 17 ▶sub _wantJWT {
Subroutine _wantJWT: called CC=1 SCAR=0.0
1381 17 my ( $self, $rp ) = @_;
1382 17 return $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenJWT};
1383 }
1384  
1385 4 ▶sub makeJWT {
Subroutine makeJWT: called CC=8 SCAR=20.8
Pod undocumented
1386 4 my ( $self, $req, $id, $sessionInfo, $at_info, $ttl ) = @_;
1387  
1388 4 my $rp = $at_info->{rp};
1389 4 my $exp = $ttl + time;
1390 4 my $client_id = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
1391  
1392 4 my $access_token_payload = {
1393 iss => $self->get_issuer($req), # Issuer Identifier
1394 exp => $exp, # Expiration
1395 aud => $self->getAudiences($rp), # Audience
1396 jti => $id, # Access Token session ID
1397 sid => $self->getSidFromSession( $rp, $sessionInfo ), # Session id
1398 };
1399 $access_token_payload->{$_} = $at_info->{$_}
1400 4 foreach (qw(scope client_id iat));
1401  
1402 my $claims =
1403 4 $self->buildUserInfoResponseFromData( $req, $at_info->{scope}, $rp,
1404 $sessionInfo );
1405  
1406 4 my $sub = $access_token_payload->{sub} = delete $claims->{sub};
1407 4 my %extra_attr;
1408  
1409 # Release claims, or only sub
1410 4 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenClaims} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAccessTokenClaims"}) 2 2 4
1411 2 foreach ( keys %$claims ) {
1412 8 ▶ unless ( $access_token_payload->{$_} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token_payload->{$_}) 6 2 8
1413 6 $extra_attr{$_} = $access_token_payload->{$_} = $claims->{$_};
1414 }
1415 }
1416 }
1417  
1418 4 my $extra_headers = { typ => "at+JWT" };
1419  
1420 # Call hook to let the user modify payload
1421 4 my $h = $self->p->processHook( $req, 'oidcGenerateAccessToken',
1422 $access_token_payload, $rp, $extra_headers );
1423 4 ▶ return undef if ( $h != PE_OK );
Branch: 1 branch
BranchTrueFalseTotal
if $h != 0 0 4 4
1424  
1425 # Get signature algorithm
1426 4 my $alg = $self->getSignAlg($rp);
1427  
1428 4 my $jwt =
1429 $self->createJWT( $access_token_payload, $alg, $rp, $extra_headers );
1430 4 ▶ return undef unless $jwt;
Branch: 1 branch
BranchTrueFalseTotal
unless $jwt 0 4 4
1431  
1432 4 ▶ my $attr_str = (
Branch: 1 branch
BranchTrueFalseTotal
%extra_attr ? : 2 2 4
1433 %extra_attr
1434 ? ( " with attributes " . join( ',', sort( keys %extra_attr ) ) )
1435 : ''
1436 );
1437  
1438 4 my $user = $sessionInfo->{ $self->conf->{whatToTrace} };
1439 4 $self->auditLog(
1440 $req,
1441 code => "ISSUER_OIDC_ACCESS_TOKEN",
1442 rp => $rp,
1443 message => (
1444 "Access Token for $user generated for $rp as $sub with TTL $ttl$attr_str"
1445 ),
1446 user => $user,
1447 ttl => $ttl,
1448 oidc_sub => $sub,
1449 attributes => \%extra_attr,
1450 );
1451 4 return $jwt;
1452 }
1453  
1454 # Get an session from the supplied Access Token
1455 # @param id
1456 # @return new Lemonldap::NG::Common::Session object
1457 16 ▶sub getAccessToken {
Subroutine getAccessToken: called CC=5 SCAR=16.4
Pod documented
1458 16 my ( $self, $access_token ) = @_;
1459  
1460 16 my $id = getAccessTokenSessionId($access_token);
1461 16 ▶ return unless $id;
Branch: 1 branch
BranchTrueFalseTotal
unless $id 0 16 16
1462  
1463 16 my $session = $self->getOpenIDConnectSession( $id, "access_token" );
1464 16 ▶ return undef unless $session;
Branch: 1 branch
BranchTrueFalseTotal
unless $session 5 11 16
1465  
1466 11 my $stored_hash = $session->{data}->{sha256_hash};
1467 11 ▶ if ($stored_hash) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stored_hash) { } 4 7 11
1468 4 my $incoming_hash = $self->createHash( $access_token, 256 );
1469 4 ▶ if ( $stored_hash eq $incoming_hash ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stored_hash eq $incoming_hash) { } 4 0 4
1470 4 return $session;
1471 }
1472 else {
1473 0 $self->logger->error(
1474 "Incoming Access token hash $incoming_hash "
1475 . "does not match stored hash $stored_hash. "
1476 . "The access token might have been tampered with." );
1477 0 return undef;
1478 }
1479 }
1480 else {
1481 7 return $session;
1482 }
1483 }
1484  
1485 # Create a new Refresh Token
1486 # @param info hashref of session info
1487 # @return new Lemonldap::NG::Common::Session object
1488  
1489 4 ▶sub newRefreshToken {
Subroutine newRefreshToken: called CC=3 SCAR=13.3
Pod documented
1490 4 my ( $self, $rp, $info, $offline ) = @_;
1491 my $ttl =
1492 $offline
1493 ? (
1494 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsOfflineSessionExpiration}
1495 || $self->conf->{oidcServiceOfflineSessionExpiration} )
1496 4 ▶ : $self->conf->{timeout};
Branch: 1 branch
BranchTrueFalseTotal
$offline ? : 0 4 4
Condition0%0/3
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsOfflineSessionExpiration"} or $self->conf->{"oidcServiceOfflineSessionExpiration"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsOfflineSessionExpiration"} or $self->conf->{"oidcServiceOfflineSessionExpiration"}
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsOfflineSessionExpiration"} $self->conf->{"oidcServiceOfflineSessionExpiration"}
Truth table0%0/3
A or B
A= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsOfflineSessionExpiration"}B= $self->conf->{"oidcServiceOfflineSessionExpiration"}
ABresult
1X1
011
000
1497 4 $info->{_oidcRtUpdate} = time;
1498  
1499 4 return $self->getOpenIDConnectSession(
1500 undef, "refresh_token",
1501 ttl => $ttl,
1502 info => $info
1503 );
1504 }
1505  
1506 # Get existing Refresh Token
1507 # @param id
1508 # @return new Lemonldap::NG::Common::Session object
1509  
1510 4 ▶sub getRefreshToken {
Subroutine getRefreshToken: called CC=2 SCAR=7.2
Pod documented
1511 4 my ( $self, $id, $raw ) = @_;
1512  
1513 4 ▶ return $self->getOpenIDConnectSession(
Branch: 1 branch
BranchTrueFalseTotal
$raw ? : 0 4 4
1514 $id, "refresh_token",
1515 noCache => 1,
1516 ( $raw ? ( hashStore => 0 ) : () )
1517 );
1518 }
1519  
1520 2 ▶sub updateRefreshToken {
Subroutine updateRefreshToken: called CC=1 SCAR=0.0
Pod undocumented
1521 2 my ( $self, $id, $infos ) = @_;
1522 2 $infos->{_oidcRtUpdate} = time;
1523 2 return $self->updateToken( $id, $infos );
1524 }
1525  
1526 6 ▶sub updateToken {
Subroutine updateToken: called CC=2 SCAR=7.9
Pod undocumented
1527 6 my ( $self, $id, $infos ) = @_;
1528  
1529 my $oidcSession = Lemonldap::NG::Common::Session->new( {
1530 $self->_storeOpts(),
1531 cacheModule => $self->conf->{localSessionStorage},
1532 cacheModuleOptions => $self->conf->{localSessionStorageOptions},
1533 hashStore => $self->conf->{hashedSessionStore},
1534 6 id => $id,
1535 info => $infos,
1536 }
1537 );
1538  
1539 6 ▶ if ( $oidcSession->error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidcSession->error) 0 6 6
1540 0 $self->userLogger->warn("OpenIDConnect session $id not found");
1541 0 return undef;
1542 }
1543  
1544 6 return $oidcSession;
1545 }
1546  
1547 # Try to recover the OpenID Connect session corresponding to id and return session
1548 # If id is set to undef, return a new session
1549 # @return Lemonldap::NG::Common::Session object
1550 67 ▶sub getOpenIDConnectSession {
Subroutine getOpenIDConnectSession: called CC=18 SCAR=35.5
Pod documented
1551 67 my $self = shift;
1552 67 my $id = shift;
1553 67 my $type = shift;
1554  
1555 67 ▶ my $type_log = $type || "session";
Condition50%1/2
$type || 'session'
l!l
670
MC/DC0%0/1
$type || 'session'
$type
Truth table50%1/2
A
A= $type
Aresult
11
00
1556  
1557 # Check old method signature ($id, $type, $ttl, $info)
1558 67 ▶ my %opts =
Branch: 1 branch
BranchTrueFalseTotal
$_[0] && $_[0] =~ /^\d+$/ || $_[1] && ref $_[1] ? : 0 67 67
Condition55%5/9
$_[0] and $_[0] =~ /^\d+$/ or $_[1] and ref $_[1]
l!l&&r!l&&!r
0067
$_[0] and $_[0] =~ /^\d+$/
!ll&&!rl&&r
28390
$_[1] and ref $_[1]
!ll&&!rl&&r
28390
MC/DC0%0/4
$_[0] and $_[0] =~ /^\d+$/ or $_[1] and ref $_[1]
$_[0] $_[0] =~ /^\d+$/ $_[1] ref $_[1]
Truth table28%2/7
A and B or C and D
A= $_[0]B= $_[0] =~ /^\d+$/C= $_[1]D= ref $_[1]
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
1559 ( ( $_[0] and $_[0] =~ /^\d+$/ ) or ( $_[1] and ref $_[1] ) )
1560 ? ( ttl => $_[0], info => $_[1] )
1561 : (@_);
1562  
1563 67 ▶ $opts{ttl} ||= $self->conf->{timeout};
Condition66%2/3
$opts{"ttl"} ||= $self->conf->{"timeout"}
l!l&&r!l&&!r
35320
MC/DC0%0/2
$opts{"ttl"} ||= $self->conf->{"timeout"}
$opts{"ttl"} $self->conf->{"timeout"}
Truth table66%2/3
A ||= B
A= $opts{"ttl"}B= $self->conf->{"timeout"}
ABresult
1X1
011
000
1564  
1565 my $oidcSession = Lemonldap::NG::Common::Session->new( {
1566 $self->_storeOpts(),
1567 (
1568 $opts{noCache} ? ()
1569 : (
1570 cacheModule => $self->conf->{localSessionStorage},
1571 cacheModuleOptions =>
1572 $self->conf->{localSessionStorageOptions}
1573 )
1574 ),
1575 hashStore => $opts{hashStore} // $self->conf->{hashedSessionStore},
1576 id => $id,
1577 kind => $self->sessionKind,
1578 (
1579 $opts{info}
1580 ? (
1581 info => {
1582 _type => $type,
1583 _utime => time + $opts{ttl} - $self->conf->{timeout},
1584 67 ▶ %{ $opts{info} }
Branch: 2 branches
BranchTrueFalseTotal
$opts{'noCache'} ? : 4 63 67
$opts{'info'} ? : 35 32 67
Condition66%2/3
$opts{"hashStore"} // $self->conf->{"hashedSessionStore"}
l!l&&r!l&&!r
0463
MC/DC50%1/2
$opts{"hashStore"} // $self->conf->{"hashedSessionStore"}
$opts{"hashStore"} $self->conf->{"hashedSessionStore"}
Truth table66%2/3
A // B
A= $opts{"hashStore"}B= $self->conf->{"hashedSessionStore"}
ABresult
1X1
011
000
1585 }
1586 )
1587 : ()
1588 ),
1589 }
1590 );
1591  
1592 67 ▶ if ( $oidcSession->error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($oidcSession->error) 0 67 67
1593 0 ▶ if ($id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id) { } 0 0 0
1594 0 $self->userLogger->warn("OpenIDConnect $type_log $id not found");
1595 }
1596 else {
1597 0 $self->logger->error(
1598 "Unable to create new OpenIDConnect $type_log");
1599 0 $self->logger->error( $oidcSession->error );
1600 }
1601 0 return undef;
1602 }
1603  
1604 67 ▶ if ( $id and $type ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id and $type) 32 35 67
Condition66%2/3
$id and $type
!ll&&!rl&&r
35032
MC/DC50%1/2
$id and $type
$id $type
Truth table66%2/3
A and B
A= $idB= $type
ABresult
0X0
100
111
1605 32 my $storedType = $oidcSession->{data}->{_type};
1606  
1607 # Only check if a type is set in DB, for backward compatibility
1608 32 ▶ if ( $storedType and $type ne $storedType ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($storedType and $type ne $storedType) 0 32 32
Condition33%1/3
$storedType and $type ne $storedType
!ll&&!rl&&r
0320
MC/DC0%0/2
$storedType and $type ne $storedType
$storedType $type ne $storedType
Truth table33%1/3
A and B
A= $storedTypeB= $type ne $storedType
ABresult
0X0
100
111
1609 $self->logger->error( "Wrong OpenID session type: "
1610 . $oidcSession->{data}->{_type}
1611 0 . ". Expected: "
1612 . $type );
1613 0 return undef;
1614 }
1615  
1616 # Make sure the token is still valid, we already compensated for
1617 # different TTLs when storing _utime
1618 32 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (&CORE::GLOBAL::time() > $oidcSession->{"data"}{"_utime"} + $self->conf->{"timeout"}) 5 27 32
1619 time > ( $oidcSession->{data}->{_utime} + $self->conf->{timeout} ) )
1620 {
1621 5 $self->logger->notice("OpenIDConnect $type_log $id has expired");
1622 5 return undef;
1623 }
1624 }
1625  
1626 # Make sure the token is still valid, we already compensated for
1627 # different TTLs when storing _utime
1628 62 ▶ if ( time > ( $oidcSession->{data}->{_utime} + $self->conf->{timeout} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CORE::GLOBAL::time() > $oidcSession->{"data"}{"_utime"} + $self->conf->{"timeout"}) 0 62 62
1629 0 $self->logger->notice("OpenIDConnect $type_log $id has expired");
1630 0 return undef;
1631 }
1632  
1633 62 return $oidcSession;
1634 }
1635  
1636 5 ▶sub getSignAlg {
Subroutine getSignAlg: called CC=3 SCAR=11.0
Pod undocumented
1637 5 my ( $self, $rp ) = @_;
1638 my $alg =
1639 5 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenSignAlg};
1640 5 ▶ if ( !$alg ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($alg) 1 4 5
1641 1 my $default_signing_key_type =
1642 $self->_getKeyType( $self->get_public_key("default-oidc-sig") );
1643 1 ▶ $alg = ( $default_signing_key_type eq 'EC' ? 'ES256' : 'RS256' );
Branch: 1 branch
BranchTrueFalseTotal
$default_signing_key_type eq 'EC' ? : 0 1 1
1644 }
1645 5 $self->logger->debug("Access Token signature algorithm: $alg");
1646 5 return $alg;
1647 }
1648  
1649 # Store information in state database and return
1650 # corresponding session_id
1651 # @return State Session ID
1652 130 ▶sub storeState {
Subroutine storeState: called CC=5 SCAR=16.1
Pod documented
1653 130 my ( $self, $req, @data ) = @_;
1654  
1655 # check if there are data to store
1656 130 my $infos;
1657 130 foreach (@data) {
1658 520 ▶ $infos->{state}->{$_} = $req->{$_} if $req->{$_};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{$_} 1 519 520
1659 520 ▶ $infos->{state}->{"data_$_"} = $req->data->{$_} if $req->data->{$_};
Branch: 1 branch
BranchTrueFalseTotal
if $req->data->{$_} 167 353 520
1660 }
1661 130 ▶ return unless ($infos);
Branch: 1 branch
BranchTrueFalseTotal
unless $infos 0 130 130
1662  
1663 # Session type
1664 130 $infos->{_type} = "state";
1665  
1666 # Create state session and store infos
1667 130 return $self->state_ott->createToken($infos);
1668 }
1669  
1670 # Extract state information into $req
1671 1 ▶sub extractState {
Subroutine extractState: called CC=8 SCAR=23.7
Pod documented
1672 1 my ( $self, $req, $state ) = @_;
1673  
1674 1 ▶ return 0 unless $state;
Branch: 1 branch
BranchTrueFalseTotal
unless $state 0 1 1
1675  
1676 # Open state session
1677 1 my $stateSession = $self->state_ott->getToken($state);
1678  
1679 1 ▶ return 0 unless $stateSession;
Branch: 1 branch
BranchTrueFalseTotal
unless $stateSession 0 1 1
1680 1 ▶ return 0 unless $stateSession->{_type} eq "state";
Branch: 1 branch
BranchTrueFalseTotal
unless $stateSession->{"_type"} eq "state" 0 1 1
1681 1 ▶ return 0 unless $stateSession->{state};
Branch: 1 branch
BranchTrueFalseTotal
unless $stateSession->{"state"} 0 1 1
1682  
1683 # Push values in $self
1684 1 foreach ( keys %{ $stateSession->{state} } ) {
1685 1 my $tmp = $stateSession->{state}->{$_};
1686 1 ▶ if (s/^data_//) {
Branch: 2 branches
BranchTrueFalseTotal
if (s/^data_//) { } 1 0 1
elsif ($req->can($_)) { } 0 0 0
1687 1 $req->data->{$_} = $tmp;
1688 }
1689 elsif ( $req->can($_) ) {
1690 0 $req->$_($tmp);
1691 }
1692 else {
1693 0 $self->logger->warn("Unknown request property $_, skipping");
1694 }
1695 }
1696  
1697 1 return 1;
1698 }
1699  
1700 # Check signature of a JWT
1701 # @return boolean 1 if signature is verified, 0 else
1702 2 ▶sub decodeJWT {
Subroutine decodeJWT: called CC=19 SCAR=37.1
Pod undocumented
1703 2 my ( $self, $jwt, $op, $rp ) = @_;
1704  
1705 2 $self->logger->debug("Verification of JWT signature: $jwt");
1706  
1707 # Extract JWT parts
1708 2 my $jwt_header = getJWTHeader($jwt);
1709 2 my $signed_data = getJWTSignedData($jwt);
1710 2 my $signature = getJWTSignature($jwt);
1711  
1712 # Get signature algorithm
1713 2 my $alg = $jwt_header->{alg};
1714  
1715 2 $self->logger->debug("JWT signature algorithm: $alg");
1716  
1717 2 ▶ if ( $alg eq "none" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alg eq "none") 0 2 2
1718  
1719 # If none alg, signature should be empty
1720 0 ▶ if ($signature) {
Branch: 1 branch
BranchTrueFalseTotal
if ($signature) 0 0 0
1721 0 $self->logger->debug( "Signature "
1722 . $signature
1723 . " is present but algorithm is 'none'" );
1724 0 return;
1725 }
1726 $self->logger->debug(
1727 0 "JWT algorithm is 'none', signature cannot be verified");
1728 0 return;
1729 }
1730  
1731 2 my $jwks;
1732 2 ▶ if ($op) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op) { } 2 0 2
1733  
1734 # Always refresh JWKS if timeout has elapsed
1735 2 $self->refreshJWKSdataForOp($op);
1736  
1737 2 my $kid = $jwt_header->{kid};
1738  
1739 # If the JWT is signed by an unknown kid, force a refresh
1740 2 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($kid and not $self->_kid_found_in_jwks($kid, $self->opMetadata->{$op}{"jwks"})) 0 2 2
Condition33%1/3
$kid and not $self->_kid_found_in_jwks($kid, $self->opMetadata->{$op}{"jwks"})
!ll&&!rl&&r
200
MC/DC0%0/2
$kid and not $self->_kid_found_in_jwks($kid, $self->opMetadata->{$op}{"jwks"})
$kid not $self->_kid_found_in_jwks($kid, $self->opMetadata->{$op}{"jwks"})
Truth table33%1/3
A and not(B)
A= $kidB= not $self->_kid_found_in_jwks($kid, $self->opMetadata->{$op}{"jwks"})
ABresult
0X0
100
111
1741 $kid
1742 and !$self->_kid_found_in_jwks(
1743 $kid, $self->opMetadata->{$op}->{jwks}
1744 )
1745 )
1746 {
1747 0 $self->logger->debug(
1748 "Key ID $kid not found in current JWKS, forcing JWKS refresh");
1749 0 $self->refreshJWKSdataForOp( $op, 1 );
1750 }
1751  
1752 2 $jwks = $self->opMetadata->{$op}->{jwks};
1753 }
1754 else {
1755 0 $jwks = $self->rpSigKey->{$rp};
1756 }
1757  
1758 2 ▶ unless ( $alg =~ /^HS/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($alg =~ /^HS/) 1 1 2
1759 1 ▶ unless ($jwks) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($jwks) 0 1 1
1760 0 $self->logger->error(
1761 "Cannot verify $alg signature: no JWKS data found");
1762 0 return;
1763 }
1764 1 ▶ unless ( $jwks->{keys}
Branch: 1 branch
BranchTrueFalseTotal
unless ($jwks->{"keys"} and ref $jwks->{"keys"} eq "ARRAY" and @{$jwks->{"keys"};}) 0 1 1
Condition33%2/6
$jwks->{"keys"} and ref $jwks->{"keys"} eq "ARRAY" and @{$jwks->{"keys"};}
!ll&&!rl&&r
001
$jwks->{"keys"} and ref $jwks->{"keys"} eq "ARRAY"
!ll&&!rl&&r
001
MC/DC0%0/3
$jwks->{"keys"} and ref $jwks->{"keys"} eq "ARRAY" and @{$jwks->{"keys"};}
$jwks->{"keys"} ref $jwks->{"keys"} eq "ARRAY" @{$jwks->{"keys"};}
Truth table25%1/4
A and B and C
A= $jwks->{"keys"}B= ref $jwks->{"keys"} eq "ARRAY"C= @{$jwks->{"keys"};}
ABCresult
0XX0
10X0
1100
1111
1765 and ref( $jwks->{keys} ) eq 'ARRAY'
1766 1 and @{ $jwks->{keys} } )
1767 {
1768 0 $self->logger->error('Malformed JWKS, I need {"keys":[..keys..]}');
1769 0 return;
1770 }
1771 }
1772  
1773 # Choosing keys
1774 # - if algorithm is HS{digits}, the key is the ClientSecret
1775 # - if JWS has a "kid" field in its header, use it (then replace the
1776 # "key" arg of Crypt::JWT by "kid_keys" and give the whole JWKS)
1777 # - else we try the first available key of jwks document
1778 2 my @keyArgs;
1779 2 ▶ if ( $alg =~ /^HS/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($alg =~ /^HS/) { } 1 1 2
elsif ($jwt_header->{'kid'}) { } 0 1 1
1780 1 $self->logger->debug("Alg is $alg, using secret as key");
1781 @keyArgs = ( [
1782 key => $op
1783 ? $self->opOptions->{$op}->{oidcOPMetaDataOptionsClientSecret}
1784 : $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientSecret}
1785 1 ▶ ]
Branch: 1 branch
BranchTrueFalseTotal
$op ? : 1 0 1
1786 );
1787 }
1788 elsif ( $jwt_header->{kid} ) {
1789 0 $self->logger->debug(
1790 "'kid' found in JWT header, using the whole JWKS doc as 'kid_keys'"
1791 );
1792 0 @keyArgs = ( [ kid_keys => $jwks ] );
1793 }
1794 else {
1795 $self->logger->debug(
1796 "No 'kid' found in JWT header, will try all keys found in JWKS doc ("
1797 1 . @{ $jwks->{keys} }
1798 . ' key(s))' );
1799 1 @keyArgs = map { [ key => $_ ] } @{ $jwks->{keys} };
1800 }
1801  
1802 2 my $error = [];
1803 2 my $content;
1804 2 foreach my $keyArg (@keyArgs) {
1805  
1806 # JSON decoding is done here because #2748
1807 2 $content = eval {
1808 2 JSON::from_json(
1809 decode_jwt( token => $jwt, @$keyArg, decode_payload => 0 ) );
1810 };
1811 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 2 2
1812 0 $error = [ "Unable to verify JWT: $@", "Jwt was: $jwt" ];
1813 }
1814 else {
1815 2 $error = [];
1816 2 last;
1817 }
1818 }
1819 2 ▶ if (@$error) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$error) 0 2 2
1820 0 $self->logger->error($_) foreach @$error;
1821 0 return;
1822 }
1823 2 ▶ return wantarray ? ( $content, $alg ) : $content;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 2 2
1824 }
1825  
1826 0 ▶sub _kid_found_in_jwks {
Subroutine _kid_found_in_jwks: not called CC=5 SCAR=34.0
1827 0 my ( $self, $kid, $jwks ) = @_;
1828  
1829 0 ▶ return 0 if !$kid;
Branch: 1 branch
BranchTrueFalseTotal
unless $kid 0 0 0
1830  
1831 0 ▶ my @keys = $jwks ? @{ $jwks->{keys} // [] } : ();
Branch: 1 branch
BranchTrueFalseTotal
$jwks ? : 0 0 0
Condition0%0/2
$jwks->{"keys"} // []
l!l
00
MC/DC0%0/1
$jwks->{"keys"} // []
$jwks->{"keys"}
Truth table0%0/2
A
A= $jwks->{"keys"}
Aresult
11
00
1832  
1833 0 ▶ my @found = grep { $_->{kid} and $_->{kid} eq $kid } @keys;
Condition0%0/3
$_->{'kid'} && $_->{'kid'} eq $kid
!ll&&!rl&&r
000
MC/DC0%0/2
$_->{'kid'} && $_->{'kid'} eq $kid
$_->{'kid'} $_->{'kid'} eq $kid
Truth table0%0/3
A && B
A= $_->{'kid'}B= $_->{'kid'} eq $kid
ABresult
0X0
100
111
1834  
1835 0 return @found > 0;
1836 }
1837  
1838 ### HERE
1839  
1840 # Check value hash
1841 # @param value Value
1842 # @param hash Hash
1843 # @param id_token ID Token
1844 # @return boolean 1 if hash is verified, 0 else
1845 1 ▶sub verifyHash {
Subroutine verifyHash: called CC=4 SCAR=15.8
Pod documented
1846 1 my ( $self, $value, $hash, $id_token ) = @_;
1847  
1848 1 $self->logger->debug("Verification of value $value with hash $hash");
1849  
1850 1 my $jwt_header = getJWTHeader($id_token);
1851  
1852 # Get signature algorithm
1853 1 my $alg = $jwt_header->{alg};
1854  
1855 1 $self->logger->debug("ID Token signature algorithm: $alg");
1856  
1857 1 ▶ if ( $alg eq "none" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alg eq "none") 0 1 1
1858  
1859 # Not supported
1860 0 $self->logger->debug("Cannot check hash without signature algorithm");
1861 0 return 0;
1862 }
1863  
1864 1 ▶ if ( $alg =~ /(?:\w{2})(\d{3})/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alg =~ /(?:\w{2})(\d{3})/) 1 0 1
1865  
1866 # Hash Level
1867 1 my $hash_level = $1;
1868  
1869 1 $self->logger->debug("Use SHA $hash_level to check hash");
1870  
1871 1 my $cHash = $self->createHash( $value, $hash_level );
1872  
1873 # Compare values
1874 1 ▶ unless ( $cHash eq $hash ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cHash eq $hash) 0 1 1
1875 0 $self->logger->debug("Hash $hash not equal to hash $cHash");
1876 0 return 0;
1877 }
1878 1 return 1;
1879 }
1880  
1881 # Other algorithms not managed
1882 0 $self->logger->debug("Algorithm $alg not known");
1883  
1884 0 return 0;
1885 }
1886  
1887 # Create Hash
1888 # @param value Value to hash
1889 # @param hash_level SHA Hash level
1890 # @return String hash
1891 25 ▶sub createHash {
Subroutine createHash: called CC=4 SCAR=13.9
Pod documented
1892 25 my ( $self, $value, $hash_level ) = @_;
1893  
1894 25 $self->logger->debug("Use SHA $hash_level to hash $value");
1895  
1896 25 my $hash;
1897  
1898 25 ▶ if ( $hash_level eq "256" ) { $hash = sha256($value); }
Branch: 1 branch
BranchTrueFalseTotal
if ($hash_level eq 256) 15 10 25
1899 0 ▶ if ( $hash_level eq "384" ) { $hash = sha384($value); }
Branch: 1 branch
BranchTrueFalseTotal
if ($hash_level eq 384) 0 25 25
1900 25 ▶ if ( $hash_level eq "512" ) { $hash = sha512($value); }
Branch: 1 branch
BranchTrueFalseTotal
if ($hash_level eq 512) 10 15 25
1901  
1902 25 $hash = substr( $hash, 0, length($hash) / 2 );
1903 25 $hash = encode_base64url( $hash, "" );
1904  
1905 25 return $hash;
1906 }
1907  
1908 # Create error redirection
1909 # @param redirect_url Redirection URL
1910 # @param error Error code
1911 # @param error_description Human-readable ASCII encoded text description of the error
1912 # @param error_uri URI of a web page that includes additional information about the error
1913 # @param state OAuth 2.0 state value
1914 # @param fragment Set to true to return fragment component
1915 # @return void
1916  
1917 0 ▶sub returnRedirectError {
Subroutine returnRedirectError: not called CC=8 SCAR=42.8
Pod undocumented
1918 0 my ( $self, $req, $redirect_url, $error, $error_description,
1919 $error_uri, $state, $fragment )
1920 = @_;
1921  
1922 0 ▶ my $reason = $error_description ? ": $error_description" : "";
Branch: 1 branch
BranchTrueFalseTotal
$error_description ? : 0 0 0
1923 $self->auditLog(
1924 $req,
1925 code => "ISSUER_OIDC_LOGIN_FAILED",
1926 message => ( "OIDC login failed" . $reason ),
1927 ( $error_description ? ( reason => $error_description ) : () ),
1928 oauth_error => $error,
1929 portal_error => portalConsts->{PE_REDIRECT},
1930 user => $req->sessionInfo->{ $self->conf->{whatToTrace} },
1931 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$error_description ? : 0 0 0
1932  
1933 0 ▶ my $urldc =
Branch: 5 branches
BranchTrueFalseTotal
$fragment ? : 0 0 0
$redirect_url =~ /\?/ ? : 0 0 0
defined $error_description ? : 0 0 0
defined $error_uri ? : 0 0 0
defined $state ? : 0 0 0
1934 $redirect_url
1935 . ( $fragment ? '#' : $redirect_url =~ /\?/ ? '&' : '?' )
1936 . build_urlencoded(
1937 error => $error,
1938 (
1939 defined $error_description
1940 ? ( error_description => $error_description )
1941 : ()
1942 ),
1943 ( defined $error_uri ? ( error_uri => $error_uri ) : () ),
1944 ( defined $state ? ( state => $state ) : () )
1945 );
1946 0 $req->urldc($urldc);
1947 0 return PE_REDIRECT;
1948 }
1949  
1950 #sub returnJSONStatus {
1951 #my ( $self, $req, $content, $status_code ) = @_;
1952 # replace this call by $self->p->sendJSONresponse($req,$content,code=>$status_code)
1953  
1954 #sub returnJSONError {
1955 #my ( $self, $error ) = @_;
1956 #replace this by $self->p->sendError($req, $error,400);
1957 4 ▶sub sendOIDCError {
Subroutine sendOIDCError: called CC=3 SCAR=11.7
Pod undocumented
1958 4 my ( $self, $req, $err, $code, $description ) = @_;
1959 4 ▶ $code ||= 500;
Condition50%1/2
$code ||= 500
l!l
40
MC/DC0%0/1
$code ||= 500
$code
Truth table50%1/2
A
A= $code
Aresult
11
00
1960  
1961 4 ▶ return $self->sendJSONresponse(
Branch: 1 branch
BranchTrueFalseTotal
$description ? : 0 4 4
1962 $req,
1963 {
1964 error => $err,
1965 ( $description ? ( error_description => $description ) : () ),
1966 },
1967  
1968 code => $code
1969 );
1970 }
1971  
1972 #sub returnJSON {
1973 #my ( $self, $content ) = @_;
1974 #replace this call by $self->p->sendJSONresponse($req,$content)
1975  
1976 # Return Bearer error
1977 # @param error_code Error code
1978 # @param error_message Error message
1979 # @return GI response
1980 5 ▶sub returnBearerError {
Subroutine returnBearerError: called CC=1 SCAR=0.0
Pod documented
1981 5 my ( $self, $req, $error_code, $error_message ) = @_;
1982  
1983 5 my $res = $self->p->sendBinaryResponse(
1984 $req, '',
1985 code => 401,
1986 headers => [
1987 'WWW-Authenticate' =>
1988 "error=$error_code,error_description=$error_message"
1989 ]
1990 );
1991  
1992 5 $self->p->setCorsHeaderFromConfig($res);
1993  
1994 5 return $res;
1995 }
1996  
1997 0 ▶sub invalidClientResponse {
Subroutine invalidClientResponse: not called CC=3 SCAR=24.8
Pod undocumented
1998 0 my ( $self, $req ) = @_;
1999 0 ▶ if ( $req->authorization ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->authorization) { } 0 0 0
2000 0 my ($method) = $req->authorization =~ qw/^(\w+) /;
2001 0 ▶ if ($method) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method) 0 0 0
2002 0 $req->respHeaders( [ 'WWW-Authenticate' => $method ] );
2003 0 return $self->sendOIDCError( $req, 'invalid_client', 401 );
2004 }
2005 }
2006 else {
2007 0 return $self->sendOIDCError( $req, 'invalid_client', 400 );
2008 }
2009 }
2010  
2011 20 ▶sub checkEndPointAuthenticationCredentials {
Subroutine checkEndPointAuthenticationCredentials: called CC=19 SCAR=48.5
Pod undocumented
2012 20 my ( $self, $req ) = @_;
2013  
2014 # Check authentication
2015 20 my ( $client_id, $client_secret, $method ) =
2016 $self->getEndPointAuthenticationCredentials($req);
2017  
2018 20 ▶ $self->logger->debug(
Condition50%1/2
$method || 'undefined'
l!l
200
MC/DC0%0/1
$method || 'undefined'
$method
Truth table50%1/2
A
A= $method
Aresult
11
00
2019 'Authentication method: ' . ( $method || 'undefined' ) );
2020  
2021 20 ▶ unless ($client_id) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client_id) 0 20 20
2022 0 $self->logger->error(
2023 "No authentication provided to get token, or authentication type not supported"
2024 );
2025 0 return undef;
2026 }
2027  
2028 # Verify that client_id is registered in configuration
2029 20 my $rp = $self->getRP($client_id);
2030  
2031 20 ▶ unless ($rp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rp) { } 20 0 20
2032 0 $self->userLogger->error(
2033 "No registered Relying Party found with client_id $client_id");
2034 0 return undef;
2035 }
2036 else {
2037 20 $self->logger->debug("Client id $client_id match Relying Party $rp");
2038 }
2039  
2040 # Check client_secret
2041 20 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsPublic} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{'oidcRPMetaDataOptionsPublic'}) { } 0 20 20
2042  
2043 # A public client is only authenticated by the client secret
2044 # registered for it: else endpoints must not consider it as such. A
2045 # wrong secret is rejected, but a secret given to a public client
2046 # without registered secret is ignored, as before. JWS methods
2047 # (client_secret_jwt, private_key_jwt) are kept: their signature was
2048 # already verified by getEndPointAuthenticationCredentials
2049 0 ▶ if ( $method =~ /^client_secret_(?:basic|post)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method =~ /^client_secret_(?:basic|post)$/) 0 0 0
2050 my $secret =
2051 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientSecret}
2052 0 ▶ // '';
Condition0%0/2
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"} // ""
l!l
00
MC/DC0%0/1
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"} // ""
$self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"}
Truth table0%0/2
A
A= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"}
Aresult
11
00
2053 0 ▶ if ( !length $secret ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not length $secret) { } 0 0 0
elsif (not length($client_secret // '')) { } 0 0 0
elsif ($client_secret ne $secret) { } 0 0 0
2054 0 ▶ $self->logger->debug( "Relying Party $rp is public without"
Branch: 1 branch
BranchTrueFalseTotal
if length($client_secret // "") 0 0 0
Condition0%0/2
$client_secret // ""
l!l
00
MC/DC0%0/1
$client_secret // ""
$client_secret
Truth table0%0/2
A
A= $client_secret
Aresult
11
00
2055 . " client secret, given secret is ignored" )
2056 if length( $client_secret // '' );
2057 0 $method = 'none';
2058 }
2059 ▶ elsif ( !length( $client_secret // '' ) ) {
Condition0%0/2
$client_secret // ""
l!l
00
MC/DC0%0/1
$client_secret // ""
$client_secret
Truth table0%0/2
A
A= $client_secret
Aresult
11
00
2060 0 $self->logger->debug(
2061 "Relying Party $rp is public, no client secret given");
2062 0 $method = 'none';
2063 }
2064 elsif ( $client_secret ne $secret ) {
2065 0 $self->logger->error("Wrong credentials for $rp");
2066 0 return undef;
2067 }
2068 }
2069 }
2070 else {
2071 20 ▶ if ( $method eq "none" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "none") 0 20 20
2072 0 $self->logger->error(
2073 "Relying Party $rp is confidential but no known method was used"
2074 . " to authenticate on token endpoint" );
2075 0 return undef;
2076 }
2077 20 ▶ if ( $method =~ /^client_secret_(?:basic|post)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method =~ /^client_secret_(?:basic|post)$/) 20 0 20
2078 20 ▶ unless ($client_secret) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client_secret) 0 20 20
2079 0 $self->logger->error(
2080 "Relying Party $rp is confidential but no client secret was provided to authenticate on token endpoint"
2081 );
2082 0 return undef;
2083 }
2084 20 ▶ unless ( $client_secret eq
Branch: 1 branch
BranchTrueFalseTotal
unless ($client_secret eq $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"}) 0 20 20
2085 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientSecret} )
2086 {
2087 0 $self->logger->error("Wrong credentials for $rp");
2088 0 return undef;
2089 }
2090 }
2091  
2092 20 ▶ if ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAuthMethod} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthMethod"}) 0 20 20
2093 0 ▶ unless ( $method eq
Branch: 1 branch
BranchTrueFalseTotal
unless ($method eq $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsAuthMethod"}) 0 0 0
2094 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAuthMethod} )
2095 {
2096 0 $self->logger->error("Wrong authentication method for $rp");
2097 0 return undef;
2098 }
2099 }
2100 }
2101 $self->p->HANDLER->set_user( $req,
2102 20 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID} );
2103 20 return ( $rp, $method );
2104 }
2105  
2106 # Get Client ID and Client Secret
2107 # @return array (client_id, client_secret)
2108 20 ▶sub getEndPointAuthenticationCredentials {
Subroutine getEndPointAuthenticationCredentials: called CC=29 SCAR=58.2
Pod documented
2109 20 my ( $self, $req ) = @_;
2110 20 my ( $client_id, $client_secret, $scheme );
2111  
2112 20 my $authorization = $req->authorization;
2113 20 ▶ if ( $authorization and $authorization =~ m#^Basic ([[:alnum:]+/=]+)#i ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($authorization and $authorization =~ m[^Basic ([[:alnum:]+/=]+)]i) { } 17 3 20
elsif (my $atype = $req->param('client_assertion_type') and my $jws = $req->param('client_assertion') and my $_clientId = $req->param('client_id')) { } 0 3 3
elsif ($req->param('client_id') and $req->body_parameters->{'client_secret'}) { } 3 0 3
elsif ($req->param('client_id')) { } 0 0 0
Condition66%2/3
$authorization and $authorization =~ m[^Basic ([[:alnum:]+/=]+)]i
!ll&&!rl&&r
3017
MC/DC50%1/2
$authorization and $authorization =~ m[^Basic ([[:alnum:]+/=]+)]i
$authorization $authorization =~ m[^Basic ([[:alnum:]+/=]+)]i
Truth table66%2/3
A and B
A= $authorizationB= $authorization =~ m[^Basic ([[:alnum:]+/=]+)]i
ABresult
0X0
100
111
2114 17 $scheme = 'client_secret_basic';
2115 17 $self->logger->debug("Method client_secret_basic used");
2116 17 eval {
2117 17 ( $client_id, $client_secret ) =
2118 split( ':', decode_base64($1), 2 );
2119 };
2120 17 ▶ $self->logger->error("Bad authentication header: $@") if ($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 17 17
2121  
2122 # Unescape clientId and clientSecret to be compliant with RFC 6749
2123 # https://datatracker.ietf.org/doc/html/rfc6749
2124 17 $client_id = uri_unescape($client_id);
2125 17 $client_secret = uri_unescape($client_secret);
2126  
2127 # Using multiple methods is an error
2128 17 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($req->param("client_id") and $req->param("client_secret") or $req->param("client_assertion") and $req->param("client_assertion_type")) 0 17 17
Condition44%4/9
$req->param("client_id") and $req->param("client_secret") or $req->param("client_assertion") and $req->param("client_assertion_type")
l!l&&r!l&&!r
0017
$req->param("client_id") and $req->param("client_secret")
!ll&&!rl&&r
1520
$req->param("client_assertion") and $req->param("client_assertion_type")
!ll&&!rl&&r
1700
MC/DC0%0/4
$req->param("client_id") and $req->param("client_secret") or $req->param("client_assertion") and $req->param("client_assertion_type")
$req->param("client_id") $req->param("client_secret") $req->param("client_assertion") $req->param("client_assertion_type")
Truth table28%2/7
A and B or C and D
A= $req->param("client_id")B= $req->param("client_secret")C= $req->param("client_assertion")D= $req->param("client_assertion_type")
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
2129 ( $req->param('client_id') and $req->param('client_secret') )
2130 or ( $req->param('client_assertion')
2131 and $req->param('client_assertion_type') )
2132 )
2133 {
2134 0 $self->logger->error("Multiple client authentication methods used");
2135 0 ( $client_id, $client_secret ) = ( undef, undef );
2136 }
2137 }
2138  
2139 # JWS authentication
2140 ▶ elsif ( my $atype = $req->param('client_assertion_type')
Condition33%2/6
my $atype = $req->param("client_assertion_type") and my $jws = $req->param("client_assertion") and my $_clientId = $req->param("client_id")
!ll&&!rl&&r
300
my $atype = $req->param("client_assertion_type") and my $jws = $req->param("client_assertion")
!ll&&!rl&&r
300
MC/DC0%0/3
my $atype = $req->param("client_assertion_type") and my $jws = $req->param("client_assertion") and my $_clientId = $req->param("client_id")
my $atype = $req->param("client_assertion_type") my $jws = $req->param("client_assertion") my $_clientId = $req->param("client_id")
Truth table25%1/4
A and B and C
A= my $atype = $req->param("client_assertion_type")B= my $jws = $req->param("client_assertion")C= my $_clientId = $req->param("client_id")
ABCresult
0XX0
10X0
1100
1111
2141 and my $jws = $req->param('client_assertion')
2142 and my $_clientId = $req->param('client_id') )
2143 {
2144 # Type must be 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'
2145 0 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($atype eq 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer') { } 0 0 0
2146 $atype eq 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer' )
2147 {
2148 # JWS token must contain iss, sub and iss must be equal to usb
2149 0 my $payload = getJWTPayload($jws);
2150 0 ▶ if ( $payload
Branch: 1 branch
BranchTrueFalseTotal
if ($payload and ref $payload eq 'HASH' and $payload->{'iss'} and $payload->{'sub'} and $payload->{'iss'} eq $payload->{'sub'} and $payload->{'iss'} eq $_clientId) { } 0 0 0
Condition0%0/15
$payload and ref $payload eq "HASH" and $payload->{"iss"} and $payload->{"sub"} and $payload->{"iss"} eq $payload->{"sub"} and $payload->{"iss"} eq $_clientId
!ll&&!rl&&r
000
$payload and ref $payload eq "HASH" and $payload->{"iss"} and $payload->{"sub"} and $payload->{"iss"} eq $payload->{"sub"}
!ll&&!rl&&r
000
$payload and ref $payload eq "HASH" and $payload->{"iss"} and $payload->{"sub"}
!ll&&!rl&&r
000
$payload and ref $payload eq "HASH" and $payload->{"iss"}
!ll&&!rl&&r
000
$payload and ref $payload eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/6
$payload and ref $payload eq "HASH" and $payload->{"iss"} and $payload->{"sub"} and $payload->{"iss"} eq $payload->{"sub"} and $payload->{"iss"} eq $_clientId
$payload ref $payload eq "HASH" $payload->{"iss"} $payload->{"sub"} $payload->{"iss"} eq $payload->{"sub"} $payload->{"iss"} eq $_clientId
Truth table0%0/7
A and B and C and D and E and F
A= $payloadB= ref $payload eq "HASH"C= $payload->{"iss"}D= $payload->{"sub"}E= $payload->{"iss"} eq $payload->{"sub"}F= $payload->{"iss"} eq $_clientId
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
2151 and ( ref($payload) eq 'HASH' )
2152 and $payload->{iss}
2153 and $payload->{sub}
2154 and $payload->{iss} eq $payload->{sub}
2155 and $payload->{iss} eq $_clientId )
2156 {
2157 # client_id must match to a known relying party
2158 0 my $rp = $self->getRP($_clientId);
2159 0 ▶ if ($rp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rp) { } 0 0 0
2160  
2161 # RP must have a signature key registered
2162 # (key may be the secret for HS* alg)
2163 0 ▶ if ( $self->rpSigKey->{$rp}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpSigKey->{$rp} or $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsClientSecret'}) { } 0 0 0
Condition0%0/3
$self->rpSigKey->{$rp} or $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->rpSigKey->{$rp} or $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"}
$self->rpSigKey->{$rp} $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"}
Truth table0%0/3
A or B
A= $self->rpSigKey->{$rp}B= $self->rpOptions->{$rp}{"oidcRPMetaDataOptionsClientSecret"}
ABresult
1X1
011
000
2164 or $self->rpOptions->{$rp}
2165 ->{oidcRPMetaDataOptionsClientSecret} )
2166 {
2167  
2168 # Signature must be valid
2169 0 my ( $jwt, $alg ) =
2170 $self->decodeJWT( $jws, undef, $rp );
2171 0 ▶ if ($jwt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($jwt) { } 0 0 0
2172  
2173 0 ▶ $scheme =
Branch: 1 branch
BranchTrueFalseTotal
$alg =~ /^HS/i ? : 0 0 0
2174 $alg =~ /^HS/i
2175 ? 'client_secret_jwt'
2176 : 'private_key_jwt';
2177  
2178 # Token must be time-valid
2179 0 ▶ if ( $jwt->{aud} and $jwt->{exp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($jwt->{'aud'} and $jwt->{'exp'}) { } 0 0 0
Condition0%0/3
$jwt->{"aud"} and $jwt->{"exp"}
!ll&&!rl&&r
000
MC/DC0%0/2
$jwt->{"aud"} and $jwt->{"exp"}
$jwt->{"aud"} $jwt->{"exp"}
Truth table0%0/3
A and B
A= $jwt->{"aud"}B= $jwt->{"exp"}
ABresult
0X0
100
111
2180 0 ▶ if ( time < $jwt->{exp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&CORE::GLOBAL::time() < $jwt->{'exp'}) { } 0 0 0
2181 0 $self->logger->debug("JWS is valid");
2182  
2183 # Then export the client_id !
2184 0 $client_id = $_clientId;
2185 }
2186 else {
2187 0 $self->logger->error('JWS expired');
2188 }
2189 }
2190 else {
2191 0 $self->logger->error(
2192 'Bad JWS content (missing aud or exp)');
2193 }
2194 }
2195 else {
2196 0 $self->logger->error('Bad JWS signature');
2197 }
2198 }
2199 else {
2200 0 $self->logger->error("No signature key found for $rp");
2201 }
2202 }
2203 else {
2204 0 $self->logger->error(
2205 "Unable to find any RP with client_id=$_clientId");
2206 }
2207 }
2208 else {
2209 0 $self->logger->error("Bad JWS payload: $jws");
2210 }
2211 }
2212 else {
2213 0 $self->logger->error("Unsuported client_assertion_type $atype");
2214 }
2215 }
2216 ▶ elsif ( $req->param('client_id')
Condition33%1/3
$req->param("client_id") and $req->body_parameters->{"client_secret"}
!ll&&!rl&&r
003
MC/DC0%0/2
$req->param("client_id") and $req->body_parameters->{"client_secret"}
$req->param("client_id") $req->body_parameters->{"client_secret"}
Truth table33%1/3
A and B
A= $req->param("client_id")B= $req->body_parameters->{"client_secret"}
ABresult
0X0
100
111
2217 and $req->body_parameters->{client_secret} )
2218 {
2219 3 $scheme = 'client_secret_post';
2220 3 $self->logger->debug("Method client_secret_post used");
2221 3 $client_id = $req->param('client_id');
2222 3 $client_secret = $req->param('client_secret');
2223 }
2224 elsif ( $req->param('client_id') ) {
2225 0 $scheme = 'none';
2226 0 $self->logger->debug("Method none used");
2227 0 $client_id = $req->param('client_id');
2228 }
2229  
2230 20 return ( $client_id, $client_secret, $scheme );
2231 }
2232  
2233 # Get Access Token
2234 # @return access_token
2235 14 ▶sub getEndPointAccessToken {
Subroutine getEndPointAccessToken: called CC=5 SCAR=19.3
Pod documented
2236 14 my ( $self, $req ) = @_;
2237 14 my ( $access_token, $method );
2238  
2239 14 my $authorization = $req->authorization;
2240 14 ▶ if ( $authorization and $authorization =~ /^Bearer ([\w\-\.]+)/i ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($authorization and $authorization =~ /^Bearer ([\w\-\.]+)/i) { } 14 0 14
elsif ($access_token = $req->param('access_token')) { } 0 0 0
Condition33%1/3
$authorization and $authorization =~ /^Bearer ([\w\-\.]+)/i
!ll&&!rl&&r
0014
MC/DC0%0/2
$authorization and $authorization =~ /^Bearer ([\w\-\.]+)/i
$authorization $authorization =~ /^Bearer ([\w\-\.]+)/i
Truth table33%1/3
A and B
A= $authorizationB= $authorization =~ /^Bearer ([\w\-\.]+)/i
ABresult
0X0
100
111
2241 14 $self->logger->debug("Bearer access token");
2242 14 $access_token = $1;
2243 14 $method = 'header';
2244 }
2245 elsif ( $access_token = $req->param('access_token') ) {
2246 0 $self->logger->debug("GET/POST access token");
2247 0 $method = 'param';
2248 }
2249  
2250 14 ▶ return wantarray ? ( $access_token, $method ) : $access_token;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 14 0 14
2251 }
2252  
2253 # DEPRECATED, remove in 3.0, use getAttributeListFromScopeValue instead
2254 0 ▶sub getAttributesListFromClaim {
Subroutine getAttributesListFromClaim: not called CC=1 SCAR=6.9
Pod documented
2255 0 my ( $self, $rp, $scope_value ) = @_;
2256 0 return $self->getAttributesListFromScopeValue( $rp, $scope_value );
2257 }
2258  
2259 # Return list of attributes authorized for a claim
2260 # @param rp RP name
2261 # @param claim Claim
2262 # @return arrayref attributes list
2263 30 ▶sub getAttributesListFromScopeValue {
Subroutine getAttributesListFromScopeValue: called CC=1 SCAR=0.0
Pod undocumented
2264 30 my ( $self, $rp, $scope_value ) = @_;
2265 30 return $self->rpScopes->{$rp}->{$scope_value};
2266 }
2267  
2268 # Return granted scopes for this request
2269 # @param req current request
2270 # @param req selected RP
2271 # @param scope requested scope
2272 17 ▶sub getScope {
Subroutine getScope: called CC=10 SCAR=28.9
Pod undocumented
2273 17 my ( $self, $req, $rp, $scope ) = @_;
2274  
2275 17 my @scope_values = split( /\s+/, $scope );
2276  
2277 # Clean up unknown scopes
2278 17 ▶ if ( $self->conf->{oidcServiceAllowOnlyDeclaredScopes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{"oidcServiceAllowOnlyDeclaredScopes"}) 3 14 17
2279 my @known_scopes = (
2280 3 ▶ keys( %{ $self->rpScopeRules->{$rp} || {} } ),
Condition50%1/2
$self->rpScopeRules->{$rp} || {}
l!l
30
MC/DC0%0/1
$self->rpScopeRules->{$rp} || {}
$self->rpScopeRules->{$rp}
Truth table50%1/2
A
A= $self->rpScopeRules->{$rp}
Aresult
11
00
2281 3 ▶ keys( %{ $self->rpScopes->{$rp} || {} } ),
Condition50%1/2
$self->rpScopes->{$rp} || {}
l!l
30
MC/DC0%0/1
$self->rpScopes->{$rp} || {}
$self->rpScopes->{$rp}
Truth table50%1/2
A
A= $self->rpScopes->{$rp}
Aresult
11
00
2282 'openid', 'offline_access',
2283 );
2284 3 my @scope_values_tmp;
2285 3 for my $scope_value (@scope_values) {
2286 4 ▶ if ( grep { $_ eq $scope_value } @known_scopes ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_ eq $scope_value;} @known_scopes) { } 4 0 4
2287 4 push @scope_values_tmp, $scope_value;
2288 }
2289 else {
2290 0 $self->logger->warn(
2291 "Unknown scope $scope_value requested for service $rp");
2292 }
2293 }
2294 3 @scope_values = @scope_values_tmp;
2295 }
2296  
2297 # If this RP has dynamic scopes
2298 17 ▶ if ( $self->rpScopeRules->{$rp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpScopeRules->{$rp}) 17 0 17
2299  
2300 # Add dynamic scopes
2301 17 for my $dynamicScope ( keys %{ $self->rpScopeRules->{$rp} } ) {
2302  
2303 # Set a magic "$requested" variable that contains true if the
2304 # scope was requested by the application
2305 0 my $requested = grep { $_ eq $dynamicScope } @scope_values;
2306 0 my $attributes = { %{ $req->userData }, requested => $requested };
2307  
2308 # If scope is granted by the rule
2309 0 ▶ if ( $self->rpScopeRules->{$rp}->{$dynamicScope}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpScopeRules->{$rp}{$dynamicScope}->($req, $attributes)) { } 0 0 0
2310 ->( $req, $attributes ) )
2311 {
2312 # Add to list
2313 0 ▶ unless ( grep { $_ eq $dynamicScope } @scope_values ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $dynamicScope;} @scope_values) 0 0 0
2314 0 push @scope_values, $dynamicScope;
2315 }
2316  
2317 }
2318  
2319 # Else make sure it is not granted
2320 else {
2321 0 @scope_values = grep { $_ ne $dynamicScope } @scope_values;
2322 }
2323 }
2324 }
2325  
2326 17 $self->p->processHook( $req, 'oidcResolveScope', \@scope_values, $rp );
2327  
2328 17 my $scope_str = join( ' ', @scope_values );
2329 17 $self->logger->debug("Resolved scopes: $scope_str");
2330 17 return $scope_str;
2331 }
2332  
2333 # Return Hash of UserInfo data
2334 # @param scope OIDC scope
2335 # @param rp Internal Relying Party identifier
2336 # @param user_session_id User session identifier
2337 # @return hashref UserInfo data
2338 0 ▶sub buildUserInfoResponseFromId {
Subroutine buildUserInfoResponseFromId: not called CC=2 SCAR=17.9
Pod documented
2339 0 my ( $self, $req, $scope, $rp, $user_session_id ) = @_;
2340 0 my $session = $self->p->getApacheSession($user_session_id);
2341  
2342 0 ▶ return undef unless ($session);
Branch: 1 branch
BranchTrueFalseTotal
unless $session 0 0 0
2343 0 return buildUserInfoResponse( $self, $req, $scope, $rp, $session );
2344 }
2345  
2346 # Return Hash of UserInfo data
2347 # @param scope OIDC scope
2348 # @param rp Internal Relying Party identifier
2349 # @param session SSO or offline session
2350 # @return hashref UserInfo data
2351 9 ▶sub buildUserInfoResponse {
Subroutine buildUserInfoResponse: called CC=1 SCAR=0.0
Pod documented
2352 9 my ( $self, $req, $scope, $rp, $session ) = @_;
2353 9 return $self->buildUserInfoResponseFromData( $req, $scope, $rp,
2354 $session->data );
2355 }
2356  
2357 264 ▶sub _addAttributeToResponse {
Subroutine _addAttributeToResponse: called CC=8 SCAR=20.9
2358 264 my ( $self, $req, $data, $userinfo_response, $rp, $attribute ) = @_;
2359 my @attrConf = split /;/,
2360 264 ▶ ( $self->rpAttributes->{$rp}->{$attribute} || "" );
Condition100%2/2
$self->rpAttributes->{$rp}{$attribute} || ''
l!l
58206
MC/DC100%1/1
$self->rpAttributes->{$rp}{$attribute} || ''
$self->rpAttributes->{$rp}{$attribute}
Truth table100%2/2
A
A= $self->rpAttributes->{$rp}{$attribute}
Aresult
11
00
2361 264 my $session_key = $attrConf[0];
2362 264 ▶ if ($session_key) {
Branch: 1 branch
BranchTrueFalseTotal
if ($session_key) 58 206 264
2363 58 ▶ my $type = $attrConf[1] || 'string';
Condition50%1/2
$attrConf[1] || 'string'
l!l
058
MC/DC0%0/1
$attrConf[1] || 'string'
$attrConf[1]
Truth table50%1/2
A
A= $attrConf[1]
Aresult
11
00
2364 58 ▶ my $array = $attrConf[2] || 'auto';
Condition50%1/2
$attrConf[2] || 'auto'
l!l
058
MC/DC0%0/1
$attrConf[2] || 'auto'
$attrConf[2]
Truth table50%1/2
A
A= $attrConf[2]
Aresult
11
00
2365  
2366 58 my $session_value;
2367  
2368 # Lookup attribute in macros first
2369 58 ▶ if ( $self->rpMacros->{$rp}->{$session_key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rpMacros->{$rp}{$session_key}) { } 8 50 58
2370 $session_value =
2371 8 $self->rpMacros->{$rp}->{$session_key}->( $req, $data );
2372  
2373 # If not found, search in session
2374 }
2375 else {
2376 50 $session_value = $data->{$session_key};
2377 }
2378  
2379 # Handle empty values, arrays, type, etc.
2380 58 $session_value =
2381 $self->_formatValue( $session_value, $type, $array,
2382 $attribute, $req->user );
2383  
2384 # From this point on, do NOT touch $session_value
2385 # or you will break the variable's type.
2386  
2387 # Only release claim if it has a value
2388 58 ▶ if ( defined $session_value ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $session_value) 58 0 58
2389  
2390 # If this attribute is a standardized subkey (address)
2391 58 ▶ if ( COMPLEX_CLAIM->{$attribute} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ({country => 'address', formatted => 'address', locality => 'address', postal_code => 'address', region => 'address', street_address => 'address'}->{$attribute}) { } 2 56 58
2392 2 my $superkey = COMPLEX_CLAIM->{$attribute};
2393 2 $userinfo_response->{$superkey}->{$attribute} = $session_value;
2394 }
2395 else {
2396 56 $userinfo_response->{$attribute} = $session_value;
2397 }
2398 }
2399 }
2400 }
2401  
2402 # Return Hash of UserInfo data
2403 # @param scope OIDC scope
2404 # @param rp Internal Relying Party identifier
2405 # @param sessionInfo hash of session data
2406 # @return hashref UserInfo data
2407 18 ▶sub buildUserInfoResponseFromData {
Subroutine buildUserInfoResponseFromData: called CC=10 SCAR=23.2
Pod undocumented
2408 18 my ( $self, $req, $scope, $rp, $session_data ) = @_;
2409 18 my $userinfo_response = {};
2410  
2411 my $data = {
2412 18 %{$session_data},
2413 _clientId => $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID},
2414 18 _clientConfKey => $rp,
2415 _scope => $scope,
2416 };
2417 18 my $user_id = $self->getUserIDForRP( $req, $rp, $data );
2418  
2419 18 $self->logger->debug("Found corresponding user: $user_id");
2420  
2421 18 $userinfo_response->{sub} = $user_id;
2422 18 $userinfo_response->{sid} = $self->getSidFromSession( $rp, $session_data );
2423  
2424 # By default, release all exported attributes
2425 18 ▶ if ( $self->conf->{oidcServiceIgnoreScopeForClaims} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{'oidcServiceIgnoreScopeForClaims'}) { } 2 16 18
2426 2 ▶ for my $attribute ( keys %{ $self->rpAttributes->{$rp} || {} } ) {
Condition50%1/2
$self->rpAttributes->{$rp} || {}
l!l
20
MC/DC0%0/1
$self->rpAttributes->{$rp} || {}
$self->rpAttributes->{$rp}
Truth table50%1/2
A
A= $self->rpAttributes->{$rp}
Aresult
11
00
2427 12 $self->_addAttributeToResponse( $req, $data, $userinfo_response,
2428 $rp, $attribute );
2429 }
2430  
2431 # Else, iterate through scopes to find allowed attributes
2432 }
2433 else {
2434 16 foreach my $scope_value ( split( /\s/, $scope ) ) {
2435 46 ▶ next if ( $scope_value eq "openid" );
Branch: 1 branch
BranchTrueFalseTotal
if $scope_value eq "openid" 16 30 46
2436 30 $self->logger->debug(
2437 "Get attributes linked to scope value $scope_value");
2438 30 my $list =
2439 $self->getAttributesListFromScopeValue( $rp, $scope_value );
2440 $self->logger->debug(
2441 30 ▶ "-> found attributes: " . join( " ", @{ $list || [] } ) );
Condition50%1/2
$list || []
l!l
300
MC/DC0%0/1
$list || []
$list
Truth table50%1/2
A
A= $list
Aresult
11
00
2442 30 ▶ next unless $list;
Branch: 1 branch
BranchTrueFalseTotal
unless $list 0 30 30
2443 30 foreach my $attribute (@$list) {
2444 252 $self->_addAttributeToResponse( $req, $data,
2445 $userinfo_response, $rp, $attribute );
2446 }
2447 }
2448 }
2449  
2450 18 my $h = $self->p->processHook( $req, 'oidcGenerateUserInfoResponse',
2451 $userinfo_response, $rp, $data );
2452 18 ▶ return {} if ( $h != PE_OK );
Branch: 1 branch
BranchTrueFalseTotal
if $h != 0 0 18 18
2453  
2454 18 return $userinfo_response;
2455 }
2456  
2457 58 ▶sub _formatValue {
Subroutine _formatValue: called CC=4 SCAR=15.5
2458 58 my ( $self, $session_value, $type, $array, $attribute, $user ) = @_;
2459  
2460 # If $session_value is not a scalar, return it as is
2461 58 ▶ unless ( ref($session_value) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $session_value) 58 0 58
2462 58 ▶ if ( defined $session_value ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $session_value) 58 0 58
2463  
2464 # Empty strings or lists are invalid values
2465 58 ▶ if ( length($session_value) > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $session_value > 0) { } 58 0 58
2466  
2467 # Format value for JSON output: multi valuation, JSON type...
2468 58 my $separator = $self->conf->{multiValuesSeparator};
2469 58 return $self->_applyType( $session_value, $separator, $type,
2470 $array, $attribute, $user );
2471 }
2472 else {
2473 0 return undef;
2474 }
2475 }
2476 }
2477 0 return $session_value;
2478 }
2479  
2480 58 ▶sub _applyType {
Subroutine _applyType: called CC=7 SCAR=31.5
2481 58 my ( $self, $session_value, $separator, $type, $array, $attribute, $user )
2482 = @_;
2483  
2484 # Array style handling
2485 # In auto array mode, split as array only if there are multiple values
2486 58 ▶ if ( $array eq "auto" ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($array eq 'auto') { } 58 0 58
elsif ($array eq 'always') { } 0 0 0
2487 58 ▶ if ( $session_value and $session_value =~ /$separator/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($session_value and $session_value =~ /$separator/) { } 0 58 58
Condition33%1/3
$session_value and $session_value =~ /$separator/
!ll&&!rl&&r
0580
MC/DC0%0/2
$session_value and $session_value =~ /$separator/
$session_value $session_value =~ /$separator/
Truth table33%1/3
A and B
A= $session_valueB= $session_value =~ /$separator/
ABresult
0X0
100
111
2488 $session_value = [
2489 0 map { $self->_forceType( $_, $type ) }
2490 split( $separator, $session_value )
2491 ];
2492 }
2493 else {
2494 58 $session_value = $self->_forceType( $session_value, $type );
2495 }
2496  
2497 # In always array mode, always split (even on empty values)
2498 }
2499 elsif ( $array eq "always" ) {
2500 $session_value = [
2501 0 map { $self->_forceType( $_, $type ) }
2502 split( $separator, $session_value )
2503 ];
2504 }
2505  
2506 # In never array mode, return the string as-is
2507 else {
2508 # No type coaxing is possible on a flattened string
2509 0 ▶ if ( $session_value =~ /$separator/ and $type ne "string" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($session_value =~ /$separator/ and $type ne 'string') { } 0 0 0
Condition0%0/3
$session_value =~ /$separator/ and $type ne "string"
!ll&&!rl&&r
000
MC/DC0%0/2
$session_value =~ /$separator/ and $type ne "string"
$session_value =~ /$separator/ $type ne "string"
Truth table0%0/3
A and B
A= $session_value =~ /$separator/B= $type ne "string"
ABresult
0X0
100
111
2510 0 $self->logger->warn( "Cannot force type of value $session_value"
2511 . " for attribute $attribute of user "
2512 . $user
2513 . " because it is multi-valued. "
2514 . "Use auto or always as array type for this attribute" );
2515 }
2516 else {
2517 0 $session_value = $self->_forceType( $session_value, $type );
2518 }
2519 }
2520  
2521 58 return $session_value;
2522 }
2523  
2524 58 ▶sub _forceType {
Subroutine _forceType: called CC=4 SCAR=16.1
2525 58 my ( $self, $val, $type ) = @_;
2526  
2527 # Boolean
2528 58 ▶ return ( $val ? JSON::true : JSON::false ) if ( $type eq "bool" );
Branch: 2 branches
BranchTrueFalseTotal
if $type eq "bool" 0 58 58
$val ? : 0 0 0
2529  
2530 # Coax into int
2531 58 ▶ return ( $val + 0 ) if ( $type eq "int" );
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "int" 0 58 58
2532  
2533 # Coax into string
2534 58 return ( $val . "" );
2535 }
2536  
2537 # Return JWT
2538 # @param payload JWT content
2539 # @param alg Signature algorithm
2540 # @param rp Internal Relying Party identifier
2541 # @return String jwt JWT
2542  
2543 20 ▶sub createJWT {
Subroutine createJWT: called CC=3 SCAR=11.8
Pod documented
2544 20 my ( $self, $payload, $alg, $rp, $extra_headers_or_type ) = @_;
2545  
2546 20 my $extra_headers = $extra_headers_or_type;
2547  
2548 # Compatibility with old signature
2549 20 ▶ if ( !ref($extra_headers_or_type) and $extra_headers_or_type ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $extra_headers_or_type and $extra_headers_or_type) 0 20 20
Condition66%2/3
not ref $extra_headers_or_type and $extra_headers_or_type
!ll&&!rl&&r
1910
MC/DC0%0/2
not ref $extra_headers_or_type and $extra_headers_or_type
not ref $extra_headers_or_type $extra_headers_or_type
Truth table66%2/3
not(A) and B
A= not ref $extra_headers_or_typeB= $extra_headers_or_type
ABresult
0X0
100
111
2550 0 $extra_headers = { typ => $extra_headers_or_type };
2551 }
2552  
2553 20 return $self->_createJWT( $payload, $alg, $rp, $extra_headers );
2554 }
2555  
2556 0 ▶sub createJWTForOP {
Subroutine createJWTForOP: not called CC=3 SCAR=24.8
Pod undocumented
2557 0 my ( $self, $payload, $alg, $op, $extra_headers_or_type ) = @_;
2558  
2559 0 my $extra_headers = $extra_headers_or_type;
2560  
2561 # Compatibility with old signature
2562 0 ▶ if ( !ref($extra_headers_or_type) and $extra_headers_or_type ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $extra_headers_or_type and $extra_headers_or_type) 0 0 0
Condition0%0/3
not ref $extra_headers_or_type and $extra_headers_or_type
!ll&&!rl&&r
000
MC/DC0%0/2
not ref $extra_headers_or_type and $extra_headers_or_type
not ref $extra_headers_or_type $extra_headers_or_type
Truth table0%0/3
not(A) and B
A= not ref $extra_headers_or_typeB= $extra_headers_or_type
ABresult
0X0
100
111
2563 0 $extra_headers = { typ => $extra_headers_or_type };
2564 }
2565  
2566 0 return $self->_createJWT( $payload, $alg, $op, $extra_headers, 1 );
2567 }
2568  
2569 20 ▶sub _createJWT {
Subroutine _createJWT: called CC=17 SCAR=32.3
2570 20 my ( $self, $payload, $alg, $partner, $extra_headers, $isRp ) = @_;
2571  
2572 20 my @keyArg;
2573 20 ▶ $extra_headers //= {};
Condition100%2/2
$extra_headers //= {}
l!l
191
MC/DC100%1/1
$extra_headers //= {}
$extra_headers
Truth table100%2/2
A
A= $extra_headers
Aresult
11
00
2574  
2575 # Set Cript::JWT arguments depending on "alg"
2576 # a) "none"
2577 20 ▶ if ( $alg eq 'none' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($alg eq 'none') { } 0 20 20
elsif ($alg =~ /^HS/) { } 9 11 20
2578 0 @keyArg = ( allow_none => 1 );
2579 }
2580  
2581 # b) HMAC algorithms, key is the client secret
2582 elsif ( $alg =~ /^HS/ ) {
2583  
2584 # Sign with client secret
2585 my $client_secret =
2586 $isRp
2587 ? $self->opOptions->{$partner}->{oidcOPMetaDataOptionsClientSecret}
2588 9 ▶ : $self->rpOptions->{$partner}->{oidcRPMetaDataOptionsClientSecret};
Branch: 1 branch
BranchTrueFalseTotal
$isRp ? : 0 9 9
2589 9 ▶ unless ($client_secret) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client_secret) 0 9 9
2590 0 $self->logger->error(
2591 "Algorithm $alg needs a Client Secret to sign JWT");
2592 0 return;
2593 }
2594 9 @keyArg = ( key => $client_secret );
2595 }
2596  
2597 # c) asymetric algorithms
2598 else {
2599 my $key_list =
2600 $isRp
2601 ? $self->opOptions->{$partner}->{oidcOPMetaDataOptionsSigningKey}
2602 11 ▶ : $self->rpOptions->{$partner}->{oidcRPMetaDataOptionsSigningKey};
Branch: 1 branch
BranchTrueFalseTotal
$isRp ? : 0 11 11
2603 11 ▶ $key_list ||= $self->conf->{oidcServiceSignatureKey};
Condition33%1/3
$key_list ||= $self->conf->{"oidcServiceSignatureKey"}
l!l&&r!l&&!r
0110
MC/DC0%0/2
$key_list ||= $self->conf->{"oidcServiceSignatureKey"}
$key_list $self->conf->{"oidcServiceSignatureKey"}
Truth table33%1/3
A ||= B
A= $key_listB= $self->conf->{"oidcServiceSignatureKey"}
ABresult
1X1
011
000
2604 11 my $key_id = ( split( /\s*,\s*/, $key_list ) )[0];
2605 11 my $priv_key = $self->get_private_key($key_id);
2606  
2607 11 ▶ unless ($priv_key) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($priv_key) 0 11 11
2608 0 $self->logger->error(
2609 "Algorithm $alg needs a Private Key to sign JWT");
2610 0 return;
2611 }
2612  
2613 11 my $key_type = $self->_getKeyType($priv_key);
2614 11 my $required_key_type = $self->_getRequiredKeyTypeForAlg($alg);
2615 11 ▶ if ( $required_key_type and $key_type ne $required_key_type ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($required_key_type and $key_type ne $required_key_type) 0 11 11
Condition33%1/3
$required_key_type and $key_type ne $required_key_type
!ll&&!rl&&r
0110
MC/DC0%0/2
$required_key_type and $key_type ne $required_key_type
$required_key_type $key_type ne $required_key_type
Truth table33%1/3
A and B
A= $required_key_typeB= $key_type ne $required_key_type
ABresult
0X0
100
111
2616 0 $self->logger->error(
2617 "Algorithm $alg needs a $required_key_type key to sign JWT,"
2618 . " but key $key_id is $key_type" );
2619 0 return;
2620 }
2621  
2622 11 @keyArg = ( key => \$priv_key->{private}, );
2623  
2624 11 ▶ if ( $priv_key->{external_id} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($priv_key->{"external_id"}) 1 10 11
2625 1 $extra_headers->{kid} = $priv_key->{external_id};
2626 }
2627 11 my $key_info = $self->getCertInfo( $priv_key->{public} );
2628 11 ▶ if ( $key_info->{x5t} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_info->{"x5t"}) 11 0 11
2629 11 $extra_headers->{x5t} = $key_info->{x5t};
2630 }
2631 }
2632  
2633 my $noTyp =
2634 $isRp
2635 ? $self->opOptions->{$partner}->{oidcOPMetaDataOptionsNoJwtHeader}
2636 20 ▶ : $self->rpOptions->{$partner}->{oidcRPMetaDataOptionsNoJwtHeader};
Branch: 1 branch
BranchTrueFalseTotal
$isRp ? : 0 20 20
2637 20 ▶ if ($noTyp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($noTyp) { } 3 17 20
2638 3 delete $extra_headers->{typ};
2639 }
2640 else {
2641 17 ▶ $extra_headers->{typ} ||= 'JWT';
Condition100%2/2
$extra_headers->{"typ"} ||= "JWT"
l!l
161
MC/DC100%1/1
$extra_headers->{"typ"} ||= "JWT"
$extra_headers->{"typ"}
Truth table100%2/2
A
A= $extra_headers->{"typ"}
Aresult
11
00
2642 }
2643  
2644 # Encode payload here due to #2748
2645 20 my $jwt = eval {
2646 20 encode_jwt(
2647 payload => to_json($payload),
2648 alg => $alg,
2649 extra_headers => $extra_headers,
2650 @keyArg,
2651 );
2652 };
2653 20 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 20 20
2654 0 $self->logger->error("Unable to build JWT: $@");
2655 0 return;
2656 }
2657 20 return $jwt;
2658 }
2659  
2660 # Return ID Token
2661 # @param payload ID Token content
2662 # @param rp Internal Relying Party identifier
2663 # @return String id_token ID Token as JWT
2664 15 ▶sub createIDToken {
Subroutine createIDToken: called CC=3 SCAR=11.1
Pod documented
2665 15 my ( $self, $req, $payload, $rp, $sessionData ) = @_;
2666  
2667 # Get signature algorithm
2668 15 my $alg = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIDTokenSignAlg};
2669 15 $self->logger->debug("ID Token signature algorithm: $alg");
2670  
2671 15 my $extra_headers = { typ => "JWT" };
2672 15 my $h = $self->p->processHook( $req, 'oidcGenerateIDToken', $payload, $rp,
2673 $sessionData, $extra_headers );
2674 15 ▶ return undef if ( $h != PE_OK );
Branch: 1 branch
BranchTrueFalseTotal
if $h != 0 0 15 15
2675  
2676 15 my $id_token = $self->createJWT( $payload, $alg, $rp, $extra_headers );
2677 15 ▶ return undef unless $id_token;
Branch: 1 branch
BranchTrueFalseTotal
unless $id_token 0 15 15
2678  
2679 return $self->encryptToken(
2680 $rp,
2681 $id_token,
2682 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAccessTokenEncKeyMgtAlg},
2683 $self->rpOptions->{$rp}
2684 ->{oidcRPMetaDataOptionsAccessTokenEncContentEncAlg},
2685 15 );
2686 }
2687  
2688 # Return flow type
2689 # @param response_type Response type
2690 # @return String flow
2691 16 ▶sub getFlowType {
Subroutine getFlowType: called CC=1 SCAR=0.0
Pod documented
2692 16 my ( $self, $response_type ) = @_;
2693  
2694 return {
2695 "code" => "authorizationcode",
2696 "id_token" => "implicit",
2697 "id_token token" => "implicit",
2698 "code id_token" => "hybrid",
2699 "code token" => "hybrid",
2700 "code id_token token" => "hybrid",
2701 16 }->{$response_type};
2702 }
2703  
2704 # Return sub field of an ID Token
2705 # @param id_token ID Token
2706 # @return String sub
2707 0 ▶sub getIDTokenSub {
Subroutine getIDTokenSub: not called CC=1 SCAR=6.9
Pod documented
2708 0 my ( $self, $id_token ) = @_;
2709 0 my $payload = getJWTPayload($id_token);
2710 0 return $payload->{sub};
2711 }
2712  
2713 # Return JWKS representation of a key
2714 # @param key Raw key
2715 # @return HashRef JWKS key
2716 31 ▶sub key2jwks {
Subroutine key2jwks: called CC=3 SCAR=11.0
Pod documented
2717 31 my ( $self, $key, $type ) = @_;
2718  
2719 31 ▶ if ( $type and $type eq 'EC' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type and $type eq 'EC') { } 7 24 31
Condition100%3/3
$type and $type eq "EC"
!ll&&!rl&&r
1237
MC/DC100%2/2
$type and $type eq "EC"
$type $type eq "EC"
Truth table100%3/3
A and B
A= $typeB= $type eq "EC"
ABresult
0X0
100
111
2720 7 require Crypt::PK::ECC;
2721 7 my $eck = Crypt::PK::ECC->new();
2722 7 $eck->import_key( \$key );
2723 7 return $eck->export_key_jwk( 'public', 1 );
2724 }
2725 else {
2726 24 require Crypt::PK::RSA;
2727 24 my $pk = Crypt::PK::RSA->new();
2728 24 $pk->import_key( \$key );
2729 24 return $pk->export_key_jwk( 'public', 1 );
2730 }
2731 }
2732  
2733 # Return X.509 data if public key is a certificate
2734 # @param key public key or certificate
2735 # @return HashRef of JWK attributes
2736 41 ▶sub getCertInfo {
Subroutine getCertInfo: called CC=2 SCAR=6.9
Pod undocumented
2737 41 my ( $self, $key ) = @_;
2738  
2739 41 ▶ if ( $key =~ /CERTIFICATE/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /CERTIFICATE/) { } 33 8 41
2740 33 my $x509 = Crypt::OpenSSL::X509->new_from_string( $key,
2741 Crypt::OpenSSL::X509::FORMAT_PEM );
2742 33 my $der = $x509->as_string(Crypt::OpenSSL::X509::FORMAT_ASN1);
2743 33 my $hash = sha1($der);
2744 return {
2745 # Caution, x5c is B64, x5t is B64URL, this is not a mistake
2746 33 x5c => [ encode_base64( $der, '' ) ],
2747 x5t => encode_base64url($hash),
2748 };
2749  
2750 }
2751 else {
2752 8 return {};
2753 }
2754 }
2755  
2756 ### JWKS ENDPOINT
2757  
2758 # Keys to display in jwks endpoint:
2759 # Signature:
2760 # - current, new and old key to permit to clients to verify all JWT emitted
2761 # during 3 weeks
2762 # Encryption:
2763 # - only the current key. Old encryption key is kept to permit to
2764 # Auth::OPenIDCOnnect to decrypt all JWE emitted by Issuer but no
2765 # need to display any other key
2766 87 ▶sub _buildJwk {
Subroutine _buildJwk: called CC=5 SCAR=16.1
2767 87 my ( $self, $type, $key ) = @_;
2768 87 ▶ return unless $key;
Branch: 1 branch
BranchTrueFalseTotal
unless $key 57 30 87
2769  
2770 30 my $publicKeyOrCert = $key->{public};
2771 30 my $keyId = $key->{external_id};
2772 30 my $keytype = $self->_getKeyType($key);
2773 return $publicKeyOrCert
2774 ? {
2775 kty => $keytype,
2776 use => lc($type),
2777 (
2778 $type eq 'Enc'
2779 ? ( alg => $self->conf->{oidcServiceEncAlgorithmAlg} )
2780 : ()
2781 ),
2782 ( $keyId ? ( kid => $keyId ) : () ),
2783 30 %{ $self->key2jwks( $publicKeyOrCert, $keytype ) },
2784 30 ▶ %{ $self->getCertInfo($publicKeyOrCert) },
Branch: 3 branches
BranchTrueFalseTotal
$publicKeyOrCert ? : 30 0 30
$type eq 'Enc' ? : 3 27 30
$keyId ? : 26 4 30
2785 }
2786 : ();
2787 }
2788  
2789 # Handle jwks endpoint
2790 23 ▶sub jwks {
Subroutine jwks: called CC=9 SCAR=22.3
Pod undocumented
2791 23 my ( $self, $req ) = @_;
2792 23 ▶ $req->data->{dropCsp} = 1 if $self->conf->{oidcDropCspHeaders};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"oidcDropCspHeaders"} 0 23 23
2793 23 $self->logger->debug("URL detected as an OpenID Connect JWKS URL");
2794  
2795 23 my $jwks = { keys => [] };
2796 23 my $client_id = $req->param('client_id');
2797  
2798 23 my $list_sig_keys;
2799 23 ▶ if ($client_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_id) 1 22 23
2800 1 my $rp = $self->getRP($client_id);
2801 1 ▶ if ($rp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rp) 1 0 1
2802 $list_sig_keys =
2803 1 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsSigningKey};
2804 }
2805 }
2806 23 ▶ $list_sig_keys ||= $self->conf->{oidcServiceSignatureKey} || "";
Condition60%3/5
$list_sig_keys ||= $self->conf->{"oidcServiceSignatureKey"} || ""
l!l&&r!l&&!r
1220
$self->conf->{'oidcServiceSignatureKey'} || ''
l!l
220
MC/DC0%0/2
$list_sig_keys ||= $self->conf->{"oidcServiceSignatureKey"} || ""
$list_sig_keys $self->conf->{'oidcServiceSignatureKey'}
Truth table66%2/3
A ||= B
A= $list_sig_keysB= $self->conf->{'oidcServiceSignatureKey'}
ABresult
1X1
011
000
2807  
2808 23 for my $sig_key ( split( /\s*,\s*/, $list_sig_keys ) ) {
2809 64 push @{ $jwks->{keys} },
2810 $self->_buildJwk( "Sig", $self->get_public_key($sig_key) );
2811 }
2812  
2813 23 ▶ for my $enc_key (
Condition50%1/2
$self->conf->{'oidcServiceEncryptionKey'} || ''
l!l
230
MC/DC0%0/1
$self->conf->{'oidcServiceEncryptionKey'} || ''
$self->conf->{'oidcServiceEncryptionKey'}
Truth table50%1/2
A
A= $self->conf->{'oidcServiceEncryptionKey'}
Aresult
11
00
2814 split( /\s*,\s*/, ( $self->conf->{oidcServiceEncryptionKey} || "" ) ) )
2815 {
2816 23 push @{ $jwks->{keys} },
2817 $self->_buildJwk( "Enc", $self->get_public_key($enc_key) );
2818 }
2819  
2820 23 $self->logger->debug("Send JWKS response sent");
2821 23 return $self->p->sendJSONresponse( $req, $jwks );
2822 }
2823  
2824 # Build Logout Request URI
2825 # @param redirect_uri Redirect URI
2826 # @param id_token_hint ID Token
2827 # @param post_logout_redirect_uri Callback URI
2828 # @param state State
2829 # return String Logout URI
2830 0 ▶sub buildLogoutRequest {
Subroutine buildLogoutRequest: not called CC=5 SCAR=34.0
Pod documented
2831 0 my ( $self, $redirect_uri, @args ) = @_;
2832  
2833 0 my @tab = (qw(id_token_hint post_logout_redirect_uri state client_id));
2834 0 my @prms;
2835 0 ▶ for ( my $i = 0 ; $i < @tab ; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @tab) 0 0 0
2836 0 ▶ push @prms, $tab[$i], $args[$i]
Branch: 1 branch
BranchTrueFalseTotal
if defined $args[$i] 0 0 0
2837 if defined( $args[$i] );
2838 }
2839 0 my $response_url = $redirect_uri;
2840 0 ▶ $response_url .=
Branch: 2 branches
BranchTrueFalseTotal
if @prms 0 0 0
$response_url =~ /\?/ ? : 0 0 0
2841 ( $response_url =~ /\?/ ? '&' : '?' ) . build_urlencoded(@prms)
2842 if (@prms);
2843 0 return $response_url;
2844 }
2845  
2846 # Build Logout Response URI
2847 # @param redirect_uri Redirect URI
2848 # @param state State
2849 # return String Logout URI
2850 0 ▶sub buildLogoutResponse {
Subroutine buildLogoutResponse: not called CC=3 SCAR=24.8
Pod documented
2851 0 my ( $self, $redirect_uri, $state ) = @_;
2852  
2853 0 my $response_url = $redirect_uri;
2854  
2855 0 ▶ if ($state) {
Branch: 1 branch
BranchTrueFalseTotal
if ($state) 0 0 0
2856 0 ▶ $response_url .= ( $redirect_uri =~ /\?/ ? '&' : '?' );
Branch: 1 branch
BranchTrueFalseTotal
$redirect_uri =~ /\?/ ? : 0 0 0
2857 0 $response_url .= build_urlencoded( state => $state );
2858 }
2859  
2860 0 return URI->new($response_url)->as_string;
2861 }
2862  
2863 # Create session_state parameter
2864 # @param session_id Session ID
2865 # @param client_id Client ID
2866 # return String Session state
2867 14 ▶sub createSessionState {
Subroutine createSessionState: called CC=2 SCAR=6.9
Pod undocumented
2868 14 my ( $self, $session_id, $client_id ) = @_;
2869  
2870 my $salt =
2871 14 encode_base64url( $self->conf->{cipher}->encrypt($client_id) );
2872 14 my $data = $client_id . " " . $session_id . " " . $salt;
2873  
2874 14 my $hash = sha256_base64($data);
2875 14 ▶ while ( length($hash) % 4 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length($hash) % 4) 14 14 28
2876 14 $hash .= '=';
2877 }
2878  
2879 14 my $session_state = $hash . "." . $salt;
2880  
2881 14 return $session_state;
2882 }
2883  
2884 # Get request JWT from request uri
2885 # @param request_uri request uri
2886 # return String request JWT
2887 0 ▶sub getRequestJWT {
Subroutine getRequestJWT: not called CC=2 SCAR=17.9
Pod undocumented
2888 0 my ( $self, $request_uri ) = @_;
2889  
2890 0 my $response = $self->ua->get($request_uri);
2891  
2892 0 ▶ if ( $response->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_error) 0 0 0
2893 0 $self->logger->error( "Unable to get request JWT on $request_uri: "
2894 . $response->message );
2895 0 $self->logger->debug(
2896 "Request JWT response received: " . $response->as_string );
2897 0 return;
2898 }
2899  
2900 0 return $response->decoded_content;
2901 }
2902  
2903 216 ▶sub addRouteFromConf {
Subroutine addRouteFromConf: called CC=5 SCAR=16.7
Pod documented
2904 216 my ( $self, $type, %subs ) = @_;
2905  
2906 # avoid a warning in logs when route is already defined
2907 216 ▶ my $getter = { "Auth" => "authRoutes", "Unauth" => "unAuthRoutes" }->{$type}
Condition50%1/2
{'Auth', 'authRoutes', 'Unauth', 'unAuthRoutes'}->{$type} || "${type}Routes"
l!l
2160
MC/DC0%0/1
{'Auth', 'authRoutes', 'Unauth', 'unAuthRoutes'}->{$type} || "${type}Routes"
{'Auth', 'authRoutes', 'Unauth', 'unAuthRoutes'}->{$type}
Truth table50%1/2
A
A= {'Auth', 'authRoutes', 'Unauth', 'unAuthRoutes'}->{$type}
Aresult
11
00
2908 || "${type}Routes";
2909  
2910 216 my $adder = "add${type}Route";
2911 216 foreach ( keys %subs ) {
2912 1012 my $sub = $subs{$_};
2913 1012 my $path = $self->conf->{$_};
2914 1012 ▶ unless ($path) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($path) 0 1012 1012
2915 0 $self->logger->error("$_ parameter not defined");
2916 0 next;
2917 }
2918  
2919 # Avoid warning if loading modules twice
2920 1012 ▶ next if $self->p->$getter->{GET}->{ $self->path }->{$path};
Branch: 1 branch
BranchTrueFalseTotal
if $self->p->$getter->{"GET"}{$self->path}{$path} 10 1002 1012
2921  
2922 1002 $self->$adder(
2923 $self->path => { $path => $sub },
2924 [ 'GET', 'POST' ]
2925 );
2926 }
2927 }
2928  
2929 # Validate PKCE code challenge with given code challenge method
2930 # @param code_verifier
2931 # @param code_challenge
2932 # @param code_challenge_method
2933 # @return boolean 1 if challenge succeed, 0 else
2934 12 ▶sub validatePKCEChallenge {
Subroutine validatePKCEChallenge: called CC=9 SCAR=40.3
Pod documented
2935 12 my ( $self, $code_verifier, $code_challenge, $code_challenge_method ) = @_;
2936  
2937 12 ▶ unless ($code_challenge) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($code_challenge) 12 0 12
2938  
2939 # RFC 9700 section 2.1.1: Mitigate PKCE downgrade attacks
2940 # Reject code_verifier if no code_challenge was sent during authorization
2941 12 ▶ if ($code_verifier) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code_verifier) 0 12 12
2942 0 $self->userLogger->error(
2943 "PKCE downgrade attack: code_verifier provided "
2944 . "but no code_challenge was sent during authorization" );
2945 0 return 0;
2946 }
2947 12 $self->logger->debug("PKCE was not requested by the RP");
2948 12 return 1;
2949 }
2950  
2951 0 ▶ unless ($code_verifier) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($code_verifier) 0 0 0
2952 0 $self->logger->error("PKCE required but no code verifier provided");
2953 0 return 0;
2954 }
2955  
2956 0 $self->logger->debug("PKCE code verifier received: $code_verifier");
2957  
2958 0 ▶ if ( !$code_challenge_method or $code_challenge_method eq "plain" ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $code_challenge_method or $code_challenge_method eq 'plain') { } 0 0 0
elsif ($code_challenge_method eq 'S256') { } 0 0 0
Condition0%0/3
not $code_challenge_method or $code_challenge_method eq "plain"
l!l&&r!l&&!r
000
MC/DC0%0/2
not $code_challenge_method or $code_challenge_method eq "plain"
not $code_challenge_method $code_challenge_method eq "plain"
Truth table0%0/3
not(A) or B
A= not $code_challenge_methodB= $code_challenge_method eq "plain"
ABresult
1X1
011
000
2959 0 ▶ if ( $code_verifier eq $code_challenge ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code_verifier eq $code_challenge) { } 0 0 0
2960 0 $self->logger->debug("PKCE challenge validated (plain method)");
2961 0 return 1;
2962 }
2963 else {
2964 0 $self->logger->error("PKCE challenge failed (plain method)");
2965 0 return 0;
2966 }
2967 }
2968  
2969 elsif ( $code_challenge_method eq "S256" ) {
2970 0 my $code_verifier_hashed = encode_base64url( sha256($code_verifier) );
2971 0 ▶ if ( $code_verifier_hashed eq $code_challenge ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code_verifier_hashed eq $code_challenge) { } 0 0 0
2972 0 $self->logger->debug("PKCE challenge validated (S256 method)");
2973 0 return 1;
2974 }
2975 else {
2976 0 $self->logger->error("PKCE challenge failed (S256 method)");
2977 0 return 0;
2978 }
2979 }
2980  
2981 else {
2982 0 $self->logger->error("PKCE challenge method not valid");
2983 0 return 0;
2984 }
2985  
2986 0 return 0;
2987 }
2988  
2989 15 ▶sub force_id_claims {
Subroutine force_id_claims: called CC=1 SCAR=0.0
Pod undocumented
2990 15 my ( $self, $rp ) = @_;
2991 15 return $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsIDTokenForceClaims};
2992 }
2993  
2994 # https://openid.net/specs/openid-connect-core-1_0.html#IDToken
2995 # Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0
2996 # client_id of the Relying Party as an audience value. It MAY also contain
2997 # identifiers for other audiences. In the general case, the aud value is an
2998 # array of case sensitive strings. In the common special case when there is one
2999 # audience, the aud value MAY be a single case sensitive string.
3000 37 ▶sub getAudiences {
Subroutine getAudiences: called CC=2 SCAR=6.9
Pod undocumented
3001 37 my ( $self, $rp ) = @_;
3002  
3003 37 my $client_id = $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsClientID};
3004 my @addAudiences = split /\s+/,
3005 ( $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsAdditionalAudiences}
3006 37 ▶ || '' );
Condition100%2/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAdditionalAudiences'} || ''
l!l
1027
MC/DC100%1/1
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAdditionalAudiences'} || ''
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAdditionalAudiences'}
Truth table100%2/2
A
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsAdditionalAudiences'}
Aresult
11
00
3007  
3008 37 my $result = [$client_id];
3009 37 push @{$result}, @addAudiences;
3010  
3011 37 return $result;
3012 }
3013  
3014 # Returns the main attribute (sub) to use for this RP
3015 # It can be a session attribute, or per-RP macro
3016 49 ▶sub getUserIDForRP {
Subroutine getUserIDForRP: called CC=4 SCAR=14.1
Pod undocumented
3017 49 my ( $self, $req, $rp, $data ) = @_;
3018  
3019 # Use pre-computed sub if available (stored in online refresh tokens for
3020 # back-channel logout). This must use a dedicated key (_oidc_logout_sub)
3021 # and not _oidc_sub, because _oidc_sub may be set by the Auth/OpenIDConnect
3022 # module with the sub returned by an upstream OP when LL::NG acts as a
3023 # gateway (see #3627).
3024 49 ▶ return $data->{_oidc_logout_sub} if $data->{_oidc_logout_sub};
Branch: 1 branch
BranchTrueFalseTotal
if $data->{"_oidc_logout_sub"} 0 49 49
3025  
3026 my $user_id_attribute =
3027 $self->rpOptions->{$rp}->{oidcRPMetaDataOptionsUserIDAttr}
3028 49 ▶ || $self->conf->{whatToTrace};
Condition66%2/3
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsUserIDAttr'} || $self->conf->{'whatToTrace'}
l!l&&r!l&&!r
4450
MC/DC0%0/2
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsUserIDAttr'} || $self->conf->{'whatToTrace'}
$self->rpOptions->{$rp}{'oidcRPMetaDataOptionsUserIDAttr'} $self->conf->{'whatToTrace'}
Truth table66%2/3
A || B
A= $self->rpOptions->{$rp}{'oidcRPMetaDataOptionsUserIDAttr'}B= $self->conf->{'whatToTrace'}
ABresult
1X1
011
000
3029  
3030 # If the main attribute is a SP macro, resolve it
3031 # else, get it directly from session data
3032 return $self->rpMacros->{$rp}->{$user_id_attribute}
3033 ? $self->rpMacros->{$rp}->{$user_id_attribute}->( $req, $data )
3034 49 ▶ : $data->{$user_id_attribute};
Branch: 1 branch
BranchTrueFalseTotal
$self->rpMacros->{$rp}{$user_id_attribute} ? : 4 45 49
3035 }
3036  
3037 # Return storage options
3038 75 ▶sub _storeOpts {
Subroutine _storeOpts: called CC=2 SCAR=7.1
3039 75 my ($self) = @_;
3040 my $storage =
3041 $self->conf->{oidcStorage}
3042 ? {
3043 storageModule => $self->conf->{oidcStorage},
3044 storageModuleOptions => $self->conf->{oidcStorageOptions},
3045 }
3046 : {
3047 storageModule => $self->conf->{globalStorage},
3048 storageModuleOptions => $self->conf->{globalStorageOptions},
3049 75 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$self->conf->{'oidcStorage'} ? : 75 0 75
3050 75 return %$storage;
3051 }
3052  
3053 37 ▶sub generateNonce {
Subroutine generateNonce: called CC=1 SCAR=0.0
Pod undocumented
3054 37 my ($self) = @_;
3055 37 return encode_base64url( Crypt::URandom::urandom(16) );
3056 }
3057  
3058 50 ▶sub getSidFromSession {
Subroutine getSidFromSession: called CC=4 SCAR=13.9
Pod undocumented
3059 50 my ( $self, $rp, $sessionInfo ) = @_;
3060 50 ▶ return $sessionInfo->{_oidc_sid} if $sessionInfo->{_oidc_sid};
Branch: 1 branch
BranchTrueFalseTotal
if $sessionInfo->{"_oidc_sid"} 0 50 50
3061  
3062 # sid is computed from the storage ID: it is the only one available when
3063 # the session is read by its storage ID (GlobalLogout, SingleSession)
3064 50 my $storageId = $sessionInfo->{_session_storage_id};
3065 50 ▶ unless ( defined $storageId ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $storageId) 49 1 50
3066 49 $storageId = $sessionInfo->{_session_id};
3067 $storageId = id2storage($storageId)
3068 49 ▶ if $self->conf->{hashedSessionStore};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"hashedSessionStore"} 3 46 49
3069 }
3070 50 return Digest::SHA::hmac_sha256_base64( $storageId . ':' . $rp );
3071 }
3072  
3073 2 ▶sub decryptJwt {
Subroutine decryptJwt: called CC=6 SCAR=33.0
Pod undocumented
3074 2 my ( $self, $jwt ) = @_;
3075 2 my @count = split /\./, $jwt;
3076 2 ▶ if ( $#count == 4 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($#count == 4) 0 2 2
3077 0 my $key = $self->conf->{oidcServicePrivateKeyEnc};
3078 0 $self->logger->debug("Receive an encrypted JWT: $jwt");
3079 0 ▶ unless ($key) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($key) 0 0 0
3080 0 $self->logger->error('Receive an encrypted JWT but no key defined');
3081 0 return $jwt;
3082 }
3083  
3084 0 my $tmp;
3085 0 eval { $tmp = decode_jwt( token => $jwt, key => \$key, ); };
3086 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
3087 0 ▶ if ( $key = $self->conf->{oidcServiceOldPrivateKeyEnc} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key = $self->conf->{"oidcServiceOldPrivateKeyEnc"}) 0 0 0
3088 0 eval { $tmp = decode_jwt( token => $jwt, key => \$key, ); };
3089 }
3090 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
3091 0 $self->logger->error( 'Unable to decrypt JWE: ' . $@ );
3092 0 return undef;
3093 }
3094 }
3095 0 $jwt = $tmp;
3096 0 $self->logger->debug("Decrypted JWT: $jwt");
3097 }
3098 2 return $jwt;
3099 }
3100  
3101 45 ▶sub _getKeyType {
Subroutine _getKeyType: called CC=3 SCAR=11.0
3102 45 my ( $self, $key ) = @_;
3103  
3104 45 require Crypt::PK::RSA;
3105  
3106 45 my $rsa_pub = eval { Crypt::PK::RSA->new( \( $key->{public} ) ) };
3107 45 ▶ if ($rsa_pub) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rsa_pub) 38 7 45
3108 38 return "RSA";
3109 }
3110  
3111 7 require Crypt::PK::ECC;
3112  
3113 7 my $ecc_pub = eval { Crypt::PK::ECC->new( \( $key->{public} ) ) };
3114 7 ▶ if ($ecc_pub) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ecc_pub) 7 0 7
3115 7 return "EC";
3116 }
3117  
3118 0 return;
3119 }
3120  
3121 11 ▶sub _getRequiredKeyTypeForAlg {
Subroutine _getRequiredKeyTypeForAlg: called CC=3 SCAR=15.1
3122 11 my ( $self, $alg ) = @_;
3123 11 ▶ if ( $alg =~ m/^(?:R|P)S/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($alg =~ /^(?:R|P)S/) { } 11 0 11
elsif ($alg =~ /^ES/) { } 0 0 0
3124 11 return "RSA";
3125 }
3126 elsif ( $alg =~ /^ES/ ) {
3127 0 return "EC";
3128 }
3129 0 return;
3130 }
3131  
3132 55 1;
3133  
3134 __END__
« blib/lib/Lemonldap/NG/Portal/Password/Base.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Plugins/CheckHIBP.pm »