MDL-69542 enrol_lti: remaining changes for dynamic registration support

- Allow the tool to generate secure, one time, dynamic registration
URLs for use in supporting platforms.
- Registration endpoint, which validates the one time URL, makes
the registration requqest to the platform and adds the approriate
tool registration changes in the tool on success.
- Admin settings pages make use of the 'copy to clipboard' module
which is now in core.
This commit is contained in:
Jake Dallimore 2022-01-24 17:34:43 +08:00
parent d5ed4a3184
commit 66b76c4545
10 changed files with 660 additions and 1 deletions

View File

@ -0,0 +1,95 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace enrol_lti\local\ltiadvantage\external;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/externallib.php');
use enrol_lti\local\ltiadvantage\repository\application_registration_repository;
use enrol_lti\local\ltiadvantage\repository\context_repository;
use enrol_lti\local\ltiadvantage\repository\deployment_repository;
use enrol_lti\local\ltiadvantage\repository\resource_link_repository;
use enrol_lti\local\ltiadvantage\repository\user_repository;
use enrol_lti\local\ltiadvantage\service\application_registration_service;
use external_api;
use external_value;
use external_warnings;
use external_single_structure;
use external_function_parameters;
/**
* This is the external method for deleting a registration URL for use with LTI Advantage Dynamic Registration.
*
* @package enrol_lti
* @copyright 2021 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class delete_registration_url extends external_api {
/**
* Service parameters definition.
*
* @return external_function_parameters the parameters.
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters([]);
}
/**
* Delete the registration URL.
*/
public static function execute() {
self::validate_parameters(self::execute_parameters(), []);
$context = \context_system::instance();
self::validate_context($context);
if (!has_capability('moodle/site:config', $context)) {
throw new \moodle_exception('nopermissions', 'error', '', 'get registration url');
}
$appregservice = new application_registration_service(
new application_registration_repository(),
new deployment_repository(),
new resource_link_repository(),
new context_repository(),
new user_repository()
);
$appregservice->delete_registration_url();
return [
'status' => true,
'warnings' => []
];
}
/**
* Service return values definition.
*
* @return external_single_structure the return value defintion.
*/
public static function execute_returns() {
return new external_single_structure(
[
'status' => new external_value(PARAM_BOOL, 'True if the URL was deleted, false otherwise.'),
'warnings' => new external_warnings()
]
);
}
}

View File

@ -0,0 +1,109 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace enrol_lti\local\ltiadvantage\external;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/externallib.php');
use enrol_lti\local\ltiadvantage\repository\application_registration_repository;
use enrol_lti\local\ltiadvantage\repository\context_repository;
use enrol_lti\local\ltiadvantage\repository\deployment_repository;
use enrol_lti\local\ltiadvantage\repository\resource_link_repository;
use enrol_lti\local\ltiadvantage\repository\user_repository;
use enrol_lti\local\ltiadvantage\service\application_registration_service;
use external_api;
use external_warnings;
use external_single_structure;
use external_function_parameters;
use external_value;
/**
* This is the external method for getting/creating a registration URL for use with LTI Advantage Dynamic Registration.
*
* @package enrol_lti
* @copyright 2021 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class get_registration_url extends external_api {
/**
* Parameter description for the service.
*
* @return external_function_parameters
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters([
'createifmissing' => new external_value(PARAM_BOOL,
'Whether to create a registration URL if one is not found', VALUE_DEFAULT, false)
]);
}
/**
* Get the registration URL, creating one on the fly if specified in the params.
*
* @param bool $createifmissing whether to create a new registration URL automatically or not.
* @return array the URL string (empty if the URL could not be created) and warnings array.
* @throws \moodle_exception if the user doesn't have permissions.
*/
public static function execute(bool $createifmissing = false): array {
$params = self::validate_parameters(self::execute_parameters(), ['createifmissing' => $createifmissing]);
$context = \context_system::instance();
self::validate_context($context);
if (!has_capability('moodle/site:config', $context)) {
throw new \moodle_exception('nopermissions', 'error', '', 'get registration url');
}
$appregservice = new application_registration_service(
new application_registration_repository(),
new deployment_repository(),
new resource_link_repository(),
new context_repository(),
new user_repository()
);
if (!$regurl = $appregservice->get_registration_url()) {
if ($params['createifmissing']) {
$regurl = $appregservice->create_registration_url();
}
}
return [
'url' => isset($regurl) ? $regurl->out(false) : '',
'expirystring' => isset($regurl) ? get_string('registrationurlexpiry', 'enrol_lti',
date('H:i, M dS, Y', $regurl->get_expiry_time())) : '',
'warnings' => [],
];
}
/**
* Return description for the service
*
* @return external_single_structure the return structure.
*/
public static function execute_returns(): external_single_structure {
return new external_single_structure([
'url' => new external_value(PARAM_URL, 'The registration URL'),
'expirystring' => new external_value(PARAM_TEXT, 'String describing the expiry time period of the URL'),
'warnings' => new external_warnings()
]);
}
}

