OpenIDConnect.pm 58.1 KB
Newer Older
Xavier Guimard's avatar
Xavier Guimard committed
1 2 3
package Lemonldap::NG::Portal::Issuer::OpenIDConnect;

use strict;
4
use JSON qw(from_json to_json);
Xavier Guimard's avatar
Xavier Guimard committed
5
use Mouse;
6
use Lemonldap::NG::Common::FormEncode;
Xavier Guimard's avatar
Xavier Guimard committed
7
use Lemonldap::NG::Portal::Main::Constants qw(
Xavier Guimard's avatar
Xavier Guimard committed
8
  PE_BADURL
9
  PE_CONFIRM
Xavier Guimard's avatar
Xavier Guimard committed
10
  PE_ERROR
11
  PE_LOGOUT_OK
Xavier Guimard's avatar
Xavier Guimard committed
12
  PE_REDIRECT
Xavier Guimard's avatar
Xavier Guimard committed
13
  PE_OK
Xavier Guimard's avatar
Xavier Guimard committed
14
  PE_UNAUTHORIZEDPARTNER
15
  PE_OIDC_SERVICE_NOT_ALLOWED
Xavier Guimard's avatar
Xavier Guimard committed
16 17
);

18
our $VERSION = '2.0.1';
Xavier Guimard's avatar
Xavier Guimard committed
19 20

extends 'Lemonldap::NG::Portal::Main::Issuer',
Xavier Guimard's avatar
Xavier Guimard committed
21 22
  'Lemonldap::NG::Portal::Lib::OpenIDConnect',
  'Lemonldap::NG::Common::Conf::AccessLib';
Xavier Guimard's avatar
Xavier Guimard committed
23

24 25 26 27
# INTERFACE

sub beforeAuth { 'exportRequestParameters' }

Xavier Guimard's avatar
Xavier Guimard committed
28 29
# INITIALIZATION

30 31
use constant sessionKind => 'OIDCI';

32
has rule => ( is => 'rw', default => sub { {} } );
33 34
has configStorage => (
    is      => 'ro',
35
    lazy    => 1,
36 37 38 39
    default => sub {
        $_[0]->{p}->HANDLER->localConfig->{configStorage};
    }
);
40 41
has ssoMatchUrl => ( is => 'rw' );

42 43 44 45 46 47 48 49 50 51 52 53
# OIDC has 7 endpoints managed here as PSGI endpoints or in run() [Main/Issuer.pm
# manage transparent authentication for run()]:
#  - authorize   : in run()
#  - logout      : in run()
#                  => endSessionDone() for unauth users
#  - checksession: => checkSession()   for all
#  - token       : => token()          for unauth users (RP)
#  - userinfo    : => userInfo()       for unauth users (RP)
#  - jwks        : => jwks()           for unauth users (RP)
#  - register    : => registration()   for unauth users (RP)
#
# Other paths will be handle by run() and return PE_ERROR
Xavier Guimard's avatar
Xavier Guimard committed
54 55
#
# .well-known/openid-configuration is handled by metadata()
56

Xavier Guimard's avatar
Xavier Guimard committed
57 58 59
sub init {
    my ($self) = @_;

60 61 62 63 64 65 66 67 68 69 70
    # Parse activation rule
    my $hd = $self->p->HANDLER;
    $self->logger->debug( "OIDC rule -> " . $self->conf->{issuerDBOpenIDConnectRule} );
    my $rule
        = $hd->buildSub( $hd->substitute( $self->conf->{issuerDBOpenIDConnectRule} ) );
    unless ($rule) {
        $self->error( "Bad OIDC rule -> " . $hd->tsv->{jail}->error );
        return 0;
    }
    $self->{rule} = $rule;

Xavier Guimard's avatar
Xavier Guimard committed
71 72 73 74 75 76 77 78
    # Initialize RP list
    return 0
      unless ( $self->Lemonldap::NG::Portal::Main::Issuer::init()
        and $self->loadRPs );

    # Manage RP requests
    $self->addRouteFromConf(
        'Unauth',
79 80
        oidcServiceMetaDataEndSessionURI   => 'endSessionDone',
        oidcServiceMetaDataCheckSessionURI => 'checkSession',
Xavier Guimard's avatar
Xavier Guimard committed
81 82 83 84 85 86 87 88 89
        oidcServiceMetaDataTokenURI        => 'token',
        oidcServiceMetaDataUserInfoURI     => 'userInfo',
        oidcServiceMetaDataJWKSURI         => 'jwks',
        oidcServiceMetaDataRegistrationURI => 'registration',
    );

    # Manage user requests
    $self->addRouteFromConf(
        'Auth',
90
        oidcServiceMetaDataCheckSessionURI => 'checkSession',
Xavier Guimard's avatar
Xavier Guimard committed
91 92 93 94 95
        oidcServiceMetaDataTokenURI        => 'badAuthRequest',
        oidcServiceMetaDataUserInfoURI     => 'badAuthRequest',
        oidcServiceMetaDataJWKSURI         => 'badAuthRequest',
        oidcServiceMetaDataRegistrationURI => 'badAuthRequest',
    );
Xavier Guimard's avatar
Xavier Guimard committed
96 97 98 99 100 101 102 103 104 105

    # Metadata (.well-known/openid-configuration)
    $self->addUnauthRoute(
        '.well-known' => { 'openid-configuration' => 'metadata' },
        ['GET']
    );
    $self->addAuthRoute(
        '.well-known' => { 'openid-configuration' => 'metadata' },
        ['GET']
    );
106 107 108 109 110 111 112 113
    my $m =
        '^/'
      . $self->path . '/+(?:'
      . join( '|',
        $self->conf->{oidcServiceMetaDataAuthorizeURI},
        $self->conf->{oidcServiceMetaDataEndSessionURI},
      ) . ')';
    $self->ssoMatchUrl(qr/$m/);
Xavier Guimard's avatar
Xavier Guimard committed
114 115 116 117 118
    return 1;
}

# RUNNING METHODS

119 120 121 122 123
sub ssoMatch {
    my ( $self, $req ) = @_;
    return ( $req->uri =~ $self->ssoMatchUrl ? 1 : 0 );
}

