OpenIDConnect.pm 57.2 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
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
use constant sessionKind => 'OIDCI';

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

39 40
has ssoMatchUrl => ( is => 'rw' );

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

Xavier Guimard's avatar
Xavier Guimard committed
56 57 58 59 60 61 62 63 64 65 66
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',
67 68
        oidcServiceMetaDataEndSessionURI   => 'endSessionDone',
        oidcServiceMetaDataCheckSessionURI => 'checkSession',
Xavier Guimard's avatar
Xavier Guimard committed
69 70 71 72 73 74 75 76 77
        oidcServiceMetaDataTokenURI        => 'token',
        oidcServiceMetaDataUserInfoURI     => 'userInfo',
        oidcServiceMetaDataJWKSURI         => 'jwks',
        oidcServiceMetaDataRegistrationURI => 'registration',
    );

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

    # Metadata (.well-known/openid-configuration)
    $self->addUnauthRoute(
        '.well-known' => { 'openid-configuration' => 'metadata' },
        ['GET']
    );
    $self->addAuthRoute(
        '.well-known' => { 'openid-configuration' => 'metadata' },
        ['GET']
    );
94 95 96 97 98 99 100 101
    my $m =
        '^/'
      . $self->path . '/+(?:'
      . join( '|',
        $self->conf->{oidcServiceMetaDataAuthorizeURI},
        $self->conf->{oidcServiceMetaDataEndSessionURI},
      ) . ')';
    $self->ssoMatchUrl(qr/$m/);
Xavier Guimard's avatar
Xavier Guimard committed
102 103 104 105 106
    return 1;
}

# RUNNING METHODS

107 108 109 110 111
sub ssoMatch {
    my ( $self, $req ) = @_;
    return ( $req->uri =~ $self->ssoMatchUrl ? 1 : 0 );
}

112 113
# 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
114 115 116
sub run {
    my ( $self, $req, $path ) = @_;
    if ($path) {
Christophe Maudoux's avatar
Christophe Maudoux committed
117 118

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

Xavier Guimard's avatar
Xavier Guimard committed
122 123
        # AUTHORIZE
        if ( $path eq $self->conf->{oidcServiceMetaDataAuthorizeURI} ) {
124
            $self->logger->debug(
125
                "URL detected as an OpenID Connect AUTHORIZE URL");
126 127 128 129 130 131

            # 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
132
                login_hint acr_values request request_uri/
133 134
              )
            {
Xavier Guimard's avatar
Xavier Guimard committed
135 136
                if ( $req->param($param) ) {
                    $oidc_request->{$param} = $req->param($param);
137 138
                    $self->logger->debug( "OIDC request parameter $param: "
                          . $oidc_request->{$param} );
139 140 141
                    $self->p->setHiddenFormValue( $req, $param,
                        $oidc_request->{$param},
                        '', 0 );
Xavier Guimard's avatar
Xavier Guimard committed
142
                }
143 144 145 146 147 148 149
            }

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

            unless ($flow) {
150
                $self->logger->error("Unknown response type: $response_type");
151 152
                return PE_ERROR;
            }
153 154
            $self->logger->debug(
                "OIDC $flow flow requested (response type: $response_type)");
155 156 157 158 159 160 161 162 163 164

            # 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 {
165
                    $self->logger->error("Error with Request URI resolution");
166 167 168 169 170 171 172 173 174 175
                    return PE_ERROR;
                }
            }

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

                # Override OIDC parameters by request content
                foreach ( keys %$request ) {
176 177
                    $self->logger->debug(
"Override $_ OIDC param by value present in request parameter"
178 179
                    );
                    $oidc_request->{$_} = $request->{$_};
180 181
                    $self->p->setHiddenFormValue( $req, $_, $request->{$_},
                        '' );
182 183 184 185 186
                }
            }

            # Check all required parameters
            unless ( $oidc_request->{'redirect_uri'} ) {
187
                $self->logger->error("Redirect URI is required");
188 189 190
                return PE_ERROR;
            }
            unless ( $oidc_request->{'scope'} ) {
191
                $self->logger->error("Scope is required");
192
                return PE_ERROR;
193 194
            }
            unless ( $oidc_request->{'client_id'} ) {
195
                $self->logger->error("Client ID is required");
196
                return PE_ERROR;
197 198 199
            }
            if ( $flow eq "implicit" and not defined $oidc_request->{'nonce'} )
            {
200
                $self->logger->error("Nonce is required for implicit flow");
201 202 203 204 205 206 207 208 209 210 211 212 213
                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"
214
                );
