CorsService.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. <?php
  2. /*
  3. * This file is part of fruitcake/php-cors and was originally part of asm89/stack-cors
  4. *
  5. * (c) Alexander <iam.asm89@gmail.com>
  6. * (c) Barryvdh <barryvdh@gmail.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Fruitcake\Cors;
  12. use Fruitcake\Cors\Exceptions\InvalidOptionException;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. /**
  16. * @phpstan-type CorsInputOptions array{
  17. * 'allowedOrigins'?: string[],
  18. * 'allowedOriginsPatterns'?: string[],
  19. * 'supportsCredentials'?: bool,
  20. * 'allowedHeaders'?: string[],
  21. * 'allowedMethods'?: string[],
  22. * 'exposedHeaders'?: string[]|false,
  23. * 'maxAge'?: int|bool|null,
  24. * 'allowed_origins'?: string[],
  25. * 'allowed_origins_patterns'?: string[],
  26. * 'supports_credentials'?: bool,
  27. * 'allowed_headers'?: string[],
  28. * 'allowed_methods'?: string[],
  29. * 'exposed_headers'?: string[]|false,
  30. * 'max_age'?: int|bool|null
  31. * }
  32. *
  33. */
  34. class CorsService
  35. {
  36. /** @var string[] */
  37. private array $allowedOrigins = [];
  38. /** @var string[] */
  39. private array $allowedOriginsPatterns = [];
  40. /** @var string[] */
  41. private array $allowedMethods = [];
  42. /** @var string[] */
  43. private array $allowedHeaders = [];
  44. /** @var string[] */
  45. private array $exposedHeaders = [];
  46. private bool $supportsCredentials = false;
  47. private ?int $maxAge = 0;
  48. private bool $allowAllOrigins = false;
  49. private bool $allowAllMethods = false;
  50. private bool $allowAllHeaders = false;
  51. /**
  52. * @param CorsInputOptions $options
  53. */
  54. public function __construct(array $options = [])
  55. {
  56. if ($options) {
  57. $this->setOptions($options);
  58. }
  59. }
  60. /**
  61. * @param CorsInputOptions $options
  62. */
  63. public function setOptions(array $options): void
  64. {
  65. $this->allowedOrigins = $options['allowedOrigins'] ?? $options['allowed_origins'] ?? $this->allowedOrigins;
  66. $this->allowedOriginsPatterns =
  67. $options['allowedOriginsPatterns'] ?? $options['allowed_origins_patterns'] ?? $this->allowedOriginsPatterns;
  68. $this->allowedMethods = $options['allowedMethods'] ?? $options['allowed_methods'] ?? $this->allowedMethods;
  69. $this->allowedHeaders = $options['allowedHeaders'] ?? $options['allowed_headers'] ?? $this->allowedHeaders;
  70. $this->supportsCredentials =
  71. $options['supportsCredentials'] ?? $options['supports_credentials'] ?? $this->supportsCredentials;
  72. $maxAge = $this->maxAge;
  73. if (array_key_exists('maxAge', $options)) {
  74. $maxAge = $options['maxAge'];
  75. } elseif (array_key_exists('max_age', $options)) {
  76. $maxAge = $options['max_age'];
  77. }
  78. $this->maxAge = $maxAge === null ? null : (int)$maxAge;
  79. $exposedHeaders = $options['exposedHeaders'] ?? $options['exposed_headers'] ?? $this->exposedHeaders;
  80. $this->exposedHeaders = $exposedHeaders === false ? [] : $exposedHeaders;
  81. $this->normalizeOptions();
  82. }
  83. private function normalizeOptions(): void
  84. {
  85. // Normalize case
  86. $this->allowedHeaders = array_map('strtolower', $this->allowedHeaders);
  87. $this->allowedMethods = array_map('strtoupper', $this->allowedMethods);
  88. // Normalize ['*'] to true
  89. $this->allowAllOrigins = in_array('*', $this->allowedOrigins);
  90. $this->allowAllHeaders = in_array('*', $this->allowedHeaders);
  91. $this->allowAllMethods = in_array('*', $this->allowedMethods);
  92. // Transform wildcard pattern
  93. if (!$this->allowAllOrigins) {
  94. foreach ($this->allowedOrigins as $origin) {
  95. if (strpos($origin, '*') !== false) {
  96. $this->allowedOriginsPatterns[] = $this->convertWildcardToPattern($origin);
  97. }
  98. }
  99. }
  100. }
  101. /**
  102. * Create a pattern for a wildcard, based on Str::is() from Laravel
  103. *
  104. * @see https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Str.php
  105. * @param string $pattern
  106. * @return string
  107. */
  108. private function convertWildcardToPattern($pattern)
  109. {
  110. $pattern = preg_quote($pattern, '#');
  111. // Asterisks are translated into zero-or-more regular expression wildcards
  112. // to make it convenient to check if the strings starts with the given
  113. // pattern such as "*.example.com", making any string check convenient.
  114. $pattern = str_replace('\*', '.*', $pattern);
  115. return '#^' . $pattern . '\z#u';
  116. }
  117. public function isCorsRequest(Request $request): bool
  118. {
  119. return $request->headers->has('Origin');
  120. }
  121. public function isPreflightRequest(Request $request): bool
  122. {
  123. return $request->getMethod() === 'OPTIONS' && $request->headers->has('Access-Control-Request-Method');
  124. }
  125. public function handlePreflightRequest(Request $request): Response
  126. {
  127. $response = new Response();
  128. $response->setStatusCode(204);
  129. return $this->addPreflightRequestHeaders($response, $request);
  130. }
  131. public function addPreflightRequestHeaders(Response $response, Request $request): Response
  132. {
  133. $this->configureAllowedOrigin($response, $request);
  134. if ($response->headers->has('Access-Control-Allow-Origin')) {
  135. $this->configureAllowCredentials($response, $request);
  136. $this->configureAllowedMethods($response, $request);
  137. $this->configureAllowedHeaders($response, $request);
  138. $this->configureMaxAge($response, $request);
  139. }
  140. return $response;
  141. }
  142. public function isOriginAllowed(Request $request): bool
  143. {
  144. if ($this->allowAllOrigins === true) {
  145. return true;
  146. }
  147. $origin = (string) $request->headers->get('Origin');
  148. if (in_array($origin, $this->allowedOrigins)) {
  149. return true;
  150. }
  151. foreach ($this->allowedOriginsPatterns as $pattern) {
  152. if (preg_match($pattern, $origin)) {
  153. return true;
  154. }
  155. }
  156. return false;
  157. }
  158. public function addActualRequestHeaders(Response $response, Request $request): Response
  159. {
  160. $this->configureAllowedOrigin($response, $request);
  161. if ($response->headers->has('Access-Control-Allow-Origin')) {
  162. $this->configureAllowCredentials($response, $request);
  163. $this->configureExposedHeaders($response, $request);
  164. }
  165. return $response;
  166. }
  167. private function configureAllowedOrigin(Response $response, Request $request): void
  168. {
  169. if ($this->allowAllOrigins === true && !$this->supportsCredentials) {
  170. // Safe+cacheable, allow everything
  171. $response->headers->set('Access-Control-Allow-Origin', '*');
  172. } elseif ($this->isSingleOriginAllowed()) {
  173. // Single origins can be safely set
  174. $response->headers->set('Access-Control-Allow-Origin', array_values($this->allowedOrigins)[0]);
  175. } else {
  176. // For dynamic headers, set the requested Origin header when set and allowed
  177. if ($this->isCorsRequest($request) && $this->isOriginAllowed($request)) {
  178. $response->headers->set('Access-Control-Allow-Origin', (string) $request->headers->get('Origin'));
  179. }
  180. $this->varyHeader($response, 'Origin');
  181. }
  182. }
  183. private function isSingleOriginAllowed(): bool
  184. {
  185. if ($this->allowAllOrigins === true || count($this->allowedOriginsPatterns) > 0) {
  186. return false;
  187. }
  188. return count($this->allowedOrigins) === 1;
  189. }
  190. private function configureAllowedMethods(Response $response, Request $request): void
  191. {
  192. if ($this->allowAllMethods === true) {
  193. $allowMethods = strtoupper((string) $request->headers->get('Access-Control-Request-Method'));
  194. $this->varyHeader($response, 'Access-Control-Request-Method');
  195. } else {
  196. $allowMethods = implode(', ', $this->allowedMethods);
  197. }
  198. $response->headers->set('Access-Control-Allow-Methods', $allowMethods);
  199. }
  200. private function configureAllowedHeaders(Response $response, Request $request): void
  201. {
  202. if ($this->allowAllHeaders === true) {
  203. $allowHeaders = (string) $request->headers->get('Access-Control-Request-Headers');
  204. $this->varyHeader($response, 'Access-Control-Request-Headers');
  205. } else {
  206. $allowHeaders = implode(', ', $this->allowedHeaders);
  207. }
  208. $response->headers->set('Access-Control-Allow-Headers', $allowHeaders);
  209. }
  210. private function configureAllowCredentials(Response $response, Request $request): void
  211. {
  212. if ($this->supportsCredentials) {
  213. $response->headers->set('Access-Control-Allow-Credentials', 'true');
  214. }
  215. }
  216. private function configureExposedHeaders(Response $response, Request $request): void
  217. {
  218. if ($this->exposedHeaders) {
  219. $response->headers->set('Access-Control-Expose-Headers', implode(', ', $this->exposedHeaders));
  220. }
  221. }
  222. private function configureMaxAge(Response $response, Request $request): void
  223. {
  224. if ($this->maxAge !== null) {
  225. $response->headers->set('Access-Control-Max-Age', (string) $this->maxAge);
  226. }
  227. }
  228. public function varyHeader(Response $response, string $header): Response
  229. {
  230. if (!$response->headers->has('Vary')) {
  231. $response->headers->set('Vary', $header);
  232. } else {
  233. $varyHeaders = $response->getVary();
  234. if (!in_array($header, $varyHeaders, true)) {
  235. if (count($response->headers->all('Vary')) === 1) {
  236. $response->setVary(((string)$response->headers->get('Vary')) . ', ' . $header);
  237. } else {
  238. $response->setVary($header, false);
  239. }
  240. }
  241. }
  242. return $response;
  243. }
  244. }