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

use strict;
Xavier Guimard's avatar
Xavier Guimard committed
4
use 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
Xavier Guimard's avatar
Xavier Guimard committed
15 16 17 18 19
);

our $VERSION = '2.0.0';

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

23 24 25 26
# INTERFACE

sub beforeAuth { 'exportRequestParameters' }

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

29 30
has configStorage => (
    is      => 'ro',
31
    lazy    => 1,
32 33 34 35 36
    default => sub {
        $_[0]->{p}->HANDLER->localConfig->{configStorage};
    }
);

37 38 39 40 41 42 43 44 45 46 47 48
# 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
49 50
#
# .well-known/openid-configuration is handled by metadata()
51

Xavier Guimard's avatar
Xavier Guimard committed
52 53 54 55 56 57 58 59 60 61 62
sub init {
    my ($self) = @_;

    # Initialize RP list
    return 0
      unless ( $self->Lemonldap::NG::Portal::Main::Issuer::init()
        and $self->loadRPs );

    # Manage RP requests
    $self->addRouteFromConf(
        'Unauth',
63 64
        oidcServiceMetaDataEndSessionURI   => 'endSessionDone',
        oidcServiceMetaDataCheckSessionURI => 'checkSession',
Xavier Guimard's avatar
Xavier Guimard committed
65 66 67 68 69 70 71 72 73
        oidcServiceMetaDataTokenURI        => 'token',
        oidcServiceMetaDataUserInfoURI     => 'userInfo',
        oidcServiceMetaDataJWKSURI         => 'jwks',
        oidcServiceMetaDataRegistrationURI => 'registration',
    );

    # Manage user requests
    $self->addRouteFromConf(
        'Auth',
74
        oidcServiceMetaDataCheckSessionURI => 'checkSession',
Xavier Guimard's avatar
Xavier Guimard committed
75 76 77 78 79
        oidcServiceMetaDataTokenURI        => 'badAuthRequest',
        oidcServiceMetaDataUserInfoURI     => 'badAuthRequest',
        oidcServiceMetaDataJWKSURI         => 'badAuthRequest',
        oidcServiceMetaDataRegistrationURI => 'badAuthRequest',
    );
Xavier Guimard's avatar
Xavier Guimard committed
80 81 82 83 84 85 86 87 88 89

    # Metadata (.well-known/openid-configuration)
    $self->addUnauthRoute(
        '.well-known' => { 'openid-configuration' => 'metadata' },
        ['GET']
    );
    $self->addAuthRoute(
        '.well-known' => { 'openid-configuration' => 'metadata' },
        ['GET']
    );
Xavier Guimard's avatar
Xavier Guimard committed
90 91 92 93 94
    return 1;
}

# RUNNING METHODS

95 96
# 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
97 98 99 100 101 102
sub run {
    my ( $self, $req, $path ) = @_;
    if ($path) {

        # AUTHORIZE
        if ( $path eq $self->conf->{oidcServiceMetaDataAuthorizeURI} ) {
103 104
            $self->logger->debug(
                "URL  detected as an OpenID Connect AUTHORIZE URL");
105 106 107 108 109 110

            # 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
111
                login_hint acr_values request request_uri/
112 113
              )
            {
Xavier Guimard's avatar
Xavier Guimard committed
114 115
                if ( $req->param($param) ) {
                    $oidc_request->{$param} = $req->param($param);
116 117
                    $self->logger->debug( "OIDC request parameter $param: "
                          . $oidc_request->{$param} );
118 119 120
                    $self->p->setHiddenFormValue( $req, $param,
                        $oidc_request->{$param},
                        '', 0 );
Xavier Guimard's avatar
Xavier Guimard committed
121
                }
122 123 124 125 126 127 128
            }

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

            unless ($flow) {
129
                $self->logger->error("Unknown response type: $response_type");
130 131
                return PE_ERROR;
            }
132 133
            $self->logger->debug(
                "OIDC $flow flow requested (response type: $response_type)");
134 135 136 137 138 139 140 141 142 143

            # 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 {
144
                    $self->logger->error("Error with Request URI resolution");
145 146 147 148 149 150 151 152 153 154
                    return PE_ERROR;
                }
            }

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

                # Override OIDC parameters by request content
                foreach ( keys %$request ) {
155 156
                    $self->logger->debug(
"Override $_ OIDC param by value present in request parameter"
157 158
                    );
                    $oidc_request->{$_} = $request->{$_};
159 160
                    $self->p->setHiddenFormValue( $req, $_, $request->{$_},
                        '' );
161 162 163 164 165
                }
            }

            # Check all required parameters
            unless ( $oidc_request->{'redirect_uri'} ) {
166
                $self->logger->error("Redirect URI is required");
167 168 169
                return PE_ERROR;
            }
            unless ( $oidc_request->{'scope'} ) {
170
                $self->logger->error("Scope is required");
171
                return PE_ERROR;
172 173
            }
            unless ( $oidc_request->{'client_id'} ) {
174
                $self->logger->error("Client ID is required");
175
                return PE_ERROR;
176 177 178
            }
            if ( $flow eq "implicit" and not defined $oidc_request->{'nonce'} )
            {
179
                $self->logger->error("Nonce is required for implicit flow");
180 181 182 183 184 185 186 187 188 189 190 191 192
                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"
193
                );
