Passed
Push — master ( 9b9c6c...ef704e )
by Daniel
35:52 queued 24:20
created

src/Control/Middleware/AllowedHostsMiddleware.php (1 issue)

1
<?php
2
3
namespace SilverStripe\Control\Middleware;
4
5
use SilverStripe\Control\Director;
6
use SilverStripe\Control\HTTPRequest;
7
use SilverStripe\Control\HTTPResponse;
8
9
/**
10
 * Secures requests by only allowing a whitelist of Host values
11
 */
12
class AllowedHostsMiddleware implements HTTPMiddleware
13
{
14
    /**
15
     * List of allowed hosts
16
     *
17
     * @var array
18
     */
19
    private $allowedHosts = [];
20
21
    /**
22
     * @return array List of allowed Host header values
23
     */
24
    public function getAllowedHosts()
25
    {
26
        return $this->allowedHosts;
27
    }
28
29
    /**
30
     * Sets the list of allowed Host header values
31
     * Can also specify a comma separated list
32
     *
33
     * @param array|string $allowedHosts
34
     * @return $this
35
     */
36
    public function setAllowedHosts($allowedHosts)
37
    {
38
        if (is_string($allowedHosts)) {
39
            $allowedHosts = preg_split('/ *, */', $allowedHosts);
40
        }
41
        $this->allowedHosts = $allowedHosts;
0 ignored issues
show
Documentation Bug introduced by
It seems like $allowedHosts can also be of type false. However, the property $allowedHosts is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
42
        return $this;
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48
    public function process(HTTPRequest $request, callable $delegate)
49
    {
50
        $allowedHosts = $this->getAllowedHosts();
51
52
        // check allowed hosts
53
        if ($allowedHosts
54
            && !Director::is_cli()
55
            && !in_array($request->getHeader('Host'), $allowedHosts)
56
        ) {
57
            return new HTTPResponse('Invalid Host', 400);
58
        }
59
60
        return $delegate($request);
61
    }
62
}
63