first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -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 core\oauth2\discovery;
use core\http_client;
use GuzzleHttp\Exception\ClientException;
/**
* Simple reader class, allowing OAuth 2 Authorization Server Metadata to be read from an auth server's well-known.
*
* {@link https://www.rfc-editor.org/rfc/rfc8414}
*
* @package core
* @copyright 2023 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class auth_server_config_reader {
/** @var \stdClass the config object read from the discovery document. */
protected \stdClass $metadata;
/** @var \moodle_url the base URL for the auth server which was last used during a read.*/
protected \moodle_url $issuerurl;
/**
* Constructor.
*
* @param http_client $httpclient an http client instance.
* @param string $wellknownsuffix the well-known suffix, defaulting to 'oauth-authorization-server'.
*/
public function __construct(protected http_client $httpclient,
protected string $wellknownsuffix = 'oauth-authorization-server') {
}
/**
* Read the metadata from the remote host.
*
* @param \moodle_url $issuerurl the auth server issuer URL.
* @return \stdClass the configuration data object.
* @throws ClientException|\GuzzleHttp\Exception\GuzzleException if the http client experiences any problems.
*/
public function read_configuration(\moodle_url $issuerurl): \stdClass {
$this->issuerurl = $issuerurl;
$this->validate_uri();
$url = $this->get_configuration_url()->out(false);
$response = $this->httpclient->request('GET', $url);
$this->metadata = json_decode($response->getBody());
return $this->metadata;
}
/**
* Make sure the base URI is suitable for use in discovery.
*
* @return void
* @throws \moodle_exception if the URI fails validation.
*/
protected function validate_uri() {
if (!empty($this->issuerurl->get_query_string())) {
throw new \moodle_exception('Error: '.__METHOD__.': Auth server base URL cannot contain a query component.');
}
if (strtolower($this->issuerurl->get_scheme()) !== 'https') {
throw new \moodle_exception('Error: '.__METHOD__.': Auth server base URL must use HTTPS scheme.');
}
// This catches URL fragments. Since a query string is ruled out above, out_omit_querystring(false) returns only fragments.
if ($this->issuerurl->out_omit_querystring() != $this->issuerurl->out(false)) {
throw new \moodle_exception('Error: '.__METHOD__.': Auth server base URL must not contain fragments.');
}
}
/**
* Get the Auth server metadata URL.
*
* Per {@link https://www.rfc-editor.org/rfc/rfc8414#section-3}, if the issuer URL contains a path component,
* the well known suffix is added between the host and path components.
*
* @return \moodle_url the full URL to the auth server metadata.
*/
protected function get_configuration_url(): \moodle_url {
$path = $this->issuerurl->get_path();
if (!empty($path) && $path !== '/') {
// Insert the well known suffix between the host and path components.
$port = $this->issuerurl->get_port() ? ':'.$this->issuerurl->get_port() : '';
$uri = $this->issuerurl->get_scheme() . "://" . $this->issuerurl->get_host() . $port ."/".
".well-known/" . $this->wellknownsuffix . $path;
} else {
// No path, just append the well known suffix.
$uri = $this->issuerurl->out(false);
$uri .= (substr($uri, -1) == '/' ? '' : '/');
$uri .= ".well-known/$this->wellknownsuffix";
}
return new \moodle_url($uri);
}
}
@@ -0,0 +1,164 @@
<?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 core\oauth2\discovery;
use curl;
use stdClass;
use moodle_exception;
use core\oauth2\issuer;
use core\oauth2\endpoint;
/**
* Class for provider discovery definition, to allow services easily discover and process information.
* This abstract class is called from core\oauth2\api when discovery points need to be updated.
*
* @package core
* @since Moodle 3.11
* @copyright 2021 Sara Arjona (sara@moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class base_definition {
/**
* Get the URL for the discovery manifest.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @return string The URL of the discovery file, containing the endpoints.
*/
abstract public static function get_discovery_endpoint_url(issuer $issuer): string;
/**
* Process the discovery information and create endpoints defined with the expected format.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @param stdClass $info The discovery information, with the endpoints to process and create.
* @return void
*/
abstract protected static function process_configuration_json(issuer $issuer, stdClass $info): void;
/**
* Process how to map user field information.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @return void
*/
abstract protected static function create_field_mappings(issuer $issuer): void;
/**
* Self-register the issuer if the 'registration' endpoint exists and client id and secret aren't defined.
*
* @param issuer $issuer The OAuth issuer to register.
* @return void
*/
abstract protected static function register(issuer $issuer): void;
/**
* Create endpoints for this issuer.
*
* @param issuer $issuer Issuer the endpoints should be created for.
* @return issuer
*/
public static function create_endpoints(issuer $issuer): issuer {
static::discover_endpoints($issuer);
return $issuer;
}
/**
* If the discovery endpoint exists for this issuer, try and determine the list of valid endpoints.
*
* @param issuer $issuer
* @return int The number of discovered services.
*/
public static function discover_endpoints($issuer): int {
// Early return if baseurl is empty.
if (empty($issuer->get('baseurl'))) {
return 0;
}
// Get the discovery URL and check if it has changed.
$creatediscoveryendpoint = false;
$url = $issuer->get_endpoint_url('discovery');
$providerurl = static::get_discovery_endpoint_url($issuer);
if (!$url || $url != $providerurl) {
$url = $providerurl;
$creatediscoveryendpoint = true;
}
// Remove the existing endpoints before starting discovery.
foreach (endpoint::get_records(['issuerid' => $issuer->get('id')]) as $endpoint) {
// Discovery endpoint will be removed only if it will be created later, once we confirm it's working as expected.
if ($creatediscoveryendpoint || $endpoint->get('name') != 'discovery_endpoint') {
$endpoint->delete();
}
}
// Early return if discovery URL is empty.
if (empty($url)) {
return 0;
}
$curl = new curl();
if (!$json = $curl->get($url)) {
$msg = 'Could not discover end points for identity issuer: ' . $issuer->get('name') . " [URL: $url]";
throw new moodle_exception($msg);
}
if ($msg = $curl->error) {
throw new moodle_exception('Could not discover service endpoints: ' . $msg);
}
$info = json_decode($json);
if (empty($info)) {
$msg = 'Could not discover end points for identity issuer: ' . $issuer->get('name') . " [URL: $url]";
throw new moodle_exception($msg);
}
if ($creatediscoveryendpoint) {
// Create the discovery endpoint (because it didn't exist and the URL exists and is returning some valid JSON content).
static::create_discovery_endpoint($issuer, $url);
}
static::process_configuration_json($issuer, $info);
static::create_field_mappings($issuer);
static::register($issuer);
return endpoint::count_records(['issuerid' => $issuer->get('id')]);
}
/**
* Helper method to create discovery endpoint.
*
* @param issuer $issuer Issuer the endpoints should be created for.
* @param string $url Discovery endpoint URL.
* @return endpoint The endpoint created.
*
* @throws \core\invalid_persistent_exception
*/
protected static function create_discovery_endpoint(issuer $issuer, string $url): endpoint {
$record = (object) [
'issuerid' => $issuer->get('id'),
'name' => 'discovery_endpoint',
'url' => $url,
];
$endpoint = new endpoint(0, $record);
$endpoint->create();
return $endpoint;
}
}
@@ -0,0 +1,183 @@
<?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 core\oauth2\discovery;
use curl;
use stdClass;
use moodle_exception;
use core\oauth2\issuer;
use core\oauth2\endpoint;
/**
* Class for IMS Open Badge Connect API (aka OBv2.1) discovery definition.
*
* @package core
* @since Moodle 3.11
* @copyright 2021 Sara Arjona (sara@moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class imsbadgeconnect extends base_definition {
/**
* Get the URL for the discovery manifest.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @return string The URL of the discovery file, containing the endpoints.
*/
public static function get_discovery_endpoint_url(issuer $issuer): string {
$url = $issuer->get('baseurl');
if (!empty($url)) {
// Add slash at the end of the base url.
$url .= (substr($url, -1) == '/' ? '' : '/');
// Append the well-known file for IMS OBv2.1.
$url .= '.well-known/badgeconnect.json';
}
return $url;
}
/**
* Process the discovery information and create endpoints defined with the expected format.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @param stdClass $info The discovery information, with the endpoints to process and create.
* @return void
*/
protected static function process_configuration_json(issuer $issuer, stdClass $info): void {
$info = array_pop($info->badgeConnectAPI);
foreach ($info as $key => $value) {
if (substr_compare($key, 'Url', - strlen('Url')) === 0 && !empty($value)) {
$record = new stdClass();
$record->issuerid = $issuer->get('id');
// Convert key names from xxxxUrl to xxxx_endpoint, in order to make it compliant with the Moodle oAuth API.
$record->name = strtolower(substr($key, 0, - strlen('Url'))) . '_endpoint';
$record->url = $value;
$endpoint = new endpoint(0, $record);
$endpoint->create();
} else if ($key == 'scopesOffered') {
// Get and update supported scopes.
$issuer->set('scopessupported', implode(' ', $value));
$issuer->update();
} else if ($key == 'image' && empty($issuer->get('image'))) {
// Update the image with the value in the manifest file if it's valid and empty in the issuer.
$url = filter_var($value, FILTER_SANITIZE_URL);
// Remove multiple slashes in URL. It will fix the Badgr bug with image URL defined in their manifest.
$url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
$issuer->set('image', $url);
$issuer->update();
}
} else if ($key == 'apiBase') {
(new endpoint(0, (object) [
'issuerid' => $issuer->get('id'),
'name' => $key,
'url' => $value,
]))->create();
} else if ($key == 'name') {
// Get and update issuer name.
$issuer->set('name', $value);
$issuer->update();
}
}
}
/**
* Process how to map user field information.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @return void
*/
protected static function create_field_mappings(issuer $issuer): void {
// In that case, there are no user fields to map.
}
/**
* Self-register the issuer if the 'registration' endpoint exists and client id and secret aren't defined.
*
* @param issuer $issuer The OAuth issuer to register.
* @return void
*/
protected static function register(issuer $issuer): void {
global $CFG, $SITE;
$clientid = $issuer->get('clientid');
$clientsecret = $issuer->get('clientsecret');
// Registration request for getting client id and secret will be done only they are empty in the issuer.
// For now this can't be run from PHPUNIT (because IMS testing platform needs real URLs). In the future, this
// request can be moved to the moodle-exttests repository.
if (empty($clientid) && empty($clientsecret) && (!defined('PHPUNIT_TEST') || !PHPUNIT_TEST)) {
$url = $issuer->get_endpoint_url('registration');
if ($url) {
$scopes = str_replace("\r", " ", $issuer->get('scopessupported'));
// Add slash at the end of the site URL.
$hosturl = $CFG->wwwroot;
$hosturl .= (substr($CFG->wwwroot, -1) == '/' ? '' : '/');
// Create the registration request following the format defined in the IMS OBv2.1 specification.
$request = [
'client_name' => $SITE->fullname,
'client_uri' => $hosturl,
'logo_uri' => $hosturl . 'pix/moodlelogo.png',
'tos_uri' => $hosturl,
'policy_uri' => $hosturl,
'software_id' => 'moodle',
'software_version' => $CFG->version,
'redirect_uris' => [
$hosturl . 'admin/oauth2callback.php'
],
'token_endpoint_auth_method' => 'client_secret_basic',
'grant_types' => [
'authorization_code',
'refresh_token'
],
'response_types' => [
'code'
],
'scope' => $scopes
];
$jsonrequest = json_encode($request);
$curl = new curl();
$curl->setHeader(['Content-type: application/json']);
$curl->setHeader(['Accept: application/json']);
// Send the registration request.
if (!$jsonresponse = $curl->post($url, $jsonrequest)) {
$msg = 'Could not self-register identity issuer: ' . $issuer->get('name') .
". Wrong URL or JSON data [URL: $url]";
throw new moodle_exception($msg);
}
// Process the response and update client id and secret if they are valid.
$response = json_decode($jsonresponse);
if (property_exists($response, 'client_id')) {
$issuer->set('clientid', $response->client_id);
$issuer->set('clientsecret', $response->client_secret);
$issuer->update();
} else {
$msg = 'Could not self-register identity issuer: ' . $issuer->get('name') .
'. Invalid response ' . $jsonresponse;
throw new moodle_exception($msg);
}
}
}
}
}
@@ -0,0 +1,124 @@
<?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 core\oauth2\discovery;
use stdClass;
use core\oauth2\issuer;
use core\oauth2\endpoint;
use core\oauth2\user_field_mapping;
/**
* Class for Open ID Connect discovery definition.
*
* @package core
* @since Moodle 3.11
* @copyright 2021 Sara Arjona (sara@moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class openidconnect extends base_definition {
/**
* Get the URL for the discovery manifest.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @return string The URL of the discovery file, containing the endpoints.
*/
public static function get_discovery_endpoint_url(issuer $issuer): string {
$url = $issuer->get('baseurl');
if (!empty($url)) {
// Add slash at the end of the base url.
$url .= (substr($url, -1) == '/' ? '' : '/');
// Append the well-known file for OIDC.
$url .= '.well-known/openid-configuration';
}
return $url;
}
/**
* Process the discovery information and create endpoints defined with the expected format.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @param stdClass $info The discovery information, with the endpoints to process and create.
* @return void
*/
protected static function process_configuration_json(issuer $issuer, stdClass $info): void {
foreach ($info as $key => $value) {
if (substr_compare($key, '_endpoint', - strlen('_endpoint')) === 0) {
$record = new stdClass();
$record->issuerid = $issuer->get('id');
$record->name = $key;
$record->url = $value;
$endpoint = new endpoint(0, $record);
$endpoint->create();
}
if ($key == 'scopes_supported') {
$issuer->set('scopessupported', implode(' ', $value));
$issuer->update();
}
}
}
/**
* Process how to map user field information.
*
* @param issuer $issuer The OAuth issuer the endpoints should be discovered for.
* @return void
*/
protected static function create_field_mappings(issuer $issuer): void {
// Remove existing user field mapping.
foreach (user_field_mapping::get_records(['issuerid' => $issuer->get('id')]) as $userfieldmapping) {
$userfieldmapping->delete();
}
// Create the default user field mapping list.
$mapping = [
'given_name' => 'firstname',
'middle_name' => 'middlename',
'family_name' => 'lastname',
'email' => 'email',
'nickname' => 'alternatename',
'picture' => 'picture',
'address' => 'address',
'phone' => 'phone1',
'locale' => 'lang',
];
foreach ($mapping as $external => $internal) {
$record = (object) [
'issuerid' => $issuer->get('id'),
'externalfield' => $external,
'internalfield' => $internal
];
$userfieldmapping = new user_field_mapping(0, $record);
$userfieldmapping->create();
}
}
/**
* Self-register the issuer if the 'registration' endpoint exists and client id and secret aren't defined.
*
* @param issuer $issuer The OAuth issuer to register.
* @return void
*/
protected static function register(issuer $issuer): void {
// Registration not supported (at least for now).
}
}