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

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