215 216 217
                return PE_UNAUTHORIZEDPARTNER;
            }
            else {
218
                $self->logger->debug("Client id $client_id matches RP $rp");
219 220
            }

221
            # Check if this RP is authorized
222
            if ( my $rule = $self->spRules->{$rp} ) {
223 224 225
                unless ( $rule->( $req, $req->sessionInfo ) ) {
                    $self->userLogger->warn( 'User '
                          . $req->sessionInfo->{ $self->conf->{whatToTrace} }
226
                          . "was not authorized to access to $rp" );
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
                    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;
                }
246 247 248 249 250 251
            }

            # Check if flow is allowed
            if ( $flow eq "authorizationcode"
                and not $self->conf->{oidcServiceAllowAuthorizationCodeFlow} )
            {
252 253
                $self->userLogger->error(
                    "Authorization code flow is not allowed");
254 255 256 257 258 259 260 261 262 263
                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} )
            {
264
                $self->logger->error("Implicit flow is not allowed");
265 266 267 268 269 270 271 272 273 274
                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} )
            {
275
                $self->logger->error("Hybrid flow is not allowed");
276 277 278 279 280 281 282 283 284
                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
285 286 287 288 289 290 291 292 293
            my $prompt = $oidc_request->{'prompt'};
            if (
                    $prompt
                and $prompt =~ /\blogin\b/
                and (
                    time - $req->sessionInfo->{_utime} >
                    $self->conf->{portalForceAuthnInterval} )
              )
            {
294
                $self->logger->debug(
295
"Reauthentication required by Relying Party in prompt parameter"
296
                );
Xavier Guimard's avatar
Xavier Guimard committed
297
                return $self->reAuth($req);
298 299 300 301 302
            }

            my $max_age         = $oidc_request->{'max_age'};
            my $_lastAuthnUTime = $req->{sessionInfo}->{_lastAuthnUTime};
            if ( $max_age && time > $_lastAuthnUTime + $max_age ) {
303
                $self->logger->debug(
304
"Reauthentication forced because authentication time ($_lastAuthnUTime) is too old (>$max_age s)"
305
                );
Xavier Guimard's avatar
Xavier Guimard committed
306
                return $self->reAuth($req);
307 308 309 310
            }

            # Check openid scope
            unless ( $oidc_request->{'scope'} =~ /\bopenid\b/ ) {
311
                $self->logger->debug("No openid scope found");
312 313 314 315 316 317 318 319 320 321 322 323 324 325

                #TODO manage standard OAuth request
                return PE_OK;
            }

            # Check Request JWT signature
            if ( $oidc_request->{'request'} ) {
                unless (
                    $self->verifyJWTSignature(
                        $oidc_request->{'request'},
                        undef, $rp
                    )
                  )
                {
326
                    $self->logger->error(
327
                        "JWT signature request can not be verified");
328 329 330
                    return PE_ERROR;
                }
                else {
331
                    $self->logger->debug("JWT signature request verified");
332 333 334 335 336 337 338
                }
            }

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

339
                $self->logger->debug("Check sub of ID Token $id_token_hint");
340 341 342 343 344

                # 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
345 346
                  ->{oidcRPMetaDataOptionsUserIDAttr}
                  || $self->conf->{whatToTrace};
347 348
                my $user_id = $req->{sessionInfo}->{$user_id_attribute};
                unless ( $sub eq $user_id ) {
349
                    $self->userLogger->error(
350
                        "ID Token hint sub $sub does not match user $user_id");
351 352 353
                    return $self->returnRedirectError(
                        $req,
                        $oidc_request->{'redirect_uri'},
354
                        'invalid_request',
355
                        "Current user does not match id_token_hint sub",
356 357 358 359 360 361
                        undef,
                        $oidc_request->{'state'},
                        ( $flow ne "authorizationcode" )
                    );
                }
                else {
362
                    $self->logger->debug(
363
                        "ID Token hint sub $sub matches current user");
364 365 366 367 368 369 370
                }
            }

            # Obtain consent
            my $bypassConsent = $self->conf->{oidcRPMetaDataOptions}->{$rp}
              ->{oidcRPMetaDataOptionsBypassConsent};
            if ($bypassConsent) {
371
                $self->logger->debug(
372
"Consent is disabled for Relying Party $rp, user will not be prompted"
373 374 375 376
                );
            }
            else {
                my $ask_for_consent = 1;
377 378
                my $_oidcConsents;
                my @RPoidcConsent = ();
379

380 381
                # Loading existing oidcConsents
                $self->logger->debug("Looking for OIDC Consents ...");
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
                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 = [];
                }