194 195 196 197 198 199 200
                return PE_UNAUTHORIZEDPARTNER;
            }
            else {
                $self->logger->debug("Client id $client_id match RP $rp");
            }

            # Check if this RP is authorizated
201
            if ( my $rule = $self->spRules->{$rp} ) {
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                unless ( $rule->( $req, $req->sessionInfo ) ) {
                    $self->userLogger->warn( 'User '
                          . $req->sessionInfo->{ $self->conf->{whatToTrace} }
                          . "was not authorizated to access to $rp" );
                    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;
                }
225 226 227 228 229 230
            }

            # Check if flow is allowed
            if ( $flow eq "authorizationcode"
                and not $self->conf->{oidcServiceAllowAuthorizationCodeFlow} )
            {
231 232
                $self->userLogger->error(
                    "Authorization code flow is not allowed");
233 234 235 236 237 238 239 240 241 242
                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} )
            {
243
                $self->logger->error("Implicit flow is not allowed");
244 245 246 247 248 249 250 251 252 253
                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} )
            {
254
                $self->logger->error("Hybrid flow is not allowed");
255 256 257 258 259 260 261 262 263
                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
264 265 266 267 268 269 270 271 272
            my $prompt = $oidc_request->{'prompt'};
            if (
                    $prompt
                and $prompt =~ /\blogin\b/
                and (
                    time - $req->sessionInfo->{_utime} >
                    $self->conf->{portalForceAuthnInterval} )
              )
            {
273 274
                $self->logger->debug(
"Reauthentication requested by Relying Party in prompt parameter"
275
                );
Xavier Guimard's avatar
Xavier Guimard committed
276
                return $self->reAuth($req);
277 278 279 280 281
            }

            my $max_age         = $oidc_request->{'max_age'};
            my $_lastAuthnUTime = $req->{sessionInfo}->{_lastAuthnUTime};
            if ( $max_age && time > $_lastAuthnUTime + $max_age ) {
282 283
                $self->logger->debug(
"Reauthentication forced cause authentication time ($_lastAuthnUTime) is too old (>$max_age s)"
284
                );
Xavier Guimard's avatar
Xavier Guimard committed
285
                return $self->reAuth($req);
286 287 288 289
            }

            # Check openid scope
            unless ( $oidc_request->{'scope'} =~ /\bopenid\b/ ) {
290
                $self->logger->debug("No openid scope found");
291 292 293 294 295 296 297 298 299 300 301 302 303 304

                #TODO manage standard OAuth request
                return PE_OK;
            }

            # Check Request JWT signature
            if ( $oidc_request->{'request'} ) {
                unless (
                    $self->verifyJWTSignature(
                        $oidc_request->{'request'},
                        undef, $rp
                    )
                  )
                {
305 306
                    $self->logger->error(
                        "Request JWT signature could not be verified");
307 308 309
                    return PE_ERROR;
                }
                else {
310
                    $self->logger->debug("Request JWT signature verified");
311 312 313 314 315 316 317
                }
            }

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

318
                $self->logger->debug("Check sub of ID Token $id_token_hint");
319 320 321 322 323

                # 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
324 325
                  ->{oidcRPMetaDataOptionsUserIDAttr}
                  || $self->conf->{whatToTrace};
326 327
                my $user_id = $req->{sessionInfo}->{$user_id_attribute};
                unless ( $sub eq $user_id ) {
328 329
                    $self->userLogger->error(
                        "ID Token hint sub $sub do not match user $user_id");
330 331 332
                    return $self->returnRedirectError(
                        $req,
                        $oidc_request->{'redirect_uri'},
333
                        'invalid_request',
334 335 336 337 338 339 340
                        "current user do not match id_token_hint sub",
                        undef,
                        $oidc_request->{'state'},
                        ( $flow ne "authorizationcode" )
                    );
                }
                else {
341 342
                    $self->logger->debug(
                        "ID Token hint sub $sub match current user");
343 344 345 346 347 348 349
                }
            }

            # Obtain consent
            my $bypassConsent = $self->conf->{oidcRPMetaDataOptions}->{$rp}
              ->{oidcRPMetaDataOptionsBypassConsent};
            if ($bypassConsent) {
350 351
                $self->logger->debug(
                    "Consent is disabled for RP $rp, user will not be prompted"
352 353 354 355 356 357 358 359 360 361 362 363 364
                );
            }
            else {
                my $ask_for_consent = 1;
                if (    $req->{sessionInfo}->{"_oidc_consent_time_$rp"}
                    and $req->{sessionInfo}->{"_oidc_consent_scope_$rp"} )
                {
                    $ask_for_consent = 0;
                    my $consent_time =
                      $req->{sessionInfo}->{"_oidc_consent_time_$rp"};
                    my $consent_scope =
                      $req->{sessionInfo}->{"_oidc_consent_scope_$rp"};

365 366
                    $self->logger->debug(
"Consent already given for Relying Party $rp (time: $consent_time, scope: $consent_scope)"
367 368 369 370 371 372 373
                    );

                    # Check accepted scope
                    foreach my $requested_scope (
                        split( /\s+/, $oidc_request->{'scope'} ) )
                    {
                        if ( $consent_scope =~ /\b$requested_scope\b/ ) {
374 375
                            $self->logger->debug(
                                "Scope $requested_scope already accepted");
376 377
                        }
                        else {
378 379
                            $self->logger->debug(
"Scope $requested_scope was not previously accepted"
380 381 382 383 384 385 386
                            );
                            $ask_for_consent = 1;
                            last;
                        }
                    }

                    # Check prompt parameter
387 388
                    $ask_for_consent = 1
                      if ( $prompt and $prompt =~ /\bconsent\b/ );
389 390
                }
                if ($ask_for_consent) {
Xavier Guimard's avatar
Xavier Guimard committed
391 392 393
                    if (    $req->param('confirm')
                        and $req->param('confirm') == 1 )
                    {
394
                        $self->p->updatePersistentSession( $req,
395
                            { "_oidc_consent_time_$rp" => time } );
Xavier Guimard's avatar
Xavier Guimard committed
396
                        $self->p->updatePersistentSession(
397
                            $req,
398 399 400 401 402
                            {
                                "_oidc_consent_scope_$rp" =>
                                  $oidc_request->{'scope'}
                            }
                        );
403 404
                        $self->logger->debug(
                            "Consent given for Relying Party $rp");
405
                    }
Xavier Guimard's avatar
Xavier Guimard committed
406 407 408
                    elsif ( $req->param('confirm')
                        and $req->param('confirm') == -1 )
                    {
409 410
                        $self->logger->debug(
                            "User refused consent for Relying party $rp");
411 412 413 414 415 416 417 418 419 420 421
                        return $self->returnRedirectError(
                            $req,
                            $oidc_request->{'redirect_uri'},
                            "consent_required",
                            "consent not given",
                            undef,
                            $oidc_request->{'state'},
                            ( $flow ne "authorizationcode" )
                        );
                    }
                    else {
422 423
                        $self->logger->debug(
                            "Obtain user consent for Relying Party $rp");
424 425

                        # Return error if prompt is none
Xavier Guimard's avatar
Xavier Guimard committed
426
                        if ( $prompt and $prompt =~ /\bnone\b/ ) {
427 428
                            $self->logger->debug(
                                "Consent is needed but prompt is none");
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
                            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};
445
                        my $imgSrc;
446 447

                        if ($icon) {
448
                            $imgSrc =
449 450 451 452 453 454 455 456 457 458 459 460
                              ( $icon =~ m#^https?://# )
                              ? $icon
                              : $self->p->staticPrefic . "/common/" . $icon;
                        }

                        my $scope_messages = {
                            openid  => 'yourIdentity',
                            profile => 'yourProfile',
                            email   => 'yourEmail',
                            address => 'yourAddress',
                            phone   => 'yourPhone',
                        };
461
                        my @list;
462 463 464
                        foreach my $requested_scope (
                            split( /\s/, $oidc_request->{'scope'} ) )
                        {
465 466 467 468 469 470 471 472 473 474 475 476
                            if ( my $message =
                                $scope_messages->{$requested_scope} )
                            {
                                push @list, { m => $message };
                            }
                            else {
                                push @list,
                                  {
                                    m => 'anotherInformation',
                                    n => $requested_scope
                                  };
                            }
477
                        }
478 479 480 481
                        $req->info(
                            $self->loadTemplate(
                                'oidcGiveConsent',
                                params => {
Xavier Guimard's avatar
Xavier Guimard committed
482 483 484
                                    displayName => $display_name,
                                    imgUrl      => $imgSrc,
                                    list        => \@list,
485 486 487
                                }
                            )
                        );
488 489 490 491 492 493 494 495 496 497 498 499 500 501
                        $req->datas->{activeTimer} = 0;
                        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
502 503
                my $codeSession = $self->getOpenIDConnectSession(
                    undef,
504 505 506 507 508 509 510 511 512
                    {
                        redirect_uri    => $oidc_request->{'redirect_uri'},
                        scope           => $oidc_request->{'scope'},
                        user_session_id => $req->id,
                        _utime          => time,
                        nonce           => $oidc_request->{'nonce'},
                    }
                );

513
                # Generate code
Xavier Guimard's avatar
Xavier Guimard committed
514
                my $code = $codeSession->id();
515 516 517

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

518 519 520 521 522 523 524
                # Build Response
                my $response_url = $self->buildAuthorizationCodeAuthnResponse(
                    $oidc_request->{'redirect_uri'},
                    $code, $oidc_request->{'state'},
                    $session_state
                );

525
                $self->logger->debug("Redirect user to $response_url");
526 527
                $req->urldc($response_url);

Xavier Guimard's avatar
Xavier Guimard committed
528
                return PE_REDIRECT;
529 530 531 532 533 534 535 536
            }

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

                my $access_token;
                my $at_hash;

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

539
                    # Store data in access token
540
                    # Generate access_token
Xavier Guimard's avatar
Xavier Guimard committed
541 542
                    my $accessTokenSession = $self->getOpenIDConnectSession(
                        undef,
543 544 545 546 547 548 549
                        {
                            scope           => $oidc_request->{'scope'},
                            rp              => $rp,
                            user_session_id => $req->id,
                            _utime          => time,
                        }
                    );
550 551

                    unless ($accessTokenSession) {
552 553
                        $self->logger->error(
                            "Unable to create OIDC session for access_token");
554 555 556 557 558 559 560 561
                        $self->returnRedirectError( $req,
                            $oidc_request->{'redirect_uri'},
                            "server_error", undef, undef,
                            $oidc_request->{'state'}, 1 );
                    }

                    $access_token = $accessTokenSession->id;

562 563
                    $self->logger->debug(
                        "Generated access token: $access_token");
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618

                    # 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 );

619
                $self->logger->debug("Generated id token: $id_token");
620 621 622 623 624 625 626 627 628 629 630 631 632

                # 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
                );

633
                $self->logger->debug("Redirect user to $response_url");
Xavier Guimard's avatar
Xavier Guimard committed
634
                $req->urldc($response_url);
635

Xavier Guimard's avatar
Xavier Guimard committed
636
                return PE_REDIRECT;
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
            }

            # 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
653 654
                my $codeSession = $self->getOpenIDConnectSession(
                    undef,
655 656 657 658 659 660 661 662 663
                    {
                        redirect_uri    => $oidc_request->{'redirect_uri'},
                        scope           => $oidc_request->{'scope'},
                        user_session_id => $req->id,
                        _utime          => time,
                        nonce           => $oidc_request->{'nonce'},
                    }
                );

664
                # Generate code
Xavier Guimard's avatar
Xavier Guimard committed
665
                my $code = $codeSession->id();
666 667 668

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

669 670 671 672 673 674
                # 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
675 676
                    my $accessTokenSession = $self->getOpenIDConnectSession(
                        undef,
677 678 679 680 681 682 683
                        {
                            scope           => $oidc_request->{'scope'},
                            rp              => $rp,
                            user_session_id => $req->id,
                            _utime          => time,
                        }
                    );
684 685

                    unless ($accessTokenSession) {
686 687
                        $self->logger->error(
                            "Unable to create OIDC session for access_token");
688 689 690 691 692 693 694 695
                        return $self->returnRedirectError( $req,
                            $oidc_request->{'redirect_uri'},
                            "server_error", undef, undef,
                            $oidc_request->{'state'}, 1 );
                    }

                    $access_token = $accessTokenSession->id;

696 697
                    $self->logger->debug(
                        "Generated access token: $access_token");
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716

                    # 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
717
                      || $self->conf->{whatToTrace};
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
                    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 );

