Completed
Push — boesing-optimized-cors-preflig... ( 1a1405...eb8691 )
by Vytautas
01:38
created

CorsService::populateCorsResponse()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 8.7217
c 0
b 0
f 0
cc 6
nc 8
nop 3
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license.
17
 */
18
19
namespace ZfrCors\Service;
20
21
use Zend\Mvc\Router\Http\RouteMatch as DeprecatedRouteMatch;
22
use Zend\Router\Http\RouteMatch;
23
use Zend\Http\Header;
24
use Zend\Uri\UriFactory;
25
use ZfrCors\Exception\DisallowedOriginException;
26
use ZfrCors\Exception\InvalidOriginException;
27
use ZfrCors\Options\CorsOptions;
28
use Zend\Http\Request as HttpRequest;
29
use Zend\Http\Response as HttpResponse;
30
31
/**
32
 * Service that offers a simple mechanism to handle CORS requests
33
 *
34
 * This service closely follow the specification here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
35
 *
36
 * @license MIT
37
 * @author  Florent Blaison <[email protected]>
38
 */
39
class CorsService
40
{
41
    /**
42
     * @var CorsOptions
43
     */
44
    protected $options;
45
46
    /**
47
     * @param CorsOptions $options
48
     */
49
    public function __construct(CorsOptions $options)
50
    {
51
        $this->options = $options;
52
    }
53
54
    /**
55
     * Check if the HTTP request is a CORS request by checking if the Origin header is present and that the
56
     * request URI is not the same as the one in the Origin
57
     *
58
     * @param  HttpRequest $request
59
     * @return bool
60
     */
61
    public function isCorsRequest(HttpRequest $request)
62
    {
63
        $headers = $request->getHeaders();
64
65
        if (! $headers->has('Origin')) {
66
            return false;
67
        }
68
69
        try {
70
            $origin = $headers->get('Origin');
71
        } catch (Header\Exception\InvalidArgumentException $exception) {
72
            throw InvalidOriginException::fromInvalidHeaderValue();
73
        }
74
75
        if (! $origin instanceof Header\Origin) {
76
            throw InvalidOriginException::fromInvalidHeaderValue();
77
        }
78
79
        $originUri  = UriFactory::factory($origin->getFieldValue());
80
        $requestUri = $request->getUri();
81
82
        // According to the spec (http://tools.ietf.org/html/rfc6454#section-4), we should check host, port and scheme
83
84
        return (! ($originUri->getHost() === $requestUri->getHost())
85
            || ! ($originUri->getPort() === $requestUri->getPort())
86
            || ! ($originUri->getScheme() === $requestUri->getScheme())
87
        );
88
    }
89
90
    /**
91
     * Check if the CORS request is a preflight request
92
     *
93
     * @param  HttpRequest $request
94
     * @return bool
95
     */
96
    public function isPreflightRequest(HttpRequest $request)
97
    {
98
        return $this->isCorsRequest($request)
99
            && strtoupper($request->getMethod()) === 'OPTIONS'
100
            && $request->getHeaders()->has('Access-Control-Request-Method');
101
    }
102
103
    /**
104
     * Create a preflight response by adding the corresponding headers
105
     *
106
     * @param  HttpRequest  $request
107
     * @return HttpResponse
108
     */
109
    public function createPreflightCorsResponse(HttpRequest $request)
110
    {
111
        $response = new HttpResponse();
112
        $response->setStatusCode(200);
113
114
        $headers = $response->getHeaders();
115
116
        $headers->addHeaderLine('Access-Control-Allow-Origin', $this->getAllowedOriginValue($request));
117
        $headers->addHeaderLine('Access-Control-Allow-Methods', implode(', ', $this->options->getAllowedMethods()));
118
        $headers->addHeaderLine('Access-Control-Allow-Headers', implode(', ', $this->options->getAllowedHeaders()));
119
        $headers->addHeaderLine('Access-Control-Max-Age', $this->options->getMaxAge());
120
        $headers->addHeaderLine('Content-Length', 0);
121
122
        if ($this->options->getAllowedCredentials()) {
123
            $headers->addHeaderLine('Access-Control-Allow-Credentials', 'true');
124
        }
125
126
        return $response;
127
    }
128
129
    /**
130
     * Create a preflight response by adding the correspoding headers which are merged with per-route configuration
131
     *
132
     * @param HttpRequest                          $request
133
     * @param RouteMatch|DeprecatedRouteMatch|null $routeMatch
134
     *
135
     * @return HttpResponse
136
     */
137
    public function createPreflightCorsResponseWithRouteOptions(HttpRequest $request, $routeMatch = null)
138
    {
139
        $options = $this->options;
140
        if ($routeMatch instanceof RouteMatch || $routeMatch instanceof DeprecatedRouteMatch) {
0 ignored issues
show
Bug introduced by
The class Zend\Mvc\Router\Http\RouteMatch does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
141
            $options->setFromArray($routeMatch->getParam(CorsOptions::ROUTE_PARAM) ?: []);
142
        }
143
        $response = $this->createPreflightCorsResponse($request);
144
145
        return $response;
146
    }
147
148
    /**
149
     * Populate a simple CORS response
150
     *
151
     * @param  HttpRequest               $request
152
     * @param  HttpResponse              $response
153
     * @param  null|RouteMatch           $routeMatch
154
     * @return HttpResponse
155
     * @throws DisallowedOriginException If the origin is not allowed
156
     */
157
    public function populateCorsResponse(HttpRequest $request, HttpResponse $response, $routeMatch = null)
158
    {
159
        if ($routeMatch instanceof RouteMatch) {
160
            $this->options->setFromArray($routeMatch->getParam(CorsOptions::ROUTE_PARAM) ?: []);
161
        }
162
163
        $origin = $this->getAllowedOriginValue($request);
164
165
        // If $origin is "null", then it means that the origin is not allowed. As this is
166
        // a simple request, it is useless to continue the processing as it will be refused
167
        // by the browser anyway, so we throw an exception
168
        if ($origin === 'null') {
169
            $origin = $request->getHeader('Origin');
170
            $originHeader = $origin ? $origin->getFieldValue() : '';
0 ignored issues
show
Bug introduced by
The method getFieldValue does only exist in Zend\Http\Header\HeaderInterface, but not in ArrayIterator.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
171
            throw new DisallowedOriginException(
172
                sprintf(
173
                    'The origin "%s" is not authorized',
174
                    $originHeader
175
                )
176
            );
177
        }
178
179
        $headers = $response->getHeaders();
180
        $headers->addHeaderLine('Access-Control-Allow-Origin', $origin);
181
        $headers->addHeaderLine('Access-Control-Expose-Headers', implode(', ', $this->options->getExposedHeaders()));
182
183
        $headers = $this->ensureVaryHeader($response);
184
185
        if ($this->options->getAllowedCredentials()) {
186
            $headers->addHeaderLine('Access-Control-Allow-Credentials', 'true');
187
        }
188
189
        $response->setHeaders($headers);
190
191
        return $response;
192
    }
193
194
    /**
195
     * Get a single value for the "Access-Control-Allow-Origin" header
196
     *
197
     * According to the spec, it is not valid to set multiple origins separated by commas. Only accepted
198
     * value are wildcard ("*"), an exact domain or a null string.
199
     *
200
     * @link http://www.w3.org/TR/cors/#access-control-allow-origin-response-header
201
     * @param  HttpRequest $request
202
     * @return string
203
     */
204
    protected function getAllowedOriginValue(HttpRequest $request)
205
    {
206
        $allowedOrigins = $this->options->getAllowedOrigins();
207
208
        $origin = $request->getHeader('Origin');
209
210
        if ($origin) {
211
            $origin = $origin->getFieldValue();
0 ignored issues
show
Bug introduced by
The method getFieldValue does only exist in Zend\Http\Header\HeaderInterface, but not in ArrayIterator.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
212
            if (in_array('*', $allowedOrigins)) {
213
                return $origin;
214
            }
215
            foreach ($allowedOrigins as $allowedOrigin) {
216
                if (fnmatch($allowedOrigin, $origin)) {
217
                    return $origin;
218
                }
219
            }
220
        }
221
222
        return 'null';
223
    }
224
225
    /**
226
     * Ensure that the Vary header is set.
227
     *
228
     *
229
     * @link http://www.w3.org/TR/cors/#resource-implementation
230
     * @param HttpResponse $response
231
     * @return \Zend\Http\Headers
232
     */
233
    public function ensureVaryHeader(HttpResponse $response)
234
    {
235
        $headers = $response->getHeaders();
236
        // If the origin is not "*", we should add the "Origin" value to the "Vary" header
237
        // See more: http://www.w3.org/TR/cors/#resource-implementation
238
        $allowedOrigins = $this->options->getAllowedOrigins();
239
240
        if (in_array('*', $allowedOrigins)) {
241
            return $headers;
242
        }
243
        if ($headers->has('Vary')) {
244
            $varyHeader = $headers->get('Vary');
245
            $varyValue  = $varyHeader->getFieldValue() . ', Origin';
0 ignored issues
show
Bug introduced by
The method getFieldValue does only exist in Zend\Http\Header\HeaderInterface, but not in ArrayIterator.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
246
247
            $headers->removeHeader($varyHeader);
0 ignored issues
show
Bug introduced by
It seems like $varyHeader defined by $headers->get('Vary') on line 244 can also be of type boolean or object<ArrayIterator>; however, Zend\Http\Headers::removeHeader() does only seem to accept object<Zend\Http\Header\HeaderInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
248
            $headers->addHeaderLine('Vary', $varyValue);
249
        } else {
250
            $headers->addHeaderLine('Vary', 'Origin');
251
        }
252
253
        return $headers;
254
    }
255
}
256