398

399
                # Read existing RP
400
                @RPoidcConsent = grep { $_->{rp} eq $rp } @$_oidcConsents;
Xavier Guimard's avatar
Xavier Guimard committed
401
                unless (@RPoidcConsent) {
402 403 404
                    $self->logger->debug("No Relying Party $rp Consent found");

                    # Set default value
405 406
                    push @RPoidcConsent,
                      { rp => $rp, epoch => '', scope => '' };
407 408
                }

409
                if (   $RPoidcConsent[0]{rp} eq $rp
410 411
                    && $RPoidcConsent[0]{epoch}
                    && $RPoidcConsent[0]{scope} )
412
                {
413 414 415
                    $ask_for_consent = 0;
                    my $consent_time  = $RPoidcConsent[0]{epoch};
                    my $consent_scope = $RPoidcConsent[0]{scope};
416 417
                    $self->logger->debug(
"Consent already given for Relying Party $rp (time: $consent_time, scope: $consent_scope)"
418 419 420 421 422 423 424
                    );

                    # Check accepted scope
                    foreach my $requested_scope (
                        split( /\s+/, $oidc_request->{'scope'} ) )
                    {
                        if ( $consent_scope =~ /\b$requested_scope\b/ ) {
425 426
                            $self->logger->debug(
                                "Scope $requested_scope already accepted");
427 428
                        }
                        else {
429 430
                            $self->logger->debug(
"Scope $requested_scope was not previously accepted"
431 432 433 434 435 436 437
                            );
                            $ask_for_consent = 1;
                            last;
                        }
                    }

                    # Check prompt parameter
438 439
                    $ask_for_consent = 1
                      if ( $prompt and $prompt =~ /\bconsent\b/ );
440 441
                }
                if ($ask_for_consent) {
Xavier Guimard's avatar
Xavier Guimard committed
442 443 444
                    if (    $req->param('confirm')
                        and $req->param('confirm') == 1 )
                    {
445
                        $RPoidcConsent[0]{epoch} = time;
446 447
                        $RPoidcConsent[0]{scope} = $oidc_request->{'scope'};
                        push @{$_oidcConsents}, @RPoidcConsent;
448 449 450 451 452
                        $self->logger->debug(
                            "Append Relying Party $rp Consent");
                        $self->p->updatePersistentSession( $req,
                            { _oidcConsents => to_json($_oidcConsents) } );

453 454
                        $self->logger->debug(
                            "Consent given for Relying Party $rp");
455
                    }
Xavier Guimard's avatar
Xavier Guimard committed
456 457 458
                    elsif ( $req->param('confirm')
                        and $req->param('confirm') == -1 )
                    {
459 460
                        $self->logger->debug(
                            "User refused consent for Relying party $rp");
461 462 463 464 465 466 467 468 469 470 471
                        return $self->returnRedirectError(
                            $req,
                            $oidc_request->{'redirect_uri'},
                            "consent_required",
                            "consent not given",
                            undef,
                            $oidc_request->{'state'},
                            ( $flow ne "authorizationcode" )
                        );
                    }
                    else {
472
                        $self->logger->debug(
473
                            "Request user consent for Relying Party $rp");
474 475

                        # Return error if prompt is none
Xavier Guimard's avatar
Xavier Guimard committed
476
                        if ( $prompt and $prompt =~ /\bnone\b/ ) {
477
                            $self->logger->debug(
478 479
                                "Consent is requiered but prompt is set to none"
                            );
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
                            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};
496
                        my $imgSrc;
497 498

                        if ($icon) {
499
                            $imgSrc =
500 501 502 503 504 505 506 507 508 509 510 511
                              ( $icon =~ m#^https?://# )
                              ? $icon
                              : $self->p->staticPrefic . "/common/" . $icon;
                        }

                        my $scope_messages = {
                            openid  => 'yourIdentity',
                            profile => 'yourProfile',
                            email   => 'yourEmail',
                            address => 'yourAddress',
                            phone   => 'yourPhone',
                        };
512
                        my @list;
513 514 515
                        foreach my $requested_scope (
                            split( /\s/, $oidc_request->{'scope'} ) )
                        {
516 517 518 519 520 521 522 523 524 525 526 527
                            if ( my $message =
                                $scope_messages->{$requested_scope} )
                            {
                                push @list, { m => $message };
                            }
                            else {
                                push @list,
                                  {
                                    m => 'anotherInformation',
                                    n => $requested_scope
                                  };
                            }
528
                        }
529 530 531 532
                        $req->info(
                            $self->loadTemplate(
                                'oidcGiveConsent',
                                params => {
Xavier Guimard's avatar
Xavier Guimard committed
533 534 535
                                    displayName => $display_name,
                                    imgUrl      => $imgSrc,
                                    list        => \@list,
536 537 538
                                }
                            )
                        );
Xavier Guimard's avatar
Xavier Guimard committed
539
                        $req->data->{activeTimer} = 0;
540 541 542 543 544 545 546 547 548 549 550 551 552
                        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
553 554
                my $codeSession = $self->getOpenIDConnectSession(
                    undef,
555 556 557 558 559 560 561 562 563
                    {
                        redirect_uri    => $oidc_request->{'redirect_uri'},
                        scope           => $oidc_request->{'scope'},
                        user_session_id => $req->id,
                        _utime          => time,
                        nonce           => $oidc_request->{'nonce'},
                    }
                );

564
                # Generate code
Xavier Guimard's avatar
Xavier Guimard committed
565
                my $code = $codeSession->id();
566 567 568

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

569 570 571 572 573 574 575
                # Build Response
                my $response_url = $self->buildAuthorizationCodeAuthnResponse(
                    $oidc_request->{'redirect_uri'},
                    $code, $oidc_request->{'state'},
                    $session_state
                );

576
                $self->logger->debug("Redirect user to $response_url");
577 578
                $req->urldc($response_url);

Xavier Guimard's avatar
Xavier Guimard committed
579
                return PE_REDIRECT;
580 581 582 583 584 585 586 587
            }

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

                my $access_token;
                my $at_hash;

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

590
                    # Store data in access token
591
                    # Generate access_token
Xavier Guimard's avatar
Xavier Guimard committed
592 593
                    my $accessTokenSession = $self->getOpenIDConnectSession(
                        undef,
594 595 596 597 598 599 600
                        {
                            scope           => $oidc_request->{'scope'},
                            rp              => $rp,
                            user_session_id => $req->id,
                            _utime          => time,
                        }
                    );
601 602

                    unless ($accessTokenSession) {
603 604
                        $self->logger->error(
                            "Unable to create OIDC session for access_token");
605 606 607 608 609 610 611 612
                        $self->returnRedirectError( $req,
                            $oidc_request->{'redirect_uri'},
                            "server_error", undef, undef,
                            $oidc_request->{'state'}, 1 );
                    }

                    $access_token = $accessTokenSession->id;

613 614
                    $self->logger->debug(
                        "Generated access token: $access_token");
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 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

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

670
                $self->logger->debug("Generated id token: $id_token");
671 672 673 674 675 676 677 678 679 680 681 682 683

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

684
                $self->logger->debug("Redirect user to $response_url");
Xavier Guimard's avatar
Xavier Guimard committed
685
                $req->urldc($response_url);
686

Xavier Guimard's avatar
Xavier Guimard committed
687
                return PE_REDIRECT;
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
            }

            # 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
704 705
                my $codeSession = $self->getOpenIDConnectSession(
                    undef,
706 707 708 709 710 711 712 713 714
                    {
                        redirect_uri    => $oidc_request->{'redirect_uri'},
                        scope           => $oidc_request->{'scope'},
                        user_session_id => $req->id,
                        _utime          => time,
                        nonce           => $oidc_request->{'nonce'},
                    }
                );

715
                # Generate code
Xavier Guimard's avatar
Xavier Guimard committed
716
                my $code = $codeSession->id();
717 718 719

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

720 721 722 723 724 725
                # 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
726 727
                    my $accessTokenSession = $self->getOpenIDConnectSession(
                        undef,
728 729 730 731 732 733 734
                        {
                            scope           => $oidc_request->{'scope'},
                            rp              => $rp,
                            user_session_id => $req->id,
                            _utime          => time,
                        }
                    );
735 736

                    unless ($accessTokenSession) {
737 738
                        $self->logger->error(
                            "Unable to create OIDC session for access_token");
739 740 741 742 743 744 745 746
                        return $self->returnRedirectError( $req,
                            $oidc_request->{'redirect_uri'},
                            "server_error", undef, undef,
                            $oidc_request->{'state'}, 1 );
                    }

                    $access_token = $accessTokenSession->id;

747 748
                    $self->logger->debug(
                        "Generated access token: $access_token");
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767

                    # 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
768
                      || $self->conf->{whatToTrace};
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
                    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 );

