# The LearningOnline Network # Basic LTI Authentication Module # # $Id: ltiauth.pm,v 1.2 2017/12/07 15:36:25 raeburn Exp $ # # Copyright Michigan State University Board of Trustees # # This file is part of the LearningOnline Network with CAPA (LON-CAPA). # # LON-CAPA is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # LON-CAPA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with LON-CAPA; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # /home/httpd/html/adm/gpl.txt # # http://www.lon-capa.org/ # package Apache::ltiauth; use strict; use LONCAPA qw(:DEFAULT :match); use Apache::Constants qw(:common :http); use Net::OAuth; use Apache::lonlocal; use Apache::lonnet; use Apache::loncommon; use Apache::lonacc; use LONCAPA::ltiutils; sub handler { my $r = shift; my $requri = $r->uri; # # Retrieve data POSTed by LTI Consumer on launch # &Apache::lonacc::get_posted_cgi($r); my $params = {}; foreach my $key (sort(keys(%env))) { if ($key =~ /^form\.(.+)$/) { $params->{$1} = $env{$key}; } } unless (keys(%{$params})) { &invalid_request($r,1); return OK; } unless ($params->{'oauth_consumer_key'} && $params->{'oauth_nonce'} && $params->{'oauth_timestamp'} && $params->{'oauth_version'} && $params->{'oauth_signature'} && $params->{'oauth_signature_method'}) { &invalid_request($r,2); return OK; } # # Retrieve "internet domains" for all this institution's LON-CAPA # nodes. # my ($udom,$uname,$uhome,$cdom,$cnum,$symb,$mapurl,@intdoms); my $lonhost = $r->dir_config('lonHostID'); my $internet_names = &Apache::lonnet::get_internet_names($lonhost); if (ref($internet_names) eq 'ARRAY') { @intdoms = @{$internet_names}; } # # For user who launched LTI in Consumer, determine user's domain in # LON-CAPA. # # Order is: # # (a) from custom_userdomain item in POSTed data # (b) from lis_person_sourcedid in POSTed data # (c) from default "log-in" domain for node # (can support multidomain servers, where specific domain is # first part of hostname). # # Note: "internet domain" for user's domain must be one of the # "internet domain(s)" for the institution's LON-CAPA servers. # if (exists($params->{'custom_userdomain'})) { if ($params->{'custom_userdomain'} =~ /^$match_domain$/) { my $uprimary_id = &Apache::lonnet::domain($params->{'custom_userdomain'},'primary'); if ($uprimary_id ne '') { my $uintdom = &Apache::lonnet::internet_dom($uprimary_id); if (($uintdom ne '') && (grep(/^\Q$uintdom\E$/,@intdoms))) { $udom = $params->{'custom_userdomain'}; } } } } my $defdom = &Apache::lonnet::default_login_domain(); my ($domain,$possuname,$possudom,$possmapuser); if ($env{'form.lis_person_sourcedid'} =~ /^($match_username)\:($match_domain)$/) { ($possuname,$possudom) = ($1,$2); if ($udom eq '') { my $uintdom = &Apache::lonnet::domain($possudom,'primary'); if (($uintdom ne '') && (grep(/^\Q$uintdom\E$/,@intdoms))) { $udom = $possudom; $possmapuser = 'lis_person_sourcedid'; } else { $udom = $defdom; } } elsif ($udom eq $possudom) { $possmapuser = 'lis_person_sourcedid'; } } unless ($possuname) { if ($env{'form.lis_person_sourcedid'} =~ /^$match_username$/) { $possuname = $env{'form.lis_person_sourcedid'}; $possmapuser = 'lis_person_sourcedid'; } elsif ($env{'form.lis_person_contact_email_primary'} =~ /^$match_username$/) { $possuname = $env{'form.lis_person_contact_email_primary'}; $possmapuser = 'lis_person_contact_email_primary'; } unless ($udom) { $udom = $defdom; } } # # Determine course's domain in LON-CAPA # # Order is: # # (a) from custom_coursedomain item in POSTed data # (b) from tail of requested URL (after /adm/lti) if it has format of a symb # (c) from tail of requested URL (after /adm/lti) if it has format of a map # (d) from tail of requested URL (after /adm/lti) if it has format /domain/courseID # (e) from tail of requested URL (after /adm/lti) if it has format /tiny/domain/... # i.e., a shortened URL (see bug #6400) -- not implemented yet. # (f) same as user's domain # # Request invalid if custom_coursedomain is defined and is inconsistent with # domain contained in requested URL. # # Note: "internet domain" for course's domain must be one of the # internet domains for the institution's LON-CAPA servers. # if (exists($params->{'custom_coursedomain'})) { if ($params->{'custom_coursedomain'} =~ /^$match_domain$/) { my $cprimary_id = &Apache::lonnet::domain($params->{'custom_coursedomain'},'primary'); if ($cprimary_id ne '') { my $cintdom = &Apache::lonnet::internet_dom($cprimary_id); if (($cintdom ne '') && (grep(/^\Q$cintdom\E$/,@intdoms))) { $cdom = $params->{'custom_coursedomain'}; } } } } my ($tail) = ($requri =~ m{^/adm/lti(|/.*)$}); my $urlcnum; if ($tail ne '') { my $urlcdom; 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,3); return OK; } if ($rest eq '') { $mapurl = $tail; } else { $symb = $tail; $symb =~ s{^/+}{}; } #FIXME Need to handle encrypted URLs } elsif ($tail =~ m{^/($match_domain)/($match_courseid)$}) { ($urlcdom,$urlcnum) = ($1,$2); if (($cdom ne '') && ($cdom ne $urlcdom)) { &invalid_request($r,4); return OK; } } if (($cdom eq '') && ($urlcdom ne '')) { my $cprimary_id = &Apache::lonnet::domain($urlcdom,'primary'); if ($cprimary_id ne '') { my $cintdom = &Apache::lonnet::internet_dom($cprimary_id); if (($cintdom ne '') && (grep(/^\Q$cintdom\E$/,@intdoms))) { $cdom = $urlcdom; } } else { $urlcnum = ''; } } } if ($cdom eq '') { if ($udom ne '') { $cdom = $udom; } else { $cdom = $defdom; } } # # Retrieve information for LTI Consumers in course domain # and populate hash -- %lti_by_key -- for which keys # are those defined in domain configuration for LTI. # my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider'); unless (keys(%lti) > 0) { &invalid_request($r,5); return OK; } my %lti_by_key; if (keys(%lti)) { foreach my $id (keys(%lti)) { if (ref($lti{$id}) eq 'HASH') { my $key = $lti{$id}{'key'}; push(@{$lti_by_key{$key}},$id); } } } # # Verify the signed request using the secret for those # Consumers for which the key in the POSTed data matches # keys in the domain configuration for LTI. # my $hostname = $r->hostname; my $protocol = 'http'; if ($ENV{'SERVER_PORT'} == 443) { $protocol = 'https'; } my ($itemid,$key,$secret,@ltiroles); $key = $params->{'oauth_consumer_key'}; if (ref($lti_by_key{$key}) eq 'ARRAY') { foreach my $id (@{$lti_by_key{$key}}) { if (ref($lti{$id}) eq 'HASH') { $secret = $lti{$id}{'secret'}; my $request = Net::OAuth->request('request token')->from_hash($params, request_url => $protocol.'://'.$hostname.$requri, request_method => $env{'request.method'}, consumer_secret => $secret,); if ($request->verify()) { $itemid = $id; last; } } } } # # Request is invalid if the signed request could not be verified # for the Consumer key and Consumer secret from the domain # configuration in LON-CAPA for that LTI Consumer. # unless (($itemid) && (ref($lti{$itemid}) eq 'HASH')) { &invalid_request($r,6); return OK; } # # Determine if nonce in POSTed data has expired. # If unexpired, confirm it has not already been used. # unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'}, $lti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) { &invalid_request($r,7); return OK; } # # Determinine if source of username matches requirement from the # domain configuration for the specific LTI Consumer. # if ($lti{$itemid}{'mapuser'} eq $possmapuser) { $uname = $possuname; } elsif ($lti{$itemid}{'mapuser'} eq 'lis_person_sourcedid') { if ($params->{'lis_person_sourcedid'} =~ /^$match_username$/) { $uname = $possuname; } } elsif ($lti{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') { if ($params->{'lis_person_contact_email_primary'} =~ /^$match_username$/) { $uname = $params->{'lis_person_contact_email_primary'}; } } elsif (exists($params->{$lti{$itemid}{'mapuser'}})) { if ($params->{$lti{$itemid}{'mapuser'}} =~ /^$match_username$/) { $uname = $params->{$lti{$itemid}{'mapuser'}}; } } # # Determine the courseID of the LON-CAPA course to which the # launch of LON-CAPA should provide access. # # Order is: # # (a) from course mapping (if the link between Consumer "course" and # Provider "course" has been established previously). # (b) from tail of requested URL (after /adm/lti) if it has format of a symb # (c) from tail of requested URL (after /adm/lti) if it has format of a map # (d) from tail of requested URL (after /adm/lti) if it has format /domain/courseID # (e) from tail of requested URL (after /adm/lti) if it has format /tiny/domain/... # i.e., a shortened URL (see bug #6400) -- not implemented yet. # # If Consumer course included in POSTed data points as a target course which # has a format which matches a LON-CAPA courseID, but the course does not # exist, the request is invalid. # my ($sourcecrs,%consumers); if ($lti{$itemid}{'mapcrs'} eq 'course_offering_sourcedid') { $sourcecrs = $params->{'course_offering_sourcedid'}; } elsif ($lti{$itemid}{'mapcrs'} eq 'context_id') { $sourcecrs = $params->{'context_id'}; } elsif ($lti{$itemid}{'mapcrs'} ne '') { $sourcecrs = $params->{$lti{$itemid}{'mapcrs'}}; } my $posscnum; if ($sourcecrs ne '') { %consumers = &Apache::lonnet::get_dom('lticonsumers',[$sourcecrs],$cdom); if (exists($consumers{$sourcecrs})) { if ($consumers{$sourcecrs} =~ /^$match_courseid$/) { my $crshome = &Apache::lonnet::homeserver($consumers{$sourcecrs},$cdom); if ($crshome =~ /(con_lost|no_host|no_such_host)/) { &invalid_request($r,8); return OK; } else { $posscnum = $consumers{$sourcecrs}; } } } } if ($urlcnum ne '') { if ($posscnum ne '') { if ($posscnum ne $urlcnum) { &invalid_request($r,9); return OK; } else { $cnum = $posscnum; } } else { my $crshome = &Apache::lonnet::homeserver($urlcnum,$cdom); if ($crshome =~ /(con_lost|no_host|no_such_host)/) { &invalid_request($r,10); return OK; } else { $cnum = $urlcnum; } } } elsif ($posscnum ne '') { $cnum = $posscnum; } # # Get LON-CAPA role to use from role-mapping of Consumer roles # defined in domain configuration for the appropriate LTI # Consumer. # # If multiple LON-CAPA roles are indicated, choose based # on the order: cc, in, ta, ep, st # my $reqrole; my @roleorder = ('cc','in','ta','ep','st'); if ($params->{'roles'} =~ /,/) { @ltiroles = split(/\s*,\s*/,$params->{'role'}); } else { my $singlerole = $params->{'roles'}; $singlerole =~ s/^\s|\s+$//g; @ltiroles = ($singlerole); } if (@ltiroles) { if (ref($lti{$itemid}{maproles}) eq 'HASH') { my %possroles; map { $possroles{$lti{$itemid}{maproles}{$_}} = 1; } @ltiroles; my @possibles = keys(%possroles); if (@possibles == 1) { if (grep(/^\Q$possibles[0]\E$/,@roleorder)) { $reqrole = $possibles[0]; } } elsif (@possibles > 1) { foreach my $item (@roleorder) { if ($possroles{$item}) { $reqrole = $item; last; } } } } } # # If no LON-CAPA username -- is user allowed to create one? # my $selfcreate; if (($uname ne '') && ($udom ne '')) { $uhome = &Apache::lonnet::homeserver($uname,$udom); if ($uhome =~ /(con_lost|no_host|no_such_host)/) { &Apache::lonnet::logthis(" LTI authorized unknown user $uname:$udom "); if (ref($lti{$itemid}{'makeuser'}) eq 'ARRAY') { if (@{$lti{$itemid}{'makeuser'}} > 0) { foreach my $ltirole (@ltiroles) { if (grep(/^\Q$ltirole\E$/,@{$lti{$itemid}{'makeuser'}})) { $selfcreate = 1; } } } } if ($selfcreate) { #FIXME Do user creation here. return OK } else { &invalid_request($r,11); return OK; } } } else { &invalid_request($r,12); return OK; } # # If no LON-CAPA course available, check if domain's configuration # for the specific LTI Consumer allows a new course to be created # (requires role in Consumer to be: Instructor). # if ($cnum eq '') { if ((@ltiroles) && (grep(/^Instructor$/,@ltiroles)) && ($lti{$itemid}{'mapcrs'})) { #FIXME Create a new LON-CAPA course here. return OK; } else { &invalid_request($r,13); return OK; } } # # If LON-CAPA course is a Community, and LON-CAPA role # indicated is cc, change role indicated to co. # if ($reqrole eq 'cc') { if (($cdom ne '') && ($cnum ne '')) { my %crsenv = &Apache::lonnet::coursedescription($cnum.'_'.$cdom,{ 'one_time' => 1,}); if ($crsenv{'type'} eq 'Community') { $reqrole = 'co'; } } } # # Determine if user has required LON-CAPA role # in the mapped LON-CAPA course. # my $role; my %crsroles = &Apache::lonnet::get_my_roles($uname,$udom,'userroles',undef,[$reqrole],[$cdom]); if (exists($crsroles{$cnum.':'.$cdom.':'.$reqrole})) { $role = $reqrole.'./'.$cdom.'/'.$cnum; #FIXME Need to accommodate sections } elsif (ref($lti{$itemid}{'selfenroll'}) eq 'ARRAY') { if (grep(/^\Q$reqrole\E$/,@{$lti{$itemid}{'selfenroll'}})) { #FIXME Do self-enrollment here return OK; } else { &invalid_request($r,14); } } # # Store consumer-to-LON-CAPA course mapping # if (($sourcecrs ne '') && ($consumers{$sourcecrs} eq '') && ($cnum ne '')) { &Apache::lonnet::put_dom('lticonsumers',{ $sourcecrs => $cnum },$cdom); } # # Check if user should be hosted here or switched to another server. # &Apache::lonnet::logthis(" LTI authorized user: $uname:$udom role: $role course: $cnum:$cdom"); $r->user($uname); 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($lowest_load,$lowest_load,1,$udom); } } if ($otherserver ne '') { my @hosts = &Apache::lonnet::current_machine_ids(); if (grep(/^\Q$otherserver\E$/,@hosts)) { $hosthere = $otherserver; } } } if (($is_balancer) && (!$hosthere)) { # login but immediately go to switch server. &Apache::lonauth::success($r,$uname,$udom,$uhome,'noredirect'); if ($symb) { $env{'form.symb'} = $symb; } if ($role) { $env{'form.role'} = $role; } if ($lti{$itemid}{'passback'}) { if ($params->{'lis_result_sourcedid'}) { $env{'request.lti.passbackid'} = $params->{'lis_result_sourcedid'}; } if ($params->{'lis_outcome_service_url'}) { $env{'request.lti.passbackurl'} = $params->{'lis_outcome_service_url'}; } } if (($lti{$itemid}{'roster'}) && (grep(/^Instructor$/,@ltiroles))) { if ($params->{'ext_ims_lis_memberships_id'}) { $env{'request.lti.rosterid'} = $params->{'ext_ims_lis_memberships_id'}; } if ($params->{'ext_ims_lis_memberships_url'}) { $env{'request.lti.rosterurl'} = $params->{'ext_ims_lis_memberships_url'}; } } $env{'request.lti.login'} = 1; foreach my $key (%{$params}) { delete($env{'form.'.$key}); } 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 need data that # migrate expects to do login foreach my $key (%{$params}) { delete($env{'form.'.$key}); } my $ip = $r->get_remote_host(); my %info=('ip' => $ip, 'domain' => $udom, 'username' => $uname, 'server' => $lonhost, 'lti.login' => 1, ); if ($role) { $info{'role'} = $role; } if ($symb) { $info{'symb'} = $symb; } if ($lti{$itemid}{'passback'}) { if ($params->{'lis_result_sourcedid'}) { $info{'lti.passbackid'} = $params->{'lis_result_sourcedid'} } if ($params->{'lis_outcome_service_url'}) { $info{'lti.passbackurl'} = $params->{'lis_outcome_service_url'} } } if (($lti{$itemid}{'roster'}) && (grep(/^Instructor$/,@ltiroles))) { if ($params->{'ext_ims_lis_memberships_id'}) { $info{'lti.rosterid'} = $params->{'ext_ims_lis_memberships_id'}; } if ($params->{'ext_ims_lis_memberships_url'}) { $info{'lti.rosterurl'} = $params->{'ext_ims_lis_memberships_url'}; } } unless ($info{'symb'}) { if ($mapurl) { $info{'origurl'} = $mapurl; if ($mapurl =~ m{/default_\d+\.sequence$}) { $info{'origurl'} .= (($mapurl =~/\?/)?'&':'?').'navmap=1'; } } else { unless ($tail eq '/adm/roles') { $info{'origurl'} = '/adm/navmaps'; } } } if (($is_balancer) && ($hosthere)) { $info{'noloadbalance'} = $hosthere; } my $token = &Apache::lonnet::tmpput(\%info,$lonhost); $env{'form.token'} = $token; $r->internal_redirect('/adm/migrateuser'); $r->set_handlers('PerlHandler'=> undef); } return OK; } sub invalid_request { my ($r,$num) = @_; &Apache::loncommon::content_type($r,'text/html'); $r->send_http_header; if ($r->header_only) { return; } &Apache::lonlocal::get_language_handle($r); $r->print( &Apache::loncommon::start_page('Invalid LTI call'). &mt('Invalid LTI call [_1]',$num). &Apache::loncommon::end_page()); return; } 1;