Skip to content

Commit

Permalink
Merge branch 'MDL-81405-master' of https://github.com/jleyva/moodle
Browse files Browse the repository at this point in the history
  • Loading branch information
snake committed Apr 8, 2024
2 parents 84b1cbd + 8ed8388 commit 4c2b9f5
Show file tree
Hide file tree
Showing 8 changed files with 226 additions and 147 deletions.
@@ -0,0 +1,41 @@
<?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 tool_mobile\local\hooks\output;
use core\session\utility\cookie_helper;

/**
* Allows plugins to modify headers.
*
* @package tool_mobile
* @copyright 2024 Juan Leyva
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class before_http_headers {
/**
* Callback to allow modify headers.
*
* @param \core\hook\output\before_http_headers $hook
*/
public static function callback(\core\hook\output\before_http_headers $hook): void {
global $CFG;

// Set Partitioned and Secure attributes to the MoodleSession cookie if the user is using the Moodle app.
if (\core_useragent::is_moodle_app()) {
cookie_helper::add_attributes_to_cookie_response_header('MoodleSession'.$CFG->sessioncookie, ['Secure', 'Partitioned']);
}
}
}
Expand Up @@ -15,6 +15,7 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

namespace tool_mobile\local\hooks\user;
use core\session\utility\cookie_helper;

/**
* Handles mobile app launches when a third-party auth plugin did not properly set $SESSION->wantsurl.
Expand All @@ -39,5 +40,10 @@ public static function callback(\core\hook\user\after_complete_login $hook): voi
$SESSION->wantsurl = (new \moodle_url("/$CFG->admin/tool/mobile/launch.php", $params))->out(false);
}
}

// Set Partitioned and Secure attributes to the MoodleSession cookie if the user is using the Moodle app.
if (\core_useragent::is_moodle_app()) {
cookie_helper::add_attributes_to_cookie_response_header('MoodleSession'.$CFG->sessioncookie, ['Secure', 'Partitioned']);
}
}
}
4 changes: 4 additions & 0 deletions admin/tool/mobile/db/hooks.php
Expand Up @@ -44,4 +44,8 @@
'callback' => 'tool_mobile\local\hooks\user\after_user_passed_mfa::callback',
'priority' => 500,
],
[
'hook' => \core\hook\output\before_http_headers::class,
'callback' => [\tool_mobile\local\hooks\output\before_http_headers::class, 'callback'],
],
];
146 changes: 4 additions & 142 deletions auth/lti/classes/local/ltiadvantage/utility/cookie_helper.php
Expand Up @@ -15,13 +15,11 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

namespace auth_lti\local\ltiadvantage\utility;
use core\session\utility\cookie_helper as core_cookie_helper;

/**
* Helper class providing utils dealing with cookies in LTI, particularly 3rd party cookies.
*
* This class primarily provides a means to augment outbound cookie headers, in order to satisfy browser-specific
* requirements for setting 3rd party cookies.
*
* @package auth_lti
* @copyright 2024 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
Expand All @@ -37,62 +35,6 @@ final class cookie_helper {
/** @var int Cookies are supported via explicit partitioning. */
public const COOKIE_METHOD_EXPLICIT_PARTITIONING = 2;

/**
* Make sure the given attributes are set on the Set-Cookie response header identified by name=$cookiename.
*
* This function only affects Set-Cookie headers and modifies the headers directly with the required changes, if any.
*
* @param string $cookiename the cookie name.
* @param array $attributes the attributes to set/ensure are set.
* @return void
*/
public static function add_attributes_to_cookie_response_header(string $cookiename, array $attributes): void {

$setcookieheaders = array_filter(headers_list(), function($val) {
return preg_match("/Set-Cookie:/i", $val);
});
if (empty($setcookieheaders)) {
return;
}

$updatedheaders = self::cookie_response_headers_add_attributes($setcookieheaders, [$cookiename], $attributes);

// Note: The header_remove() method is quite crude and removes all headers of that header name.
header_remove('Set-Cookie');
foreach ($updatedheaders as $header) {
header($header, false);
}
}

/**
* Given a list of HTTP header strings, return a list of HTTP header strings where the matched 'Set-Cookie' headers
* have been updated with the attributes defined in $attribute - an array of strings.
*
* This method does not verify whether a given attribute is valid or not. It blindly sets it and returns the header
* strings. It's up to calling code to determine whether an attribute makes sense or not.
*
* @param array $headerstrings the array of header strings.
* @param array $cookiestomatch the array of cookie names to match.
* @param array $attributes the attributes to set on each matched 'Set-Cookie' header.
* @param bool $casesensitive whether to match the attribute in a case-sensitive way.
* @return array the updated array of header strings.
*/
public static function cookie_response_headers_add_attributes(array $headerstrings, array $cookiestomatch, array $attributes,
bool $casesensitive = false): array {

return array_map(function($headerstring) use ($attributes, $casesensitive, $cookiestomatch) {
if (!self::cookie_response_header_matches_names($headerstring, $cookiestomatch)) {
return $headerstring;
}
foreach ($attributes as $attribute) {
if (!self::cookie_response_header_contains_attribute($headerstring, $attribute, $casesensitive)) {
$headerstring = self::cookie_response_header_append_attribute($headerstring, $attribute);
}
}
return $headerstring;
}, $headerstrings);
}

