--- loncom/lti/ltiauth.pm	2022/02/01 23:13:20	1.30
+++ loncom/lti/ltiauth.pm	2023/05/24 14:55:57	1.41
@@ -1,7 +1,7 @@
 # The LearningOnline Network
 # Basic LTI Authentication Module
 #
-# $Id: ltiauth.pm,v 1.30 2022/02/01 23:13:20 raeburn Exp $
+# $Id: ltiauth.pm,v 1.41 2023/05/24 14:55:57 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -30,7 +30,8 @@ package Apache::ltiauth;
 
 use strict;
 use LONCAPA qw(:DEFAULT :match);
-use Apache::Constants qw(:common :http);
+use Encode;
+use Apache::Constants qw(:common :http :remotehost);
 use Apache::lonlocal;
 use Apache::lonnet;
 use Apache::loncommon;
@@ -63,7 +64,7 @@ sub handler {
     my $params = {};
     foreach my $key (sort(keys(%env))) {
         if ($key =~ /^form\.(.+)$/) {
-            $params->{$1} = $env{$key};
+            $params->{$1} = &Encode::decode('UTF-8',$env{$key});
         }
     }
 #
@@ -79,7 +80,7 @@ sub handler {
     }
 
     unless (keys(%{$params})) {
-        &invalid_request($r,1);
+        &invalid_request($r,'No parameters included in launch request');
         return OK;
     }
 
@@ -89,7 +90,7 @@ sub handler {
             $params->{'oauth_version'} &&
             $params->{'oauth_signature'} &&
             $params->{'oauth_signature_method'}) {
-        &invalid_request($r,2);
+        &invalid_request($r,'One or more required parameters missing from launch request');
         return OK;
     }
 
@@ -116,7 +117,7 @@ sub handler {
 #
     if ($requri =~ m{^/adm/launch(|/.*)$}) {
         my $tail = $1;
-        if ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
+        if ($tail =~ m{^/tiny/$match_domain/\w+$}) {
             my ($urlcdom,$urlcnum) = &course_from_tinyurl($tail);
             if (($urlcdom ne '') && ($urlcnum ne '')) {
                 $cdom = $urlcdom;
@@ -142,30 +143,105 @@ sub handler {
 # where url was /adm/launch/tiny/$cdom/$uniqueid
 #
 
-                        my ($itemid,$ltitype,%crslti);
-                        $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,$cnum,'deeplink');
+                        my ($itemid,$ltitype,%crslti,%lti_in_use,$ltiuser);
+                        $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,$cnum,'linkprot');
                         if ($itemid) {
                             %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                         }
                         if (($itemid) && (ref($crslti{$itemid}) eq 'HASH')) {
                             $ltitype = 'c';
-                            unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
-                                                                    $crslti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
-                                &invalid_request($r,3);
+                            if (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
+                                                                $crslti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
+                                %lti_in_use = %{$crslti{$itemid}};
+                            } else {
+                                &invalid_request($r,'Time limit exceeded for launch request credentials');
                                 return OK;
                             }
                         } else {
+                            $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,'','linkprot');
                             my %lti;
-                            $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,'','deeplink');
                             if ($itemid) {
-                                %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
+                                %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                             }
                             if (($itemid) && (ref($lti{$itemid}) eq 'HASH')) {
                                 $ltitype = 'd';
-                                unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
+                                if (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
                                                                         $lti{$itemid}{'lifetime'},$cdom,
                                                                         $r->dir_config('lonLTIDir'))) {
-                                    &invalid_request($r,4);
+                                    %lti_in_use = %{$lti{$itemid}};
+                                } else {
+                                    &invalid_request($r,'Time limit exceeded for launch request credentials');
+                                    return OK;
+                                }
+                            }
+                        }
+                        my $exiturl;
+                        if (($itemid) && ($lti_in_use{'returnurl'} ne '')) {
+                            if (exists($params->{$lti_in_use{'returnurl'}})) {
+                                $exiturl = $params->{$lti_in_use{'returnurl'}};
+                            } elsif (exists($params->{'custom_'.$lti_in_use{'returnurl'}})) {
+                                $exiturl = $params->{'custom_'.$lti_in_use{'returnurl'}};
+                            }
+                        }
+                        if (($itemid) && ($lti_in_use{'requser'})) {
+                            my %courseinfo = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
+                            my $ltiauth;
+                            if (exists($courseinfo{'internal.ltiauth'})) {
+                                $ltiauth = $courseinfo{'internal.ltiauth'};
+                            } else {
+                                my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
+                                $ltiauth = $domdefs{'crsltiauth'};
+                            }
+                            if ($ltiauth) {
+                                my $possuname;
+                                my $mapuser = $lti_in_use{'mapuser'};
+                                if ($mapuser eq 'sourcedid') {
+                                    if ($params->{'lis_person_sourcedid'} =~ /^$match_username$/) {
+                                        $possuname = $params->{'lis_person_sourcedid'};
+                                    }
+                                } elsif ($mapuser eq 'email') {
+                                    if ($params->{'lis_person_contact_email_primary'} =~ /^$match_username$/) {
+                                        $possuname = $params->{'lis_person_contact_email_primary'};
+                                    }
+                                } elsif (exists($params->{$mapuser})) {
+                                    if ($params->{$mapuser} =~ /^$match_username$/) {
+                                        $possuname = $params->{$mapuser};
+                                    }
+                                }
+                                if ($possuname ne '') {
+                                    my $uhome = &Apache::lonnet::homeserver($possuname,$cdom);
+                                    unless ($uhome eq 'no_host') {
+                                        my $uname = $possuname;
+                                        my ($is_student,$is_nonstudent);
+                                        my %course_roles =
+                                            &Apache::lonnet::get_my_roles($uname,$cdom,,'userroles',['active'],
+                                                                          ['cc','co','in','ta','ep','ad','st','cr'],
+                                                                          [$cdom]);
+                                        foreach my $key (keys(%course_roles)) {
+                                            my ($trest,$tdomain,$trole,$sec) = split(/:/,$key);
+                                            if (($trest eq $cnum) && ($tdomain eq $cdom)) {
+                                                if ($trole eq 'st') {
+                                                    $is_student = 1;
+                                                } else {
+                                                    $is_nonstudent = 1;
+                                                    last;
+                                                }
+                                            }
+                                        }
+                                        if (($is_student) && (!$is_nonstudent)) {
+                                            unless (&Apache::lonnet::is_advanced_user($uname,$cdom)) {
+                                                foreach my $key (%{$params}) {
+                                                    delete($env{'form.'.$key});
+                                                }
+                                                &linkprot_session($r,$uname,$cnum,$cdom,$uhome,$itemid,$ltitype,$tail,$lonhost,$exiturl);
+                                                return OK;
+                                            }
+                                        }
+                                        $ltiuser = $uname.':'.$cdom;
+                                    }
+                                }
+                                if ($lti_in_use{'notstudent'} eq 'reject') {
+                                    &invalid_request($r,'Information for valid user missing from launch request');
                                     return OK;
                                 }
                             }
@@ -174,28 +250,38 @@ sub handler {
                             foreach my $key (%{$params}) {
                                 delete($env{'form.'.$key});
                             }
-                            my $ltoken = &Apache::lonnet::tmpput({'linkprot' => $itemid.$ltitype.':'.$tail},
-                                                                 $lonhost,'link');
-                            if ($ltoken) {
+                            my %info = (
+                                          'linkprot' => $itemid.$ltitype.':'.$tail,
+                                       );
+                            if ($ltiuser ne '') {
+                                $info{'linkprotuser'} = $ltiuser;
+                            }
+                            if ($exiturl ne '') {
+                                $info{'linkprotexit'} = $exiturl; 
+                            }
+                            my $ltoken = &Apache::lonnet::tmpput(\%info,$lonhost,'link');
+                            if (($ltoken eq 'con_lost') || ($ltoken eq 'refused') || ($ltoken =~ /^error:/) ||
+                                ($ltoken eq 'unknown_cmd') || ($ltoken eq 'no_such_host') ||
+                                ($ltoken eq '')) {
+                                &invalid_request($r,'Failed to store information from launch request');
+                            } else {
                                 $r->internal_redirect($tail.'?ltoken='.$ltoken);
                                 $r->set_handlers('PerlHandler'=> undef);
-                            } else {
-                                &invalid_request($r,5);
                             }
                         } else {
-                            &invalid_request($r,6);
+                            &invalid_request($r,'Launch request could not be validated');
                         }
                     } else {
-                        &invalid_request($r,7);
+                        &invalid_request($r,'Launch unavailable on this LON-CAPA server');
                     }
                 } else {
-                    &invalid_request($r,8);
+                    &invalid_request($r,'Launch unavailable for this domain');
                 }
             } else {
-                &invalid_request($r,9);
+                &invalid_request($r,'Invalid launch URL');
             }
         } else {
-            &invalid_request($r,10);
+            &invalid_request($r,'Invalid launch URL');
         }
         return OK;
     }