45
enrol/lti/db/services.php Normal file
View File

@ -0,0 +1,45 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* LTI enrolment external functions.
*
* @package enrol_lti
* @category external
* @copyright 2021 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$functions = [
'enrol_lti_get_lti_advantage_registration_url' => [
'classname' => 'enrol_lti\local\ltiadvantage\external\get_registration_url',
'classpath' => '',
'description' => 'Get a secure, one-time-use registration URL',
'type' => 'write',
'capabilities' => 'moodle/site:config',
'ajax' => true,
],
'enrol_lti_delete_lti_advantage_registration_url' => [
'classname' => 'enrol_lti\local\ltiadvantage\external\delete_registration_url',
'classpath' => '',
'description' => 'Delete the secure, one-time-use registration URL',
'type' => 'write',
'capabilities' => 'moodle/site:config',
'ajax' => true,
]
];

191
enrol/lti/register.php Normal file
View File

@ -0,0 +1,191 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* LTI Advantage Initiate Dynamic Registration endpoint.
*
* https://www.imsglobal.org/spec/lti-dr/v1p0
*
* This endpoint handles the Registration Initiation Launch, in which a platform (via the user agent) sends their
* OpenID config URL and an optional registration token (to be used as the access token in the registration request).
*
* The code then makes the required dynamic registration calls, namely:
* 1. It fetches the platform's OpenID config by making a GET request to the provided OpenID config URL.
* 2. It then POSTS a client registration request (along with the registration token provided by the platform),
*
* Finally, the code returns to the user agent signalling a completed registration, via a HTML5 web message
* (postMessage). This lets the browser know the window may be closed.
*
* @package enrol_lti
* @copyright 2021 Jake Dallimore <jrhdallimore@gmail.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use enrol_lti\local\ltiadvantage\entity\application_registration;
use enrol_lti\local\ltiadvantage\repository\application_registration_repository;
use enrol_lti\local\ltiadvantage\repository\context_repository;
use enrol_lti\local\ltiadvantage\repository\deployment_repository;
use enrol_lti\local\ltiadvantage\repository\resource_link_repository;
use enrol_lti\local\ltiadvantage\repository\user_repository;
use enrol_lti\local\ltiadvantage\service\application_registration_service;
require_once(__DIR__."/../../config.php");
global $OUTPUT, $PAGE, $CFG;
require_once($CFG->libdir . '/filelib.php');
$PAGE->set_context(context_system::instance());
$PAGE->set_pagelayout('popup');
// URL to the platform's OpenID configuration.
$openidconfigurl = required_param('openid_configuration', PARAM_URL);
// Token generated by the platform, which must be sent back in registration request.
$regtoken = required_param('registration_token', PARAM_RAW);
if (!preg_match('/[a-zA-Z0-9-_.]+/', $regtoken)) { // 0 on no match, FALSE on error.
throw new coding_exception('Invalid registration_token.');
}
// Moodle-specific token used to secure the dynamic registration URL.
$token = required_param('token', PARAM_ALPHANUM);
$appregservice = new application_registration_service(
new application_registration_repository(),
new deployment_repository(),
new resource_link_repository(),
new context_repository(),
new user_repository()
);
if (!$regurl = $appregservice->get_registration_url($token)) {
throw new moodle_exception('invalidexpiredregistrationurl', 'enrol_lti');
}
$appregservice->delete_registration_url();
// Get the OpenID config from the platform.
$curl = new curl();
$openidconfig = $curl->get($openidconfigurl);
$errno = $curl->get_errno();
if ($errno !== 0) {
throw new coding_exception("Error '{$errno}' while getting OpenID config from platform: {$openidconfig}");
}
$openidconfig = json_decode($openidconfig);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new moodle_exception('ltiadvdynregerror:invalidopenidconfigjson', 'enrol_lti');
}
$regendpoint = $openidconfig->registration_endpoint ?? null;
if (empty($regendpoint)) {
throw new coding_exception('Missing registration endpoint in OpenID configuration');
}
// Build the client registration request to send to the platform.
$wwwrooturl = $CFG->wwwroot;
$parsed = parse_url($wwwrooturl);
$sitefullname = format_string(get_site()->fullname);
$regrequest = (object) [
'application_type' => 'web',
'grant_types' => ['client_credentials', 'implicit'],
'response_types' => ['id_token'],
'initiate_login_uri' => $CFG->wwwroot . '/enrol/lti/login.php',
'redirect_uris' => [
$CFG->wwwroot . '/enrol/lti/launch.php',
$CFG->wwwroot . '/enrol/lti/launch_deeplink.php',
],
// TODO: Consider whether to support client_name#ja syntax for multi language support - see MDL-73109.
'client_name' => get_string('moodle', 'enrol_lti'),
'jwks_uri' => $CFG->wwwroot . '/enrol/lti/jwks.php',
'logo_uri' => $OUTPUT->image_url('moodlelogo')->out(false),
'token_endpoint_auth_method' => 'private_key_jwt',
'https://purl.imsglobal.org/spec/lti-tool-configuration' => [
'domain' => $parsed['host'],
'target_link_uri' => $CFG->wwwroot . '/enrol/lti/launch.php',
'custom_parameters' => [],
'scopes' => [
'https://purl.imsglobal.org/spec/lti-ags/scope/lineitem',
'https://purl.imsglobal.org/spec/lti-ags/scope/result.readonly',
'https://purl.imsglobal.org/spec/lti-ags/scope/score',
'https://purl.imsglobal.org/spec/lti-nrps/scope/contextmembership.readonly',
],
'claims' => [
'iss',
'sub',
'aud',
'given_name',
'family_name',
'email',
'picture',
],
'messages' => [
(object) [
'type' => 'LtiDeepLinkingRequest',
'allowLearner' => false,
'target_link_uri' => $CFG->wwwroot . '/enrol/lti/launch_deeplink.php',
// TODO: Consider whether to support label#ja syntax for multi language support - see MDL-73109.
'label' => get_string('registrationdeeplinklabel', 'enrol_lti', $sitefullname),
'placements' => [
"ContentArea"
],
],
(object) [
'type' => 'LtiResourceLinkRequest',
'allowLearner' => true,
'target_link_uri' => $CFG->wwwroot . '/enrol/lti/launch.php',
// TODO: Consider whether to support label#ja syntax for multi language support - see MDL-73109.
'label' => get_string('registrationresourcelinklabel', 'enrol_lti', $sitefullname),
'placements' => [
"ContentArea"
],
],
]
]
];
$curl->setHeader(['Authorization: Bearer ' . $regtoken]);
$regrequest = json_encode($regrequest);
$regresponse = $curl->post($regendpoint, $regrequest);
$errno = $curl->get_errno();
if ($errno !== 0) {
throw new coding_exception("Error '{$errno}' while posting client registration request to client: {$regresponse}");
}
if ($regresponse) {
$regresponse = json_decode($regresponse);
if ($regresponse->client_id) {
$toolconfig = $regresponse->{'https://purl.imsglobal.org/spec/lti-tool-configuration'};
$appregrepo = new application_registration_repository();
if ($appregrepo->find_by_platform($openidconfig->issuer, $regresponse->client_id)) {
throw new moodle_exception('existingregistrationerror', 'enrol_lti');
}
// Registration of the tool on the platform was successful. Now save the platform registration.
$appreg = application_registration::create(
$openidconfig->issuer,
new moodle_url($openidconfig->issuer),
$regresponse->client_id,
new moodle_url($openidconfig->authorization_endpoint),
new moodle_url($openidconfig->jwks_uri),
new moodle_url($openidconfig->token_endpoint)
);
$savedappreg = $appregrepo->save($appreg);
$deployment = $savedappreg->add_tool_deployment($toolconfig->deployment_id, $toolconfig->deployment_id);
$deploymentrepo = new deployment_repository();
$deploymentrepo->save($deployment);
}
}
echo "<script>(window.opener || window.parent).postMessage({subject: 'org.imsglobal.lti.close'});</script>";