124 125
# Main method (launched only for authenticated users, see Main/Issuer.pm)
# run() manages only "authorize" and "logout" endpoints.
Xavier Guimard's avatar
Xavier Guimard committed
126 127
sub run {
    my ( $self, $req, $path ) = @_;
128 129 130 131 132 133 134

    # Check activation rule
    unless ( $self->rule->( $req, $req->sessionInfo ) ) {
        $self->userLogger->error('OIDC service not authorized');
        return PE_OIDC_SERVICE_NOT_ALLOWED;
    }

Xavier Guimard's avatar
Xavier Guimard committed
135
    if ($path) {
Christophe Maudoux's avatar
Christophe Maudoux committed
136 137

        # Convert old format OIDC Consents
Christophe Maudoux's avatar
Christophe Maudoux committed
138
        my $ConvertedConsents = $self->_convertOldFormatConsents($req);
139
        $self->logger->debug("$ConvertedConsents consent(s) converted");
Christophe Maudoux's avatar
Christophe Maudoux committed
140

Xavier Guimard's avatar
Xavier Guimard committed
141 142
        # AUTHORIZE
        if ( $path eq $self->conf->{oidcServiceMetaDataAuthorizeURI} ) {
143
            $self->logger->debug(
144
                "URL detected as an OpenID Connect AUTHORIZE URL");
145 146 147 148 149 150

            # Get and save parameters
            my $oidc_request = {};
            foreach my $param (
                qw/response_type scope client_id state redirect_uri nonce
                response_mode display prompt max_age ui_locales id_token_hint
151
                login_hint acr_values request request_uri/
152 153
              )
            {
Xavier Guimard's avatar
Xavier Guimard committed
154 155
                if ( $req->param($param) ) {
                    $oidc_request->{$param} = $req->param($param);
156 157
                    $self->logger->debug( "OIDC request parameter $param: "
                          . $oidc_request->{$param} );
158 159 160
                    $self->p->setHiddenFormValue( $req, $param,
                        $oidc_request->{$param},
                        '', 0 );
Xavier Guimard's avatar
Xavier Guimard committed
161
                }
162 163 164 165 166 167 168
            }

            # Detect requested flow
            my $response_type = $oidc_request->{'response_type'};
            my $flow          = $self->getFlowType($response_type);

            unless ($flow) {
169
                $self->logger->error("Unknown response type: $response_type");
170 171
                return PE_ERROR;
            }
172 173
            $self->logger->debug(
                "OIDC $flow flow requested (response type: $response_type)");
174 175 176 177 178 179 180 181 182 183

            # Extract request_uri/request parameter
            if ( $oidc_request->{'request_uri'} ) {
                my $request =
                  $self->getRequestJWT( $oidc_request->{'request_uri'} );

                if ($request) {
                    $oidc_request->{'request'} = $request;
                }
                else {
184
                    $self->logger->error("Error with Request URI resolution");
185 186 187 188 189 190 191 192 193 194
                    return PE_ERROR;
                }
            }

            if ( $oidc_request->{'request'} ) {
                my $request =
                  $self->getJWTJSONData( $oidc_request->{'request'} );

                # Override OIDC parameters by request content
                foreach ( keys %$request ) {
195 196
                    $self->logger->debug(
"Override $_ OIDC param by value present in request parameter"
197 198
                    );
                    $oidc_request->{$_} = $request->{$_};
199 200
                    $self->p->setHiddenFormValue( $req, $_, $request->{$_},
                        '' );
201 202 203 204 205
                }
            }

            # Check all required parameters
            unless ( $oidc_request->{'redirect_uri'} ) {
206
                $self->logger->error("Redirect URI is required");
207 208 209
                return PE_ERROR;
            }
            unless ( $oidc_request->{'scope'} ) {
210
                $self->logger->error("Scope is required");
211
                return PE_ERROR;
212 213
            }
            unless ( $oidc_request->{'client_id'} ) {
214
                $self->logger->error("Client ID is required");
215
                return PE_ERROR;
216 217 218
            }
            if ( $flow eq "implicit" and not defined $oidc_request->{'nonce'} )
            {
219
                $self->logger->error("Nonce is required for implicit flow");
220 221 222 223 224 225 226 227 228 229 230 231 232
                return PE_ERROR;
            }

            # Check client_id
            my $client_id = $oidc_request->{'client_id'};
            $self->logger->debug("Request from client id $client_id");

            # Verify that client_id is registered in configuration
            my $rp = $self->getRP($client_id);

            unless ($rp) {
                $self->logger->error(
"No registered Relying Party found with client_id $client_id"
233
                );
234 235 236
                return PE_UNAUTHORIZEDPARTNER;
            }
            else {
237
                $self->logger->debug("Client id $client_id matches RP $rp");
238 239
            }

240
            # Check if this RP is authorized
241
            if ( my $rule = $self->spRules->{$rp} ) {
242 243 244
                unless ( $rule->( $req, $req->sessionInfo ) ) {
                    $self->userLogger->warn( 'User '
                          . $req->sessionInfo->{ $self->conf->{whatToTrace} }
245
                          . "was not authorized to access to $rp" );
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
                    return PE_UNAUTHORIZEDPARTNER;
                }
            }

            # Check redirect_uri
            my $redirect_uri  = $oidc_request->{'redirect_uri'};
            my $redirect_uris = $self->conf->{oidcRPMetaDataOptions}->{$rp}
              ->{oidcRPMetaDataOptionsRedirectUris};

            if ($redirect_uris) {
                my $redirect_uri_allowed = 0;
                foreach ( split( /\s+/, $redirect_uris ) ) {
                    $redirect_uri_allowed = 1 if $redirect_uri eq $_;
                }
                unless ($redirect_uri_allowed) {
                    $self->userLogger->error(
                        "Redirect URI $redirect_uri not allowed");
                    return PE_BADURL;
                }
265 266 267 268 269 270
            }

            # Check if flow is allowed
            if ( $flow eq "authorizationcode"
                and not $self->conf->{oidcServiceAllowAuthorizationCodeFlow} )
            {
271 272
                $self->userLogger->error(
                    "Authorization code flow is not allowed");
273 274 275 276 277 278 279 280 281 282
                return $self->returnRedirectError(
                    $req,           $oidc_request->{'redirect_uri'},
                    "server_error", "Authorization code flow not allowed",
                    undef,          $oidc_request->{'state'},
                    0
                );
            }
            if ( $flow eq "implicit"
                and not $self->conf->{oidcServiceAllowImplicitFlow} )
            {
283
                $self->logger->error("Implicit flow is not allowed");
284 285 286 287 288 289 290 291 292 293
                return $self->returnRedirectError(
                    $req,           $oidc_request->{'redirect_uri'},
                    "server_error", "Implicit flow not allowed",
                    undef,          $oidc_request->{'state'},
                    1
                );
            }
            if ( $flow eq "hybrid"
                and not $self->conf->{oidcServiceAllowHybridFlow} )
            {
294
                $self->logger->error("Hybrid flow is not allowed");
295 296 297 298 299 300 301 302 303
                return $self->returnRedirectError(
                    $req,           $oidc_request->{'redirect_uri'},
                    "server_error", "Hybrid flow not allowed",
                    undef,          $oidc_request->{'state'},
                    1
                );
            }

            # Check if user needs to be reauthenticated
Xavier Guimard's avatar
Xavier Guimard committed
304 305 306 307 308 309 310 311 312
            my $prompt = $oidc_request->{'prompt'};
            if (
                    $prompt
                and $prompt =~ /\blogin\b/
                and (
                    time - $req->sessionInfo->{_utime} >
                    $self->conf->{portalForceAuthnInterval} )
              )
            {
313
                $self->logger->debug(
314
"Reauthentication required by Relying Party in prompt parameter"
315
                );
Xavier Guimard's avatar
Xavier Guimard committed
316
                return $self->reAuth($req);
317 318 319 320 321
            }

            my $max_age         = $oidc_request->{'max_age'};
            my $_lastAuthnUTime = $req->{sessionInfo}->{_lastAuthnUTime};
            if ( $max_age && time > $_lastAuthnUTime + $max_age ) {
322
                $self->logger->debug(
323
"Reauthentication forced because authentication time ($_lastAuthnUTime) is too old (>$max_age s)"
324
                );
Xavier Guimard's avatar
Xavier Guimard committed
325
                return $self->reAuth($req);
326 327
            }

328 329 330 331 332 333 334
            # Check scope validity
            unless ( $oidc_request->{'scope'} =~ /^[a-zA-Z_\-\s]+$/ ) {
                $self->logger->error( "Submitted scope is not valid: "
                      . $oidc_request->{'scope'} );
                return PE_ERROR;
            }

335 336
            # Check openid scope
            unless ( $oidc_request->{'scope'} =~ /\bopenid\b/ ) {
337
                $self->logger->debug("No openid scope found");
338 339 340 341 342 343 344 345 346 347 348 349 350 351

                #TODO manage standard OAuth request
                return PE_OK;
            }

            # Check Request JWT signature
            if ( $oidc_request->{'request'} ) {
                unless (
                    $self->verifyJWTSignature(
                        $oidc_request->{'request'},
                        undef, $rp
                    )
                  )
                {
352
                    $self->logger->error(
353
                        "JWT signature request can not be verified");
354 355 356
                    return PE_ERROR;
                }
                else {
357
                    $self->logger->debug("JWT signature request verified");
358 359 360 361 362 363 364
                }
            }

            # Check id_token_hint
            my $id_token_hint = $oidc_request->{'id_token_hint'};
            if ($id_token_hint) {

365
                $self->logger->debug("Check sub of ID Token $id_token_hint");
366 367 368 369 370

                # Check that id_token_hint sub match current user
                my $sub = $self->getIDTokenSub($id_token_hint);
                my $user_id_attribute =
                  $self->conf->{oidcRPMetaDataOptions}->{$rp}
Xavier Guimard's avatar
Xavier Guimard committed
371 372
                  ->{oidcRPMetaDataOptionsUserIDAttr}
                  || $self->conf->{whatToTrace};
373 374
                my $user_id = $req->{sessionInfo}->{$user_id_attribute};
                unless ( $sub eq $user_id ) {
375
                    $self->userLogger->error(
376
                        "ID Token hint sub $sub does not match user $user_id");
377 378 379
                    return $self->returnRedirectError(
                        $req,
                        $oidc_request->{'redirect_uri'},
380
                        'invalid_request',
381
                        "Current user does not match id_token_hint sub",
382 383 384 385 386 387
                        undef,
                        $oidc_request->{'state'},
                        ( $flow ne "authorizationcode" )
                    );
                }
                else {
388
                    $self->logger->debug(
389
                        "ID Token hint sub $sub matches current user");
390 391 392 393 394 395 396
                }
            }

            # Obtain consent
            my $bypassConsent = $self->conf->{oidcRPMetaDataOptions}->{$rp}
              ->{oidcRPMetaDataOptionsBypassConsent};
            if ($bypassConsent) {
397
                $self->logger->debug(
398
"Consent is disabled for Relying Party $rp, user will not be prompted"
399 400 401 402
                );
            }
            else {
                my $ask_for_consent = 1;
403 404
                my $_oidcConsents;
                my @RPoidcConsent = ();
405

406 407
                # Loading existing oidcConsents
                $self->logger->debug("Looking for OIDC Consents ...");
408

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
                if ( $req->{sessionInfo}->{_oidcConsents} ) {
                    $_oidcConsents = eval {
                        from_json( $req->{sessionInfo}->{_oidcConsents},
                            { allow_nonref => 1 } );
                    };
                    if ($@) {
                        $self->logger->error(
                            "Corrupted session (_oidcConsents): $@");
                        return PE_ERROR;
                    }
                }
                else {
                    $self->logger->debug("No OIDC Consent found");
                    $_oidcConsents = [];
                }
424

425
                # Read existing RP
426
                @RPoidcConsent = grep { $_->{rp} eq $rp } @$_oidcConsents;
Xavier Guimard's avatar
Xavier Guimard committed
427
                unless (@RPoidcConsent) {
428 429 430
                    $self->logger->debug("No Relying Party $rp Consent found");

                    # Set default value
431 432
                    push @RPoidcConsent,
                      { rp => $rp, epoch => '', scope => '' };
433 434
                }

435
                if (   $RPoidcConsent[0]{rp} eq $rp
436 437
                    && $RPoidcConsent[0]{epoch}
                    && $RPoidcConsent[0]{scope} )
438
                {
439 440 441
                    $ask_for_consent = 0;
                    my $consent_time  = $RPoidcConsent[0]{epoch};
                    my $consent_scope = $RPoidcConsent[0]{scope};
442 443
                    $self->logger->debug(
"Consent already given for Relying Party $rp (time: $consent_time, scope: $consent_scope)"
444 445 446 447 448 449 450
                    );

                    # Check accepted scope
                    foreach my $requested_scope (
                        split( /\s+/, $oidc_request->{'scope'} ) )
                    {
                        if ( $consent_scope =~ /\b$requested_scope\b/ ) {
451 452
                            $self->logger->debug(
                                "Scope $requested_scope already accepted");
453 454
                        }
                        else {
455 456
                            $self->logger->debug(
"Scope $requested_scope was not previously accepted"
457 458 459 460 461 462 463
                            );
                            $ask_for_consent = 1;
                            last;
                        }
                    }

                    # Check prompt parameter
464 465
                    $ask_for_consent = 1
                      if ( $prompt and $prompt =~ /\bconsent\b/ );
466 467
                }
                if ($ask_for_consent) {
Xavier Guimard's avatar
Xavier Guimard committed
468 469 470
                    if (    $req->param('confirm')
                        and $req->param('confirm') == 1 )
                    {
471
                        $RPoidcConsent[0]{epoch} = time;
472 473
                        $RPoidcConsent[0]{scope} = $oidc_request->{'scope'};
                        push @{$_oidcConsents}, @RPoidcConsent;
474 475 476 477 478
                        $self->logger->debug(
                            "Append Relying Party $rp Consent");
                        $self->p->updatePersistentSession( $req,
                            { _oidcConsents => to_json($_oidcConsents) } );

479 480
                        $self->logger->debug(
                            "Consent given for Relying Party $rp");
481
                    }
Xavier Guimard's avatar
Xavier Guimard committed
482 483 484
                    elsif ( $req->param('confirm')
                        and $req->param('confirm') == -1 )
                    {
485 486
                        $self->logger->debug(
                            "User refused consent for Relying party $rp");
487 488 489 490 491 492 493 494 495 496 497
                        return $self->returnRedirectError(
                            $req,
                            $oidc_request->{'redirect_uri'},
                            "consent_required",
                            "consent not given",
                            undef,
                            $oidc_request->{'state'},
                            ( $flow ne "authorizationcode" )
                        );
                    }
                    else {
498
                        $self->logger->debug(
499
                            "Request user consent for Relying Party $rp");
500 501

                        # Return error if prompt is none
Xavier Guimard's avatar
Xavier Guimard committed
502
                        if ( $prompt and $prompt =~ /\bnone\b/ ) {
503
                            $self->logger->debug(
504 505
                                "Consent is requiered but prompt is set to none"
                            );
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
                            return $self->returnRedirectError(
                                $req,
                                $oidc_request->{'redirect_uri'},
                                "consent_required",
                                "consent required",
                                undef,
                                $oidc_request->{'state'},
                                ( $flow ne "authorizationcode" )
                            );
                        }

                        my $display_name =
                          $self->conf->{oidcRPMetaDataOptions}->{$rp}
                          ->{oidcRPMetaDataOptionsDisplayName};
                        my $icon = $self->conf->{oidcRPMetaDataOptions}->{$rp}
                          ->{oidcRPMetaDataOptionsIcon};
522
                        my $imgSrc;
523 524

                        if ($icon) {
525
                            $imgSrc =
526 527 528 529 530 531 532 533 534 535 536 537
                              ( $icon =~ m#^https?://# )
                              ? $icon
                              : $self->p->staticPrefic . "/common/" . $icon;
                        }

                        my $scope_messages = {
                            openid  => 'yourIdentity',
                            profile => 'yourProfile',
                            email   => 'yourEmail',
                            address => 'yourAddress',
                            phone   => 'yourPhone',
                        };
538
                        my @list;
539 540 541
                        foreach my $requested_scope (
                            split( /\s/, $oidc_request->{'scope'} ) )
                        {
542 543 544 545 546 547 548 549 550 551 552 553
                            if ( my $message =
                                $scope_messages->{$requested_scope} )
                            {
                                push @list, { m => $message };
                            }
                            else {
                                push @list,
                                  {
                                    m => 'anotherInformation',
                                    n => $requested_scope
                                  };
                            }
554
                        }
555 556 557 558
                        $req->info(
                            $self->loadTemplate(
                                'oidcGiveConsent',
                                params => {
Xavier Guimard's avatar
Xavier Guimard committed
559 560 561
                                    displayName => $display_name,
                                    imgUrl      => $imgSrc,
                                    list        => \@list,
562 563 564
                                }
                            )
                        );
Xavier Guimard's avatar
Xavier Guimard committed
565
                        $req->data->{activeTimer} = 0;
566 567 568 569 570 571 572 573 574 575 576 577 578
                        return PE_CONFIRM;
                    }
                }
            }

            # Create session_state
            my $session_state =
              $self->createSessionState( $req->id, $client_id );

            # Authorization Code Flow
            if ( $flow eq "authorizationcode" ) {

                # Store data in session
Xavier Guimard's avatar
Xavier Guimard committed
579 580
                my $codeSession = $self->getOpenIDConnectSession(
                    undef,
581 582 583 584 585 586 587 588 589
                    {
                        redirect_uri    => $oidc_request->{'redirect_uri'},
                        scope           => $oidc_request->{'scope'},
                        user_session_id => $req->id,
                        _utime          => time,
                        nonce           => $oidc_request->{'nonce'},
                    }
                );

590
                # Generate code
Xavier Guimard's avatar
Xavier Guimard committed
591
                my $code = $codeSession->id();
592 593 594

                $self->logger->debug("Generated code: $code");

595 596 597 598 599 600 601
                # Build Response
                my $response_url = $self->buildAuthorizationCodeAuthnResponse(
                    $oidc_request->{'redirect_uri'},
                    $code, $oidc_request->{'state'},
                    $session_state
                );

602
                $self->logger->debug("Redirect user to $response_url");
603 604
                $req->urldc($response_url);

Xavier Guimard's avatar
Xavier Guimard committed
605
                return PE_REDIRECT;
606 607 608 609 610 611 612 613
            }

            # Implicit Flow
            if ( $flow eq "implicit" ) {

                my $access_token;
                my $at_hash;

614
                if ( $response_type =~ /\btoken\b/ ) {
615

616
                    # Store data in access token
617
                    # Generate access_token
Xavier Guimard's avatar
Xavier Guimard committed
618 619
                    my $accessTokenSession = $self->getOpenIDConnectSession(
                        undef,
620 621 622 623 624 625 626
                        {
                            scope           => $oidc_request->{'scope'},
                            rp              => $rp,
                            user_session_id => $req->id,
                            _utime          => time,
                        }
                    );
627 628

                    unless ($accessTokenSession) {
629 630
                        $self->logger->error(
                            "Unable to create OIDC session for access_token");
631 632 633 634 635 636 637 638
                        $self->returnRedirectError( $req,
                            $oidc_request->{'redirect_uri'},
                            "server_error", undef, undef,
                            $oidc_request->{'state'}, 1 );
                    }

                    $access_token = $accessTokenSession->id;

639 640
                    $self->logger->debug(
                        "Generated access token: $access_token");
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695

                    # Compute hash to store in at_hash
                    my $alg = $self->conf->{oidcRPMetaDataOptions}->{$rp}
                      ->{oidcRPMetaDataOptionsIDTokenSignAlg};
                    my ($hash_level) = ( $alg =~ /(?:\w{2})(\d{3})/ );
                    $at_hash = $self->createHash( $access_token, $hash_level );
                }

                # ID token payload
                my $id_token_exp = $self->conf->{oidcRPMetaDataOptions}->{$rp}
                  ->{oidcRPMetaDataOptionsIDTokenExpiration};
                $id_token_exp += time;

                my $authenticationLevel =
                  $req->{sessionInfo}->{authenticationLevel};
                my $id_token_acr;
                foreach (
                    keys %{ $self->conf->{oidcServiceMetaDataAuthnContext} } )
                {
                    if ( $self->conf->{oidcServiceMetaDataAuthnContext}->{$_} eq
                        $authenticationLevel )
                    {
                        $id_token_acr = $_;
                        last;
                    }
                }

                my $user_id_attribute =
                  $self->conf->{oidcRPMetaDataOptions}->{$rp}
                  ->{oidcRPMetaDataOptionsUserIDAttr}
                  || $self->conf->{whatToTrace};
                my $user_id = $req->{sessionInfo}->{$user_id_attribute};

                my $id_token_payload_hash = {
                    iss => $self->conf->{oidcServiceMetaDataIssuer}
                    ,    # Issuer Identifier
                    sub => $user_id,         # Subject Identifier
                    aud => [$client_id],     # Audience
                    exp => $id_token_exp,    # expiration
                    iat => time,             # Issued time
                    auth_time => $req->{sessionInfo}->{_lastAuthnUTime}
                    ,                        # Authentication time
                    azp   => $client_id,                 # Authorized party
                                                         # TODO amr
                    nonce => $oidc_request->{'nonce'}    # Nonce
                };

                $id_token_payload_hash->{'at_hash'} = $at_hash if $at_hash;
                $id_token_payload_hash->{'acr'} = $id_token_acr
                  if $id_token_acr;

                # Create ID Token
                my $id_token =
                  $self->createIDToken( $id_token_payload_hash, $rp );

696
                $self->logger->debug("Generated id token: $id_token");
697 698 699 700 701 702 703 704 705 706 707 708 709

                # Send token response
                my $expires_in = $self->conf->{oidcRPMetaDataOptions}->{$rp}
                  ->{oidcRPMetaDataOptionsAccessTokenExpiration};

                # Build Response
                my $response_url = $self->buildImplicitAuthnResponse(
                    $oidc_request->{'redirect_uri'},
                    $access_token, $id_token, $expires_in,
                    $oidc_request->{'state'},
                    $session_state
                );

710
                $self->logger->debug("Redirect user to $response_url");
Xavier Guimard's avatar
Xavier Guimard committed
711
                $req->urldc($response_url);
712

Xavier Guimard's avatar
Xavier Guimard committed
713
                return PE_REDIRECT;
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
            }

            # Hybrid Flow
            if ( $flow eq "hybrid" ) {

                my $access_token;
                my $id_token;
                my $at_hash;
                my $c_hash;

                # Hash level
                my $alg = $self->conf->{oidcRPMetaDataOptions}->{$rp}
                  ->{oidcRPMetaDataOptionsIDTokenSignAlg};
                my ($hash_level) = ( $alg =~ /(?:\w{2})(\d{3})/ );

                # Store data in session
Xavier Guimard's avatar
Xavier Guimard committed
730 731
                my $codeSession = $self->getOpenIDConnectSession(
                    undef,
732 733 734 735 736 737 738 739 740
                    {
                        redirect_uri    => $oidc_request->{'redirect_uri'},
                        scope           => $oidc_request->{'scope'},
                        user_session_id => $req->id,
                        _utime          => time,
                        nonce           => $oidc_request->{'nonce'},
                    }
                );

741
                # Generate code
Xavier Guimard's avatar
Xavier Guimard committed
742
                my $code = $codeSession->id();
743 744 745

                $self->logger->debug("Generated code: $code");

746 747 748 749 750 751
                # Compute hash to store in c_hash
                $c_hash = $self->createHash( $code, $hash_level );

                if ( $response_type =~ /\btoken\b/ ) {

                    # Generate access_token
Xavier Guimard's avatar
Xavier Guimard committed
752 753
                    my $accessTokenSession = $self->getOpenIDConnectSession(
                        undef,
754 755 756 757 758 759 760
                        {
                            scope           => $oidc_request->{'scope'},
                            rp              => $rp,
                            user_session_id => $req->id,
                            _utime          => time,
                        }
                    );
761 762

                    unless ($accessTokenSession) {
763 764
                        $self->logger->error(
                            "Unable to create OIDC session for access_token");
765 766 767 768 769 770 771 772
                        return $self->returnRedirectError( $req,
                            $oidc_request->{'redirect_uri'},
                            "server_error", undef, undef,
                            $oidc_request->{'state'}, 1 );
                    }

                    $access_token = $accessTokenSession->id;

773 774
                    $self->logger->debug(
                        "Generated access token: $access_token");
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793

                    # Compute hash to store in at_hash
                    $at_hash = $self->createHash( $access_token, $hash_level );
                }

                if ( $response_type =~ /\bid_token\b/ ) {

                    # ID token payload
                    my $id_token_exp =
                      $self->conf->{oidcRPMetaDataOptions}->{$rp}
                      ->{oidcRPMetaDataOptionsIDTokenExpiration};
                    $id_token_exp += time;

                    my $id_token_acr =
                      "loa-" . $req->{sessionInfo}->{authenticationLevel};

                    my $user_id_attribute =
                      $self->conf->{oidcRPMetaDataOptions}->{$rp}
                      ->{oidcRPMetaDataOptionsUserIDAttr}
Xavier Guimard's avatar
Xavier Guimard committed
794
                      || $self->conf->{whatToTrace};
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
                    my $user_id = $req->{sessionInfo}->{$user_id_attribute};

                    my $id_token_payload_hash = {
                        iss => $self->conf->{oidcServiceMetaDataIssuer}
                        ,    # Issuer Identifier
                        sub => $user_id,         # Subject Identifier
                        aud => [$client_id],     # Audience
                        exp => $id_token_exp,    # expiration
                        iat => time,             # Issued time
                        auth_time => $req->{sessionInfo}->{_lastAuthnUTime}
                        ,                        # Authentication time
                        acr => $id_token_acr
                        ,    # Authentication Context Class Reference
                        azp   => $client_id,                 # Authorized party
                                                             # TODO amr
                        nonce => $oidc_request->{'nonce'}    # Nonce
                    };

                    $id_token_payload_hash->{'at_hash'} = $at_hash if $at_hash;
                    $id_token_payload_hash->{'c_hash'}  = $c_hash  if $c_hash;

                    # Create ID Token
                    $id_token =
                      $self->createIDToken( $id_token_payload_hash, $rp );

820
                    $self->logger->debug("Generated id token: $id_token");
821 822 823 824 825 826 827 828 829 830 831 832 833
                }

                my $expires_in = $self->conf->{oidcRPMetaDataOptions}->{$rp}
                  ->{oidcRPMetaDataOptionsAccessTokenExpiration};

                # Build Response
                my $response_url = $self->buildHybridAuthnResponse(
                    $oidc_request->{'redirect_uri'}, $code,
                    $access_token,                   $id_token,
                    $expires_in,                     $oidc_request->{'state'},
                    $session_state
                );

834
                $self->logger->debug("Redirect user to $response_url");
835
                $req->urldc($response_url);
Xavier Guimard's avatar
Xavier Guimard committed
836
                return PE_REDIRECT;
837 838
            }

839
            $self->logger->debug("None flow has been selected");
840
            return PE_OK;
Xavier Guimard's avatar
Xavier Guimard committed
841
        }
842 843

        # LOGOUT
Xavier Guimard's avatar
Xavier Guimard committed
844
        elsif ( $path eq $self->conf->{oidcServiceMetaDataEndSessionURI} ) {
845 846
            $self->logger->debug(
                "URL detected as an OpenID Connect END SESSION URL");
847 848 849 850 851

            # Set hidden fields
            my $oidc_request = {};
            foreach my $param (qw/id_token_hint post_logout_redirect_uri state/)
            {
Xavier Guimard's avatar
Xavier Guimard committed
852
                if ( $oidc_request->{$param} = $req->param($param) ) {
853 854
                    $self->logger->debug( "OIDC request parameter $param: "
                          . $oidc_request->{$param} );
Xavier Guimard's avatar
Xavier Guimard committed
855
                    $self->p->setHiddenFormValue( $req, $param,
Xavier Guimard's avatar
Xavier Guimard committed
856 857
                        $oidc_request->{$param}, '' );
                }
858 859 860 861 862 863 864 865
            }

            my $post_logout_redirect_uri =
              $oidc_request->{'post_logout_redirect_uri'};
            my $state = $oidc_request->{'state'};

            # Ask consent for logout
            if ( $req->param('confirm') ) {
866
                my $err;
Xavier Guimard's avatar
Xavier Guimard committed
867
                if ( $req->param('confirm') == 1 ) {
868 869 870 871 872 873
                    $req->steps(
                        [
                            @{ $self->p->beforeLogout }, 'authLogout',
                            'deleteSession'
                        ]
                    );
874
                    $err = $req->error( $self->p->process($req) );
Xavier Guimard's avatar
Xavier Guimard committed
875 876 877 878 879 880
                    if ( $err and $err != PE_LOGOUT_OK ) {
                        if ( $err > 0 ) {
                            $self->logger->error(
                                "Logout process returns error code $err");
                            return PE_ERROR;
                        }
Xavier Guimard's avatar
Xavier Guimard committed
881 882
                        return $err;
                    }
883 884 885 886
                }

                if ($post_logout_redirect_uri) {

887 888 889 890
                    # Check redirect URI is allowed
                    my $redirect_uri_allowed = 0;
                    foreach ( keys %{ $self->conf->{oidcRPMetaDataOptions} } ) {
                        my $logout_rp = $_;
Xavier Guimard's avatar
Xavier Guimard committed
891 892 893 894
                        if ( my $redirect_uris =
                            $self->conf->{oidcRPMetaDataOptions}->{$logout_rp}
                            ->{oidcRPMetaDataOptionsPostLogoutRedirectUris} )
                        {
895

Xavier Guimard's avatar
Xavier Guimard committed
896 897 898
                            foreach ( split( /\s+/, $redirect_uris ) ) {
                                if ( $post_logout_redirect_uri eq $_ ) {
                                    $self->logger->debug(
899
"$post_logout_redirect_uri is an allowed logout redirect URI for RP $logout_rp"
Xavier Guimard's avatar
Xavier Guimard committed
900 901 902
                                    );
                                    $redirect_uri_allowed = 1;
                                }
903 904 905 906 907 908 909 910 911 912
                            }
                        }
                    }

                    unless ($redirect_uri_allowed) {
                        $self->logger->error(
                            "$post_logout_redirect_uri is not allowed");
                        return PE_BADURL;
                    }

913 914 915 916 917
                    # Build Response
                    my $response_url =
                      $self->buildLogoutResponse( $post_logout_redirect_uri,
                        $state );

918
                    $self->logger->debug("Redirect user to $response_url");
919
                    $req->urldc($response_url);
Xavier Guimard's avatar
Xavier Guimard committed
920
                    return PE_REDIRECT;
921
                }
922 923 924
                return $req->param('confirm') == 1
                  ? ( $err ? $err : PE_LOGOUT_OK )
                  : PE_OK;
925 926
            }

927
            $req->info( $self->loadTemplate('oidcLogout') );
Xavier Guimard's avatar
Xavier Guimard committed
928
            $req->data->{activeTimer} = 0;
929
            return PE_CONFIRM;
Xavier Guimard's avatar
Xavier Guimard committed
930 931
        }
    }
932
    $self->logger->error("Unknown OIDC endpoint $path, skipping");
933
    return PE_ERROR;
Xavier Guimard's avatar
Xavier Guimard committed
934 935
}

936
# Handle token endpoint
Xavier Guimard's avatar
Xavier Guimard committed
937 938
sub token {
    my ( $self, $req ) = @_;
939
    $self->logger->debug("URL detected as an OpenID Connect TOKEN URL");
Xavier Guimard's avatar
Xavier Guimard committed
940 941 942 943 944 945

    # Check authentication
    my ( $client_id, $client_secret ) =
      $self->getEndPointAuthenticationCredentials($req);

    unless ( $client_id && $client_secret ) {
946 947
        $self->logger->error(
"No authentication provided to get token, or authentication type not supported"
Xavier Guimard's avatar
Xavier Guimard committed
948
        );
949
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
950 951 952 953 954 955
    }

    # Verify that client_id is registered in configuration
    my $rp = $self->getRP($client_id);

    unless ($rp) {
956 957
        $self->userLogger->error(
            "No registered Relying Party found with client_id $client_id");
958
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
959 960
    }
    else {
961
        $self->logger->debug("Client id $client_id match Relying Party $rp");
Xavier Guimard's avatar
Xavier Guimard committed
962 963 964 965 966 967
    }

    # Check client_secret
    unless ( $client_secret eq $self->conf->{oidcRPMetaDataOptions}->{$rp}
        ->{oidcRPMetaDataOptionsClientSecret} )
    {
968
        $self->logger->error("Wrong credentials for $rp");
969
        return $self->p->sendError( 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
970 971 972
    }

    # Get code session
Xavier Guimard's avatar
Xavier Guimard committed
973
    my $code = $req->param('code');
Xavier Guimard's avatar
Xavier Guimard committed
974

975
    $self->logger->debug("OpenID Connect Code: $code");
Xavier Guimard's avatar
Xavier Guimard committed
976 977 978 979

    my $codeSession = $self->getOpenIDConnectSession($code);

    unless ($codeSession) {
980
        $self->logger->error("Unable to find OIDC session $code");
Xavier Guimard's avatar
Xavier Guimard committed
981
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
982 983 984
    }

    # Check we have the same redirect_uri value
Xavier Guimard's avatar
Xavier Guimard committed
985
    unless ( $req->param("redirect_uri") eq $codeSession->data->{redirect_uri} )
Xavier Guimard's avatar
Xavier Guimard committed
986
    {
987
        $self->userLogger->error( "Provided redirect_uri does not match "
988
              . $codeSession->{redirect_uri} );
Xavier Guimard's avatar
Xavier Guimard committed
989
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
990 991 992 993
    }

    # Get user identifier
    my $apacheSession =
Xavier Guimard's avatar
Xavier Guimard committed
994 995
      $self->p->getApacheSession( $codeSession->data->{user_session_id},
        noInfo => 1 );
Xavier Guimard's avatar
Xavier Guimard committed
996 997

    unless ($apacheSession) {
998 999
        $self->userLogger->error(
            "Unable to find user session linked to OIDC session $code");
Xavier Guimard's avatar
Xavier Guimard committed
1000
        $codeSession->remove();
Xavier Guimard's avatar
Xavier Guimard committed
1001
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
1002 1003 1004
    }

    my $user_id_attribute =
Xavier Guimard's avatar
Xavier Guimard committed
1005 1006
      $self->conf->{oidcRPMetaDataOptions}->{$rp}
      ->{oidcRPMetaDataOptionsUserIDAttr}
Xavier Guimard's avatar
Xavier Guimard committed
1007 1008 1009
      || $self->conf->{whatToTrace};
    my $user_id = $apacheSession->data->{$user_id_attribute};

1010
    $self->logger->debug("Found corresponding user: $user_id");
Xavier Guimard's avatar
Xavier Guimard committed
1011 1012

    # Generate access_token
Xavier Guimard's avatar
Xavier Guimard committed
1013 1014
    my $accessTokenSession = $self->getOpenIDConnectSession(
        undef,
Xavier Guimard's avatar
Xavier Guimard committed
1015 1016 1017 1018 1019 1020 1021 1022
        {
            scope           => $codeSession->data->{scope},
            rp              => $rp,
            user_session_id => $apacheSession->id,
            _utime          => time,
        }
    );

1023 1024 1025 1026
    unless ($accessTokenSession) {
        $self->userLogger->error(
            "Unable to create OIDC session for access_token");
        $codeSession->remove();
Xavier Guimard's avatar
Xavier Guimard committed
1027
        return $self->p->sendError( $req, 'invalid_request', 400 );
1028 1029
    }

Xavier Guimard's avatar
Xavier Guimard committed
1030 1031
    my $access_token = $accessTokenSession->id;

1032
    $self->logger->debug("Generated access token: $access_token");
Xavier Guimard's avatar
Xavier Guimard committed
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

    # Compute hash to store in at_hash
    my $alg = $self->conf->{oidcRPMetaDataOptions}->{$rp}
      ->{oidcRPMetaDataOptionsIDTokenSignAlg};
    my ($hash_level) = ( $alg =~ /(?:\w{2})(\d{3})/ );
    my $at_hash = $self->createHash( $access_token, $hash_level );

    # ID token payload
    my $id_token_exp = $self->conf->{oidcRPMetaDataOptions}->{$rp}
      ->{oidcRPMetaDataOptionsIDTokenExpiration};
    $id_token_exp += time;

    my $id_token_acr = "loa-" . $apacheSession->data->{authenticationLevel};

    my $id_token_payload_hash = {
Xavier Guimard's avatar
Xavier Guimard committed
1048 1049 1050 1051 1052
        iss => $self->conf->{oidcServiceMetaDataIssuer},    # Issuer Identifier
        sub => $user_id,                                    # Subject Identifier
        aud => [$client_id],                                # Audience
        exp => $id_token_exp,                               # expiration
        iat => time,                                        # Issued time
1053 1054
        auth_time => $apacheSession->data->{_lastAuthnUTime}
        ,    # Authentication time
Xavier Guimard's avatar
Xavier Guimard committed
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
        acr => $id_token_acr,    # Authentication Context Class Reference
        azp => $client_id,       # Authorized party
                                 # TODO amr
    };

    my $nonce = $codeSession->data->{nonce};
    $id_token_payload_hash->{nonce} = $nonce if defined $nonce;
    $id_token_payload_hash->{'at_hash'} = $at_hash if $at_hash;

    # Create ID Token
    my $id_token = $self->createIDToken( $id_token_payload_hash, $rp );

1067
    $self->logger->debug("Generated id token: $id_token");
Xavier Guimard's avatar
Xavier Guimard committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

    # Send token response
    my $expires_in = $self->conf->{oidcRPMetaDataOptions}->{$rp}
      ->{oidcRPMetaDataOptionsAccessTokenExpiration};

    my $token_response = {
        access_token => $access_token,
        token_type   => 'Bearer',
        expires_in   => $expires_in,
        id_token     => $id_token,
    };

1080 1081 1082 1083 1084
    my $cRP = $apacheSession->data->{_oidcConnectedRP} || '';
    unless ( $cRP =~ /\b$rp\b/ ) {
        $self->p->updateSession( $req, { _oidcConnectedRP => "$rp,$cRP" },
            $apacheSession->id );
    }
1085

1086
    $self->logger->debug("Send token response");
Xavier Guimard's avatar
Xavier Guimard committed
1087 1088

    $codeSession->remove();
Xavier Guimard's avatar
Xavier Guimard committed
1089
    return $self->p->sendJSONresponse( $req, $token_response );
Xavier Guimard's avatar
Xavier Guimard committed
1090 1091
}

1092
# Handle uerinfo endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1093 1094
sub userInfo {
    my ( $self, $req ) = @_;
1095
    $self->logger->debug("URL detected as an OpenID Connect USERINFO URL");
Xavier Guimard's avatar
Xavier Guimard committed
1096 1097 1098 1099

    my $access_token = $self->getEndPointAccessToken($req);

    unless ($access_token) {
1100
        $self->logger->error("Unable to get access_token");
1101 1102
        return $self->returnBearerError( 'invalid_request',
            "Access token not found in request", 401 );
Xavier Guimard's avatar
Xavier Guimard committed
1103 1104
    }

1105
    $self->logger->debug("Received Access Token $access_token");
Xavier Guimard's avatar
Xavier Guimard committed
1106 1107 1108 1109

    my $accessTokenSession = $self->getOpenIDConnectSession($access_token);

    unless ($accessTokenSession) {
1110 1111
        $self->userLogger->error(
            "Unable to get access token session for id $access_token");
1112 1113
        return $self->returnBearerError( 'invalid_request',
            'Invalid request', 401 );
Xavier Guimard's avatar
Xavier Guimard committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    }

    # Get access token session data
    my $scope           = $accessTokenSession->data->{scope};
    my $rp              = $accessTokenSession->data->{rp};
    my $user_session_id = $accessTokenSession->data->{user_session_id};

    my $userinfo_response =
      $self->buildUserInfoResponse( $scope, $rp, $user_session_id );
    unless ($userinfo_response) {
1124 1125
        return $self->returnBearerError( 'invalid_request', 'Invalid request',
            401 );
Xavier Guimard's avatar
Xavier Guimard committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    }

    my $userinfo_sign_alg = $self->conf->{oidcRPMetaDataOptions}->{$rp}
      ->{oidcRPMetaDataOptionsUserInfoSignAlg};

    unless ($userinfo_sign_alg) {
        return $self->p->sendJSONresponse( $req, $userinfo_response );
    }
    else {
        my $userinfo_jwt =
          $self->createJWT( $userinfo_response, $userinfo_sign_alg, $rp );
1137
        $self->logger->debug("Return UserInfo as JWT: $userinfo_jwt");
Xavier Guimard's avatar
Xavier Guimard committed
1138 1139 1140 1141 1142 1143 1144 1145 1146
        return [
            200,
            [
                'Content-Type'   => 'application/jwt',
                'Content-Length' => length($userinfo_jwt)
            ],
            [$userinfo_jwt]
        ];
    }
Xavier Guimard's avatar
Xavier Guimard committed
1147 1148
}

1149
# Handle jwks endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1150 1151
sub jwks {
    my ( $self, $req ) = @_;
1152
    $self->logger->debug("URL detected as an OpenID Connect JWKS URL");
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164

    my $jwks = { keys => [] };

    my $public_key_sig = $self->conf->{oidcServicePublicKeySig};
    my $key_id_sig     = $self->conf->{oidcServiceKeyIdSig};
    if ($public_key_sig) {
        my $key = $self->key2jwks($public_key_sig);
        $key->{kty} = "RSA";
        $key->{use} = "sig";
        $key->{kid} = $key_id_sig if $key_id_sig;
        push @{ $jwks->{keys} }, $key;
    }
1165
    $self->logger->debug("Send JWKS response sent");
1166
    return $self->p->sendJSONresponse( $req, $jwks );
Xavier Guimard's avatar
Xavier Guimard committed
1167 1168
}

1169
# Handle register endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1170 1171
sub registration {
    my ( $self, $req ) = @_;
1172
    $self->logger->debug("URL detected as an OpenID Connect REGISTRATION URL");
1173 1174 1175 1176

    # TODO: check Initial Access Token

    # Specific message to allow DOS detection
Xavier Guimard's avatar
Xavier Guimard committed
1177
    my $source_ip = $req->address;
1178 1179
    $self->logger->notice(
        "OpenID Connect Registration request from $source_ip");
1180 1181 1182

    # Check dynamic registration is allowed
    unless ( $self->conf->{oidcServiceAllowDynamicRegistration} ) {
1183
        $self->logger->error("Dynamic registration is not allowed");
Xavier Guimard's avatar
Xavier Guimard committed
1184
        return $self->p->sendError( $req, 'server_error' );
1185 1186 1187
    }

    # Get client metadata
1188
    my $client_metadata_json = $req->content;
1189
    unless ($client_metadata_json) {
Xavier Guimard's avatar
Xavier Guimard committed
1190
        return $self->p->sendError( $req, 'Missing POST data', 400 );
1191 1192
    }

1193
    $self->logger->debug("Client metadata received: $client_metadata_json");
1194 1195 1196 1197 1198 1199

    my $client_metadata       = $self->decodeJSON($client_metadata_json);
    my $registration_response = {};

    # Check redirect_uris
    unless ( $client_metadata->{redirect_uris} ) {
1200
        $self->logger->error("Field redirect_uris is mandatory");
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
        return $self->p->sendError( $req, 'invalid_client_metadata', 400 );
    }

    # RP identifier
    my $registration_time = time;
    my $rp                = "register-$registration_time";

    # Generate Client ID and Client Password
    my $client_id     = random_string("ssssssssssssssssssssssssssssss");
    my $client_secret = random_string("ssssssssssssssssssssssssssssss");

    # Register known parameters
    my $client_name =
      $client_metadata->{client_name} || "Self registered client";
    my $logo_uri = $client_metadata->{logo_uri};
    my $id_token_signed_response_alg =
      $client_metadata->{id_token_signed_response_alg} || "RS256";
    my $userinfo_signed_response_alg =
      $client_metadata->{userinfo_signed_response_alg};
    my $redirect_uris = $client_metadata->{redirect_uris};

    # Register RP in global configuration
Xavier Guimard's avatar
Xavier Guimard committed
1223
    my $conf = $self->confAcc->getConf( { raw => 1 } );
1224 1225 1226

    $conf->{cfgAuthor}   = "OpenID Connect Registration ($client_name)";
    $conf->{cfgAuthorIP} = $source_ip;
1227
    $conf->{cfgVersion}  = $VERSION;
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265

    $conf->{oidcRPMetaDataExportedVars}->{$rp} = {};
    $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsClientID} =
      $client_id;
    $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsClientSecret}
      = $client_secret;
    $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsDisplayName} =
      $client_name;
    $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsIcon} =
      $logo_uri;
    $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsIDTokenSignAlg}
      = $id_token_signed_response_alg;
    $conf->{oidcRPMetaDataOptions}->{$rp}->{oidcRPMetaDataOptionsRedirectUris}
      = join( ' ', @$redirect_uris );
    $conf->{oidcRPMetaDataOptions}->{$rp}
      ->{oidcRPMetaDataOptionsUserInfoSignAlg} = $userinfo_signed_response_alg
      if defined $userinfo_signed_response_alg;

    if ( $self->confAcc->saveConf($conf) ) {

        # Reload RP list
        $self->loadRPs();

        # Send registration response
        $registration_response->{'client_id'}            = $client_id;
        $registration_response->{'client_secret'}        = $client_secret;
        $registration_response->{'client_id_issued_at'}  = $registration_time;
        $registration_response->{'client_id_expires_at'} = 0;
        $registration_response->{'client_name'}          = $client_name;
        $registration_response->{'logo_uri'}             = $logo_uri;
        $registration_response->{'id_token_signed_response_alg'} =
          $id_token_signed_response_alg;
        $registration_response->{'redirect_uris'} = $redirect_uris;
        $registration_response->{'userinfo_signed_response_alg'} =
          $userinfo_signed_response_alg
          if defined $userinfo_signed_response_alg;
    }
    else {
1266 1267
        $self->logger->error(
            "Configuration not saved: $Lemonldap::NG::Common::Conf::msg");
1268 1269 1270
        return $self->p->sendError( $req, 'server_error', 500 );
    }