/**
* Check whether cookies can be used with the current user agent and, if so, via what method they are set.
*
Expand Down Expand Up @@ -144,7 +86,7 @@ public static function do_cookie_check(\moodle_url $pageurl): void {
// LTI needs to guarantee the 'SameSite=None', 'Secure' (and sometimes 'Partitioned') attributes are set on the
// MoodleSession cookie. This is done via manipulation of the outgoing headers after the cookie check redirect. To
// guarantee these outgoing Set-Cookie headers will be created after the redirect, expire the current cookie.
self::expire_moodlesession();
core_cookie_helper::expire_moodlesession();

redirect($pageurl);
} else {
Expand Down Expand Up @@ -187,27 +129,6 @@ public static function get_cookies_supported_method(): int {
return $SESSION->auth_lti_cookie_method ?? self::COOKIE_METHOD_NOT_SUPPORTED;
}

/**
* Forces the expiry of the MoodleSession cookie.
*
* This is useful to force a new Set-Cookie header on the next redirect.
*
* @return void
*/
private static function expire_moodlesession(): void {
global $CFG;

$setcookieheader = array_filter(headers_list(), function($val) use ($CFG) {
return self::cookie_response_header_matches_name($val, 'MoodleSession'.$CFG->sessioncookie);
});
if (!empty($setcookieheader)) {
$expirestr = 'Expires='.gmdate(DATE_RFC7231, time() - 60);
self::add_attributes_to_cookie_response_header('MoodleSession'.$CFG->sessioncookie, [$expirestr]);
} else {
setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 60);
}
}

/**
* Sets up the session cookie according to the method used in the cookie check, and with SameSite=None; Secure attributes.
*
Expand All @@ -222,7 +143,7 @@ public static function setup_session_cookie(): void {
if (self::get_cookies_supported_method() == self::COOKIE_METHOD_EXPLICIT_PARTITIONING) {
$atts[] = 'Partitioned';
}
self::add_attributes_to_cookie_response_header('MoodleSession' . $CFG->sessioncookie, $atts);
core_cookie_helper::add_attributes_to_cookie_response_header('MoodleSession' . $CFG->sessioncookie, $atts);
}
}

Expand All @@ -246,66 +167,7 @@ private static function set_test_cookie(string $name, string $value, bool $parti
setcookie($name, $value, $atts);

if (is_moodle_cookie_secure() && $partitioned) {
self::add_attributes_to_cookie_response_header($name, ['Partitioned']);
}
}

/**
* Check whether the header string is a 'Set-Cookie' header for the cookie identified by $cookiename.
*
* @param string $headerstring the header string to check.
* @param string $cookiename the name of the cookie to match.
* @return bool true if the header string is a Set-Cookie header for the named cookie, false otherwise.
*/
private static function cookie_response_header_matches_name(string $headerstring, string $cookiename): bool {
// Generally match the format, but in a case-insensitive way so that 'set-cookie' and "SET-COOKIE" are both valid.
return preg_match("/Set-Cookie: *$cookiename=/i", $headerstring)
// Case-sensitive match on cookiename, which is case-sensitive.
&& preg_match("/: *$cookiename=/", $headerstring);
}

/**
* Check whether the header string is a 'Set-Cookie' header for the cookies identified in the $cookienames array.
*
* @param string $headerstring the header string to check.
* @param array $cookienames the array of cookie names to match.
* @return bool true if the header string is a Set-Cookie header for one of the named cookies, false otherwise.
*/
private static function cookie_response_header_matches_names(string $headerstring, array $cookienames): bool {
foreach ($cookienames as $cookiename) {
if (self::cookie_response_header_matches_name($headerstring, $cookiename)) {
return true;
}
}
return false;
}

/**
* Check whether the header string contains the given attribute.
*
* @param string $headerstring the header string to check.
* @param string $attribute the attribute to check for.
* @param bool $casesensitive whether to perform a case-sensitive check.
* @return bool true if the header contains the attribute, false otherwise.
*/
private static function cookie_response_header_contains_attribute(string $headerstring, string $attribute,
bool $casesensitive): bool {

if ($casesensitive) {
return str_contains($headerstring, $attribute);
core_cookie_helper::add_attributes_to_cookie_response_header($name, ['Partitioned']);
}
return str_contains(strtolower($headerstring), strtolower($attribute));
}

/**
* Append the given attribute to the header string.
*
* @param string $headerstring the header string to append to.
* @param string $attribute the attribute to append.
* @return string the updated header string.
*/
private static function cookie_response_header_append_attribute(string $headerstring, string $attribute): string {
$headerstring = rtrim($headerstring, ';'); // Sometimes included.
return "$headerstring; $attribute;";
}
}
2 changes: 1 addition & 1 deletion enrol/lti/classes/local/ltiadvantage/lib/lti_cookie.php
Expand Up @@ -16,7 +16,7 @@

namespace enrol_lti\local\ltiadvantage\lib;

use auth_lti\local\ltiadvantage\utility\cookie_helper;
use core\session\utility\cookie_helper;
use Packback\Lti1p3\Interfaces\ICookie;

/**
Expand Down

0 comments on commit 4c2b9f5

Please sign in to comment.