794
                    $self->logger->debug("Generated id token: $id_token");
795 796 797 798 799 800 801 802 803 804 805 806 807
                }

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

808
                $self->logger->debug("Redirect user to $response_url");
809
                $req->urldc($response_url);
Xavier Guimard's avatar
Xavier Guimard committed
810
                return PE_REDIRECT;
811 812
            }

813
            $self->logger->debug("None flow has been selected");
814
            return PE_OK;
Xavier Guimard's avatar
Xavier Guimard committed
815
        }
816 817

        # LOGOUT
Xavier Guimard's avatar
Xavier Guimard committed
818
        elsif ( $path eq $self->conf->{oidcServiceMetaDataEndSessionURI} ) {
819 820
            $self->logger->debug(
                "URL detected as an OpenID Connect END SESSION URL");
821 822 823 824 825

            # 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
826
                if ( $oidc_request->{$param} = $req->param($param) ) {
827 828
                    $self->logger->debug( "OIDC request parameter $param: "
                          . $oidc_request->{$param} );
Xavier Guimard's avatar
Xavier Guimard committed
829
                    $self->p->setHiddenFormValue( $req, $param,
Xavier Guimard's avatar
Xavier Guimard committed
830 831
                        $oidc_request->{$param}, '' );
                }
832 833 834 835 836 837 838 839
            }

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

            # Ask consent for logout
            if ( $req->param('confirm') ) {
840
                my $err;
Xavier Guimard's avatar
Xavier Guimard committed
841
                if ( $req->param('confirm') == 1 ) {
842 843 844 845 846 847
                    $req->steps(
                        [
                            @{ $self->p->beforeLogout }, 'authLogout',
                            'deleteSession'
                        ]
                    );
848
                    $err = $req->error( $self->p->process($req) );
Xavier Guimard's avatar
Xavier Guimard committed
849 850 851 852 853 854
                    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
855 856
                        return $err;
                    }
857 858 859 860
                }

                if ($post_logout_redirect_uri) {

861 862 863 864
                    # 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
865 866 867 868
                        if ( my $redirect_uris =
                            $self->conf->{oidcRPMetaDataOptions}->{$logout_rp}
                            ->{oidcRPMetaDataOptionsPostLogoutRedirectUris} )
                        {
869

Xavier Guimard's avatar
Xavier Guimard committed
870 871 872
                            foreach ( split( /\s+/, $redirect_uris ) ) {
                                if ( $post_logout_redirect_uri eq $_ ) {
                                    $self->logger->debug(
873
"$post_logout_redirect_uri is an allowed logout redirect URI for RP $logout_rp"
Xavier Guimard's avatar
Xavier Guimard committed
874 875 876
                                    );
                                    $redirect_uri_allowed = 1;
                                }
877 878 879 880 881 882 883 884 885 886
                            }
                        }
                    }

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