743
                    $self->logger->debug("Generated id token: $id_token");
744 745 746 747 748 749 750 751 752 753 754 755 756
                }

                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
                );

757
                $self->logger->debug("Redirect user to $response_url");
758
                $req->urldc($response_url);
Xavier Guimard's avatar
Xavier Guimard committed
759
                return PE_REDIRECT;
760 761
            }

762
            $self->logger->debug("No flow has been selected");
763
            return PE_OK;
Xavier Guimard's avatar
Xavier Guimard committed
764
        }
765 766

        # LOGOUT
Xavier Guimard's avatar
Xavier Guimard committed
767
        elsif ( $path eq $self->conf->{oidcServiceMetaDataEndSessionURI} ) {
768 769
            $self->logger->debug(
                "URL detected as an OpenID Connect END SESSION URL");
770 771 772 773 774

            # 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
775
                if ( $oidc_request->{$param} = $req->param($param) ) {
776 777
                    $self->logger->debug( "OIDC request parameter $param: "
                          . $oidc_request->{$param} );
Xavier Guimard's avatar
Xavier Guimard committed
778
                    $self->p->setHiddenFormValue( $req, $param,
Xavier Guimard's avatar
Xavier Guimard committed
779 780
                        $oidc_request->{$param}, '' );
                }
781 782 783 784 785 786 787 788
            }

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

            # Ask consent for logout
            if ( $req->param('confirm') ) {
789
                my $err;
Xavier Guimard's avatar
Xavier Guimard committed
790
                if ( $req->param('confirm') == 1 ) {
791 792 793 794 795 796
                    $req->steps(
                        [
                            @{ $self->p->beforeLogout }, 'authLogout',
                            'deleteSession'
                        ]
                    );
797
                    $err = $req->error( $self->p->process($req) );
Xavier Guimard's avatar
Xavier Guimard committed
798 799 800 801 802 803
                    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
804 805
                        return $err;
                    }
806 807 808 809
                }

                if ($post_logout_redirect_uri) {

810 811 812 813
                    # 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
814 815 816 817
                        if ( my $redirect_uris =
                            $self->conf->{oidcRPMetaDataOptions}->{$logout_rp}
                            ->{oidcRPMetaDataOptionsPostLogoutRedirectUris} )
                        {
818

Xavier Guimard's avatar
Xavier Guimard committed
819 820 821
                            foreach ( split( /\s+/, $redirect_uris ) ) {
                                if ( $post_logout_redirect_uri eq $_ ) {
                                    $self->logger->debug(
822
"$post_logout_redirect_uri is an allowed logout redirect URI for RP $logout_rp"
Xavier Guimard's avatar
Xavier Guimard committed
823 824 825
                                    );
                                    $redirect_uri_allowed = 1;
                                }
826 827 828 829 830 831 832 833 834 835
                            }
                        }
                    }

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

