blib/lib/Lemonldap/NG/Portal/Plugins/OIDCNativeSso.pm untested

filter: Statementstmt 0.0% 0 / 110 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 5 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 177 CC 21 SCAR 42.6
CC
21
Cov
0%
tokenExchangeHook
182.0
resolveScope
20.0
tokenResponse
12.0
CRAP 70.5
1 package Lemonldap::NG::Portal::Plugins::OIDCNativeSso;
2  
3 use strict;
4 use Digest::SHA qw(sha256_hex);
5 use Mouse;
6 use Lemonldap::NG::Common::JWT qw(getJWTPayload);
7 use Lemonldap::NG::Portal::Issuer::OpenIDConnect;
8 use Lemonldap::NG::Portal::Main::Constants qw(
9 PE_BADCREDENTIALS
10 PE_ERROR
11 PE_OK
12 PE_SENDRESPONSE
13 );
14 use String::Random qw/random_string/;
15  
16 our $VERSION = '2.21.0';
17  
18 extends 'Lemonldap::NG::Portal::Main::Plugin';
19  
20 use constant hook => {
21  
22 # Step 1 verify that device_sso scope is authorized during authorization request
23 oidcResolveScope => 'resolveScope',
24  
25 # Step 2: generate device_secret
26 oidcGenerateAccessToken => 'accessTokenHook',
27 oidcGenerateIDToken => 'addDsHash',
28 oidcGenerateTokenResponse => 'tokenResponse',
29  
30 # Step 3: give new access_token when device_secret is valid
31 oidcGotTokenExchange => 'tokenExchangeHook',
32 };
33  
34 has oidc => (
35 is => 'ro',
36 lazy => 1,
37 default => sub {
38 $_[0]
39 ->p->loadedModules->{'Lemonldap::NG::Portal::Issuer::OpenIDConnect'};
40 }
41 );
42  
43 sub init {
44 my ($self) = @_;
45 unless ( $self->conf->{issuerDBOpenIDConnectActivation} ) {
46 $self->logger->error(
47 'This plugin can be used only if OIDC server is enabled');
48 return 0;
49 }
50 1;
51 }
52  
53 use constant sessionKind => 'OIDCI';
54  
55 # STEP 1: verify that device_sso scope is authorized during authorization request
56  
57 sub resolveScope {
58 my ( $self, $req, $scopeList, $rp ) = @_;
59 unless (
60 $self->oidc->rpOptions->{$rp}->{oidcRPMetaDataOptionsAllowNativeSso} )
61 {
62 my @scopes;
63  
64 # To keep $scopeList reference, empty related array then populate it
65 while (@$scopeList) {
66 my $tmp = shift(@$scopeList);
67 if ( $tmp eq 'device_sso' ) {
68 $self->userLogger->error(
69 "Request scope device_sso for an unauthorized RP: $rp");
70 }
71 else {
72 push @scopes, $tmp unless $tmp eq 'device_sso';
73 }
74 }
75 push @$scopeList, @scopes;
76 }
77 return PE_OK;
78 }
79  
80 # STEP 2: generate device_secret
81 sub accessTokenHook {
82 my ( $self, $req, $payload, $rp ) = @_;
83 if ( $payload->{scope} =~ /\bdevice_sso\b/ ) {
84 $req->data->{oidcNativeSso} = {
85 scope => $payload->{scope},
86 ds_hash => random_string( 's' x 32 ),
87 };
88 }
89 return PE_OK;
90 }
91  
92 sub addDsHash {
93 my ( $self, $req, $payload, $rp ) = @_;
94 if ( $req->data->{oidcNativeSso} ) {
95 $payload->{ds_hash} = $req->data->{oidcNativeSso}->{ds_hash};
96 }
97 return PE_OK;
98 }
99  
100 sub tokenResponse {
101 my ( $self, $req, $rp, $tokenResponse, $oidcSession, $sessionInfo ) = @_;
102 if ( $req->data->{oidcNativeSso} ) {
103 my %userInfo = ( ds_hash => $req->data->{oidcNativeSso}->{ds_hash} );
104 for my $userKey ( grep !/^(_session|_utime$|_lastSeen$)/,
105 keys %$sessionInfo )
106 {
107 $userInfo{$userKey} = $sessionInfo->{$userKey};
108 }
109 my $deviceSecret = $self->oidc->getOpenIDConnectSession(
110 undef,
111 'device_secret',
112  
113 # Fix device_secret timeout to the same value than offline token
114 $self->oidc->rpOptions->{$rp}->{oidcRPMetaDataOptionsAllowOffline}
115 ? ( $self->oidc->rpOptions->{$rp}
116 ->{oidcRPMetaDataOptionsOfflineSessionExpiration}
117 || $self->conf->{oidcServiceOfflineSessionExpiration} )
118 : $self->conf->{timeout},
119 {
120 %userInfo,
121 redirect_uri => $oidcSession->{redirect_uri},
122 scope => $req->data->{oidcNativeSso}->{scope},
123 client_id => $self->conf->{oidcRPMetaDataOptions}->{$rp}
124 ->{oidcRPMetaDataOptionsClientID},
125 _session_uid => $sessionInfo->{_user},
126 auth_time => $sessionInfo->{_lastAuthnUTime},
127 grant_type => "authorizationcode",
128 id_token_h => sha256_hex( $tokenResponse->{id_token} ),
129 },
130 );
131 $tokenResponse->{device_secret} = $deviceSecret->id;
132 }
133 return PE_OK;
134 }
135  
136 use constant T_LOG_PREFIX => 'Native SSO token exchange: ';
137  
138 # STEP 3: give new access_token when device_secret is valid
139 sub tokenExchangeHook {
140 my ( $self, $req, $rp ) = @_;
141  
142 # Ignore request if token exchange isn't for this plugin
143 return PE_OK
144 unless $req->param('actor_token_type') eq
145 'urn:x-oath:params:oauth:token-type:device-secret';
146  
147 if ( $self->conf->{oidcRPMetaDataOptions}->{$rp}
148 ->{oidcRPMetaDataOptionsAllowNativeSso} )
149 {
150 # STEP 3.1: Check parameters
151  
152 # Required parameter list
153 foreach (
154 qw(audience subject_token subject_token_type actor_token actor_token_type)
155 )
156 {
157 unless ( $req->param($_) ) {
158 $self->userLogger->error( T_LOG_PREFIX . "missing $_" );
159 return PE_ERROR;
160 }
161 }
162  
163 # Check for static parameters
164 unless ( $req->param('subject_token_type') eq
165 'urn:ietf:params:oauth:token-type:id_token' )
166 {
167 $self->userLogger->error(
168 T_LOG_PREFIX . 'Bad subject_token_type or actor_token_type' );
169 return PE_ERROR;
170 }
171  
172 # Check for audience that should be the issuer
173 # (given by "iss" field of id_token)
174  
175 unless ( $req->param('audience') eq $self->oidc->iss ) {
176 $self->userLogger->error( T_LOG_PREFIX
177 . 'missing or bad audience '
178 . $req->param('audience') );
179 return PE_ERROR;
180 }
181  
182 # Check for device_secret
183 my $deviceSecret = $req->param('actor_token');
184 my $session =
185 $self->oidc->getOpenIDConnectSession( $deviceSecret,
186 "device_secret" );
187 unless ($session) {
188 $self->userLogger->error(
189 T_LOG_PREFIX . "bad device_secret $deviceSecret" );
190 return PE_ERROR;
191 }
192  
193 # Check for id_token
194 my $idTokenHint = $req->param('subject_token');
195 unless ( sha256_hex($idTokenHint) eq $session->data->{id_token_h} ) {
196 $self->userLogger->error(
197 T_LOG_PREFIX . 'subject_token does not match actor_token' );
198 return PE_ERROR;
199 }
200  
201 # Check also for ds_hash
202 my $dsHash = getJWTPayload($idTokenHint)->{ds_hash};
203 unless ( $dsHash eq $session->data->{ds_hash} ) {
204 $self->userLogger->error( T_LOG_PREFIX . 'ds_hash mismatch' );
205 return PE_ERROR;
206 }
207  
208 # STEP 3.2: generate new refresh_token and access_token
209 my ( $access_token, $refresh_token );
210  
211 $self->oidc->getAttributesForUser( $req, $session ) or return PE_ERROR;
212  
213 if (
214 $self->oidc->rpOptions->{$rp}->{oidcRPMetaDataOptionsAllowOffline} )
215 {
216 my %refreshInfo = (
217 map {
218 /^(?:_session_.*|_utime$|ds_hash|id_token_h|client_id|redirect_uri|_type)$/
219 ? ()
220 : ( $_ => $session->data->{$_} )
221 } keys %{ $session->data }
222 );
223 my $refreshTokenSession = $self->oidc->newRefreshToken(
224 $rp,
225 {
226 %refreshInfo,
227  
228 # TODO: adapt scope if asked
229 #scope =>
230 client_id => $self->oidc->rpOptions->{$rp}
231 ->{oidcRPMetaDataOptionsClientID},
232 _session_uid => $session->data->{_session_uid},
233 auth_time => $session->data->{_lastAuthnUTime},
234 }
235 );
236 $refresh_token = $refreshTokenSession->id;
237 }
238  
239 $access_token = $self->oidc->newAccessToken(
240 $req, $rp,
241 $session->data->{scope},
242 $session->data,
243 {
244 # TODO: offline_session_id must point to refresh_token
245 offline_session_id => $refresh_token,
246 grant_type => $session->data->{grant_type},
247 }
248 );
249  
250 unless ($access_token) {
251 $self->userLogger->error("Unable to create Access Token");
252 return PE_ERROR;
253 }
254  
255 # Send response
256  
257 my $response = {
258 issued_token_type =>
259 'urn:ietf:params:oauth:token-type:access_token',
260 token_type => 'Bearer',
261 access_token => $access_token,
262 expires_in => 'TODO',
263 ( $refresh_token ? ( refresh_token => $refresh_token ) : () ),
264 };
265  
266 $req->response( $self->p->sendJSONresponse( $req, $response ) );
267 return PE_SENDRESPONSE;
268 }
269 else {
270 $self->userLogger->error(
271 "$rp isn't allowed to request for a device_secret");
272 return PE_ERROR;
273 }
274  
275 # Else ignore this request
276 return PE_OK;
277 }
278  
279 1;