887 888 889 890 891
                    # Build Response
                    my $response_url =
                      $self->buildLogoutResponse( $post_logout_redirect_uri,
                        $state );

892
                    $self->logger->debug("Redirect user to $response_url");
893
                    $req->urldc($response_url);
Xavier Guimard's avatar
Xavier Guimard committed
894
                    return PE_REDIRECT;
895
                }
896 897 898
                return $req->param('confirm') == 1
                  ? ( $err ? $err : PE_LOGOUT_OK )
                  : PE_OK;
899 900
            }

901
            $req->info( $self->loadTemplate('oidcLogout') );
Xavier Guimard's avatar
Xavier Guimard committed
902
            $req->data->{activeTimer} = 0;
903
            return PE_CONFIRM;
Xavier Guimard's avatar
Xavier Guimard committed
904 905
        }
    }
906
    $self->logger->error("Unknown OIDC endpoint $path, skipping");
907
    return PE_ERROR;
Xavier Guimard's avatar
Xavier Guimard committed
908 909
}

910
# Handle token endpoint
Xavier Guimard's avatar
Xavier Guimard committed
911 912
sub token {
    my ( $self, $req ) = @_;
913
    $self->logger->debug("URL detected as an OpenID Connect TOKEN URL");
Xavier Guimard's avatar
Xavier Guimard committed
914 915 916 917 918 919

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

    unless ( $client_id && $client_secret ) {
920 921
        $self->logger->error(
"No authentication provided to get token, or authentication type not supported"
Xavier Guimard's avatar
Xavier Guimard committed
922
        );
923
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
924 925 926 927 928 929
    }

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

    unless ($rp) {
930 931
        $self->userLogger->error(
            "No registered Relying Party found with client_id $client_id");
932
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
933 934
    }
    else {
935
        $self->logger->debug("Client id $client_id match Relying Party $rp");
Xavier Guimard's avatar
Xavier Guimard committed
936 937 938 939 940 941
    }

    # Check client_secret
    unless ( $client_secret eq $self->conf->{oidcRPMetaDataOptions}->{$rp}
        ->{oidcRPMetaDataOptionsClientSecret} )
    {
942
        $self->logger->error("Wrong credentials for $rp");
943
        return $self->p->sendError( 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
944 945 946
    }

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

949
    $self->logger->debug("OpenID Connect Code: $code");
Xavier Guimard's avatar
Xavier Guimard committed
950 951 952 953

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

    unless ($codeSession) {
954
        $self->logger->error("Unable to find OIDC session $code");
Xavier Guimard's avatar
Xavier Guimard committed
955
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
956 957 958
    }

    # Check we have the same redirect_uri value
Xavier Guimard's avatar
Xavier Guimard committed
959
    unless ( $req->param("redirect_uri") eq $codeSession->data->{redirect_uri} )
Xavier Guimard's avatar
Xavier Guimard committed
960
    {
961
        $self->userLogger->error( "Provided redirect_uri does not match "
962
              . $codeSession->{redirect_uri} );
Xavier Guimard's avatar
Xavier Guimard committed
963
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
964 965 966 967
    }

    # Get user identifier
    my $apacheSession =
Xavier Guimard's avatar
Xavier Guimard committed
968 969
      $self->p->getApacheSession( $codeSession->data->{user_session_id},
        noInfo => 1 );
Xavier Guimard's avatar
Xavier Guimard committed
970 971

    unless ($apacheSession) {
972 973
        $self->userLogger->error(
            "Unable to find user session linked to OIDC session $code");
Xavier Guimard's avatar
Xavier Guimard committed
974
        $codeSession->remove();
Xavier Guimard's avatar
Xavier Guimard committed
975
        return $self->p->sendError( $req, 'invalid_request', 400 );
Xavier Guimard's avatar
Xavier Guimard committed
976 977 978
    }

    my $user_id_attribute =
Xavier Guimard's avatar
Xavier Guimard committed
979 980
      $self->conf->{oidcRPMetaDataOptions}->{$rp}
      ->{oidcRPMetaDataOptionsUserIDAttr}
Xavier Guimard's avatar
Xavier Guimard committed
981 982 983
      || $self->conf->{whatToTrace};
    my $user_id = $apacheSession->data->{$user_id_attribute};

984
    $self->logger->debug("Found corresponding user: $user_id");
Xavier Guimard's avatar
Xavier Guimard committed
985 986

    # Generate access_token
Xavier Guimard's avatar
Xavier Guimard committed
987 988
    my $accessTokenSession = $self->getOpenIDConnectSession(
        undef,
Xavier Guimard's avatar
Xavier Guimard committed
989 990 991 992 993 994 995 996
        {
            scope           => $codeSession->data->{scope},
            rp              => $rp,
            user_session_id => $apacheSession->id,
            _utime          => time,
        }
    );

997 998 999 1000
    unless ($accessTokenSession) {
        $self->userLogger->error(
            "Unable to create OIDC session for access_token");
        $codeSession->remove();
Xavier Guimard's avatar
Xavier Guimard committed
1001
        return $self->p->sendError( $req, 'invalid_request', 400 );
1002 1003
    }

Xavier Guimard's avatar
Xavier Guimard committed
1004 1005
    my $access_token = $accessTokenSession->id;

1006
    $self->logger->debug("Generated access token: $access_token");
Xavier Guimard's avatar
Xavier Guimard committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021

    # 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
1022 1023 1024 1025 1026
        iss => $self->conf->{oidcServiceMetaDataIssuer},    # Issuer Identifier
        sub => $user_id,                                    # Subject Identifier
        aud => [$client_id],                                # Audience
        exp => $id_token_exp,                               # expiration
        iat => time,                                        # Issued time
1027 1028
        auth_time => $apacheSession->data->{_lastAuthnUTime}
        ,    # Authentication time
Xavier Guimard's avatar
Xavier Guimard committed
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        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 );

1041
    $self->logger->debug("Generated id token: $id_token");
Xavier Guimard's avatar
Xavier Guimard committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

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

1054 1055 1056 1057 1058
    my $cRP = $apacheSession->data->{_oidcConnectedRP} || '';
    unless ( $cRP =~ /\b$rp\b/ ) {
        $self->p->updateSession( $req, { _oidcConnectedRP => "$rp,$cRP" },
            $apacheSession->id );
    }
1059

1060
    $self->logger->debug("Send token response");
Xavier Guimard's avatar
Xavier Guimard committed
1061 1062

    $codeSession->remove();
Xavier Guimard's avatar
Xavier Guimard committed
1063
    return $self->p->sendJSONresponse( $req, $token_response );
Xavier Guimard's avatar
Xavier Guimard committed
1064 1065
}