836 837 838 839 840
                    # Build Response
                    my $response_url =
                      $self->buildLogoutResponse( $post_logout_redirect_uri,
                        $state );

841
                    $self->logger->debug("Redirect user to $response_url");
842
                    $req->urldc($response_url);
Xavier Guimard's avatar
Xavier Guimard committed
843
                    return PE_REDIRECT;
844
                }
845 846 847
                return $req->param('confirm') == 1
                  ? ( $err ? $err : PE_LOGOUT_OK )
                  : PE_OK;
848 849
            }

850
            $req->info( $self->loadTemplate('oidcLogout') );
851 852
            $req->datas->{activeTimer} = 0;
            return PE_CONFIRM;
Xavier Guimard's avatar
Xavier Guimard committed
853 854
        }
    }
855
    $self->logger->error("Unknown OIDC endpoint $path, skipping");
856
    return PE_ERROR;
Xavier Guimard's avatar
Xavier Guimard committed
857 858
}

859
# Handle token endpoint
Xavier Guimard's avatar
Xavier Guimard committed
860 861
sub token {
    my ( $self, $req ) = @_;
862
    $self->logger->debug("URL detected as an OpenID Connect TOKEN URL");
Xavier Guimard's avatar
Xavier Guimard committed
863 864 865 866 867 868

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

    unless ( $client_id && $client_secret ) {
869 870
        $self->logger->error(
"No authentication provided to get token, or authentication type not supported"
Xavier Guimard's avatar
Xavier Guimard committed
871
        );
872
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
873 874 875 876 877 878
    }

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

    unless ($rp) {
879 880
        $self->userLogger->error(
            "No registered Relying Party found with client_id $client_id");
881
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
882 883
    }
    else {
884
        $self->logger->debug("Client id $client_id match RP $rp");
Xavier Guimard's avatar
Xavier Guimard committed
885 886 887 888 889 890
    }

    # Check client_secret
    unless ( $client_secret eq $self->conf->{oidcRPMetaDataOptions}->{$rp}
        ->{oidcRPMetaDataOptionsClientSecret} )
    {
891
        $self->logger->error("Wrong credentials for $rp");
892
        return $self->p->sendError( 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
893 894 895
    }

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

898
    $self->logger->debug("OpenID Connect Code: $code");
Xavier Guimard's avatar
Xavier Guimard committed
899 900 901 902

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

    unless ($codeSession) {
903
        $self->logger->error("Unable to find OIDC session $code");
904
        $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
905 906 907
    }

    # Check we have the same redirect_uri value
Xavier Guimard's avatar
Xavier Guimard committed
908
    unless ( $req->param("redirect_uri") eq $codeSession->data->{redirect_uri} )
Xavier Guimard's avatar
Xavier Guimard committed
909
    {
910 911
        $self->userLogger->error( "Provided redirect_uri is different from "
              . $codeSession->{redirect_uri} );
912
        $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
913 914 915 916
    }

    # Get user identifier
    my $apacheSession =
Xavier Guimard's avatar
Xavier Guimard committed
917 918
      $self->p->getApacheSession( $codeSession->data->{user_session_id},
        noInfo => 1 );
Xavier Guimard's avatar
Xavier Guimard committed
919 920

    unless ($apacheSession) {
921 922
        $self->userLogger->error(
            "Unable to find user session linked to OIDC session $code");
Xavier Guimard's avatar
Xavier Guimard committed
923
        $codeSession->remove();
924
        $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
925 926 927
    }

    my $user_id_attribute =
Xavier Guimard's avatar
Xavier Guimard committed
928 929
      $self->conf->{oidcRPMetaDataOptions}->{$rp}
      ->{oidcRPMetaDataOptionsUserIDAttr}
Xavier Guimard's avatar
Xavier Guimard committed
930 931 932
      || $self->conf->{whatToTrace};
    my $user_id = $apacheSession->data->{$user_id_attribute};

933
    $self->logger->debug("Found corresponding user: $user_id");
Xavier Guimard's avatar
Xavier Guimard committed
934 935

    # Generate access_token
Xavier Guimard's avatar
Xavier Guimard committed
936 937
    my $accessTokenSession = $self->getOpenIDConnectSession(
        undef,
Xavier Guimard's avatar
Xavier Guimard committed
938 939 940 941 942 943 944 945
        {
            scope           => $codeSession->data->{scope},
            rp              => $rp,
            user_session_id => $apacheSession->id,
            _utime          => time,
        }
    );

946 947 948 949
    unless ($accessTokenSession) {
        $self->userLogger->error(
            "Unable to create OIDC session for access_token");
        $codeSession->remove();
950
        $self->p->sendError( $req, 'invalid_request', 400 );
951 952
    }

Xavier Guimard's avatar
Xavier Guimard committed
953 954
    my $access_token = $accessTokenSession->id;

955
    $self->logger->debug("Generated access token: $access_token");
Xavier Guimard's avatar
Xavier Guimard committed
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

    # 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
971 972 973 974 975
        iss => $self->conf->{oidcServiceMetaDataIssuer},    # Issuer Identifier
        sub => $user_id,                                    # Subject Identifier
        aud => [$client_id],                                # Audience
        exp => $id_token_exp,                               # expiration
        iat => time,                                        # Issued time
976 977
        auth_time => $apacheSession->data->{_lastAuthnUTime}
        ,    # Authentication time
Xavier Guimard's avatar
Xavier Guimard committed
978 979 980 981 982 983 984 985 986 987 988 989
        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 );

990
    $self->logger->debug("Generated id token: $id_token");
Xavier Guimard's avatar
Xavier Guimard committed
991 992 993 994 995 996 997 998 999 1000 1001 1002

    # 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,
    };