View File

@ -0,0 +1,108 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace enrol_lti\local\ltiadvantage\external;
use enrol_lti\local\ltiadvantage\repository\application_registration_repository;
use enrol_lti\local\ltiadvantage\repository\context_repository;
use enrol_lti\local\ltiadvantage\repository\deployment_repository;
use enrol_lti\local\ltiadvantage\repository\resource_link_repository;
use enrol_lti\local\ltiadvantage\repository\user_repository;
use enrol_lti\local\ltiadvantage\service\application_registration_service;
use external_api;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
/**
* Test class for enrol_lti\local\ltiadvantage\external\delete_registration_url.
*
* @package enrol_lti
* @copyright 2021 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \enrol_lti\local\ltiadvantage\external\delete_registration_url
*/
class delete_registration_url_test extends \externallib_advanced_testcase {
/**
* Setup for the test cases.
*/
protected function setUp(): void {
$this->resetAfterTest();
}
/**
* Test registration URL deletion.
*
* @dataProvider delete_registration_data_provider
* @param bool $existing whether the test is dealing with deleting an existing registration URL or not.
* @param bool $permissions whether the user has permissions to delete or not.
* @covers ::execute
*/
public function test_delete_registration(bool $existing, bool $permissions) {
$appregservice = new application_registration_service(
new application_registration_repository(),
new deployment_repository(),
new resource_link_repository(),
new context_repository(),
new user_repository()
);
if ($existing) {
$appregservice->create_registration_url();
}
if ($permissions) {
$this->setAdminUser();
$result = delete_registration_url::execute();
$result = external_api::clean_returnvalue(delete_registration_url::execute_returns(), $result);
$this->assertTrue($result['status']);
$this->assertNull($appregservice->get_registration_url());
} else {
$user = $this->getDataGenerator()->create_user();
$this->setUser($user);
$this->expectException(\moodle_exception::class);
delete_registration_url::execute();
}
}
/**
* Data provider for testing delete_registration_url().
* @return array the test data.
*/
public function delete_registration_data_provider() {
return [
'No prior registration' => [
'existing' => false,
'permissions' => true,
],
'Existing registration' => [
'existing' => true,
'permissions' => true,
],
'Existing, no permissions' => [
'existing' => true,
'permissions' => false
],
'No prior registration, no permissions' => [
'existing' => false,
'permissions' => false
]
];
}
}

