-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathSecFetchSiteFilter.php
More file actions
74 lines (57 loc) · 1.72 KB
/
SecFetchSiteFilter.php
File metadata and controls
74 lines (57 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\filters;
use Craft;
use yii\base\ActionFilter;
use yii\web\BadRequestHttpException;
/**
* Action filter for validating the `Sec-Fetch-Site` header.
*
* @since 4.18.0
*/
class SecFetchSiteFilter extends ActionFilter
{
use ConditionalFilterTrait;
/**
* Whether to use origin verification only (no CSRF token fallback).
*/
public bool $originOnly = true;
/**
* Whether to accept `same-site` in addition to `same-origin` (e.g. subdomains).
*/
public bool $allowSameSite = false;
public string $headerName = 'Sec-Fetch-Site';
public ?string $errorMessage = null;
public ?array $safeMethods = null;
/**
* @inheritdoc
*/
public function beforeAction($action): bool
{
$this->setDefaults();
$request = Craft::$app->getRequest();
if (in_array($request->getMethod(), $this->safeMethods, true)) {
return true;
}
$secFetchSite = $request->getHeaders()->get($this->headerName);
if ($secFetchSite === 'same-origin') {
return true;
}
if ($secFetchSite === 'same-site' && $this->allowSameSite) {
return true;
}
if ($this->originOnly) {
throw new BadRequestHttpException($this->errorMessage);
}
return true;
}
private function setDefaults(): void
{
$this->safeMethods = $this->safeMethods ?? Craft::$app->getRequest()->csrfTokenSafeMethods;
$this->errorMessage = $this->errorMessage ?? Craft::t('yii', 'Unable to verify your data submission.');
}
}