1066
# Handle uerinfo endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1067 1068
sub userInfo {
    my ( $self, $req ) = @_;
1069
    $self->logger->debug("URL detected as an OpenID Connect USERINFO URL");
Xavier Guimard's avatar
Xavier Guimard committed
1070 1071 1072 1073

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

    unless ($access_token) {
1074
        $self->logger->error("Unable to get access_token");
1075 1076
        return $self->returnBearerError( 'invalid_request',
            "Access token not found in request", 401 );
Xavier Guimard's avatar
Xavier Guimard committed
1077 1078
    }

1079
    $self->logger->debug("Received Access Token $access_token");
Xavier Guimard's avatar
Xavier Guimard committed
1080 1081 1082 1083

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

    unless ($accessTokenSession) {
1084 1085
        $self->userLogger->error(
            "Unable to get access token session for id $access_token");
1086 1087
        return $self->returnBearerError( 'invalid_request',
            'Invalid request', 401 );
Xavier Guimard's avatar
Xavier Guimard committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    }

    # 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) {
1098 1099
        return $self->returnBearerError( 'invalid_request', 'Invalid request',
            401 );
Xavier Guimard's avatar
Xavier Guimard committed
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    }

    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 );
1111
        $self->logger->debug("Return UserInfo as JWT: $userinfo_jwt");