View File

@ -0,0 +1,108 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace enrol_lti\local\ltiadvantage\external;
use external_api;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
/**
* Test class for enrol_lti\local\ltiadvantage\external\get_registration_url.
*
* @package enrol_lti
* @copyright 2021 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \enrol_lti\local\ltiadvantage\external\get_registration_url
*/
class get_registration_url_test extends \externallib_advanced_testcase {
/**
* Test the behaviour of get_registration_url() as an admin user with permissions.
*
* @covers ::execute
*/
public function test_get_registration_url() {
global $CFG;
$this->resetAfterTest();
$this->setAdminUser();
// Get a registration URL before one has been created.
$result = get_registration_url::execute();
$result = external_api::clean_returnvalue(get_registration_url::execute_returns(), $result);
$this->assertEquals('', $result['url']);
// Get a registration URL, creating one in the process.
$result = get_registration_url::execute(true);
$result = external_api::clean_returnvalue(get_registration_url::execute_returns(), $result);
$this->assertStringContainsString($CFG->wwwroot . '/enrol/lti/register.php?token=', $result['url']);
// Get a registration URL again, this time confirming we get back the still-valid URL.
$result2 = get_registration_url::execute();
$result2 = external_api::clean_returnvalue(get_registration_url::execute_returns(), $result2);
$this->assertEquals($result['url'], $result2['url']);
// Get a registration URL again, this time confirming we get back the still-valid URL despite asking for
// autocreation.
$result3 = get_registration_url::execute(true);
$result3 = external_api::clean_returnvalue(get_registration_url::execute_returns(), $result3);
$this->assertEquals($result['url'], $result3['url']);
}
/**
* Test the behaviour of get_registration_url() for users without permission.
*
* @dataProvider get_registration_url_permission_data_provider
* @param bool $createifmissing whether to attempt to create the registration URL or not.
* @param array $expected the array of expected values.
* @covers ::execute
*/
public function test_get_registration_url_permissions(bool $createifmissing, array $expected) {
$this->resetAfterTest();
$user = $this->getDataGenerator()->create_user();
$this->setUser($user);
$this->expectException($expected['exception']);
get_registration_url::execute($createifmissing);
}
/**
* Data provider for testing get_registration_url calls for users without permissions.
*
* @return array the test data.
*/
public function get_registration_url_permission_data_provider() {
return [
'no auto creation' => [
'createifmissing' => false,
'expected' => [
'exception' => \moodle_exception::class
]
],
'auto creation' => [
'createifmissing' => true,
'expected' => [
'exception' => \moodle_exception::class
]
]
];
}
}