@@ -296,7 +382,7 @@ sub handler {
         if ($tail =~ m{^/uploaded/($match_domain)/($match_courseid)/(?:default|supplemental)(?:|_\d+)\.(?:sequence|page)(|___\d+___.+)$}) {
             ($urlcdom,$urlcnum,my $rest) = ($1,$2,$3);
             if (($cdom ne '') && ($cdom ne $urlcdom)) {
-                &invalid_request($r,11);
+                &invalid_request($r,'Incorrect domain in requested URL');
                 return OK;
             }
             if ($rest eq '') {
@@ -315,13 +401,13 @@ sub handler {
         } elsif ($tail =~ m{^/($match_domain)/($match_courseid)$}) {
             ($urlcdom,$urlcnum) = ($1,$2);
             if (($cdom ne '') && ($cdom ne $urlcdom)) {
-                &invalid_request($r,12);
+                &invalid_request($r,'Incorrect domain in requested URL');
                 return OK;
             }
         } elsif ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
             ($urlcdom,$urlcnum) = &course_from_tinyurl($tail);
             if (($urlcdom eq '') || ($urlcnum eq '')) {
-                &invalid_request($r,13);
+                &invalid_request($r,'Invalid URL shortcut');
                 return OK;
             }
         }
@@ -367,7 +453,7 @@ sub handler {
 # configuration in LON-CAPA for that LTI Consumer.
 #
     unless (($itemid) && (ref($lti{$itemid}) eq 'HASH')) {
-        &invalid_request($r,14);
+        &invalid_request($r,'Launch request could not be validated');
         return OK;
     }
 
@@ -377,7 +463,7 @@ sub handler {
 #
     unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
                                             $lti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
-        &invalid_request($r,15);
+        &invalid_request($r,'Time limit exceeded for launch request credentials');
         return OK;
     }
 
@@ -398,10 +484,10 @@ sub handler {
                 $r->internal_redirect($tail.'?ltoken='.$ltoken);
                 $r->set_handlers('PerlHandler'=> undef);
             } else {
-                &invalid_request($r,16);
+                &invalid_request($r,'Failed to store information from launch request');
             }
         } else {
-            &invalid_request($r,17);
+            &invalid_request($r,'Launch URL invalid for matched launch credentials');
         }
         return OK;
     }
@@ -463,7 +549,7 @@ sub handler {
                 my $storedcnum = $1;
                 my $crshome = &Apache::lonnet::homeserver($storedcnum,$cdom);
                 if ($crshome =~ /(con_lost|no_host|no_such_host)/) {
-                    &invalid_request($r,18);
+                    &invalid_request($r,'Invalid courseID included in launch data');
                     return OK;
                 } else {
                     $posscnum = $storedcnum;
@@ -475,7 +561,7 @@ sub handler {
     if ($urlcnum ne '') {
         if ($posscnum ne '') {
             if ($posscnum ne $urlcnum) {
-                &invalid_request($r,19);
+                &invalid_request($r,'Course ID included in launch data incompatible with URL');
                 return OK;
             } else {
                 $cnum = $posscnum;
@@ -483,7 +569,7 @@ sub handler {
         } else {
             my $crshome = &Apache::lonnet::homeserver($urlcnum,$cdom);
             if ($crshome =~ /(con_lost|no_host|no_such_host)/) {
-                &invalid_request($r,20);
+                &invalid_request($r,'Valid course ID could not be extracted from requested URL');
                 return OK;
             } else {
                 $cnum = $urlcnum;
@@ -548,7 +634,7 @@ sub handler {
                                                     $domdesc,\%data,\%alerts,\%rulematch,
                                                     \%inst_results,\%curr_rules,%got_rules);
                 if ($result eq 'notallowed') {
-                    &invalid_request($r,21);
+                    &invalid_request($r,'Account creation not permitted for this user');
                 } elsif ($result eq 'ok') {
                     if (($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'mapcrs'}) &&
                         ($lti{$itemid}{'makecrs'})) {
@@ -557,16 +643,16 @@ sub handler {
                         }
                     }
                 } else {
-                    &invalid_request($r,22);
+                    &invalid_request($r,'An error occurred during account creation');
                     return OK;
                 }
             } else {
-                &invalid_request($r,23);
+                &invalid_request($r,'Account creation not permitted');
                 return OK;
             }
         }
     } else {
-        &invalid_request($r,24);
+        &invalid_request($r,'Could not determine username and/or domain for user');
         return OK;
     }
 
@@ -589,10 +675,10 @@ sub handler {
                                  $symb,$cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,
                                  $reqcrs,$sourcecrs);
                 } else {
-                    &invalid_request($r,25);
+                    &invalid_request($r,'No LON-CAPA course available, and creation is not permitted for this user');
                 }
             } else {
-                &invalid_request($r,26);
+                &invalid_request($r,'No LON-CAPA course available, and creation is not permitted');
             }
         } else {
             &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,undef,$mapurl,$tail,
@@ -683,7 +769,7 @@ sub handler {
             }
         }
         if ($reqrole eq '') {
-            &invalid_request($r,27);
+            &invalid_request($r,'No matching role available in LON-CAPA course, and not permitted to self-enroll');
             return OK;
         } else {
             unless (%crsenv) {
@@ -693,10 +779,10 @@ sub handler {
             my $default_enrollment_end_date   = $crsenv{'default_enrollment_end_date'};
             my $now = time;
             if ($default_enrollment_end_date && $default_enrollment_end_date <= $now) {
-                &invalid_request($r,28);
+                &invalid_request($r,'No active role available in LON-CAPA course, and past end date for self-enrollment');
                 return OK;
             } elsif ($default_enrollment_start_date && $default_enrollment_start_date >$now) {
-                &invalid_request($r,29);
+                &invalid_request($r,'No active role available in LON-CAPA course, and brefor start date for self-enrollment');
                 return OK;
             } else {
                 $selfenrollrole = $reqrole.'./'.$cdom.'/'.$cnum;
@@ -759,7 +845,7 @@ sub handler {
 
 sub get_lti_itemid {
     my ($requri,$hostname,$params,$cdom,$cnum,$context) = @_;
-    return unless ((ref($params) eq 'HASH');
+    return unless (ref($params) eq 'HASH');
     my $protocol = 'http';
     if ($ENV{'SERVER_PORT'} == 443) {
         $protocol = 'https';
@@ -828,24 +914,7 @@ sub lti_session {
     } else {
         &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, course dom: $cdom");
     }
-    my ($is_balancer,$otherserver,$hosthere);
-    ($is_balancer,$otherserver) =
-        &Apache::lonnet::check_loadbalancing($uname,$udom,'login');
-    if ($is_balancer) {
-        if ($otherserver eq '') {
-            my $lowest_load;
-            ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($udom);
-            if ($lowest_load > 100) {
-                $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$udom);
-            }
-        }
-        if ($otherserver ne '') {
-            my @hosts = &Apache::lonnet::current_machine_ids();
-            if (grep(/^\Q$otherserver\E$/,@hosts)) {
-                $hosthere = $otherserver;
-            }
-        }
-    }
+    my ($is_balancer,$otherserver,$hosthere) = &check_balancer($r,$uname,$udom);
     my $protocol = 'http';
     if ($ENV{'SERVER_PORT'} == 443) {
         $protocol = 'https';
@@ -924,8 +993,7 @@ sub lti_session {
         $r->internal_redirect($redirecturl);
         $r->set_handlers('PerlHandler'=> undef);
     } else {
-        # need to login them in, so generate the need data that
-        # migrate expects to do login
+        # need to login them in, so generate the data migrate expects to do login
         foreach my $key (keys(%{$params})) {
             delete($env{'form.'.$key});
         }
@@ -937,7 +1005,7 @@ sub lti_session {
                                                       $r->dir_config('ltiIDsDir'),
                                                       $protocol,$r->hostname);
         }
-        my $ip = $r->get_remote_host();
+        my $ip = &Apache::lonnet::get_requestor_ip($r,REMOTE_NOLOOKUP);
         my %info=('ip'        => $ip,
                   'domain'    => $udom,
                   'username'  => $uname,
@@ -1003,8 +1071,85 @@ sub lti_session {
     return;
 }
 
+sub linkprot_session {
+    my ($r,$uname,$cnum,$cdom,$uhome,$itemid,$ltitype,$dest,$lonhost,$exiturl) = @_;
+    $r->user($uname);
+    if ($ltitype eq 'c') {
+        &Apache::lonnet::logthis("Course Link Protector ($itemid) authorized student: $uname:$cdom, course: $cdom\_$cnum");
+    } elsif ($ltitype eq 'd') {
+        &Apache::lonnet::logthis("Domain LTI for link protection ($itemid) authorized student: $uname:$cdom, course: $cdom\_$cnum");
+    }
+    my ($is_balancer,$otherserver,$hosthere) = &check_balancer($r,$uname,$cdom);
+    if (($is_balancer) && (!$hosthere)) {
+        # login but immediately go to switch server
+        &Apache::lonauth::success($r,$uname,$cdom,$uhome,'noredirect');
+        $env{'form.origurl'} = $dest;
+        $env{'request.linkprot'} = $itemid.$ltitype.':'.$dest;
+        $env{'request.linkprotuser'} = $uname.':'.$cdom;
+        $env{'request.deeplink.login'} = $dest;
+        if ($exiturl ne '') {
+            $env{'request.linkprotexit'} = $exiturl;
+        }
+        my $redirecturl = '/adm/switchserver';
+        if ($otherserver ne '') {
+            $redirecturl .= '?otherserver='.$otherserver;
+        }
+        $r->internal_redirect($redirecturl);
+        $r->set_handlers('PerlHandler'=> undef);
+    } else {
+        # need to login them in, so generate the data migrate expects to do login
+        my $ip = &Apache::lonnet::get_requestor_ip($r,REMOTE_NOLOOKUP);
+        my %info=('ip'             => $ip,
+                  'domain'         => $cdom,
+                  'username'       => $uname,
+                  'server'         => $lonhost,
+                  'linkprot'       => $itemid.$ltitype.':'.$dest,
+                  'linkprotuser'   => $uname.':'.$cdom,
+                  'home'           => $uhome,
+                  'origurl'        => $dest,
+                  'deeplink.login' => $dest,
+                 );
+        if ($exiturl ne '') {
+            $info{'linkprotexit'} = $exiturl; 
+        }
+        my $token = &Apache::lonnet::tmpput(\%info,$lonhost);
+        $env{'form.token'} = $token;
+        $r->internal_redirect('/adm/migrateuser');
+        $r->set_handlers('PerlHandler'=> undef);
+    }
+    return;
+}
+
+sub check_balancer {
+    my ($r,$uname,$udom) = @_;
+    my ($is_balancer,$otherserver,$hosthere);
+    ($is_balancer,$otherserver) =
+        &Apache::lonnet::check_loadbalancing($uname,$udom,'login');
+    if ($is_balancer) {
+        # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
+        my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
+        if (($found_server) && ($balancer_cookie =~ /^\Q$udom\E_\Q$uname\E_/)) {
+            $otherserver = $found_server;
+        }
+        if ($otherserver eq '') {
+            my $lowest_load;
+            ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($udom);
+            if ($lowest_load > 100) {
+                $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$udom);
+            }
+        }
+        if ($otherserver ne '') {
+            my @hosts = &Apache::lonnet::current_machine_ids();
+            if (grep(/^\Q$otherserver\E$/,@hosts)) {
+                $hosthere = $otherserver;
+            }
+        }
+    }
+    return ($is_balancer,$otherserver,$hosthere);
+}
+
 sub invalid_request {
-    my ($r,$num) = @_;
+    my ($r,$msg) = @_;
     &Apache::loncommon::content_type($r,'text/html');
     $r->send_http_header;
     if ($r->header_only) {
@@ -1013,7 +1158,12 @@ sub invalid_request {
     &Apache::lonlocal::get_language_handle($r);
     $r->print(
         &Apache::loncommon::start_page('Invalid LTI call','',{ 'only_body' => 1,}).
-        &mt('Invalid LTI call [_1]',$num).
+        '<h3>'.&mt('Invalid LTI launch request').'</h3>'.
+        '<p class="LC_warning">'.
+        &mt('Launch of LON-CAPA is unavailable from the "external tool" link you had followed in another web application.').
+        ' '.&mt('Launch failed for the following reason:').
+        '</p>'.
+        '<p class="LC_error">'.$msg.'</p>'.
         &Apache::loncommon::end_page());
     return;
 }