1003 1004 1005
    my $cRP = join ',', $rp, $apacheSession->data->{_oidcConnectedRP} || '';
    $self->p->updateSession( $req, { _oidcConnectedRP => $cRP },
        $apacheSession->id );
1006

1007
    $self->logger->debug("Send token response");
Xavier Guimard's avatar
Xavier Guimard committed
1008 1009

    $codeSession->remove();
Xavier Guimard's avatar
Xavier Guimard committed
1010
    return $self->p->sendJSONresponse( $req, $token_response );
Xavier Guimard's avatar
Xavier Guimard committed
1011 1012
}

1013
# Handle uerinfo endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1014 1015
sub userInfo {
    my ( $self, $req ) = @_;
1016
    $self->logger->debug("URL detected as an OpenID Connect USERINFO URL");
Xavier Guimard's avatar
Xavier Guimard committed
1017 1018 1019 1020

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

    unless ($access_token) {
1021
        $self->logger->error("Unable to get access_token");
1022 1023
        return $self->returnBearerError( 'invalid_request',
            "Access token not found in request", 401 );
Xavier Guimard's avatar
Xavier Guimard committed
1024 1025
    }

1026
    $self->logger->debug("Received Access Token $access_token");
Xavier Guimard's avatar
Xavier Guimard committed
1027 1028 1029 1030

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

    unless ($accessTokenSession) {
1031 1032
        $self->userLogger->error(
            "Unable to get access token session for id $access_token");
1033 1034
        return $self->returnBearerError( 'invalid_request',
            'Invalid request', 401 );
Xavier Guimard's avatar
Xavier Guimard committed
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    }

    # 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) {
1045 1046
        return $self->returnBearerError( 'invalid_request', 'Invalid request',
            401 );
Xavier Guimard's avatar
Xavier Guimard committed
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    }

    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 );