View File

@ -24,7 +24,7 @@
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2021052516; // The current plugin version (Date: YYYYMMDDXX).
$plugin->version = 2021052517; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2021052500; // Requires this Moodle version.
$plugin->component = 'enrol_lti'; // Full name of the plugin (used for diagnostics).
$plugin->dependencies = [

View File

@ -362,6 +362,7 @@ class icon_system_fontawesome extends icon_system_font {
'core:t/calc_off' => 'fa-calculator', // TODO: Change to better icon once we have stacked icon support or more icons.
'core:t/calc' => 'fa-calculator',
'core:t/check' => 'fa-check',
'core:t/clipboard' => 'fa-clipboard',
'core:t/cohort' => 'fa-users',
'core:t/collapsed_empty_rtl' => 'fa-caret-square-o-left',
'core:t/collapsed_empty' => 'fa-caret-square-o-right',

BIN
pix/t/clipboard.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 B

2
pix/t/clipboard.svg Normal file
View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<svg width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M768 1664h896v-640h-416q-40 0-68-28t-28-68v-416h-384v1152zm256-1440v-64q0-13-9.5-22.5t-22.5-9.5h-704q-13 0-22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h704q13 0 22.5-9.5t9.5-22.5zm256 672h299l-299-299v299zm512 128v672q0 40-28 68t-68 28h-960q-40 0-68-28t-28-68v-160h-544q-40 0-68-28t-28-68v-1344q0-40 28-68t68-28h1088q40 0 68 28t28 68v328q21 13 36 28l408 408q28 28 48 76t20 88z" fill="#999"/></svg>

After

Width:  |  Height:  |  Size: 536 B