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

AllowedHostsMiddleware   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 51
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getAllowedHosts() 0 4 1
A setAllowedHosts() 0 8 2
A process() 0 14 4
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