1271
    $self->logger->debug("Registration response sent");
1272 1273
    return $self->p->sendJSONresponse( $req, $registration_response,
        code => 201 );
Xavier Guimard's avatar
Xavier Guimard committed
1274 1275
}

1276
# Handle logout endpoint for unauthenticated users
Xavier Guimard's avatar
Xavier Guimard committed
1277 1278
sub endSessionDone {
    my ( $self, $req ) = @_;
1279 1280
    $self->logger->debug("URL  detected as an OpenID Connect END SESSION URL");
    $self->logger->debug("User is already logged out");
1281

Xavier Guimard's avatar
Xavier Guimard committed
1282 1283
    my $post_logout_redirect_uri = $req->param('post_logout_redirect_uri');
    my $state                    = $req->param('state');
1284 1285 1286

    if ($post_logout_redirect_uri) {

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
        # Check redirect URI is allowed
        my $redirect_uri_allowed = 0;
        foreach ( keys %{ $self->conf->{oidcRPMetaDataOptions} } ) {
            my $logout_rp = $_;
            my $redirect_uris =
              $self->conf->{oidcRPMetaDataOptions}->{$logout_rp}
              ->{oidcRPMetaDataOptionsPostLogoutRedirectUris};

            foreach ( split( /\s+/, $redirect_uris ) ) {
                if ( $post_logout_redirect_uri eq $_ ) {
                    $self->logger->debug(
"$post_logout_redirect_uri is an allowed logout redirect URI for RP $logout_rp"
                    );
                    $redirect_uri_allowed = 1;
                }
            }
        }

        unless ($redirect_uri_allowed) {
            $self->logger->error("$post_logout_redirect_uri is not allowed");
            return $self->p->login($req);
        }

1310 1311 1312 1313
        # Build Response
        my $response_url =
          $self->buildLogoutResponse( $post_logout_redirect_uri, $state );

1314
        $self->logger->debug("Redirect user to $response_url");
1315 1316 1317 1318 1319
        return [ 302, [ Location => $response_url ], [] ];
    }

    # Else, normal login process
    return $self->p->login($req);