Xavier Guimard's avatar
Xavier Guimard committed
1112 1113 1114 1115 1116 1117 1118 1119 1120
        return [
            200,
            [
                'Content-Type'   => 'application/jwt',
                'Content-Length' => length($userinfo_jwt)
            ],
            [$userinfo_jwt]
        ];
    }
Xavier Guimard's avatar
Xavier Guimard committed
1121 1122
}

1123
# Handle jwks endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1124 1125
sub jwks {
    my ( $self, $req ) = @_;
1126
    $self->logger->debug("URL detected as an OpenID Connect JWKS URL");
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

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

1143
# Handle register endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1144 1145
sub registration {
    my ( $self, $req ) = @_;
1146
    $self->logger->debug("URL detected as an OpenID Connect REGISTRATION URL");
1147 1148 1149 1150

    # TODO: check Initial Access Token

    # Specific message to allow DOS detection
Xavier Guimard's avatar
Xavier Guimard committed
1151
    my $source_ip = $req->address;
1152 1153
    $self->logger->notice(
        "OpenID Connect Registration request from $source_ip");
1154 1155 1156

    # Check dynamic registration is allowed
    unless ( $self->conf->{oidcServiceAllowDynamicRegistration} ) {
1157
        $self->logger->error("Dynamic registration is not allowed");
Xavier Guimard's avatar
Xavier Guimard committed
1158
        return $self->p->sendError( $req, 'server_error' );
1159 1160 1161
    }

    # Get client metadata
1162
    my $client_metadata_json = $req->content;
1163
    unless ($client_metadata_json) {
Xavier Guimard's avatar
Xavier Guimard committed
1164
        return $self->p->sendError( $req, 'Missing POST data', 400 );
1165 1166
    }

1167
    $self->logger->debug("Client metadata received: $client_metadata_json");
1168 1169 1170 1171 1172 1173

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

    # Check redirect_uris
    unless ( $client_metadata->{redirect_uris} ) {
1174
        $self->logger->error("Field redirect_uris is mandatory");
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
        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
1197
    my $conf = $self->confAcc->getConf( { raw => 1 } );
1198 1199 1200

    $conf->{cfgAuthor}   = "OpenID Connect Registration ($client_name)";
    $conf->{cfgAuthorIP} = $source_ip;
1201
    $conf->{cfgVersion}  = $VERSION;
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

    $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 {
1240 1241
        $self->logger->error(
            "Configuration not saved: $Lemonldap::NG::Common::Conf::msg");
1242 1243 1244
        return $self->p->sendError( $req, 'server_error', 500 );
    }

1245
    $self->logger->debug("Registration response sent");
1246 1247
    return $self->p->sendJSONresponse( $req, $registration_response,
        code => 201 );
Xavier Guimard's avatar
Xavier Guimard committed
1248 1249
}

1250
# Handle logout endpoint for unauthenticated users
Xavier Guimard's avatar
Xavier Guimard committed
1251 1252
sub endSessionDone {
    my ( $self, $req ) = @_;
1253 1254
    $self->logger->debug("URL  detected as an OpenID Connect END SESSION URL");
    $self->logger->debug("User is already logged out");
1255

Xavier Guimard's avatar
Xavier Guimard committed
1256 1257
    my $post_logout_redirect_uri = $req->param('post_logout_redirect_uri');
    my $state                    = $req->param('state');
1258 1259 1260

    if ($post_logout_redirect_uri) {

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
        # 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);
        }

1284 1285 1286 1287
        # Build Response
        my $response_url =
          $self->buildLogoutResponse( $post_logout_redirect_uri, $state );

1288
        $self->logger->debug("Redirect user to $response_url");
1289 1290 1291 1292 1293
        return [ 302, [ Location => $response_url ], [] ];
    }

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

1296
# Handle checksession endpoint
Xavier Guimard's avatar
Xavier Guimard committed
1297 1298
sub checkSession {
    my ( $self, $req ) = @_;
Christophe Maudoux's avatar
Christophe Maudoux committed
1299
    $self->logger->debug("URL detected as an OpenID Connect CHECK SESSION URL");
1300 1301

    # TODO: access_control_allow_origin => '*'
1302
    $req->frame(1);
Xavier Guimard's avatar
Xavier Guimard committed
1303 1304 1305 1306
    return $self->p->sendHtml(
        $req,
        '../common/oidc_checksession',
        params => {
Xavier Guimard's avatar
Xavier Guimard committed
1307
            COOKIENAME => $self->conf->{cookieName},
Xavier Guimard's avatar
Xavier Guimard committed
1308
        }
1309
    );
Xavier Guimard's avatar
Xavier Guimard committed
1310 1311 1312 1313 1314 1315 1316 1317
}

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

1318
# Nothing to do here