├── .versionrc.json
├── .release-please-manifest.json
├── .gitignore
├── .github
├── FUNDING.yml
├── workflows
│ ├── release-please.yml
│ └── check-extension.yaml
├── ISSUE_TEMPLATE
│ ├── other.md
│ ├── documentation.md
│ ├── feature_request.md
│ ├── bug_report.md
│ └── performance_issue.md
├── PULL_REQUEST_TEMPLATE.md
└── CODEOWNERS
├── docs
├── stories
│ ├── examples
│ │ ├── cors_allowed_methods-in-cloud.jpg
│ │ └── pwa-configuration.php
│ ├── security.md
│ ├── varnish.md
│ ├── no-wild-card.md
│ └── configuring-the-headers.md
├── build
│ └── README.md
├── faq
│ └── faqs.md
├── DEVELOPER.md
└── upgrading
│ └── guide.md
├── registration.php
├── etc
├── di.xml
├── module.xml
├── config.xml
├── webapi_rest
│ └── di.xml
└── graphql
│ └── di.xml
├── release-please-config.json
├── Validator
├── CorsValidatorInterface.php
└── CorsValidator.php
├── package.json
├── Request
└── RestRequest.php
├── Test
├── Integration
│ ├── HeaderManagerConfigurationTest.php
│ ├── RegistrationTest.php
│ ├── CorsConfigurationDiTest.php
│ ├── CorsValidatorDiTest.php
│ ├── Preflight
│ │ ├── GraphQlResponseTest.php
│ │ └── WebApiResponseTest.php
│ └── Response
│ │ ├── GraphQlResponseTest.php
│ │ └── WebApiResponseTest.php
└── Unit
│ ├── Configuration
│ ├── ConfigurationCleanerTest.php
│ ├── RestCorsConfigurationTest.php
│ └── GraphQlCorsConfigurationTest.php
│ ├── HeaderProvider
│ ├── CorsVaryHeaderProviderTest.php
│ ├── CorsAllowCredentialsHeaderProviderTest.php
│ ├── CorsMaxAgeHeaderProviderTest.php
│ ├── CorsAllowOriginHeaderProviderTest.php
│ ├── CorsAllowMethodsHeaderProviderTest.php
│ └── CorsAllowHeadersHeaderProviderTest.php
│ └── Validator
│ └── CorsValidatorTest.php
├── LICENSE
├── Controller
└── NoopController.php
├── Configuration
├── ConfigurationCleaner.php
├── CorsConfigurationInterface.php
├── GraphQl
│ └── CorsConfiguration.php
└── Rest
│ └── CorsConfiguration.php
├── Response
├── HeaderProvider
│ ├── CorsVaryHeaderProvider.php
│ ├── CorsAllowCredentialsHeaderProvider.php
│ ├── CorsMaxAgeHeaderProvider.php
│ ├── CorsExposeHeadersProvider.php
│ ├── CorsAllowHeadersHeaderProvider.php
│ ├── CorsAllowMethodsHeaderProvider.php
│ └── CorsAllowOriginHeaderProvider.php
├── Preflight
│ ├── GraphQl
│ │ └── PreflightRequestHandler.php
│ └── Rest
│ │ └── PreflightRequestHandler.php
└── HeaderManager.php
├── composer.json
├── Plugin
└── FastLauncher.php
├── CODE_OF_CONDUCT.md
├── README.md
├── CHANGELOG.md
└── CONTRIBUTING.md
/.versionrc.json:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/.release-please-manifest.json:
--------------------------------------------------------------------------------
1 | {".":"2.1.1"}
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /vendor/
2 | node_modules/
3 | composer.lock
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: graycoreio
--------------------------------------------------------------------------------
/docs/stories/examples/cors_allowed_methods-in-cloud.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/graycoreio/magento2-cors/HEAD/docs/stories/examples/cors_allowed_methods-in-cloud.jpg
--------------------------------------------------------------------------------
/registration.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.github/workflows/release-please.yml:
--------------------------------------------------------------------------------
1 | name: Create Release
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 |
8 | jobs:
9 | release-please:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: google-github-actions/release-please-action@v3
13 | with:
14 | token: ${{ secrets.GRAYCORE_GITHUB_TOKEN }}
15 | command: manifest
16 | default-branch: master
17 |
--------------------------------------------------------------------------------
/release-please-config.json:
--------------------------------------------------------------------------------
1 | {
2 | "bootstrap-sha": "e65e6708a9ac8cbe9835b99ffc60a8f307e1310f",
3 | "bump-minor-pre-major": true,
4 | "bump-patch-for-minor-pre-major": true,
5 | "draft-pull-request": true,
6 | "prerelease": true,
7 | "include-component-in-tag": false,
8 | "include-v-in-tag": true,
9 | "pull-request-title-pattern": "chore: release ${version}",
10 | "packages": {
11 | ".": {
12 | "release-type": "php"
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/docs/stories/security.md:
--------------------------------------------------------------------------------
1 | # Security
2 |
3 | ## Security By Default
4 | By default this extension will do nothing! This is entirely by design. In order for you to add CORS headers, we HIGHLY recommend [understanding the security risks involved with CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).
5 |
6 | We want to you configure the module to do precisely what you want. To make this process easier, you can [follow along with our configuration guide](/docs/stories/configuring-the-headers.md).
--------------------------------------------------------------------------------
/etc/module.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/docs/faq/faqs.md:
--------------------------------------------------------------------------------
1 | # FAQ
2 |
3 | ## Can I configure this package from the admin panel?
4 | No. We will never merge a PR that allows an administrator to modify CORS headers from the admin panel. CORS Headers
5 | should only be configured by qualified developers and security administrators. CORS is fundamentally a security relaxation protocol with significant ramifications when misconfigured. Allowing access from the admin panel circumvents the **critical** knowledge pathway and will put user information at risk, which we will not allow under any circumstances.
6 |
--------------------------------------------------------------------------------
/Validator/CorsValidatorInterface.php:
--------------------------------------------------------------------------------
1 | ",
17 | "license": "MIT",
18 | "bugs": {
19 | "url": "https://github.com/graycoreio/magento2-cors/issues"
20 | },
21 | "homepage": "https://github.com/graycoreio/magento2-cors#readme",
22 | "devDependencies": {
23 | "standard-version": "^9.1.1"
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/other.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Other
3 | about: Report a general issue that isn't covered by other issue templates.
4 | title: '[OTHER]'
5 | labels: ''
6 | assignees: ''
7 | ---
8 |
9 |
14 |
15 | # :question: Other
16 |
17 |
18 |
19 | ## Environment
20 |
21 |
22 | magento2-cors version: X.Y.Z
23 | Magento version: X.Y.Z
24 | PHP Version version: X.Y.Z
25 |
26 |
27 | Others:
28 |
29 |
--------------------------------------------------------------------------------
/Request/RestRequest.php:
--------------------------------------------------------------------------------
1 | isGet()
29 | && !$subject->isPost()
30 | && !$subject->isPut()
31 | && !$subject->isDelete()
32 | && !$subject->isOptions()
33 | ) {
34 | throw new InputException(__('Request method is invalid.'));
35 | }
36 | return $subject->getMethod();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Test/Integration/HeaderManagerConfigurationTest.php:
--------------------------------------------------------------------------------
1 | markTestIncomplete('This test has not been implemented yet.');
22 | }
23 |
24 | public function testTheModuleDoesNotAddCorsHeadersInTheGlobalScope()
25 | {
26 | $this->markTestIncomplete('This test has not been implemented yet.');
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/etc/config.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | 86400
11 | 0
12 |
13 |
14 |
15 |
16 |
17 | 86400
18 | 0
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.github/workflows/check-extension.yaml:
--------------------------------------------------------------------------------
1 | name: Check Extension
2 |
3 | on:
4 | workflow_dispatch: {}
5 | schedule:
6 | - cron: 0 12 10 * *
7 | push:
8 | branches:
9 | - master
10 | paths-ignore:
11 | - "docs/**"
12 | - package.json
13 | - package-lock.json
14 | - "*.md"
15 | pull_request:
16 | branches:
17 | - master
18 | paths-ignore:
19 | - "docs/**"
20 | - package.json
21 | - package-lock.json
22 | - "*.md"
23 |
24 | jobs:
25 | compute_matrix:
26 | runs-on: ubuntu-latest
27 | outputs:
28 | matrix: ${{ steps.supported-version.outputs.matrix }}
29 | steps:
30 | - uses: graycoreio/github-actions-magento2/supported-version@main
31 | id: supported-version
32 | with:
33 | include_services: true
34 | check-extension:
35 | needs: compute_matrix
36 | uses: graycoreio/github-actions-magento2/.github/workflows/check-extension.yaml@main
37 | with:
38 | matrix: ${{ needs.compute_matrix.outputs.matrix }}
39 | fail-fast: false
40 | secrets:
41 | composer_auth: ${{ secrets.COMPOSER_AUTH }}
42 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 - 2020 Graycore, LLC
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/documentation.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Documentation Request
3 | about: Request additional documentation or clarification on a feature.
4 | title: '[DOCS]'
5 | labels: 'docs'
6 | assignees: 'damienwebdev'
7 | ---
8 |
9 |
14 |
15 | # :page_facing_up: Documentation Request
16 |
17 | ## What were you doing?
18 |
19 |
20 |
21 | ## Expected behavior
22 |
23 |
24 |
25 | ## Existing Documentation
26 |
27 |
28 | ## Environment
29 |
30 |
31 | magento2-cors version: X.Y.Z
32 | Magento version: X.Y.Z
33 | PHP Version version: X.Y.Z
34 |
35 |
36 | Others:
37 |
38 |
--------------------------------------------------------------------------------
/Test/Unit/Configuration/ConfigurationCleanerTest.php:
--------------------------------------------------------------------------------
1 | configurationCleaner = new ConfigurationCleaner();
26 | }
27 | public function testItProperlyCleansArray()
28 | {
29 | $string = "1, 2, 3, 4";
30 | $this->assertEquals(["1","2","3","4"], $this->configurationCleaner->processDelimitedString($string));
31 | $string = "1,, 2,, 3, 4";
32 | $this->assertEquals(["1","2","3","4"], $this->configurationCleaner->processDelimitedString($string));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Controller/NoopController.php:
--------------------------------------------------------------------------------
1 | _headerManager = $headerManager;
34 | $this->_response = $response;
35 | }
36 |
37 | /**
38 | * Dispatch application action
39 | *
40 | * @param RequestInterface $request
41 | * @return ResponseInterface
42 | */
43 | public function dispatch(RequestInterface $request)
44 | {
45 | $this->_headerManager->applyHeaders($this->_response);
46 | return $this->_response;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature Request
3 | about: Ask for a new feature, or something that you'd like to see changed.
4 | title: '[FEAT]'
5 | labels: 'feat'
6 | assignees: 'damienwebdev'
7 | ---
8 |
9 |
14 |
15 | # :bulb: Feature request
16 |
17 | ## Feature Name
18 |
19 |
20 |
21 | ## The Desired Behavior
22 |
23 |
24 |
25 | ## Your Use Case
26 |
27 |
28 |
29 | ## Prior Work
30 |
31 |
32 |
33 | ## Environment
34 |
35 |
36 | magento2-cors version: X.Y.Z
37 | Magento version: X.Y.Z
38 | PHP Version version: X.Y.Z
39 |
40 |
41 | Others:
42 |
43 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report or Regression
3 | about: Create a report to help us fix an issue or regression
4 | title: '[BUG]'
5 | labels: 'bug'
6 | assignees: 'damienwebdev'
7 | ---
8 |
9 |
14 |
15 | # :bug: Bug report
16 |
17 | ## Current Behavior
18 |
19 |
20 |
21 | ## Expected Behavior
22 |
23 |
24 |
25 | ## Minimal reproduction of the problem with instructions
26 |
27 |
28 |
29 | ## What is the motivation / use case for changing the behavior?
30 |
31 |
32 |
33 | ## Environment
34 |
35 |
36 | magento2-cors version: X.Y.Z
37 | Magento version: X.Y.Z
38 | PHP Version version: X.Y.Z
39 |
40 |
41 | Others:
42 |
43 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/performance_issue.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Performance Issue
3 | about: Create a report about a performance problem.
4 | title: '[PERF]'
5 | labels: 'perf'
6 | assignees: 'damienwebdev'
7 | ---
8 |
9 |
14 |
15 | # :turtle: Performance Issue
16 |
17 | ## Current behavior
18 |
19 |
20 |
21 | ## Expected behavior
22 |
23 |
24 |
25 | ## Minimal reproduction of the problem with instructions
26 |
27 |
28 |
29 | ## What is the motivation / use case for changing the behavior?
30 |
31 |
32 |
33 | ## Environment
34 |
35 |
36 | magento2-cors version: X.Y.Z
37 | Magento version: X.Y.Z
38 | PHP Version version: X.Y.Z
39 |
40 |
41 | Others:
42 |
43 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ## PR Checklist
2 | Please check if your PR fulfills the following requirements:
3 |
4 | - [ ] The commit message follows our guidelines: https://github.com/graycoreio/magento2-cors/blob/master/CONTRIBUTING.md#commit
5 | - [ ] Tests for the changes have been added (for bug fixes / features)
6 | - [ ] Docs have been added / updated (for bug fixes / features)
7 |
8 |
9 | ## PR Type
10 | What kind of change does this PR introduce?
11 |
12 |
13 | ```
14 | [ ] Bugfix
15 | [ ] Feature
16 | [ ] Code style update (formatting, local variables)
17 | [ ] Refactoring (no functional changes, no api changes)
18 | [ ] Build related changes
19 | [ ] CI related changes
20 | [ ] Documentation content changes
21 | [ ] Other... Please describe:
22 | ```
23 |
24 | ## What is the current behavior?
25 |
26 |
27 | Fixes: N/A
28 |
29 |
30 | ## What is the new behavior?
31 |
32 |
33 | ## Does this PR introduce a breaking change?
34 | ```
35 | [ ] Yes
36 | [ ] No
37 | ```
38 |
39 |
40 |
41 |
42 | ## Other information
--------------------------------------------------------------------------------
/docs/DEVELOPER.md:
--------------------------------------------------------------------------------
1 | # Developer Documentation
2 |
3 | ## Contributing
4 | Please read the [contributing guidelines here](https://github.com/graycoreio/magento2-cors/blob/develop/CONTRIBUTING.md).
5 |
6 | ## Building the Project
7 | This project is intended to be installed as a composer dependency for a Magento application, so if you're working with it as a custom module, you'll need to install your own Magento instance and then this project as a dependency.
8 |
9 | ### Prerequisites
10 | * [Git](https://git-scm.com/)
11 | * PHP 7.2+
12 | * [Magento](https://github.com/magento/magento2)
13 | * Check the versions supported by the project in the README
14 | * [Composer](https://getcomposer.org/)
15 |
16 |
17 | ## Testing
18 | Tests help us ensure code quality and backwards compatibility across various Magento and PHP versions. Please make sure you write clear and concise tests BEFORE you write your code, otherwise there will be no way to verify that your tests achieve the intended goals.
19 |
20 | ### Unit Tests
21 | You can run the unit tests by defined by the `composer` script.
22 |
23 | ```bash
24 | composer run-script unit-test
25 | ```
26 |
27 | ## Integration Tests
28 | These must be run from the Magento application's `dev/tests/integration` directory.
29 |
30 | ```bash
31 | ../../../vendor/bin/phpunit --testsuite "Graycore_Magento2Cors"
32 | ```
--------------------------------------------------------------------------------
/docs/stories/examples/pwa-configuration.php:
--------------------------------------------------------------------------------
1 | [
5 | 'default' => [
6 | 'web' => [
7 | 'graphql' => [
8 | 'cors_max_age' => 86400,
9 | 'cors_allow_credentials' => 1,
10 | 'cors_allowed_methods' => 'POST, OPTIONS, GET',
11 | 'cors_expose_headers' => 'X-Magento-Cache-Id',
12 | 'cors_allowed_headers' =>
13 | 'Content-Currency, Store, X-Magento-Cache-Id, X-Captcha, Content-Type, Authorization, DNT, TE',
14 | // Angular
15 | 'cors_allowed_origins' =>
16 | 'http://localhost:4200, https://localhost:4200',
17 | // Angular + Universal
18 | 'cors_allowed_origins' =>
19 | 'http://localhost:4200, https://localhost:4200, http://localhost:4000, https://localhost:4000',
20 | // Express
21 | 'cors_allowed_origins' =>
22 | 'https://frontend.example.com, http://localhost:3000, https://localhost:3000',
23 | // PWA Studio (PWA Studio Generates a random port, so we can't provide a configuration)
24 | ]
25 | ]
26 | ]
27 | ]
28 | ];
29 |
--------------------------------------------------------------------------------
/Test/Integration/RegistrationTest.php:
--------------------------------------------------------------------------------
1 | assertArrayHasKey($this->moduleName, $registrar->getPaths(ComponentRegistrar::MODULE));
31 | }
32 |
33 | public function testTheModuleIsConfiguredAndEnabled()
34 | {
35 | $manager = ObjectManager::getInstance();
36 | $moduleList = $manager->create(ModuleList::class);
37 |
38 | $this->assertTrue($moduleList->has($this->moduleName));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/docs/upgrading/guide.md:
--------------------------------------------------------------------------------
1 | # Upgrade Guide
2 |
3 | When we make breaking changes, we will post the breaking changes here.
4 |
5 | ## v1.* to v2.0
6 |
7 | The layer in which we compute whether or not an incoming preflight request receives CORS headers has changed in v2.0.0. Previously, we leveraged a plugin around the relevant native Magento 2 Controller (webapi_rest/graphql) and as a result, we incurred significant overhead from Magento code when computing CORS headers.
8 |
9 | In v2.0, we no longer incur this overhead by adding a plugin around application launch and creating our own custom controller. It is **very possible** that we broke expectations of anything that plugs-in around this plugin or adds additional CORS headers other than our own.
10 |
11 | For 99.99% of GraphQl/Rest API deployments, the API is used sessionlessly. As such, we can take the opportunity to improve performance for the majority at the expense of the minority. If this breaks your codebase, please submit an issue and we will see what can be done to remedy your specific use-case.
12 |
13 | In theory, most dependents simply need to upgrade to v2.0 and there are no breaking changes.
14 |
15 | **However,** if you were expecting to use the native GraphQl/REST controller when computing CORS headers (and everything else that entails - like having a Magento session, for example) that guarantee is no-longer provided.
16 |
17 |
--------------------------------------------------------------------------------
/Configuration/ConfigurationCleaner.php:
--------------------------------------------------------------------------------
1 | 0s && (bereq.method == "GET" || bereq.method == "HEAD" || bereq.method == "OPTIONS")) {
47 | unset beresp.http.set-cookie;
48 | }
49 |
50 | ...
51 | }
52 | ```
--------------------------------------------------------------------------------
/Test/Unit/HeaderProvider/CorsVaryHeaderProviderTest.php:
--------------------------------------------------------------------------------
1 | provider = new CorsVaryHeaderProvider();
42 | }
43 |
44 | public function testGetName()
45 | {
46 | $this->assertEquals($this::HEADER_NAME, $this->provider->getName(), 'Wrong header name');
47 | }
48 |
49 | public function testGetValue()
50 | {
51 | $this->assertEquals($this::HEADER_VALUE, $this->provider->getValue(), 'Wrong default header value');
52 | }
53 |
54 | public function testCanApply()
55 | {
56 | $this->assertEquals(true, $this->provider->canApply(), 'Incorrect canApply result');
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Response/HeaderProvider/CorsVaryHeaderProvider.php:
--------------------------------------------------------------------------------
1 | _response = $response;
42 | $this->_headerManager = $headerManager;
43 | }
44 |
45 | /**
46 | * Handle preflight requests for GraphQL endpoint.
47 | *
48 | * @param GraphQlController $subject
49 | * @param callable $next
50 | * @param RequestInterface $request
51 | * @return \Magento\Framework\App\Response\HttpInterface
52 | */
53 | public function aroundDispatch(GraphQlController $subject, callable $next, RequestInterface $request)
54 | {
55 | if ($request instanceof Http && $request->isOptions()) {
56 | $this->_headerManager->beforeSendResponse($this->_response);
57 | $this->_response->setPublicHeaders(86400);
58 | return $this->_response;
59 | }
60 |
61 | return $next($request);
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Response/HeaderProvider/CorsAllowCredentialsHeaderProvider.php:
--------------------------------------------------------------------------------
1 | configuration = $configuration;
42 | $this->validator = $validator;
43 | }
44 |
45 | /**
46 | * Get the header value.
47 | *
48 | * @return string
49 | */
50 | public function getValue()
51 | {
52 | return "true";
53 | }
54 |
55 | /**
56 | * Determine if the header can be applied.
57 | *
58 | * @return bool
59 | */
60 | public function canApply()
61 | {
62 | return $this->validator->originIsValid() && $this->configuration->getAllowCredentials();
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/etc/webapi_rest/di.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | - Graycore\Cors\Response\HeaderProvider\CorsAllowHeadersHeaderProvider
9 | - Graycore\Cors\Response\HeaderProvider\CorsAllowOriginHeaderProvider
10 | - Graycore\Cors\Response\HeaderProvider\CorsAllowMethodsHeaderProvider
11 | - Graycore\Cors\Response\HeaderProvider\CorsMaxAgeHeaderProvider
12 | - Graycore\Cors\Response\HeaderProvider\CorsExposeHeadersProvider
13 | - Graycore\Cors\Response\HeaderProvider\CorsAllowCredentialsHeaderProvider
14 | - Graycore\Cors\Response\HeaderProvider\CorsVaryHeaderProvider
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "graycore/magento2-cors",
3 | "description": "A Magento 2 module that enables CORS on the GraphQL and REST Apis",
4 | "type": "magento2-module",
5 | "license": "MIT",
6 | "authors": [
7 | {
8 | "name": "Damien Retzinger",
9 | "email": "damienwebdev@gmail.com"
10 | }
11 | ],
12 | "scripts": {
13 | "test": "phpunit --bootstrap vendor/autoload.php test",
14 | "unit-test": "vendor/bin/phpunit ./Test/Unit",
15 | "lint": "phpcs . --standard=Magento2 --ignore='vendor/*,node_modules/*'",
16 | "post-install-cmd": [
17 | "([ $COMPOSER_DEV_MODE -eq 0 ] || vendor/bin/phpcs --config-set installed_paths ../../magento/magento-coding-standard/,../../magento/php-compatibility-fork/)"
18 | ],
19 | "post-update-cmd": [
20 | "([ $COMPOSER_DEV_MODE -eq 0 ] || vendor/bin/phpcs --config-set installed_paths ../../magento/magento-coding-standard/,../../magento/php-compatibility-fork/)"
21 | ]
22 | },
23 | "archive": {
24 | "exclude": [
25 | "/docs",
26 | "/Test",
27 | "README.md"
28 | ]
29 | },
30 | "minimum-stability": "stable",
31 | "autoload": {
32 | "psr-4": {
33 | "Graycore\\Cors\\": ""
34 | },
35 | "files": [
36 | "registration.php"
37 | ]
38 | },
39 | "require": {
40 | "magento/framework": "^102.0 || ^103.0"
41 | },
42 | "require-dev": {
43 | "magento/magento-coding-standard": "^38.0",
44 | "magento/php-compatibility-fork": "^0.1.0",
45 | "phpunit/phpunit": "^8.2 || ^9.0",
46 | "squizlabs/php_codesniffer": "^3.4"
47 | },
48 | "repositories": {
49 | "0": {
50 | "type": "composer",
51 | "url": "https://repo.magento.com/"
52 | }
53 | },
54 | "config": {
55 | "preferred-install": "dist",
56 | "sort-packages": true,
57 | "allow-plugins": {
58 | "magento/composer-dependency-version-audit-plugin": true,
59 | "dealerdirect/phpcodesniffer-composer-installer": true
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Response/Preflight/Rest/PreflightRequestHandler.php:
--------------------------------------------------------------------------------
1 | _response = $response;
43 | $this->_headerManager = $headerManager;
44 | }
45 |
46 | /**
47 | * Handle preflight requests for REST endpoint.
48 | *
49 | * @param RestController $subject
50 | * @param callable $next
51 | * @param RequestInterface $request
52 | * @return \Magento\Framework\App\Response\HttpInterface|string
53 | */
54 | public function aroundDispatch(RestController $subject, callable $next, RequestInterface $request)
55 | {
56 | if ($request instanceof Http && $request->isOptions()) {
57 | $this->_headerManager->applyHeaders($this->_response);
58 | $this->_response->setPublicHeaders(86400);
59 | return $this->_response;
60 |
61 | }
62 |
63 | /** @var HttpResponse $response */
64 | return $next($request);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Test/Integration/CorsConfigurationDiTest.php:
--------------------------------------------------------------------------------
1 | objectManager = ObjectManager::getInstance();
28 | }
29 |
30 | /**
31 | * @magentoAppArea global
32 | */
33 | public function testItDoesNotPresentAConcretionForTheCorsConfigurationInterfaceInTheGlobalScope()
34 | {
35 | $this->expectException(
36 | \Error::class,
37 | "Cannot instantiate interface Graycore\Cors\Validator\CorsConfigurationInterface"
38 | );
39 | $this->objectManager->get(CorsConfigurationInterface::class);
40 | }
41 |
42 | /**
43 | * @magentoAppArea graphql
44 | */
45 | public function testItPresentsAConcretionForTheCorsConfigurationInterfaceInTheGraphQlScope()
46 | {
47 | $this->assertInstanceOf(
48 | GraphQlCorsConfiguration::class,
49 | $this->objectManager->get(CorsConfigurationInterface::class)
50 | );
51 | }
52 |
53 | /**
54 | * @magentoAppArea webapi_rest
55 | */
56 | public function testItPresentsAConcretionForTheCorsConfigurationInterfaceInTheRestScope()
57 | {
58 | $this->assertInstanceOf(
59 | RestCorsConfiguration::class,
60 | $this->objectManager->get(CorsConfigurationInterface::class)
61 | );
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Response/HeaderProvider/CorsMaxAgeHeaderProvider.php:
--------------------------------------------------------------------------------
1 | configuration = $configuration;
47 | $this->validator = $validator;
48 | }
49 |
50 | /**
51 | * Get the header value.
52 | *
53 | * @return string|null
54 | */
55 | public function getValue(): ?string
56 | {
57 | return $this->configuration->getMaxAge() ? $this->configuration->getMaxAge() : $this->headerValue;
58 | }
59 |
60 | /**
61 | * Determine if the header can be applied.
62 | *
63 | * @return bool
64 | */
65 | public function canApply(): bool
66 | {
67 | return $this->validator->isPreflightRequest() && $this->validator->originIsValid() && $this->getValue();
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/Test/Integration/CorsValidatorDiTest.php:
--------------------------------------------------------------------------------
1 | objectManager = ObjectManager::getInstance();
31 | }
32 |
33 | /**
34 | * @magentoAppArea global
35 | */
36 | public function testItDoesNotPresentAConcretionForTheCorsValidatorInterfaceInTheGlobalScope()
37 | {
38 | $this->expectException(
39 | \Error::class,
40 | "Cannot instantiate interface Graycore\Cors\Validator\CorsValidatorInterface"
41 | );
42 | $this->objectManager->get(CorsValidatorInterface::class);
43 | }
44 |
45 | /**
46 | * @magentoAppArea graphql
47 | */
48 | public function testItPresentsAConcretionForTheCorsValidatorInterfaceInTheGraphQlScope()
49 | {
50 | $this->assertInstanceOf(
51 | CorsValidator::class,
52 | $this->objectManager->get(CorsValidatorInterface::class)
53 | );
54 | }
55 |
56 | /**
57 | * @magentoAppArea webapi_rest
58 | */
59 | public function testItPresentsAConcretionForTheCorsValidatorInterfaceInTheWebApiRestScope()
60 | {
61 | $this->assertInstanceOf(
62 | CorsValidator::class,
63 | $this->objectManager->get(CorsValidatorInterface::class)
64 | );
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Response/HeaderProvider/CorsExposeHeadersProvider.php:
--------------------------------------------------------------------------------
1 | configuration = $configuration;
47 | $this->validator = $validator;
48 | }
49 |
50 | /**
51 | * Get the header value.
52 | *
53 | * @return string
54 | */
55 | public function getValue()
56 | {
57 | return $this->configuration->getExposedHeaders()
58 | ? implode(',', $this->configuration->getExposedHeaders())
59 | : $this->headerValue;
60 | }
61 |
62 | /**
63 | * Determine if the header can be applied.
64 | *
65 | * @return bool
66 | */
67 | public function canApply(): bool
68 | {
69 | return !$this->validator->isPreflightRequest() && $this->validator->originIsValid() && $this->getValue();
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/Response/HeaderProvider/CorsAllowHeadersHeaderProvider.php:
--------------------------------------------------------------------------------
1 | configuration = $configuration;
47 | $this->validator = $validator;
48 | }
49 |
50 | /**
51 | * Get the header value.
52 | *
53 | * @return string
54 | */
55 | public function getValue()
56 | {
57 | return $this->configuration->getAllowedHeaders()
58 | ? implode(',', $this->configuration->getAllowedHeaders())
59 | : $this->headerValue;
60 | }
61 |
62 | /**
63 | * Determine if the header can be applied.
64 | *
65 | * @return bool
66 | */
67 | public function canApply()
68 | {
69 | return $this->validator->isPreflightRequest() && $this->validator->originIsValid() && $this->getValue();
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/Response/HeaderManager.php:
--------------------------------------------------------------------------------
1 | headerProviders = $headerProviderList;
38 | }
39 |
40 | /**
41 | * Apply CORS headers to the response.
42 | *
43 | * @param \Magento\Framework\App\Response\HttpInterface $response
44 | * @return \Magento\Framework\App\Response\HttpInterface
45 | */
46 | public function applyHeaders(\Magento\Framework\App\Response\HttpInterface $response)
47 | {
48 | foreach ($this->headerProviders as $provider) {
49 | if ($provider->canApply()) {
50 | $response->setHeader($provider->getName(), $provider->getValue());
51 | }
52 | }
53 | return $response;
54 | }
55 |
56 | /**
57 | * Apply CORS headers before sending response.
58 | *
59 | * @param \Magento\Framework\App\Response\HttpInterface $subject
60 | * @return void
61 | * @codeCoverageIgnore
62 | */
63 | public function beforeSendResponse(\Magento\Framework\App\Response\HttpInterface $subject)
64 | {
65 | $this->applyHeaders($subject);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Response/HeaderProvider/CorsAllowMethodsHeaderProvider.php:
--------------------------------------------------------------------------------
1 | configuration = $configuration;
47 | $this->validator = $validator;
48 | }
49 |
50 | /**
51 | * Get the header value.
52 | *
53 | * @return string
54 | */
55 | public function getValue()
56 | {
57 | return $this->configuration->getAllowedMethods()
58 | ? implode(',', $this->configuration->getAllowedMethods())
59 | : $this->headerValue;
60 | }
61 |
62 | /**
63 | * Determine if the header can be applied.
64 | *
65 | * @return bool
66 | */
67 | public function canApply()
68 | {
69 | return $this->validator->isPreflightRequest() && $this->validator->originIsValid() && $this->getValue();
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/Test/Unit/HeaderProvider/CorsAllowCredentialsHeaderProviderTest.php:
--------------------------------------------------------------------------------
1 | corsValidatorMock = $this->createMock(CorsValidatorInterface::class);
42 | $this->corsConfigurationMock = $this->createMock(CorsConfigurationInterface::class);
43 | $this->provider = new CorsAllowCredentialsHeaderProvider(
44 | $this->corsConfigurationMock,
45 | $this->corsValidatorMock
46 | );
47 | }
48 |
49 | public function testGetName()
50 | {
51 | $this->assertEquals($this::HEADER_NAME, $this->provider->getName(), 'Wrong header name');
52 | }
53 |
54 | public function testNotAppliedIfNotConfigured()
55 | {
56 | $this->corsConfigurationMock->method('getAllowCredentials')->willReturn(false);
57 | $this->corsValidatorMock->method('originIsValid')->willReturn(true);
58 | $this->assertEquals(false, $this->provider->canApply(), 'Incorrectly applied header');
59 | }
60 |
61 | public function testHeaderAppliedIfConfigured()
62 | {
63 | $this->corsConfigurationMock->method('getAllowCredentials')->willReturn(true);
64 | $this->corsValidatorMock->method('originIsValid')->willReturn(true);
65 | $this->assertEquals(true, $this->provider->canApply());
66 | $this->assertEquals('true', $this->provider->getValue());
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
2 | # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
3 | # $$ Magento 2 Cors Code Owners $$
4 | # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
5 | # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
6 | #
7 | # The configuration for Code Owners for graycoreio/magento2-cors.
8 | #
9 | # For more info see: https://help.github.com/articles/about-codeowners/
10 | #
11 |
12 |
13 | # ================================================
14 | # Concepts
15 | # ================================================
16 | #
17 | # 1. A CodeOwner should only review what they are comfortable reviewing. If you're not comfortable, say something.
18 | # 2. It is a CodeOwners responsibility to only accept the changes that they understand and deem necessary.
19 | # 3. The CodeOwners have final say on whether or not code is accepted.
20 | # 4. If multiple CodeOwners are listed, ALL code owners must approve the PR prior to merge.
21 | # 5. CodeOwners work in conjunction with Github's "Number of Required Approvals (1)" requirement.
22 |
23 |
24 | # ================================================
25 | # GitHub username registry
26 | # ================================================
27 |
28 | # damienwebdev - Damien Retzinger
29 | # Nolan-Arnold - Nolan Arnold
30 |
31 |
32 |
33 | ######################################################################################################
34 | #
35 | # Team structure and memberships
36 | # ------------------------------
37 | #
38 | #
39 | # Any changes to team structure or memberships must first be made in this file and only then
40 | # implemented in the GitHub UI.
41 | #######################################################################################################
42 |
43 |
44 | ######################################################################################################
45 | #
46 | # CODEOWNERS rules
47 | # -----------------
48 | #
49 | # All the following rules are applied in the order specified in this file.
50 | # The last rule that matches wins!
51 | #
52 | # See https://git-scm.com/docs/gitignore#_pattern_format for pattern syntax docs.
53 | #
54 | ######################################################################################################
55 |
56 |
57 | # ================================================
58 | # Default Owners
59 | # ================================================
60 |
61 | * @damienwebdev
62 |
63 | # ================================================
64 | # CODEOWNERS Owners owners ...
65 | # ================================================
66 |
67 | /.github/CODEOWNERS @damienwebdev
68 |
--------------------------------------------------------------------------------
/Plugin/FastLauncher.php:
--------------------------------------------------------------------------------
1 | _objectManager = $objectManager;
54 | $this->_areaList = $areaList;
55 | $this->_configLoader = $configLoader;
56 | $this->_state = $state;
57 | $this->_request = $request;
58 | }
59 |
60 | /**
61 | * Intercept application launch to handle preflight requests.
62 | *
63 | * @param \Magento\Framework\AppInterface $subject
64 | * @param callable $proceed
65 | * @return \Magento\Framework\App\ResponseInterface
66 | */
67 | public function aroundLaunch(\Magento\Framework\AppInterface $subject, callable $proceed)
68 | {
69 | if ($this->_request->getMethod() === RequestHttp::METHOD_OPTIONS) {
70 | $areaCode = $this->_areaList->getCodeByFrontName($this->_request->getFrontName());
71 | if ($areaCode !== Area::AREA_WEBAPI_REST &&
72 | $areaCode !== Area::AREA_GRAPHQL
73 | ) {
74 | return $proceed();
75 | }
76 | $this->_state->setAreaCode($areaCode);
77 | $this->_objectManager->configure($this->_configLoader->load($areaCode));
78 | /** @var \Graycore\Cors\Controller\NoopController::class */
79 | $controller = $this->_objectManager->get(\Graycore\Cors\Controller\NoopController::class);
80 | $response = $controller->dispatch($this->_request);
81 | return $response;
82 | };
83 |
84 | return $proceed();
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/Test/Unit/Configuration/RestCorsConfigurationTest.php:
--------------------------------------------------------------------------------
1 | scopeConfigMock = $this->createMock(ScopeConfigInterface::class);
34 | $this->configuration = new CorsConfiguration($this->scopeConfigMock);
35 | }
36 |
37 | public function testItReturnsAnArrayOfAllowedOrigins()
38 | {
39 | $this->scopeConfigMock->method('getValue')->willReturn('https://www.example.com');
40 | $this->assertEquals(['https://www.example.com'], $this->configuration->getAllowedOrigins());
41 | }
42 |
43 | public function testIfTheConfigurationIsEmptyItWillReturnAnEmptyArray()
44 | {
45 | $this->scopeConfigMock->method('getValue')->willReturn('');
46 | $this->assertEquals([], $this->configuration->getAllowedOrigins());
47 | }
48 |
49 | public function testIfTheConfigurationIsNullItWillReturnAnEmptyArray()
50 | {
51 | $this->scopeConfigMock->method('getValue')->willReturn(null);
52 | $this->assertEquals([], $this->configuration->getAllowedOrigins());
53 | }
54 |
55 | public function testIfTheConfigurationIsACommaSeparatedStringWithSpacesInItThenItWillReturnAnArrayOfOrigins()
56 | {
57 | $this->scopeConfigMock
58 | ->method('getValue')->willReturn('https://www.example.com, ,https://www.myother.valid.domain ');
59 | $this->assertEquals(
60 | ['https://www.example.com', 'https://www.myother.valid.domain'],
61 | $this->configuration->getAllowedOrigins()
62 | );
63 | }
64 |
65 | public function testIfAllowCredentialsNotConfiguredItWillReturnFalse()
66 | {
67 | $this->scopeConfigMock->method('isSetFlag')->willReturn(false);
68 | $this->assertEquals(false, $this->configuration->getAllowCredentials());
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Test/Unit/Configuration/GraphQlCorsConfigurationTest.php:
--------------------------------------------------------------------------------
1 | scopeConfigMock = $this->createMock(ScopeConfigInterface::class);
34 | $this->configuration = new CorsConfiguration($this->scopeConfigMock);
35 | }
36 |
37 | public function testItReturnsAnArrayOfAllowedOrigins()
38 | {
39 | $this->scopeConfigMock->method('getValue')->willReturn('https://www.example.com');
40 | $this->assertEquals(['https://www.example.com'], $this->configuration->getAllowedOrigins());
41 | }
42 |
43 | public function testIfTheConfigurationIsEmptyItWillReturnAnEmptyArray()
44 | {
45 | $this->scopeConfigMock->method('getValue')->willReturn('');
46 | $this->assertEquals([], $this->configuration->getAllowedOrigins());
47 | }
48 |
49 | public function testIfTheConfigurationIsNullItWillReturnAnEmptyArray()
50 | {
51 | $this->scopeConfigMock->method('getValue')->willReturn(null);
52 | $this->assertEquals([], $this->configuration->getAllowedOrigins());
53 | }
54 |
55 | public function testIfTheConfigurationIsACommaSeparatedStringWithSpacesInItThenItWillReturnAnArrayOfOrigins()
56 | {
57 | $this->scopeConfigMock
58 | ->method('getValue')->willReturn('https://www.example.com, ,https://www.myother.valid.domain ');
59 | $this->assertEquals(
60 | ['https://www.example.com', 'https://www.myother.valid.domain'],
61 | $this->configuration->getAllowedOrigins()
62 | );
63 | }
64 |
65 | public function testIfAllowCredentialsNotConfiguredItWillReturnFalse()
66 | {
67 | $this->scopeConfigMock->method('isSetFlag')->willReturn(false);
68 | $this->assertEquals(false, $this->configuration->getAllowCredentials());
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Test/Integration/Preflight/GraphQlResponseTest.php:
--------------------------------------------------------------------------------
1 | addHeaderLine('Origin: ' . $origin);
28 | $headers->addHeaderLine('Content-Type: application/json');
29 | $this->getRequest()->setMethod('OPTIONS')->setHeaders($headers)
30 | ->setContent('{"query": "{products(search:\"Pierce\"){total_count}}"}');
31 | $this->dispatch('/graphql');
32 | }
33 |
34 | public function testItDoesNotAddAnyCrossOriginHeadersOutOfTheBox()
35 | {
36 | $this->dispatchToGraphQlApiWithOrigin("https://www.example.com");
37 |
38 | /** @var Http $response */
39 | $response = $this->getResponse();
40 | $this->assertFalse($response->getHeader('Access-Control-Allow-Origin'));
41 | $this->assertFalse($response->getHeader('Access-Control-Max-Age'));
42 | }
43 |
44 | /**
45 | * @magentoConfigFixture default/web/graphql/cors_allowed_origins https://www.example.com
46 | */
47 | public function testItdoesNotAddAnyCrossOriginHeadersToATypicalRequest()
48 | {
49 | $this->dispatch('/');
50 |
51 | /** @var Http $response */
52 | $response = $this->getResponse();
53 | $this->assertFalse($response->getHeader('Access-Control-Allow-Origin'));
54 | }
55 |
56 | /**
57 | * @magentoConfigFixture default/web/graphql/cors_allowed_origins https://www.example.com
58 | */
59 | public function testTheGraphQlPreflightResponseContainsCrossOriginHeaders()
60 | {
61 | $this->dispatchToGraphQlApiWithOrigin("https://www.example.com");
62 |
63 | /** @var Http $response */
64 | $response = $this->getResponse();
65 | $this->assertNotFalse($response->getHeader('Access-Control-Allow-Origin'));
66 | $this->assertNotFalse($response->getHeader('Access-Control-Max-Age'));
67 | $this->assertSame(200, $response->getHttpResponseCode());
68 | $this->assertEquals("", $response->getBody());
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Response/HeaderProvider/CorsAllowOriginHeaderProvider.php:
--------------------------------------------------------------------------------
1 | validator = $validator;
56 | $this->configuration = $configuration;
57 | $this->request = $request;
58 | }
59 |
60 | /**
61 | * Check if allowed origin is wildcard.
62 | *
63 | * @return bool
64 | */
65 | private function allowedOriginIsWildcard()
66 | {
67 | return in_array('*', $this->configuration->getAllowedOrigins());
68 | }
69 |
70 | /**
71 | * Determine if the header can be applied.
72 | *
73 | * @return bool
74 | */
75 | public function canApply()
76 | {
77 | return $this->validator->originIsValid() && $this->getValue();
78 | }
79 |
80 | /**
81 | * Get the header value.
82 | *
83 | * @return string
84 | */
85 | public function getValue()
86 | {
87 | if ($this->configuration->getAllowCredentials() && $this->allowedOriginIsWildcard()) {
88 | return $this->request->getHeader('Origin');
89 | }
90 |
91 | return $this->allowedOriginIsWildcard() ? '*' : $this->request->getHeader('Origin');
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/etc/graphql/di.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | - Graycore\Cors\Response\HeaderProvider\CorsAllowHeadersHeaderProvider
9 | - Graycore\Cors\Response\HeaderProvider\CorsAllowOriginHeaderProvider
10 | - Graycore\Cors\Response\HeaderProvider\CorsAllowMethodsHeaderProvider
11 | - Graycore\Cors\Response\HeaderProvider\CorsMaxAgeHeaderProvider
12 | - Graycore\Cors\Response\HeaderProvider\CorsExposeHeadersProvider
13 | - Graycore\Cors\Response\HeaderProvider\CorsAllowCredentialsHeaderProvider
14 | - Graycore\Cors\Response\HeaderProvider\CorsVaryHeaderProvider
15 |
16 |
17 |
18 |
19 |
20 |
21 | - Graycore\Cors\Response\HeaderProvider\CorsAllowHeadersHeaderProvider
22 | - Graycore\Cors\Response\HeaderProvider\CorsAllowOriginHeaderProvider
23 | - Graycore\Cors\Response\HeaderProvider\CorsAllowMethodsHeaderProvider
24 | - Graycore\Cors\Response\HeaderProvider\CorsMaxAgeHeaderProvider
25 | - Graycore\Cors\Response\HeaderProvider\CorsExposeHeadersProvider
26 | - Graycore\Cors\Response\HeaderProvider\CorsAllowCredentialsHeaderProvider
27 | - Graycore\Cors\Response\HeaderProvider\CorsVaryHeaderProvider
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/Test/Integration/Response/GraphQlResponseTest.php:
--------------------------------------------------------------------------------
1 | addHeaderLine('Origin: ' . $origin);
28 | $headers->addHeaderLine('Content-Type: application/json');
29 | $this->getRequest()->setMethod('POST')->setHeaders($headers)
30 | ->setContent('{"query": "{products(search:\"Pierce\"){total_count}}"}');
31 | $this->dispatch('/graphql');
32 | }
33 |
34 | /**
35 | * @magentoConfigFixture default/web/graphql/cors_allowed_origins https://www.example.com
36 | */
37 | public function testItdoesNotAddAnyCrossOriginHeadersToATypicalRequest()
38 | {
39 | $headers = new Headers();
40 | $headers->addHeaderLine('Origin: https://www.example.com');
41 | $this->dispatch('/');
42 |
43 | /** @var Http $response */
44 | $response = $this->getResponse();
45 | $this->assertFalse($response->getHeader('Access-Control-Allow-Origin'));
46 | }
47 |
48 | public function testItDoesNotAddAnyCrossOriginHeadersOutOfTheBox()
49 | {
50 | $this->dispatchToGraphQlApiWithOrigin("https://www.example.com");
51 |
52 | /** @var Http $response */
53 | $response = $this->getResponse();
54 | $this->assertFalse($response->getHeader('Access-Control-Allow-Origin'));
55 | $this->assertFalse($response->getHeader('Access-Control-Max-Age'));
56 | }
57 |
58 | /**
59 | * @magentoConfigFixture default/web/api_rest/cors_allowed_origins https://www.example.com
60 | */
61 | public function testTheGraphQlApiWillResponseToACorsRequestWithA200Response()
62 | {
63 | $this->dispatchToGraphQlApiWithOrigin('https://www.example.com');
64 |
65 | /** @var Http $response */
66 | $response = $this->getResponse();
67 | $this->assertSame(200, $response->getHttpResponseCode());
68 | }
69 |
70 | /**
71 | * @magentoConfigFixture default/web/graphql/cors_allowed_origins https://www.example.com
72 | */
73 | public function testTheGraphQlResponseContainsCrossOriginHeaders()
74 | {
75 | $this->dispatchToGraphQlApiWithOrigin("https://www.example.com");
76 |
77 | /** @var Http $response */
78 | $response = $this->getResponse();
79 | $this->assertNotFalse($response->getHeader('Access-Control-Allow-Origin'));
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/docs/stories/no-wild-card.md:
--------------------------------------------------------------------------------
1 | The `Access-Control-Allow-Origin` header (a key piece of the CORS protocol) plays a crucial role in determining which websites are allowed to access resources from a server. This header allows a server to specify which origins are allowed to access its resources, thereby providing a security layer to protect against unauthorized access.
2 |
3 | However, there is a particular case where developers sometimes use the wildcard `*` value for the `Access-Control-Allow-Origin` header, which means that any origin is allowed to access the server's resources. While this might seem like a convenient shortcut, it is a particularly bad idea to use this approach. It is even more unfortunate that many documentation websites and articles geared toward developers broadly recommend this.
4 |
5 | The primary reason why using the wildcard `*` value for `Access-Control-Allow-Origin` is not recommended is that it opens up the server to potential security risks. By allowing any website to access its resources, the server becomes vulnerable to cross-site scripting (XSS) attacks, where malicious code can be injected into the server's response and executed in the user's browser. This can result in sensitive user data being stolen or manipulated, and the attacker gaining unauthorized access to the server's resources. Moreover, when any origin is allowed to access its resources, anyone can replicate the HTML/CSS/JS that exists on a website, copy it to another domain, `www.hackerwebsite.com` for instance. Now, to the end user, everything not only looks the same, but it also allows them to access their information on a potentially malicious client that may not only look exactly the way they expect, but also act exactly the same.
6 |
7 | For an example, let's say there is a server with the URL "https://example.com" that allows any origin to access its resources by setting the `Access-Control-Allow-Origin` header to "*". An attacker can create a fake website with the URL "https://malicious.com" and inject a script that sends a request to the server using the user's credentials.
8 |
9 | Here are some example cURL commands that demonstrate the attack:
10 |
11 | A legitimate request to the server as if made by a client that respects the CORS protocol (A web browser for example):
12 |
13 | ```bash
14 | curl https://example.com/api/data \
15 | -H 'Origin: https://example.com' \
16 | -H 'Authorization: Bearer '
17 | ```
18 |
19 | This request sends an authorization token to the server and retrieves data from the API.
20 |
21 | An attack using the malicious website:
22 |
23 | ```bash
24 | curl https://example.com/api/data \
25 | -H 'Origin: https://malicious.com' \
26 | -H 'Authorization: Bearer '
27 | ```
28 |
29 | This request sends the same authorization token to the server but with a different origin, which is the malicious website. Since the server allows any origin to access its resources, the request will be accepted, and the attacker can retrieve sensitive data from the server's API.
30 |
31 | In conclusion, using the wildcard (*) value for Access-Control-Allow-Origin is not recommended due to the potential security risks and privacy violations. Instead, developers should take the time to specify the appropriate origins that are allowed to access their server's resources, ensuring that their website is secure, compliant, and provides a good user experience.
32 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment
10 | include:
11 |
12 | * Using welcoming and inclusive language
13 | * Being respectful of differing viewpoints and experiences
14 | * Gracefully accepting constructive criticism
15 | * Focusing on what is best for the community
16 | * Showing empathy towards other community members
17 |
18 | Examples of unacceptable behavior by participants include:
19 |
20 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
21 | * Trolling, insulting/derogatory comments, and personal or political attacks
22 | * Public or private harassment
23 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
24 | * Other conduct which could reasonably be considered inappropriate in a professional setting
25 |
26 | ## Our Responsibilities
27 |
28 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
29 |
30 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
31 |
32 | ## Scope
33 |
34 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
35 |
36 | ## Enforcement
37 |
38 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project lead at [damien@graycore.io](mailto:damien@graycore.io). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
39 |
40 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
41 |
42 | ## Attribution
43 |
44 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
45 |
46 | [homepage]: https://www.contributor-covenant.org
47 |
--------------------------------------------------------------------------------
/Test/Integration/Preflight/WebApiResponseTest.php:
--------------------------------------------------------------------------------
1 | _response) {
29 | $this->_response = $this->_objectManager->get(\Magento\Framework\Webapi\Rest\Response::class);
30 | }
31 | return $this->_response;
32 | }
33 |
34 | private function dispatchToRestApi()
35 | {
36 | ob_start();
37 | $this->dispatch(self::ENDPOINT);
38 | $this->getResponse()->sendResponse();
39 | ob_end_clean();
40 | }
41 |
42 | private function dispatchToRestApiWithOrigin(string $origin)
43 | {
44 | $headers = new Headers();
45 | $headers->addHeaderLine('Origin: ' . $origin);
46 | $headers->addHeaderLine('Content-Type: application/json');
47 | $this->getRequest()->setMethod('OPTIONS')->setHeaders($headers);
48 | ob_start();
49 | $this->dispatch(self::ENDPOINT);
50 | $this->getResponse()->sendResponse();
51 | ob_end_clean();
52 | }
53 |
54 | public function testItDoesNotAddAnyCrossOriginHeadersOutOfTheBox()
55 | {
56 | $this->dispatchToRestApiWithOrigin("https://www.example.com");
57 |
58 | /** @var Http $response */
59 | $response = $this->getResponse();
60 | $this->assertFalse($response->getHeader('Access-Control-Allow-Origin'));
61 | $this->assertFalse($response->getHeader('Access-Control-Max-Age'));
62 | }
63 |
64 | /**
65 | * @magentoConfigFixture default/web/api_rest/cors_allowed_origins https://www.example.com
66 | */
67 | public function testItdoesNotAddAnyCrossOriginHeadersToATypicalRequest()
68 | {
69 | $this->dispatchToRestApi();
70 |
71 | /** @var Http $response */
72 | $response = $this->getResponse();
73 | $this->assertFalse($response->getHeader('Access-Control-Allow-Origin'));
74 | }
75 |
76 | /**
77 | * @magentoConfigFixture default/web/api_rest/cors_allowed_origins https://www.example.com
78 | */
79 | public function testTheWebApiPreflightResponseContainsCrossOriginHeaders()
80 | {
81 | $this->dispatchToRestApiWithOrigin("https://www.example.com");
82 |
83 | /** @var Http $response */
84 | $response = $this->getResponse();
85 | $this->assertNotFalse($response->getHeader('Access-Control-Allow-Origin'));
86 | $this->assertNotFalse($response->getHeader('Access-Control-Max-Age'));
87 | $this->assertSame(200, $response->getHttpResponseCode());
88 | $this->assertEquals("", $response->getBody());
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/Validator/CorsValidator.php:
--------------------------------------------------------------------------------
1 | configuration = $configuration;
35 | $this->request = $request;
36 | }
37 |
38 | /**
39 | * Determines whether or not the request origin is one of the origins configured for the application.
40 | *
41 | * @return bool
42 | */
43 | private function requestOriginExistsInConfiguration()
44 | {
45 | return in_array($this->request->getHeader('Origin'), $this->configuration->getAllowedOrigins());
46 | }
47 |
48 | /**
49 | * Determines whether or the configuration specifies that all origins should be allowed.
50 | *
51 | * @return bool
52 | */
53 | private function configurationIsWildcard(): bool
54 | {
55 | return in_array('*', $this->configuration->getAllowedOrigins());
56 | }
57 |
58 | /**
59 | * Determines whether or not the origin of a request is valid and should have CORS headers applied.
60 | *
61 | * @return bool
62 | */
63 | public function originIsValid(): bool
64 | {
65 | if ($this->request instanceof HttpRequest) {
66 | //Validate that we're working with something that cares about CORS
67 | if (!$this->originHeaderExists()) {
68 | return false;
69 | }
70 |
71 | return $this->configurationIsWildcard() || $this->requestOriginExistsInConfiguration();
72 | }
73 |
74 | return false;
75 | }
76 |
77 | /**
78 | * @inheritdoc
79 | */
80 | public function isPreflightRequest(): bool
81 | {
82 | if ($this->request instanceof HttpRequest) {
83 | return $this->request->getMethod() == "OPTIONS" && $this->originHeaderExists();
84 | }
85 |
86 | return false;
87 | }
88 |
89 | /**
90 | * Determines whether an origin header exists with a valid scheme.
91 | *
92 | * @return bool
93 | */
94 | private function originHeaderExists(): bool
95 | {
96 | try {
97 | return $this->request->getHeader('Origin') ? true : false;
98 | } catch (\InvalidArgumentException $exception) {
99 | // In the event of an invalid URI scheme, e.g. chrome-extension://
100 | return false;
101 | }
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/Test/Integration/Response/WebApiResponseTest.php:
--------------------------------------------------------------------------------
1 | _response) {
27 | $this->_response = $this->_objectManager->get(\Magento\Framework\Webapi\Rest\Response::class);
28 | }
29 | return $this->_response;
30 | }
31 |
32 | private function dispatchToRestApi()
33 | {
34 | ob_start();
35 | $this->dispatch(self::ENDPOINT);
36 | $this->getResponse()->sendResponse();
37 | ob_end_clean();
38 | }
39 |
40 | private function dispatchToRestApiWithOrigin(string $origin)
41 | {
42 | $headers = new Headers();
43 | $headers->addHeaderLine('Origin: ' . $origin);
44 | $headers->addHeaderLine('Content-Type: application/json');
45 | $this->getRequest()->setMethod('GET')->setHeaders($headers);
46 | ob_start();
47 | $this->dispatch(self::ENDPOINT);
48 | $this->getResponse()->sendResponse();
49 | ob_end_clean();
50 | }
51 |
52 | /**
53 | * @magentoConfigFixture default/web/api_rest/cors_allowed_origins https://www.example.com
54 | */
55 | public function testItdoesNotAddAnyCrossOriginHeadersToATypicalRequest()
56 | {
57 | $this->dispatchToRestApi();
58 |
59 | /** @var Http $response */
60 | $response = $this->getResponse();
61 | $this->assertFalse($response->getHeader('Access-Control-Allow-Origin'));
62 | }
63 |
64 | public function testItDoesNotAddAnyCrossOriginHeadersOutOfTheBox()
65 | {
66 | $this->dispatchToRestApiWithOrigin("https://www.example.com");
67 |
68 | /** @var Http $response */
69 | $response = $this->getResponse();
70 | $this->assertFalse($response->getHeader('Access-Control-Allow-Origin'));
71 | $this->assertFalse($response->getHeader('Access-Control-Max-Age'));
72 | }
73 |
74 | /**
75 | * @magentoConfigFixture default/web/api_rest/cors_allowed_origins https://www.example.com
76 | */
77 | public function testTheRestApiWillResponseToACorsRequestWithA200Response()
78 | {
79 | $this->dispatchToRestApiWithOrigin('https://www.example.com');
80 |
81 | /** @var Http $response */
82 | $response = $this->getResponse();
83 | $this->assertSame(200, $response->getHttpResponseCode());
84 | }
85 |
86 | /**
87 | * @magentoConfigFixture default/web/api_rest/cors_allowed_origins https://www.example.com
88 | */
89 | public function testTheRestApiResponseContainsCrossOriginHeaders()
90 | {
91 | $this->dispatchToRestApiWithOrigin("https://www.example.com");
92 |
93 | /** @var Http $response */
94 | $response = $this->getResponse();
95 |
96 | $this->assertNotFalse($response->getHeader('Access-Control-Allow-Origin'));
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Magento 2 CORS
2 |
3 |
4 |
5 | [](https://packagist.org/packages/graycore/magento2-cors/stats)
6 | [](https://packagist.org/packages/graycore/magento2-cors)
7 | [](https://github.com/graycoreio/magento2-cors/blob/master/LICENSE)
8 | [](https://github.com/graycoreio/magento2-cors/actions/workflows/unit.yaml)
9 | [](https://github.com/graycoreio/magento2-cors/actions/workflows/integration.yaml)
10 | [](https://github.com/graycoreio/magento2-cors/actions/workflows/install.yaml)
11 |
12 |
13 |
14 |
15 | ## Magento Version Support
16 | 
17 | 
18 |
19 | Ever try to work with the Magento GraphQL API or REST API from your browser and see the following?
20 |
21 | ```txt
22 | Access to XMLHttpRequest at 'https://my.magento.app' from origin 'http://my.webapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
23 | ```
24 |
25 | This package allows you to securely add the necessary CORS headers to the Magento 2 GraphQL or REST APIs with ease.
26 |
27 | ## Purpose
28 | When building a headless application for Magento, or working with a client that respects the CORS protocol, you will need [CORS headers](https://fetch.spec.whatwg.org/#http-cors-protocol) on your backend resource.
29 |
30 | This package will add configurable CORS Resource headers to the Magento 2 GraphQL or REST APIs, allowing you to access the GraphQL or REST APIs from your browser.
31 |
32 | ## Getting Started
33 | This module is intended to be installed with [composer](https://getcomposer.org/). From the root of your Magento 2 project:
34 |
35 | 1. Download the package
36 | ```bash
37 | composer require graycore/magento2-cors
38 | ```
39 | 2. [Configure the package](/docs/stories/configuring-the-headers.md)
40 | 3. Enable the package
41 |
42 | ```bash
43 | ./bin/magento module:enable Graycore_Cors
44 | ```
45 |
46 | ## Features
47 | * [Configurable](./docs/stories/configuring-the-headers.md)
48 | * [Respects the full CORS Protocol](https://fetch.spec.whatwg.org/#http-cors-protocol)
49 | * `Access-Control-Allow-Origin`
50 | * `Access-Control-Allow-Methods`
51 | * `Access-Control-Allow-Headers`
52 | * `Access-Control-Max-Age`
53 | * `Access-Control-Expose-Headers`
54 | * `Access-Control-Allow-Credentials`
55 |
56 | * [Security By Default](./docs/stories/security.md#security-by-default)
57 | * [Vary: Origin](https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches)
58 | ## Helpful Links
59 | * [FAQ](./docs/faq/faqs.md)
60 | * [Can I configure this from the admin panel?](./docs/faq/faqs.md#can-i-configure-this-from-the-admin-panel)
61 |
62 | ## Upgrading
63 | * [Semver Policy](https://semver.org/)
64 | * [Guide](./docs/upgrading/guide.md)
65 |
--------------------------------------------------------------------------------
/docs/stories/configuring-the-headers.md:
--------------------------------------------------------------------------------
1 | # Configuring CORS Headers
2 |
3 | ## Available Configurations
4 | We provide several configuration keys for you to configure. The configurations between REST and GraphQL are split to accomodate the "Security by Default" mentality.
5 |
6 | * `web/graphql/cors_allowed_origins` - A comma separated list of the origins allowed to the access the GraphQL API
7 | * `web/graphql/cors_allowed_methods` - A comma separated list of the allowed request methods
8 | * `web/graphql/cors_allowed_headers` - A comma separated list of the allowed response headers
9 | * `web/graphql/cors_max_age` - The duration that the CORS policy should be cached for.
10 | * `web/graphql/cors_expose_headers` - A comma separated list that indicates which headers can be exposed as part of the response.
11 | * `web/graphql/cors_allow_credentials` - Whether to allow credentials on CORS requests
12 |
13 | * `web/api_rest/cors_allowed_origins` - A comma separated list of the origins allowed to the access the REST API
14 | * `web/api_rest/cors_allowed_methods` - A comma separated list of the allowed request methods
15 | * `web/api_rest/cors_allowed_headers` - A comma separated list of the allowed response headers
16 | * `web/api_rest/cors_max_age` - The duration that the CORS policy should be cached for.
17 | * `web/api_rest/cors_expose_headers` - A comma separated list that indicates which headers can be exposed as part of the response.
18 | * `web/api_rest/cors_allow_credentials` - Whether to allow credentials on CORS requests
19 |
20 | ### Configuring for local or on-premises installations
21 |
22 | You can add the following to your `app/etc/env.php` to configure the package.
23 |
24 | ```php
25 | [
29 | 'default' => [
30 | 'web' => [
31 | 'graphql' => [
32 | 'cors_allowed_origins' => 'https://www.graphql.com, https://www.myotherallowedorigin',
33 | 'cors_allowed_methods' => 'POST, OPTIONS',
34 | 'cors_allowed_headers' => '',
35 | 'cors_max_age' => '86400',
36 | 'cors_allow_credentials' => 1
37 | ],
38 | 'api_rest' => [
39 | 'cors_allowed_origins' => 'https://www.restapi.com, https://www.myotherallowedorigin',
40 | 'cors_allowed_methods' => 'GET, POST, OPTIONS',
41 | 'cors_allowed_headers' => '',
42 | 'cors_max_age' => '86400',
43 | 'cors_allow_credentials' => 0
44 | ]
45 | ]
46 | ]
47 | ]
48 | ...
49 | ];
50 | ```
51 |
52 | > You can also optionally set the `cors_allowed_origins` key to `*` if you want to allow ALL origins access to the resource, but we strongly suggest you [understand the ramifications of this before doing so.](/docs/stories/no-wild-card.md)
53 | Note also that the CORS specification disallows a wildcard for Allowed Origins if the `cors_allow_credentials` flag is enabled. If this is the case, the server will instead echo the request Origin back as the Allow-Origin value.
54 |
55 | ### Configuring for Commerce Cloud
56 |
57 | In Commerce Cloud environments, the app/etc/env.php file is unavailable for configuring this module. Instead, use the cloud UI to set ENV settings, as documented at https://experienceleague.adobe.com/docs/commerce-cloud-service/user-guide/configure/env/variable-levels.html and https://experienceleague.adobe.com/en/docs/commerce-operations/configuration-guide/paths/override-config-settings.
58 | Here's an example of syntax for the cors_allowed_methods value:
59 | 
60 |
61 | ## Examples
62 | * [PWAs (Angular, PWA Studio, etc)](./examples/pwa-configuration.php)
63 |
--------------------------------------------------------------------------------
/Configuration/GraphQl/CorsConfiguration.php:
--------------------------------------------------------------------------------
1 | cleaner = new ConfigurationCleaner();
47 | $this->scopeConfig = $scopeConfig;
48 | }
49 |
50 | /**
51 | * Takes the configuration for Cors Origins and parses it into an array of allowed origins.
52 | *
53 | * @return array
54 | */
55 | public function getAllowedOrigins(): array
56 | {
57 | return $this->cleaner->processDelimitedString(
58 | $this->scopeConfig->getValue(self::XML_PATH_GRAPHQL_CORS_ORIGINS)
59 | );
60 | }
61 |
62 | /**
63 | * Retrieves the allowed CORS headers from configuration.
64 | *
65 | * @return array
66 | */
67 | public function getAllowedHeaders(): array
68 | {
69 | return $this->cleaner->processDelimitedString(
70 | $this->scopeConfig->getValue(self::XML_PATH_GRAPHQL_CORS_HEADERS)
71 | );
72 | }
73 |
74 | /**
75 | * Get the allowed methods.
76 | *
77 | * @return string[]
78 | */
79 | public function getAllowedMethods(): array
80 | {
81 | return $this->cleaner->processDelimitedString(
82 | $this->scopeConfig->getValue(self::XML_PATH_GRAPHQL_CORS_METHODS)
83 | );
84 | }
85 |
86 | /**
87 | * Get the max age value.
88 | *
89 | * @return string
90 | */
91 | public function getMaxAge(): string
92 | {
93 | return $this->scopeConfig->getValue(self::XML_PATH_GRAPHQL_CORS_MAX_AGE);
94 | }
95 |
96 | /**
97 | * Get whether credentials are allowed.
98 | *
99 | * @return bool
100 | */
101 | public function getAllowCredentials(): bool
102 | {
103 | return $this->scopeConfig->isSetFlag(self::XML_PATH_GRAPHQL_CORS_CREDENTIALS);
104 | }
105 |
106 | /**
107 | * Get the exposed headers.
108 | *
109 | * @return string[]
110 | */
111 | public function getExposedHeaders(): array
112 | {
113 | return $this->cleaner->processDelimitedString(
114 | $this->scopeConfig->getValue(self::XML_PATH_GRAPHQL_CORS_EXPOSE_HEADERS)
115 | );
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/Configuration/Rest/CorsConfiguration.php:
--------------------------------------------------------------------------------
1 | cleaner = new ConfigurationCleaner();
49 | $this->scopeConfig = $scopeConfig;
50 | }
51 |
52 | /**
53 | * Takes the configuration for Cors Origins and parses it into an array of allowed origins.
54 | *
55 | * @return array
56 | */
57 | public function getAllowedOrigins(): array
58 | {
59 | return $this->cleaner->processDelimitedString(
60 | $this->scopeConfig->getValue(self::XML_PATH_WEBAPI_REST_CORS_ORIGINS)
61 | );
62 | }
63 |
64 | /**
65 | * Retrieves the allowed CORS headers from configuration.
66 | *
67 | * @return array
68 | */
69 | public function getAllowedHeaders(): array
70 | {
71 | return $this->cleaner->processDelimitedString(
72 | $this->scopeConfig->getValue(self::XML_PATH_WEBAPI_REST_CORS_HEADERS)
73 | );
74 | }
75 |
76 | /**
77 | * Get the allowed methods.
78 | *
79 | * @return string[]
80 | */
81 | public function getAllowedMethods(): array
82 | {
83 | return $this->cleaner->processDelimitedString(
84 | $this->scopeConfig->getValue(self::XML_PATH_WEBAPI_REST_CORS_METHODS)
85 | );
86 | }
87 |
88 | /**
89 | * Get the max age value.
90 | *
91 | * @return string
92 | */
93 | public function getMaxAge(): string
94 | {
95 | return $this->scopeConfig->getValue(self::XML_PATH_WEBAPI_REST_CORS_MAX_AGE);
96 | }
97 |
98 | /**
99 | * Get whether credentials are allowed.
100 | *
101 | * @return bool
102 | */
103 | public function getAllowCredentials(): bool
104 | {
105 | return $this->scopeConfig->isSetFlag(self::XML_PATH_REST_CORS_CREDENTIALS);
106 | }
107 |
108 | /**
109 | * Get the exposed headers.
110 | *
111 | * @return string[]
112 | */
113 | public function getExposedHeaders(): array
114 | {
115 | return $this->cleaner->processDelimitedString(
116 | $this->scopeConfig->getValue(self::XML_PATH_WEBAPI_REST_CORS_EXPOSE_HEADERS)
117 | );
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/Test/Unit/HeaderProvider/CorsMaxAgeHeaderProviderTest.php:
--------------------------------------------------------------------------------
1 | corsValidatorMock = $this->createMock(CorsValidatorInterface::class);
48 | $this->corsConfigurationMock = $this->createMock(CorsConfigurationInterface::class);
49 | $this->provider = new CorsMaxAgeHeaderProvider($this->corsConfigurationMock, $this->corsValidatorMock);
50 | }
51 |
52 | public function testGetName()
53 | {
54 | $this->assertEquals($this::HEADER_NAME, $this->provider->getName(), 'Wrong header name');
55 | }
56 |
57 | public function testGetValue()
58 | {
59 | $this->assertEquals($this::HEADER_VALUE, $this->provider->getValue(), 'Wrong default header value');
60 | }
61 |
62 | /**
63 | * @dataProvider canApplyDataProvider
64 | */
65 | public function testCanApply($maxAge, $originResult, $isPreflightRequest, $expected)
66 | {
67 | $this->corsConfigurationMock->method('getMaxAge')->willReturn($maxAge);
68 | $this->corsValidatorMock->method('originIsValid')->willReturn($originResult);
69 | $this->corsValidatorMock->method('isPreflightRequest')->willReturn($isPreflightRequest);
70 | $this->assertEquals($expected, $this->provider->canApply(), 'Incorrect canApply result');
71 | }
72 |
73 | public function canApplyDataProvider()
74 | {
75 | return [
76 | 'invalid origin, cors request' => [
77 | '1000',
78 | false,
79 | false,
80 | false,
81 | ],
82 | 'invalid origin, preflight request' => [
83 | '1000',
84 | false,
85 | true,
86 | false,
87 | ],
88 | 'valid origin, cors request with null configured maxAge' => [
89 | null,
90 | true,
91 | false,
92 | false,
93 | ],
94 | 'valid origin, preflight request with null configured maxAge' => [
95 | null,
96 | true,
97 | true,
98 | true,
99 | ],
100 | 'valid origin, cors request with empty configured maxAge' => [
101 | '',
102 | true,
103 | false,
104 | false,
105 | ],
106 | 'valid origin, preflight request with empty configured maxAge' => [
107 | '',
108 | true,
109 | true,
110 | true,
111 | ],
112 | 'valid origin, cors request with configured age' => [
113 | '86400',
114 | true,
115 | false,
116 | false,
117 | ],
118 | 'valid origin, preflight request with configured age' => [
119 | '86400',
120 | true,
121 | true,
122 | true,
123 | ],
124 | ];
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/Test/Unit/HeaderProvider/CorsAllowOriginHeaderProviderTest.php:
--------------------------------------------------------------------------------
1 | corsValidatorMock = $this->createMock(CorsValidatorInterface::class);
55 | $this->requestMock = $this->createMock(Http::class);
56 | $this->corsConfigurationMock = $this->createMock(CorsConfigurationInterface::class);
57 |
58 | $this->provider = new CorsAllowOriginHeaderProvider(
59 | $this->corsValidatorMock,
60 | $this->corsConfigurationMock,
61 | $this->requestMock
62 | );
63 | }
64 |
65 | public function testGetName()
66 | {
67 | $this->assertEquals($this::HEADER_NAME, $this->provider->getName(), 'Wrong header name');
68 | }
69 |
70 | public function testGetDefaultHeaderValue()
71 | {
72 | $this->assertEquals($this::HEADER_VALUE, $this->provider->getValue(), 'Wrong default header value');
73 | }
74 |
75 | /**
76 | * @dataProvider getValueDataProvider
77 | */
78 | public function testGetValue($allowedOrigins, $originHeader, $expected)
79 | {
80 | $this->corsConfigurationMock->method('getAllowedOrigins')->willReturn($allowedOrigins);
81 | $this->requestMock->method('getHeader')->willReturn($originHeader);
82 | $this->assertEquals($expected, $this->provider->getValue());
83 | }
84 |
85 | public function getValueDataProvider()
86 | {
87 | return [
88 | 'valid origin' => [
89 | ['https://www.google.com', 'https://www.example.com'],
90 | 'https://www.example.com',
91 | 'https://www.example.com',
92 | ],
93 | 'wildcard origin' => [
94 | ['*'],
95 | 'https://www.example.com',
96 | '*',
97 | ],
98 | ];
99 | }
100 |
101 | /**
102 | * @dataProvider canApplyDataProvider
103 | */
104 | public function testCanApply($originIsValid, $requestOrigin, $expected)
105 | {
106 | $this->requestMock->method('getHeader')->willReturn($requestOrigin);
107 | $this->corsValidatorMock->method('originIsValid')->willReturn($originIsValid);
108 |
109 | $this->assertEquals($expected, $this->provider->canApply(), 'Incorrect canApply result');
110 | }
111 |
112 | public function canApplyDataProvider()
113 | {
114 | return [
115 | 'invalid origin' => [
116 | false,
117 | 'https://www.someorigin.com',
118 | false,
119 | ],
120 | 'valid origin' => [
121 | true,
122 | 'https://www.someorigin.com',
123 | true,
124 | ],
125 | ];
126 | }
127 |
128 | public function testWildcardOriginWithAllowCredentials()
129 | {
130 | $this->corsConfigurationMock->method('getAllowedOrigins')->willReturn(["*"]);
131 | $this->corsConfigurationMock->method('getAllowCredentials')->willReturn(true);
132 | $this->requestMock->method('getHeader')->willReturn("www.example.com");
133 | $this->assertEquals("www.example.com", $this->provider->getValue());
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/Test/Unit/HeaderProvider/CorsAllowMethodsHeaderProviderTest.php:
--------------------------------------------------------------------------------
1 | corsValidatorMock = $this->createMock(CorsValidatorInterface::class);
47 | $this->corsConfigurationMock = $this->createMock(CorsConfigurationInterface::class);
48 | $this->provider = new CorsAllowMethodsHeaderProvider($this->corsConfigurationMock, $this->corsValidatorMock);
49 | }
50 |
51 | public function testGetName()
52 | {
53 | $this->assertEquals($this::HEADER_NAME, $this->provider->getName(), 'Wrong header name');
54 | }
55 |
56 | public function testGetDefaultHeaderValue()
57 | {
58 | $this->assertEquals($this::HEADER_VALUE, $this->provider->getValue(), 'Wrong default header value');
59 | }
60 |
61 | public function testGetValueWillReturnTheDefaultValueIfTheConfigurationIsEmpty()
62 | {
63 | $stubMethods = [];
64 | $this->corsConfigurationMock->method('getAllowedMethods')->willReturn($stubMethods);
65 | $this->assertEquals('GET,POST,OPTIONS', $this->provider->getValue());
66 | }
67 |
68 | public function testItUsesTheValueDefinedByScope()
69 | {
70 | $stubMethods = ['GET'];
71 | $this->corsConfigurationMock->method('getAllowedMethods')->willReturn($stubMethods);
72 | $this->assertEquals('GET', $this->provider->getValue());
73 | }
74 |
75 | public function testItWillReturnACommaSeparatedListOfHeadersIfThereAreMultipleHeadersConfigured()
76 | {
77 | $stubMethods = ['GET', 'POST', 'OPTIONS'];
78 | $this->corsConfigurationMock->method('getAllowedMethods')->willReturn($stubMethods);
79 | $this->assertEquals('GET,POST,OPTIONS', $this->provider->getValue());
80 | }
81 |
82 | /**
83 | * @dataProvider canApplyDataProvider
84 | */
85 | public function testCanApply($methods, $originResult, $isPreflightRequest, $expected)
86 | {
87 | $this->corsConfigurationMock->method('getAllowedMethods')->willReturn($methods);
88 | $this->corsValidatorMock->method('originIsValid')->willReturn($originResult);
89 | $this->corsValidatorMock->method('isPreflightRequest')->willReturn($isPreflightRequest);
90 | $this->assertEquals($expected, $this->provider->canApply(), 'Incorrect canApply result');
91 | }
92 |
93 | public function canApplyDataProvider()
94 | {
95 | return [
96 | 'invalid origin, cors request' => [
97 | ['GET', 'POST', 'OPTIONS'],
98 | false,
99 | false,
100 | false,
101 | ],
102 | 'invalid origin, preflight request' => [
103 | ['GET', 'POST', 'OPTIONS'],
104 | false,
105 | true,
106 | false,
107 | ],
108 | 'valid origin, cors request, without configured methods' => [
109 | [],
110 | true,
111 | false,
112 | false,
113 | ],
114 | 'valid origin, preflight request, without configured methods' => [
115 | [],
116 | true,
117 | true,
118 | true,
119 | ],
120 | 'valid origin, cors request, with configured methods' => [
121 | ['GET', 'POST', 'OPTIONS'],
122 | true,
123 | false,
124 | false,
125 | ],
126 | 'valid origin, preflight request, with configured methods' => [
127 | ['GET', 'POST', 'OPTIONS'],
128 | true,
129 | true,
130 | true,
131 | ],
132 | ];
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/Test/Unit/HeaderProvider/CorsAllowHeadersHeaderProviderTest.php:
--------------------------------------------------------------------------------
1 | corsValidatorMock = $this->createMock(CorsValidatorInterface::class);
47 | $this->corsConfigurationMock = $this->createMock(CorsConfigurationInterface::class);
48 | $this->provider = new CorsAllowHeadersHeaderProvider($this->corsConfigurationMock, $this->corsValidatorMock);
49 | }
50 |
51 | public function testGetName()
52 | {
53 | $this->assertEquals($this::HEADER_NAME, $this->provider->getName(), 'Wrong header name');
54 | }
55 |
56 | public function testGetDefaultHeaderValue()
57 | {
58 | $this->assertEquals($this::HEADER_VALUE, $this->provider->getValue(), 'Wrong default header value');
59 | }
60 |
61 | public function testGetValueWillReturnAnEmptyStringIfTheConfigurationIsEmpty()
62 | {
63 | $stubHeaders = [];
64 | $this->corsConfigurationMock->method('getAllowedHeaders')->willReturn($stubHeaders);
65 | $this->assertEquals('', $this->provider->getValue());
66 | }
67 |
68 | public function testItUsesTheValueDefinedByScope()
69 | {
70 | $stubHeaders = ['My-Custom-Header'];
71 | $this->corsConfigurationMock->method('getAllowedHeaders')->willReturn($stubHeaders);
72 | $this->assertEquals('My-Custom-Header', $this->provider->getValue());
73 | }
74 |
75 | public function testItWillReturnACommaSeparatedListOfHeadersIfThereAreMultipleHeadersConfigured()
76 | {
77 | $stubHeaders = ['My-Custom-Header', 'My-Other-Custom-Header'];
78 | $this->corsConfigurationMock->method('getAllowedHeaders')->willReturn($stubHeaders);
79 | $this->assertEquals('My-Custom-Header,My-Other-Custom-Header', $this->provider->getValue());
80 | }
81 |
82 | /**
83 | * @dataProvider canApplyDataProvider
84 | */
85 | public function testCanApply($headers, $originResult, $isPreflight, $expected)
86 | {
87 | $this->corsConfigurationMock->method('getAllowedHeaders')->willReturn($headers);
88 | $this->corsValidatorMock->method('originIsValid')->willReturn($originResult);
89 | $this->corsValidatorMock->method('isPreflightRequest')->willReturn($isPreflight);
90 | $this->assertEquals($expected, $this->provider->canApply(), 'Incorrect canApply result');
91 | }
92 |
93 | public function canApplyDataProvider()
94 | {
95 | return [
96 | 'invalid origin, cors request' => [
97 | ['My-Valid-Header', 'My-Other-Valid-Header'],
98 | false,
99 | false,
100 | false,
101 | ],
102 | 'invalid origin, preflight request' => [
103 | ['My-Valid-Header', 'My-Other-Valid-Header'],
104 | false,
105 | true,
106 | false,
107 | ],
108 | 'valid origin, cors request without configured headers' => [
109 | [],
110 | true,
111 | false,
112 | false,
113 | ],
114 | 'valid origin, preflight request without configured headers' => [
115 | [],
116 | true,
117 | true,
118 | false,
119 | ],
120 | 'valid origin, cors request with header configuration' => [
121 | ['My-Valid-Header', 'My-Other-Valid-Header'],
122 | true,
123 | false,
124 | false,
125 | ],
126 | 'valid origin, preflight request with header configuration' => [
127 | ['My-Valid-Header', 'My-Other-Valid-Header'],
128 | true,
129 | true,
130 | true,
131 | ],
132 | ];
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/Test/Unit/Validator/CorsValidatorTest.php:
--------------------------------------------------------------------------------
1 | configurationMock = $this->createMock(CorsConfigurationInterface::class);
42 | $this->requestMock = $this->createMock(Http::class);
43 | $this->validator = new CorsValidator($this->configurationMock, $this->requestMock);
44 | }
45 |
46 | /**
47 | * @dataProvider originIsValidDataProvider
48 | */
49 | public function testOriginIsValid($allowedOrigins, $requestOrigin, $expected)
50 | {
51 | $this->configurationMock->method('getAllowedOrigins')->willReturn($allowedOrigins);
52 | $this->requestMock->method('getHeader')->willReturn($requestOrigin);
53 | return $this->assertEquals($expected, $this->validator->originIsValid());
54 | }
55 |
56 | public function testInvalidOriginScheme()
57 | {
58 | $this->configurationMock->method('getAllowedOrigins')->willReturn(['*']);
59 | $this->requestMock->method('getHeader')->willThrowException(
60 | new \InvalidArgumentException
61 | );
62 | return $this->assertEquals(false, $this->validator->originIsValid());
63 | }
64 |
65 | public function originIsValidDataProvider()
66 | {
67 | return [
68 | 'valid origin' => [
69 | ['https://www.example.com'],
70 | 'https://www.example.com',
71 | true,
72 | ],
73 | 'valid origin with multiple configured origins' => [
74 | ['https://www.example.com', 'https://www.myotherexample.com'],
75 | 'https://www.example.com',
76 | true,
77 | ],
78 | 'invalid origin with configured origins' => [
79 | ['https://www.example.com', 'https://www.myotherexample.com'],
80 | 'https://www.amalicicousdomain.com',
81 | false,
82 | ],
83 | 'valid origin domain with invalid origin protocol (http)' => [
84 | ['https://www.example.com'],
85 | 'http://www.example.com',
86 | false,
87 | ],
88 | 'valid origin domain with invalid origin protocol (https)' => [
89 | ['http://www.example.com'],
90 | 'https://www.example.com',
91 | false,
92 | ],
93 | 'invalid origin with no configured origins' => [
94 | [],
95 | 'https://www.amalicicousdomain.com',
96 | false,
97 | ],
98 | 'any origin with a wildcard configured' => [
99 | ['*'],
100 | 'https://some.random.domain',
101 | true,
102 | ],
103 | ];
104 | }
105 |
106 | /**
107 | * @dataProvider preflightTestDataProvider
108 | */
109 | public function testIsPreflightRequest($allowedOrigins, $requestOrigin, $method, $result)
110 | {
111 | $this->configurationMock->method('getAllowedOrigins')->willReturn($allowedOrigins);
112 | $this->requestMock->method('getHeader')->willReturn($requestOrigin);
113 | $this->requestMock->method('getMethod')->willReturn($method);
114 |
115 | return $this->assertEquals($result, $this->validator->isPreflightRequest());
116 | }
117 |
118 | public function preflightTestDataProvider()
119 | {
120 | return [
121 | 'valid origin as GET' => [
122 | ['https://www.example.com'],
123 | 'https://www.example.com',
124 | 'GET',
125 | false,
126 | ],
127 | 'valid origin as OPTIONS' => [
128 | ['https://www.example.com', 'https://www.myotherexample.com'],
129 | 'https://www.example.com',
130 | 'OPTIONS',
131 | true,
132 | ],
133 | 'invalid origin as GET' => [
134 | ['https://www.example.com'],
135 | 'https://www.anotherdomain.com',
136 | 'GET',
137 | false,
138 | ],
139 | 'invalid origin as OPTIONS' => [
140 | ['https://www.example.com', 'https://www.myotherexample.com'],
141 | 'https://www.anotherdomain.com',
142 | 'OPTIONS',
143 | true,
144 | ],
145 | ];
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 | ## [2.1.1](https://github.com/graycoreio/magento2-cors/compare/v2.1.0...v2.1.1) (2025-04-15)
6 |
7 |
8 | ### Bug Fixes
9 |
10 | * prevent 500 errors on frontend/admin routes for options requests ([627a211](https://github.com/graycoreio/magento2-cors/commit/627a21190d3636ae32303da738e87182c1536bf6))
11 |
12 | ## [2.1.0](https://github.com/graycoreio/magento2-cors/compare/v2.0.1...v2.1.0) (2024-10-10)
13 |
14 |
15 | ### Features
16 |
17 | * **docs:** augment docs for configuring Commerce Cloud ([#87](https://github.com/graycoreio/magento2-cors/issues/87)) ([d9f7f69](https://github.com/graycoreio/magento2-cors/commit/d9f7f69b301ba9bcbfb03bca8d27254a6eb98601))
18 |
19 | ## [2.0.1](https://github.com/graycoreio/magento2-cors/compare/v2.0.0...v2.0.1) (2024-02-07)
20 |
21 |
22 | ### Bug Fixes
23 |
24 | * `Access-Control-Expose-Headers` only set on preflight ([#84](https://github.com/graycoreio/magento2-cors/issues/84)) ([f2515c8](https://github.com/graycoreio/magento2-cors/commit/f2515c831641eeb9cc3dbefc082a14706158581b))
25 | * wrong di.xml configuration - missing noNamespaceSchemaLocation and xmlns:xsi ([#82](https://github.com/graycoreio/magento2-cors/issues/82)) ([104fd5d](https://github.com/graycoreio/magento2-cors/commit/104fd5dcb3a1c00e83a06973719d4aa4683cdcc6))
26 |
27 | ## [2.0.0](https://github.com/graycoreio/magento2-cors/compare/v2.0.0-rc.0...v2.0.0) (2022-10-14)
28 |
29 |
30 | ### Bug Fixes
31 |
32 | * add compatability between Laminas\Http and Zend\Http ([#75](https://github.com/graycoreio/magento2-cors/issues/75)) ([b1d4af1](https://github.com/graycoreio/magento2-cors/commit/b1d4af124b1a1a0f3ad19009a0eba5d9d973309f))
33 |
34 | ## [2.0.0-rc.0](https://github.com/graycoreio/magento2-cors/compare/v1.6.0...v2.0.0-rc.0) (2022-06-11)
35 |
36 |
37 | ### ⚠ BREAKING CHANGES
38 |
39 | * If you were expecting to use the native GraphQl/REST controller when computing CORS headers (and everything else that entails - like having a Magento session, for example) that guarantee is no-longer provided.
40 |
41 | ### Features
42 |
43 | * **graphql,rest:** add faster CORS headers ([#66](https://github.com/graycoreio/magento2-cors/issues/66)) ([cefd663](https://github.com/graycoreio/magento2-cors/commit/cefd6631d4f2aaf5347875a02d773317480783d5))
44 |
45 |
46 | * denote breaking changes ([b98b9bc](https://github.com/graycoreio/magento2-cors/commit/b98b9bcfcefa533f84e85921a9becb5be2a9ff71))
47 |
48 | ## [1.6.0](https://github.com/graycoreio/magento2-cors/compare/v1.4.1...v1.6.0) (2022-06-11)
49 |
50 |
51 | ### Features
52 |
53 | * add Magento v2.4.4 and PHP8.1 support ([#70](https://github.com/graycoreio/magento2-cors/issues/70)) ([6e8bfe1](https://github.com/graycoreio/magento2-cors/commit/6e8bfe184e47e602b26c001d986bb296d42c3665))
54 | * **rest:** extend REST request to allow OPTIONS without error ([#55](https://github.com/graycoreio/magento2-cors/issues/55)) ([eb1df2d](https://github.com/graycoreio/magento2-cors/commit/eb1df2d0c25897897998e8e3f88fcec500a8a3f8))
55 |
56 | ### [1.4.1](https://github.com/graycoreio/magento2-cors/compare/v1.4.0...v1.4.1) (2021-03-04)
57 |
58 |
59 | ### Bug Fixes
60 |
61 | * **graphql, rest:** allow caching of options requests ([#53](https://github.com/graycoreio/magento2-cors/issues/53)) ([f6b9b3f](https://github.com/graycoreio/magento2-cors/commit/f6b9b3fbf042d7c551b3993cca8e24a169309748))
62 |
63 | ## [1.4.0](https://github.com/graycoreio/magento2-cors/compare/v1.3.2...v1.4.0) (2021-03-02)
64 |
65 |
66 | ### Features
67 |
68 | * **graphql, rest:** add support for access-control-expose-headers ([#49](https://github.com/graycoreio/magento2-cors/issues/49)) ([53aac87](https://github.com/graycoreio/magento2-cors/commit/53aac87f4397352426dc5b8eef720ca22a5594f6))
69 | * **graphql, rest:** apply certain headers only to preflight requests ([#51](https://github.com/graycoreio/magento2-cors/issues/51)) ([30bcff0](https://github.com/graycoreio/magento2-cors/commit/30bcff0931134e56d0f4d4217bfe84dde1588b00))
70 | * **graphql,rest:** add support for Vary header with Origin ([#47](https://github.com/graycoreio/magento2-cors/issues/47)) ([e656909](https://github.com/graycoreio/magento2-cors/commit/e65690922063d7e52e0cd6bbed8643dda4a3d061))
71 | * **validator:** add a new method to determine whether or not a reque… ([#50](https://github.com/graycoreio/magento2-cors/issues/50)) ([8c3ef8b](https://github.com/graycoreio/magento2-cors/commit/8c3ef8b085c79dfd6aad8a6a3a725ade98e9490b))
72 |
73 | ### [1.3.2](https://github.com/graycoreio/magento2-cors/compare/v1.3.1...v1.3.2) (2020-08-10)
74 |
75 | ### [1.3.1](https://github.com/graycoreio/magento2-cors/compare/v1.3.0...v1.3.1) (2020-08-10)
76 |
77 | ## [1.3.0](https://github.com/graycoreio/magento2-cors/compare/v1.2.0...v1.3.0) (2020-05-18)
78 |
79 |
80 | ### Bug Fixes
81 |
82 | * **graphql:** prevent fatal error when using Chrome extensions for graphql querying ([#24](https://github.com/graycoreio/magento2-cors/issues/24)) ([486fe10](https://github.com/graycoreio/magento2-cors/commit/486fe10))
83 |
84 |
85 | ### Build System
86 |
87 | * **all:** added unit tests to CI ([#18](https://github.com/graycoreio/magento2-cors/issues/18)) ([aade441](https://github.com/graycoreio/magento2-cors/commit/aade441))
88 | * **all:** adding linting with phpcs ([#16](https://github.com/graycoreio/magento2-cors/issues/16)) ([8753bd2](https://github.com/graycoreio/magento2-cors/commit/8753bd2))
89 | * **all:** set up CI with Azure Pipelines ([#15](https://github.com/graycoreio/magento2-cors/issues/15)) ([f30b51f](https://github.com/graycoreio/magento2-cors/commit/f30b51f))
90 | * **ci:** run integration tests in ci ([#21](https://github.com/graycoreio/magento2-cors/issues/21)) ([a79d7f7](https://github.com/graycoreio/magento2-cors/commit/a79d7f7))
91 |
92 |
93 | ### Features
94 |
95 | * **cors:** add header provider for Allow-Credentials ([#27](https://github.com/graycoreio/magento2-cors/issues/27)) ([38bf597](https://github.com/graycoreio/magento2-cors/commit/38bf597))
96 |
97 |
98 | ### Tests
99 |
100 | * **configuration:** added/updated unit tests for config files ([#19](https://github.com/graycoreio/magento2-cors/issues/19)) ([826b68e](https://github.com/graycoreio/magento2-cors/commit/826b68e))
101 | * **integration:** updated integration tests to pass ([#23](https://github.com/graycoreio/magento2-cors/issues/23)) ([89736d7](https://github.com/graycoreio/magento2-cors/commit/89736d7))
102 |
103 |
104 |
105 | ## [1.2.0](https://github.com/graycoreio/magento2-cors/compare/v1.1.0...v1.2.0) (2020-01-20)
106 |
107 |
108 | ### Features
109 |
110 | * **rest:** fixup rest api to handle options requests ([#13](https://github.com/graycoreio/magento2-cors/issues/13)) ([3520b9d](https://github.com/graycoreio/magento2-cors/commit/3520b9d))
111 |
112 |
113 |
114 | ## [1.1.0](https://github.com/graycoreio/magento2-cors/compare/v1.0.0...v1.1.0) (2020-01-17)
115 |
116 |
117 | ### Bug Fixes
118 |
119 | * **graphql:** swap config key name ([#10](https://github.com/graycoreio/magento2-cors/issues/10)) ([2aed35c](https://github.com/graycoreio/magento2-cors/commit/2aed35c))
120 |
121 |
122 | ### Features
123 |
124 | * **rest:** add CORS support for Magento 2 REST APIs ([#11](https://github.com/graycoreio/magento2-cors/issues/11)) ([2342976](https://github.com/graycoreio/magento2-cors/commit/2342976))
125 | * **rest:** allow rest api and graphql apis to be configurable separately ([#12](https://github.com/graycoreio/magento2-cors/issues/12)) ([ff5813e](https://github.com/graycoreio/magento2-cors/commit/ff5813e))
126 |
127 |
128 |
129 | ## 1.0.0 (2019-07-23)
130 |
131 |
132 | ### Bug Fixes
133 |
134 | * **configuration:** remove backtick in di.xml ([3a6549c](https://github.com/graycoreio/magento2-cors/commit/3a6549c))
135 |
136 |
137 | ### Features
138 |
139 | * **cors:** initial package with configuration and validation for CORS headers on the GraphQL api ([493c6ad](https://github.com/graycoreio/magento2-cors/commit/493c6ad))
140 | * **release:** add basic release process ([b09b62b](https://github.com/graycoreio/magento2-cors/commit/b09b62b))
141 | * **security:** enforce security by default, no headers out of the box ([cb3291c](https://github.com/graycoreio/magento2-cors/commit/cb3291c))
142 |
143 |
144 |
145 | ## 1.0.0 (2019-07-23)
146 |
147 |
148 | ### Bug Fixes
149 |
150 | * **configuration:** remove backtick in di.xml ([3a6549c](https://github.com/graycoreio/magento2-cors/commit/3a6549c))
151 |
152 |
153 | ### Features
154 |
155 | * **cors:** initial package with configuration and validation for CORS headers on the GraphQL api ([493c6ad](https://github.com/graycoreio/magento2-cors/commit/493c6ad))
156 | * **release:** add basic release process ([b09b62b](https://github.com/graycoreio/magento2-cors/commit/b09b62b))
157 | * **security:** enforce security by default, no headers out of the box ([cb3291c](https://github.com/graycoreio/magento2-cors/commit/cb3291c))
158 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Magento 2 CORS
2 |
3 | We would love for you to contribute to "Magento 2 CORS" and help make it even better than it is
4 | today! As a contributor, here are the guidelines we would like you to follow:
5 |
6 | - [Code of Conduct](#coc)
7 | - [Question or Problem?](#question)
8 | - [Issues and Bugs](#issue)
9 | - [Feature Requests](#feature)
10 | - [Submission Guidelines](#submit)
11 | - [Coding Rules](#rules)
12 | - [Commit Message Guidelines](#commit)
13 |
14 | ## Code of Conduct
15 | Help us keep "Magento 2 CORS" open and inclusive. Please read and follow our [Code of Conduct][coc].
16 |
17 | ## Got a Question or Problem?
18 |
19 | Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on [Stack Overflow](https://stackoverflow.com/questions/tagged/magento2-cors) where the questions should be tagged with tag `magento2-cors`.
20 |
21 | Stack Overflow is a much better place to ask questions since:
22 |
23 | - there are thousands of people willing to help on Stack Overflow
24 | - questions and answers stay available for public viewing so your question / answer might help someone else
25 | - Stack Overflow's voting system assures that the best answers are prominently visible.
26 |
27 | To save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow.
28 |
29 | If you would like to chat about the question in real-time, you can reach out via [our gitter channel][gitter].
30 |
31 | ## Found a Bug?
32 | If you find a bug in the source code, you can help us by
33 | [submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can
34 | [submit a Pull Request](#submit-pr) with a fix.
35 |
36 | ## Missing a Feature?
37 | You can *request* a new feature by [submitting an issue](#submit-issue) to our GitHub
38 | Repository. If you would like to *implement* a new feature, please submit an issue with
39 | a proposal for your work first, to be sure that we can use it.
40 | Please consider what kind of change it is:
41 |
42 | * For a **Major Feature**, first open an issue and outline your proposal so that it can be
43 | discussed. This will also allow us to better coordinate our efforts, prevent duplication of work,
44 | and help you to craft the change so that it is successfully accepted into the project.
45 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
46 |
47 | ## Submission Guidelines
48 |
49 | ### Submitting an Issue
50 |
51 | Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.
52 |
53 | We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs, we will systematically ask you to provide a minimal reproduction scenario using http://plnkr.co. Having a live, reproducible scenario gives us a wealth of important information without going back & forth to you with additional questions like:
54 |
55 | - version of "Magento 2 CORS" used
56 | - 3rd-party libraries and their versions
57 | - and most importantly - a use-case that fails
58 |
59 | A minimal reproduce scenario using http://plnkr.co/ allows us to quickly confirm a bug (or point out coding problem) as well as confirm that we are fixing the right problem. If plunker is not a suitable way to demonstrate the problem (for example for issues related to our npm packaging), please create a standalone git repository demonstrating the problem.
60 |
61 | We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal plunk. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it.
62 |
63 | Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that doesn't have enough info to be reproduced.
64 |
65 | You can file new issues by filling out our [new issue form](https://github.com/graycoreio/magento2-cors/issues/new).
66 |
67 |
68 | ### Submitting a Pull Request (PR)
69 | Before you submit your Pull Request (PR) consider the following guidelines:
70 |
71 | 1. Search [GitHub](https://github.com/graycoreio/magento2-cors/pulls) for an open or closed PR
72 | that relates to your submission. You don't want to duplicate effort.
73 | 1. Fork the [graycoreio/magento2-cors](https://github.com/graycoreio/magento2-cors) repo.
74 | 1. Make your changes in a new git branch:
75 |
76 | ```shell
77 | git checkout -b my-fix-branch master
78 | ```
79 |
80 | 1. Create your patch, **including appropriate test cases**.
81 | 1. Follow our [Coding Rules](#rules).
82 | 1. Run the full test suite, as described in the [developer documentation][dev-doc],
83 | and ensure that all tests pass.
84 | 1. Commit your changes using a descriptive commit message that follows our
85 | [commit message conventions](#commit). Adherence to these conventions
86 | is necessary because release notes are automatically generated from these messages.
87 |
88 | ```shell
89 | git commit -a
90 | ```
91 | Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
92 |
93 | 1. Push your branch to GitHub:
94 |
95 | ```shell
96 | git push origin my-fix-branch
97 | ```
98 |
99 | 1. In GitHub, send a pull request to `magento2-cors:master`.
100 | * If we suggest changes then:
101 | * Make the required updates.
102 | * Re-run the "Magento 2 Cors" test suites to ensure tests are still passing.
103 | * Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
104 |
105 | ```shell
106 | git rebase master -i
107 | git push -f
108 | ```
109 | * Note: don't squash your branch until after the reviewers comment "lgtm", so they don't need to re-review your entire branch every commit.
110 |
111 | That's it! Thank you for your contribution!
112 |
113 | #### After your pull request is merged
114 |
115 | After your pull request is merged, you can safely delete your branch and pull the changes
116 | from the main (upstream) repository:
117 |
118 | * Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:
119 |
120 | ```shell
121 | git push origin --delete my-fix-branch
122 | ```
123 |
124 | * Check out the master branch:
125 |
126 | ```shell
127 | git checkout master -f
128 | ```
129 |
130 | * Delete the local branch:
131 |
132 | ```shell
133 | git branch -D my-fix-branch
134 | ```
135 |
136 | * Update your master with the latest upstream version:
137 |
138 | ```shell
139 | git pull --ff upstream master
140 | ```
141 |
142 | ## Coding Rules
143 | To ensure consistency throughout the source code, keep these rules in mind as you are working:
144 |
145 | * All features or bug fixes **must be tested** by one or more specs (unit-tests).
146 | * All public API methods **must be documented**. (Details TBC).
147 | * We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at
148 | **100 characters**. An automated formatter is available, see
149 | [DEVELOPER.md](docs/DEVELOPER.md#clang-format).
150 |
151 | ## Commit Message Guidelines
152 |
153 | We have very precise rules over how our git commit messages can be formatted. This leads to **more
154 | readable messages** that are easy to follow when looking through the **project history**.
155 |
156 | ### Commit Message Format
157 | Each commit message consists of a **header**, a **body** and a **footer**. The header has a special
158 | format that includes a **type**, a **scope** and a **subject**:
159 |
160 | ```
161 | ():
162 |
163 |
164 |
165 |