1058
        $self->logger->debug("Return UserInfo as JWT: $userinfo_jwt");
Xavier Guimard's avatar
Xavier Guimard committed
1059 1060 1061 1062 1063 1064 1065 1066 1067
        return [
            200,
            [
                'Content-Type'   => 'application/jwt',
                'Content-Length' => length($userinfo_jwt)
            ],
            [$userinfo_jwt]
        ];
    }
Xavier Guimard's avatar
Xavier Guimard committed
1068 1069
}

1070
# Handle jwks endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1071 1072
sub jwks {
    my ( $self, $req ) = @_;
1073
    $self->logger->debug("URL detected as an OpenID Connect JWKS URL");
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085

    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;
    }
1086
    $self->logger->debug("Send JWKS response sent");
1087
    return $self->p->sendJSONresponse( $req, $jwks );
Xavier Guimard's avatar
Xavier Guimard committed
1088 1089
}

1090
# Handle register endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1091 1092
sub registration {
    my ( $self, $req ) = @_;
1093
    $self->logger->debug("URL detected as an OpenID Connect REGISTRATION URL");
1094 1095 1096 1097

    # TODO: check Initial Access Token

    # Specific message to allow DOS detection
Xavier Guimard's avatar
Xavier Guimard committed
1098
    my $source_ip = $req->address;
1099 1100
    $self->logger->notice(
        "OpenID Connect Registration request from $source_ip");
1101 1102 1103

    # Check dynamic registration is allowed
    unless ( $self->conf->{oidcServiceAllowDynamicRegistration} ) {
1104
        $self->logger->error("Dynamic registration is not allowed");
1105 1106 1107 1108
        $self->p->sendError( $req, 'server_error' );
    }

    # Get client metadata
1109
    my $client_metadata_json = $req->content;
1110 1111 1112 1113
    unless ($client_metadata_json) {
        return $self->p->sendError( $req, 'Missing POST datas', 400 );
    }

1114
    $self->logger->debug("Client metadata received: $client_metadata_json");
1115 1116 1117 1118 1119 1120

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

    # Check redirect_uris
    unless ( $client_metadata->{redirect_uris} ) {
1121
        $self->logger->error("Field redirect_uris is mandatory");
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
        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
1144
    my $conf = $self->confAcc->getConf( { raw => 1 } );
1145 1146 1147

    $conf->{cfgAuthor}   = "OpenID Connect Registration ($client_name)";
    $conf->{cfgAuthorIP} = $source_ip;
1148
    $conf->{cfgVersion}  = $VERSION;
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186

    $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 {
1187 1188
        $self->logger->error(
            "Configuration not saved: $Lemonldap::NG::Common::Conf::msg");
1189 1190 1191
        return $self->p->sendError( $req, 'server_error', 500 );
    }

1192
    $self->logger->debug("Registration response sent");
1193 1194
    return $self->p->sendJSONresponse( $req, $registration_response,
        code => 201 );
Xavier Guimard's avatar
Xavier Guimard committed
1195 1196
}

1197
# Handle logout endpoint for unauthenticated users
Xavier Guimard's avatar
Xavier Guimard committed
1198 1199
sub endSessionDone {
    my ( $self, $req ) = @_;
1200 1201
    $self->logger->debug("URL  detected as an OpenID Connect END SESSION URL");
    $self->logger->debug("User is already logged out");
1202

Xavier Guimard's avatar
Xavier Guimard committed
1203 1204
    my $post_logout_redirect_uri = $req->param('post_logout_redirect_uri');
    my $state                    = $req->param('state');
1205 1206 1207

    if ($post_logout_redirect_uri) {

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
        # 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);
        }

1231 1232 1233 1234
        # Build Response
        my $response_url =
          $self->buildLogoutResponse( $post_logout_redirect_uri, $state );

1235
        $self->logger->debug("Redirect user to $response_url");
1236 1237 1238 1239 1240
        return [ 302, [ Location => $response_url ], [] ];
    }

    # Else, normal login process
    return $self->p->login($req);
Xavier Guimard's avatar
Xavier Guimard committed
1241 1242
}

