-
Notifications
You must be signed in to change notification settings - Fork 13
/
Analyzer.php
457 lines (391 loc) · 15.3 KB
/
Analyzer.php
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
<?php declare(strict_types=1);
namespace Neomerx\Cors;
/**
* Copyright 2015-2019 info@neomerx.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use Neomerx\Cors\Contracts\AnalysisResultInterface;
use Neomerx\Cors\Contracts\AnalysisStrategyInterface;
use Neomerx\Cors\Contracts\AnalyzerInterface;
use Neomerx\Cors\Contracts\Constants\CorsRequestHeaders;
use Neomerx\Cors\Contracts\Constants\CorsResponseHeaders;
use Neomerx\Cors\Contracts\Constants\SimpleRequestHeaders;
use Neomerx\Cors\Contracts\Constants\SimpleRequestMethods;
use Neomerx\Cors\Contracts\Factory\FactoryInterface;
use Neomerx\Cors\Log\LoggerAwareTrait;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
/**
* @package Neomerx\Cors
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Analyzer implements AnalyzerInterface
{
use LoggerAwareTrait {
LoggerAwareTrait::setLogger as psrSetLogger;
}
/** HTTP method for pre-flight request */
const PRE_FLIGHT_METHOD = 'OPTIONS';
/**
* @var array
*/
private const SIMPLE_METHODS = [
SimpleRequestMethods::GET => true,
SimpleRequestMethods::HEAD => true,
SimpleRequestMethods::POST => true,
];
/**
* @var string[]
*/
private const SIMPLE_LC_HEADERS_EXCLUDING_CONTENT_TYPE = [
SimpleRequestHeaders::LC_ACCEPT,
SimpleRequestHeaders::LC_ACCEPT_LANGUAGE,
SimpleRequestHeaders::LC_CONTENT_LANGUAGE,
];
/**
* @var AnalysisStrategyInterface
*/
private $strategy;
/**
* @var FactoryInterface
*/
private $factory;
/**
* @param AnalysisStrategyInterface $strategy
* @param FactoryInterface $factory
*/
public function __construct(AnalysisStrategyInterface $strategy, FactoryInterface $factory)
{
$this->factory = $factory;
$this->strategy = $strategy;
}
/**
* Create analyzer instance.
*
* @param AnalysisStrategyInterface $strategy
*
* @return AnalyzerInterface
*/
public static function instance(AnalysisStrategyInterface $strategy): AnalyzerInterface
{
return static::getFactory()->createAnalyzer($strategy);
}
/**
* @inheritdoc
*/
public function setLogger(LoggerInterface $logger)
{
$this->psrSetLogger($logger);
$this->strategy->setLogger($logger);
}
/**
* @inheritdoc
*
* @see http://www.w3.org/TR/cors/#resource-processing-model
*/
public function analyze(RequestInterface $request): AnalysisResultInterface
{
$this->logDebug('CORS analysis for request started.');
$result = $this->analyzeImplementation($request);
$this->logDebug('CORS analysis for request completed.');
return $result;
}
/**
* @param RequestInterface $request
*
* @return AnalysisResultInterface
*/
protected function analyzeImplementation(RequestInterface $request): AnalysisResultInterface
{
// check 'Host' request
if ($this->strategy->isCheckHost() === true && $this->checkIsSameHost($request) === false) {
return $this->createResult(AnalysisResultInterface::ERR_NO_HOST_HEADER);
}
// Request handlers have common part (#6.1.1 - #6.1.2 and #6.2.1 - #6.2.2)
// #6.1.1 and #6.2.1
if (empty($requestOrigin = $this->getOriginHeader($request)) === true) {
$this->logInfo('Request is not CORS (request origin is empty).');
return $this->createResult(AnalysisResultInterface::TYPE_REQUEST_OUT_OF_CORS_SCOPE);
}
if ($this->checkIsCrossOrigin($requestOrigin) === false) {
return $this->createResult(AnalysisResultInterface::TYPE_REQUEST_OUT_OF_CORS_SCOPE);
}
// #6.1.2 and #6.2.2
if ($this->strategy->isRequestOriginAllowed($requestOrigin) === false) {
$this->logInfo(
'Request origin is not allowed. Check config settings for Allowed Origins.',
['origin' => $requestOrigin]
);
return $this->createResult(AnalysisResultInterface::ERR_ORIGIN_NOT_ALLOWED);
}
// Since this point handlers have their own path for
// - simple CORS and actual CORS request (#6.1.3 - #6.1.4)
// - pre-flight request (#6.2.3 - #6.2.10)
if ($request->getMethod() === self::PRE_FLIGHT_METHOD) {
return $this->analyzeAsPreFlight($request, $requestOrigin);
}
return $this->analyzeAsRequest($request, $requestOrigin);
}
/**
* Analyze request as simple CORS or/and actual CORS request (#6.1.3 - #6.1.4).
*
* @param RequestInterface $request
* @param string $requestOrigin
*
* @return AnalysisResultInterface
*/
protected function analyzeAsRequest(RequestInterface $request, string $requestOrigin): AnalysisResultInterface
{
$this->logDebug('Request is identified as an actual CORS request.');
$headers = [];
// #6.1.3
$headers[CorsResponseHeaders::ALLOW_ORIGIN] = $requestOrigin;
if ($this->strategy->isRequestCredentialsSupported($request) === true) {
$headers[CorsResponseHeaders::ALLOW_CREDENTIALS] = CorsResponseHeaders::VALUE_ALLOW_CREDENTIALS_TRUE;
}
// #6.4
$headers[CorsResponseHeaders::VARY] = CorsRequestHeaders::ORIGIN;
// #6.1.4
$exposedHeaders = $this->strategy->getResponseExposedHeaders($request);
if (empty($exposedHeaders) === false) {
$headers[CorsResponseHeaders::EXPOSE_HEADERS] = $exposedHeaders;
}
return $this->createResult(AnalysisResultInterface::TYPE_ACTUAL_REQUEST, $headers);
}
/**
* Analyze request as CORS pre-flight request (#6.2.3 - #6.2.10).
*
* @param RequestInterface $request
* @param string $requestOrigin
*
* @return AnalysisResultInterface
*
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function analyzeAsPreFlight(RequestInterface $request, string $requestOrigin): AnalysisResultInterface
{
// #6.2.3
$requestMethod = $request->getHeader(CorsRequestHeaders::METHOD);
if (empty($requestMethod) === true) {
$this->logDebug('Request is not CORS (header ' . CorsRequestHeaders::METHOD . ' is not specified).');
return $this->createResult(AnalysisResultInterface::TYPE_REQUEST_OUT_OF_CORS_SCOPE);
}
$requestMethod = \reset($requestMethod);
// OK now we are sure it's a pre-flight request
$this->logDebug('Request is identified as a pre-flight CORS request.');
/** @var string $requestMethod */
// #6.2.4
$lcRequestHeaders = $this->getRequestedHeadersInLowerCase($request);
// #6.2.5
if ($this->strategy->isRequestMethodSupported($requestMethod) === false) {
$this->logInfo(
'Request method is not supported. Check config settings for Allowed Methods.',
['method' => $requestMethod]
);
return $this->createResult(AnalysisResultInterface::ERR_METHOD_NOT_SUPPORTED);
}
// #6.2.6
if ($this->strategy->isRequestAllHeadersSupported($lcRequestHeaders) === false) {
return $this->createResult(AnalysisResultInterface::ERR_HEADERS_NOT_SUPPORTED);
}
// pre-flight response headers
$headers = $this->createPreFlightResponseHeaders($request, $requestOrigin, $requestMethod, $lcRequestHeaders);
return $this->createResult(AnalysisResultInterface::TYPE_PRE_FLIGHT_REQUEST, $headers);
}
/**
* @param RequestInterface $request
* @param string $requestOrigin
* @param string $requestMethod
* @param array $lcRequestHeaders
*
* @return array
*/
protected function createPreFlightResponseHeaders(
RequestInterface $request,
string $requestOrigin,
string $requestMethod,
array $lcRequestHeaders
): array {
$headers = [];
// #6.2.7
$headers[CorsResponseHeaders::ALLOW_ORIGIN] = $requestOrigin;
if ($this->strategy->isRequestCredentialsSupported($request) === true) {
$headers[CorsResponseHeaders::ALLOW_CREDENTIALS] = CorsResponseHeaders::VALUE_ALLOW_CREDENTIALS_TRUE;
}
// #6.4
$headers[CorsResponseHeaders::VARY] = CorsRequestHeaders::ORIGIN;
// #6.2.8
if ($this->strategy->isPreFlightCanBeCached($request) === true) {
$headers[CorsResponseHeaders::MAX_AGE] = $this->strategy->getPreFlightCacheMaxAge($request);
}
// #6.2.9
$isSimpleMethod = isset(static::SIMPLE_METHODS[$requestMethod]);
if ($isSimpleMethod === false || $this->strategy->isForceAddAllowedMethodsToPreFlightResponse() === true) {
$headers[CorsResponseHeaders::ALLOW_METHODS] = $this->strategy->getRequestAllowedMethods($request);
}
// #6.2.10
// Has only 'simple' headers excluding Content-Type
$isSimpleExclCT = empty(\array_diff($lcRequestHeaders, static::SIMPLE_LC_HEADERS_EXCLUDING_CONTENT_TYPE));
if ($isSimpleExclCT === false || $this->strategy->isForceAddAllowedHeadersToPreFlightResponse() === true) {
$headers[CorsResponseHeaders::ALLOW_HEADERS] = $this->strategy->getRequestAllowedHeaders($request);
}
return $headers;
}
/**
* @param RequestInterface $request
*
* @return string[]
*/
protected function getRequestedHeadersInLowerCase(RequestInterface $request): array
{
$requestHeaders = [];
foreach ($request->getHeader(CorsRequestHeaders::HEADERS) as $headersList) {
$headersList = \strtolower($headersList);
foreach (\explode(CorsRequestHeaders::HEADERS_SEPARATOR, $headersList) as $header) {
// after explode header names might have spaces in the beginnings and ends so trim them
$header = \trim($header);
if (empty($header) === false) {
$requestHeaders[] = $header;
}
}
}
return $requestHeaders;
}
/**
* @param RequestInterface $request
*
* @return string
*/
protected function getOriginHeader(RequestInterface $request): string
{
if ($request->hasHeader(CorsRequestHeaders::ORIGIN) === true) {
$header = $request->getHeader(CorsRequestHeaders::ORIGIN);
if (empty($header) === false) {
return \reset($header);
}
}
return '';
}
/**
* @param RequestInterface $request
*
* @return bool
*/
protected function checkIsSameHost(RequestInterface $request): bool
{
$serverOriginHost = $this->strategy->getServerOriginHost();
$serverOriginPort = $this->strategy->getServerOriginPort();
$host = $this->getRequestHostHeader($request);
// parse `Host` header
//
// According to https://tools.ietf.org/html/rfc7230#section-5.4 `Host` header could be
//
// "uri-host" OR "uri-host:port"
//
// `parse_url` function thinks the first value is `path` and the second is `host` with `port`
// which is a bit annoying so...
$portOrNull = \parse_url($host, PHP_URL_PORT);
$hostUrl = $portOrNull === null ? $host : \parse_url($host, PHP_URL_HOST);
// Neither MDN, nor RFC tell anything definitive about Host header comparison.
// Browsers such as Firefox and Chrome do not add the optional port for
// HTTP (80) and HTTPS (443).
// So we require port match only if it specified in settings.
$isHostUrlMatch = \strcasecmp($serverOriginHost, $hostUrl) === 0;
$isSameHost =
$isHostUrlMatch === true &&
($serverOriginPort === null || $serverOriginPort === $portOrNull);
if ($isSameHost === false) {
$this->logInfo(
'Host header in request either absent or do not match server origin. ' .
'Check config settings for Server Origin and Host Check.',
['host' => $host, 'server_origin_host' => $serverOriginHost, 'server_origin_port' => $serverOriginPort]
);
}
return $isSameHost;
}
/**
* @param string $requestOrigin
*
* @return bool
*
* @see http://tools.ietf.org/html/rfc6454#section-5
*/
protected function checkIsCrossOrigin(string $requestOrigin): bool
{
$parsedUrl = \parse_url($requestOrigin);
if ($parsedUrl === false) {
$this->logWarning('Request origin header URL cannot be parsed.', ['url' => $requestOrigin]);
return false;
}
// check `host` parts
$requestOriginHost = $parsedUrl['host'] ?? '';
$serverOriginHost = $this->strategy->getServerOriginHost();
if (\strcasecmp($requestOriginHost, $serverOriginHost) !== 0) {
return true;
}
// check `port` parts
$requestOriginPort = \array_key_exists('port', $parsedUrl) === true ? (int)$parsedUrl['port'] : null;
$serverOriginPort = $this->strategy->getServerOriginPort();
if ($requestOriginPort !== $serverOriginPort) {
return true;
}
// check `scheme` parts
$requestOriginScheme = $parsedUrl['scheme'] ?? '';
$serverOriginScheme = $this->strategy->getServerOriginScheme();
if (\strcasecmp($requestOriginScheme, $serverOriginScheme) !== 0) {
return true;
}
$this->logInfo(
'Request is not CORS (request origin equals to server one).',
[
'request_origin' => $requestOrigin,
'server_origin_scheme' => $serverOriginScheme,
'server_origin_host' => $serverOriginHost,
'server_origin_port' => $serverOriginPort
]
);
return false;
}
/**
* @param int $type
* @param array $headers
*
* @return AnalysisResultInterface
*/
protected function createResult($type, array $headers = []): AnalysisResultInterface
{
return $this->factory->createAnalysisResult($type, $headers);
}
/**
* @return FactoryInterface
*/
protected static function getFactory(): FactoryInterface
{
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
return new \Neomerx\Cors\Factory\Factory();
}
/**
* @param RequestInterface $request
*
* @return null|string
*/
private function getRequestHostHeader(RequestInterface $request): ?string
{
$hostHeaderValue = $request->getHeader(CorsRequestHeaders::HOST);
$host = empty($hostHeaderValue) === true ? null : \reset($hostHeaderValue);
return $host;
}
}