Completed
Push — master ( daed8c...cf758d )
by Damian
08:03
created

AllowedHostsMiddleware::process()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 2
nop 2
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
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;
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
0 ignored issues
show
Bug Best Practice introduced by
The expression $allowedHosts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
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