1243
# Handle checksession endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1244 1245
sub checkSession {
    my ( $self, $req ) = @_;
1246 1247
    $self->logger->debug(
        "URL  detected as an OpenID Connect CHECK SESSION URL");
1248 1249

    # TODO: access_control_allow_origin => '*'
1250
    $req->frame(1);
Xavier Guimard's avatar
Xavier Guimard committed
1251 1252 1253 1254
    return $self->p->sendHtml(
        $req,
        '../common/oidc_checksession',
        params => {
Xavier Guimard's avatar
Xavier Guimard committed
1255
            COOKIENAME => $self->conf->{cookieName},
Xavier Guimard's avatar
Xavier Guimard committed
1256
        }
1257
    );
Xavier Guimard's avatar
Xavier Guimard committed
1258 1259 1260 1261 1262 1263 1264 1265
}

sub badAuthRequest {
    my ( $self, $req ) = @_;
    return $self->p->sendError( $req,
        $req->uri . ' may not be called by an authenticated user', 400 );
}

1266
# Nothing to do here
Xavier Guimard's avatar
Xavier Guimard committed
1267 1268
sub logout {
    my ( $self, $req ) = @_;
1269 1270 1271 1272
    if ( my $s = $req->userData->{_oidcConnectedRP} ) {
        my @rps = grep /\w/, split( ',', $s );
        foreach my $rp (@rps) {
            my $rpConf = $self->conf->{oidcRPMetaDataOptions}->{$rp};
1273 1274 1275 1276
            unless ($rpConf) {
                $self->logger->error("Unknown RP $rp");
                return PE_ERROR;
            }
1277 1278
            if ( my $url = $rpConf->{oidcRPMetaDataOptionsLogoutUrl} ) {
                if ( $rpConf->{oidcRPMetaDataOptionsLogoutType} eq 'front' ) {
1279 1280 1281 1282 1283 1284 1285
                    if ( $rpConf->{oidcRPMetaDataOptionsLogoutSessionRequired} )
                    {
                        my $user_id_attribute =
                          $self->conf->{oidcRPMetaDataOptions}->{$rp}
                          ->{oidcRPMetaDataOptionsUserIDAttr}
                          || $self->conf->{whatToTrace};
                        my $user_id = $req->{sessionInfo}->{$user_id_attribute};
Xavier Guimard's avatar
Xavier Guimard committed
1286
                        $url .= ( $url =~ /\?/ ? '&' : '?' )
1287 1288 1289 1290 1291
                          . build_urlencoded(
                            iss => $self->conf->{oidcServiceMetaDataIssuer},
                            sid => $user_id
                          );
                    }
1292 1293 1294 1295 1296 1297 1298 1299 1300
                    $req->info( qq'<iframe src="$url" class="noborder">'
                          . '</iframe>' );
                }
                else {
                    # TODO
                }
            }
        }
    }
1301
    return PE_OK;
Xavier Guimard's avatar
Xavier Guimard committed
1302 1303 1304 1305
}

