Skip to content

Commit

Permalink
Merge branch 'master' into fix20282
Browse files Browse the repository at this point in the history
  • Loading branch information
Izumi-kun committed Dec 6, 2024
2 parents 07a382c + 80f2545 commit a9d0095
Show file tree
Hide file tree
Showing 7 changed files with 173 additions and 10 deletions.
4 changes: 4 additions & 0 deletions framework/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ Yii Framework 2 Change Log
- Enh #20273: Remove unnecessary `paragonie/random_compat` dependency (timwolla)
- Chg #20276: Removed autogenerated migration phpdoc (userator)
- Bug #20282: Fix compatibility with PHP 8.4: deprecated constant E_STRICT (Izumi-kun)
- Bug #20284: Revert punycode to 1.4.x which supports pre ES6 format (mtangoo)
- New #20279: Add to the `\yii\web\Request` CSRF validation by custom HTTP header (olegbaturin)
- Enh #20279: Add to the `\yii\web\Request` `csrfHeader` property to configure a custom HTTP header for CSRF validation (olegbaturin)
- Enh #20279: Add to the `\yii\web\Request` `csrfTokenSafeMethods` property to configure a custom safe HTTP methods list (olegbaturin)

2.0.51 July 18, 2024
--------------------
Expand Down
2 changes: 1 addition & 1 deletion framework/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"cebe/markdown": "~1.0.0 | ~1.1.0 | ~1.2.0",
"bower-asset/jquery": "3.7.*@stable | 3.6.*@stable | 3.5.*@stable | 3.4.*@stable | 3.3.*@stable | 3.2.*@stable | 3.1.*@stable | 2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable",
"bower-asset/inputmask": "^5.0.8 ",
"bower-asset/punycode": "^2.2",
"bower-asset/punycode": "^1.4",
"bower-asset/yii2-pjax": "~2.0.1"
},
"autoload": {
Expand Down
2 changes: 1 addition & 1 deletion framework/db/BaseActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -1783,7 +1783,7 @@ private function isValueDifferent($newValue, $oldValue)
{
if (is_array($newValue) && is_array($oldValue)) {
// Only sort associative arrays
$sorter = function(&$array) {
$sorter = function (&$array) {
if (ArrayHelper::isAssociative($array)) {
ksort($array);
}
Expand Down
1 change: 0 additions & 1 deletion framework/db/mssql/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -823,5 +823,4 @@ public function createColumnSchemaBuilder($type, $length = null)
{
return Yii::createObject(ColumnSchemaBuilder::className(), [$type, $length, $this->db]);
}

}
55 changes: 48 additions & 7 deletions framework/web/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
* not available.
* @property-read CookieCollection $cookies The cookie collection.
* @property-read string $csrfToken The token used to perform CSRF validation.
* @property-read string|null $csrfTokenFromHeader The CSRF token sent via [[CSRF_HEADER]] by browser. Null is
* @property-read string|null $csrfTokenFromHeader The CSRF token sent via [[csrfHeader]] by browser. Null is
* returned if no such header is sent.
* @property-read array $eTags The entity tags.
* @property-read HeaderCollection $headers The header collection.
Expand Down Expand Up @@ -91,7 +91,7 @@
class Request extends \yii\base\Request
{
/**
* The name of the HTTP header for sending CSRF token.
* Default name of the HTTP header for sending CSRF token.
*/
const CSRF_HEADER = 'X-CSRF-Token';
/**
Expand All @@ -113,10 +113,41 @@ class Request extends \yii\base\Request
* `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered.
* You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]].
*
* For SPA, you can use CSRF validation by custom header with a random or an empty value.
* Include a header with the name specified by [[csrfHeader]] to requests that must be validated.
* Warning! CSRF validation by custom header can be used only for same-origin requests or
* with CORS configured to allow requests from the list of specific origins only.
*
* @see Controller::enableCsrfValidation
* @see https://en.wikipedia.org/wiki/Cross-site_request_forgery
*/
public $enableCsrfValidation = true;
/**
* @var string the name of the HTTP header for sending CSRF token. Defaults to [[CSRF_HEADER]].
* This property may be changed for Yii API applications only.
* Don't change this property for Yii Web application.
*/
public $csrfHeader = self::CSRF_HEADER;
/**
* @var array the name of the HTTP header for sending CSRF token.
* by default validate CSRF token on non-"safe" methods only
* This property is used only when [[enableCsrfValidation]] is true.
* @see https://datatracker.ietf.org/doc/html/rfc9110#name-safe-methods
*/
public $csrfTokenSafeMethods = ['GET', 'HEAD', 'OPTIONS'];
/**
* @var array "unsafe" methods not triggered a CORS-preflight request
* This property is used only when both [[enableCsrfValidation]] and [[validateCsrfHeaderOnly]] are true.
* @see https://fetch.spec.whatwg.org/#http-cors-protocol
*/
public $csrfHeaderUnsafeMethods = ['GET', 'HEAD', 'POST'];
/**
* @var bool whether to use custom header only to CSRF validation of SPA. Defaults to false.
* If false and [[enableCsrfValidation]] is true, CSRF validation by token will used.
* Warning! CSRF validation by custom header can be used for Yii API applications only.
* @see https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#employing-custom-request-headers-for-ajaxapi
*/
public $validateCsrfHeaderOnly = false;
/**
* @var string the name of the token used to prevent CSRF. Defaults to '_csrf'.
* This property is used only when [[enableCsrfValidation]] is true.
Expand Down Expand Up @@ -1772,10 +1803,14 @@ protected function loadCookies()
* along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.
* @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time
* this method is called, a new CSRF token will be generated and persisted (in session or cookie).
* @return string the token used to perform CSRF validation.
* @return null|string the token used to perform CSRF validation. Null is returned if the [[validateCsrfHeaderOnly]] is true.
*/
public function getCsrfToken($regenerate = false)
{
if ($this->validateCsrfHeaderOnly) {
return null;
}

if ($this->_csrfToken === null || $regenerate) {
$token = $this->loadCsrfToken();
if ($regenerate || empty($token)) {
Expand Down Expand Up @@ -1819,11 +1854,11 @@ protected function generateCsrfToken()
}

/**
* @return string|null the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent.
* @return string|null the CSRF token sent via [[csrfHeader]] by browser. Null is returned if no such header is sent.
*/
public function getCsrfTokenFromHeader()
{
return $this->headers->get(static::CSRF_HEADER);
return $this->headers->get($this->csrfHeader);
}

/**
Expand Down Expand Up @@ -1860,8 +1895,14 @@ protected function createCsrfCookie($token)
public function validateCsrfToken($clientSuppliedToken = null)
{
$method = $this->getMethod();
// only validate CSRF token on non-"safe" methods https://tools.ietf.org/html/rfc2616#section-9.1.1
if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {

if ($this->validateCsrfHeaderOnly) {
return in_array($method, $this->csrfHeaderUnsafeMethods, true)
? $this->headers->has($this->csrfHeader)
: true;
}

if (!$this->enableCsrfValidation || in_array($method, $this->csrfTokenSafeMethods, true)) {
return true;
}

Expand Down
118 changes: 118 additions & 0 deletions tests/framework/web/RequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,124 @@ public function testCsrfTokenHeader()
}
}

public function testCustomSafeMethodsCsrfTokenValidation()
{
$this->mockWebApplication();

$request = new Request();
$request->csrfTokenSafeMethods = ['OPTIONS'];
$request->enableCsrfCookie = false;
$request->enableCsrfValidation = true;

$token = $request->getCsrfToken();

// accept any value on custom safe request
foreach (['OPTIONS'] as $method) {
$_SERVER['REQUEST_METHOD'] = $method;
$this->assertTrue($request->validateCsrfToken($token));
$this->assertTrue($request->validateCsrfToken($token . 'a'));
$this->assertTrue($request->validateCsrfToken([]));
$this->assertTrue($request->validateCsrfToken([$token]));
$this->assertTrue($request->validateCsrfToken(0));
$this->assertTrue($request->validateCsrfToken(null));
$this->assertTrue($request->validateCsrfToken());
}

// only accept valid token on other requests
foreach (['GET', 'HEAD', 'POST'] as $method) {
$_SERVER['REQUEST_METHOD'] = $method;
$this->assertTrue($request->validateCsrfToken($token));
$this->assertFalse($request->validateCsrfToken($token . 'a'));
$this->assertFalse($request->validateCsrfToken([]));
$this->assertFalse($request->validateCsrfToken([$token]));
$this->assertFalse($request->validateCsrfToken(0));
$this->assertFalse($request->validateCsrfToken(null));
$this->assertFalse($request->validateCsrfToken());
}
}

public function testCsrfHeaderValidation()
{
$this->mockWebApplication();

$request = new Request();
$request->validateCsrfHeaderOnly = true;
$request->enableCsrfValidation = true;

// only accept valid header on unsafe requests
foreach (['GET', 'HEAD', 'POST'] as $method) {
$_SERVER['REQUEST_METHOD'] = $method;
$request->headers->remove(Request::CSRF_HEADER);
$this->assertFalse($request->validateCsrfToken());

$request->headers->add(Request::CSRF_HEADER, '');
$this->assertTrue($request->validateCsrfToken());
}

// accept no value on other requests
foreach (['DELETE', 'PATCH', 'PUT', 'OPTIONS'] as $method) {
$_SERVER['REQUEST_METHOD'] = $method;
$this->assertTrue($request->validateCsrfToken());
}
}

public function testCustomHeaderCsrfHeaderValidation()
{
$this->mockWebApplication();

$request = new Request();
$request->csrfHeader = 'X-JGURDA';
$request->validateCsrfHeaderOnly = true;
$request->enableCsrfValidation = true;

// only accept valid header on unsafe requests
foreach (['GET', 'HEAD', 'POST'] as $method) {
$_SERVER['REQUEST_METHOD'] = $method;
$request->headers->remove('X-JGURDA');
$this->assertFalse($request->validateCsrfToken());

$request->headers->add('X-JGURDA', '');
$this->assertTrue($request->validateCsrfToken());
}
}

public function testCustomUnsafeMethodsCsrfHeaderValidation()
{
$this->mockWebApplication();

$request = new Request();
$request->csrfHeaderUnsafeMethods = ['POST'];
$request->validateCsrfHeaderOnly = true;
$request->enableCsrfValidation = true;

// only accept valid custom header on unsafe requests
foreach (['POST'] as $method) {
$_SERVER['REQUEST_METHOD'] = $method;
$request->headers->remove(Request::CSRF_HEADER);
$this->assertFalse($request->validateCsrfToken());

$request->headers->add(Request::CSRF_HEADER, '');
$this->assertTrue($request->validateCsrfToken());
}

// accept no value on other requests
foreach (['GET', 'HEAD'] as $method) {
$_SERVER['REQUEST_METHOD'] = $method;
$request->headers->remove(Request::CSRF_HEADER);
$this->assertTrue($request->validateCsrfToken());
}
}

public function testNoCsrfTokenCsrfHeaderValidation()
{
$this->mockWebApplication();

$request = new Request();
$request->validateCsrfHeaderOnly = true;

$this->assertEquals($request->getCsrfToken(), null);
}

public function testResolve()
{
$this->mockWebApplication([
Expand Down
1 change: 1 addition & 0 deletions tests/framework/web/session/SessionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ public function testParamsAfterSessionStart()
$this->assertNotEquals($oldUseCookies, $newUseCookies);
$this->assertFalse($newUseCookies);
}
$session->setUseCookies($oldUseCookies);

$oldGcProbability = $session->getGCProbability();
$session->setGCProbability(100);
Expand Down

0 comments on commit a9d0095

Please sign in to comment.