# Internal methods

Xavier Guimard's avatar
Xavier Guimard committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
sub metadata {
    my ( $self, $req ) = @_;
    my $issuerDBOpenIDConnectPath = $self->conf->{issuerDBOpenIDConnectPath};
    my $authorize_uri    = $self->conf->{oidcServiceMetaDataAuthorizeURI};
    my $token_uri        = $self->conf->{oidcServiceMetaDataTokenURI};
    my $userinfo_uri     = $self->conf->{oidcServiceMetaDataUserInfoURI};
    my $jwks_uri         = $self->conf->{oidcServiceMetaDataJWKSURI};
    my $registration_uri = $self->conf->{oidcServiceMetaDataRegistrationURI};
    my $endsession_uri   = $self->conf->{oidcServiceMetaDataEndSessionURI};
    my $checksession_uri = $self->conf->{oidcServiceMetaDataCheckSessionURI};

    my $path   = $self->path . '/';
    my $issuer = $self->conf->{oidcServiceMetaDataIssuer};
    $path = "/" . $path unless ( $issuer =~ /\/$/ );
    my $baseUrl = $issuer . $path;

    my @acr = keys %{ $self->conf->{oidcServiceMetaDataAuthnContext} };

    # Add a slash to path value if issuer has no trailing slash

    # Create OpenID configuration hash;
    return $self->p->sendJSONresponse(
        $req,
        {
            issuer => $issuer,

            # Endpoints
            token_endpoint         => $baseUrl . $token_uri,
            userinfo_endpoint      => $baseUrl . $userinfo_uri,
            jwks_uri               => $baseUrl . $jwks_uri,
            authorization_endpoint => $baseUrl . $authorize_uri,
            end_session_endpoint   => $baseUrl . $endsession_uri,
            check_session_iframe   => $baseUrl . $checksession_uri,
1339 1340 1341 1342 1343 1344

            # Logout capabilities
            backchannel_logout_supported          => JSON::true,
            backchannel_logout_session_supported  => JSON::true,
            frontchannel_logout_supported         => JSON::true,
            frontchannel_logout_session_supported => JSON::true,
Xavier Guimard's avatar
Xavier Guimard committed
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
            (
                $self->conf->{oidcServiceAllowDynamicRegistration}
                ? ( registration_endpoint => $baseUrl . $registration_uri )
                : ()
            ),

            # Scopes
            scopes_supported => [qw/openid profile email address phone/],
            response_types_supported => [
                "code",
                "id_token",
                "id_token token",
                "code id_token",
                "code token",
                "code id_token token"
            ],
            grant_types_supported   => [qw/authorization_code implicit hybrid/],
            acr_values_supported    => \@acr,
            subject_types_supported => ["public"],
            token_endpoint_auth_methods_supported =>
              [qw/client_secret_post client_secret_basic/],
1366
            claims_supported                 => [qw/sub iss auth_time acr/],
Xavier Guimard's avatar
Xavier Guimard committed
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
            request_parameter_supported      => JSON::true,
            request_uri_parameter_supported  => JSON::true,
            require_request_uri_registration => JSON::false,

            # Algorithms
            id_token_signing_alg_values_supported =>
              [qw/none HS256 HS384 HS512 RS256 RS384 RS512/],
            userinfo_signing_alg_values_supported =>
              [qw/none HS256 HS384 HS512 RS256 RS384 RS512/],
        }
    );

    # response_modes_supported}

    # id_token_encryption_alg_values_supported
    # id_token_encryption_enc_values_supported

    # userinfo_encryption_alg_values_supported
    # userinfo_encryption_enc_values_supported
    # request_object_signing_alg_values_supported
    # request_object_encryption_alg_values_supported
    # request_object_encryption_enc_values_supported

    # token_endpoint_auth_signing_alg_values_supported
    # display_values_supported
    # claim_types_supported
    # RECOMMENDED # claims_supported
    # service_documentation
    # claims_locales_supported
    # ui_locales_supported
    # claims_parameter_supported

    # op_policy_uri
    # op_tos_uri
}

1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
# Store request parameters in %ENV
sub exportRequestParameters {
    my ( $self, $req ) = @_;

    foreach my $param (
        qw/response_type scope client_id state redirect_uri nonce
        response_mode display prompt max_age ui_locales id_token_hint
        login_hint acr_values request request_uri/
      )
    {
        if ( $req->param($param) ) {
1414
            $req->env->{ "llng_oidc_" . $param } = $req->param($param);
1415 1416 1417
        }
    }

1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    # Extract request_uri/request parameter
    my $request = $req->param('request');
    if ( $req->param('request_uri') ) {
        $request = $self->getRequestJWT( $req->param('request_uri') );
    }

    if ($request) {
        my $request_data = $self->getJWTJSONData($request);
        foreach ( keys %$request_data ) {
            $req->env->{ "llng_oidc_" . $_ } = $request_data->{$_};
        }
    }