From 46db9d82d3984f80f653e338d662fce506049220 Mon Sep 17 00:00:00 2001 From: Alexander Paliarush Date: Thu, 17 Mar 2016 16:07:25 -0500 Subject: [PATCH 01/25] MAGETWO-50551: When saving product or category cache cleared by general tag --- .../Observer/InvalidateVarnishObserver.php | 1 - app/code/Magento/Catalog/Model/Product.php | 35 +++++++++++++++++++ .../PageCache/Observer/FlushCacheByTags.php | 3 -- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php b/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php index 0ac121dc1def3..eb2ac66f66dc4 100644 --- a/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php +++ b/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php @@ -48,7 +48,6 @@ public function execute(\Magento\Framework\Event\Observer $observer) $tags = []; $pattern = "((^|,)%s(,|$))"; foreach ($object->getIdentities() as $tag) { - $tags[] = sprintf($pattern, preg_replace("~_\\d+$~", '', $tag)); $tags[] = sprintf($pattern, $tag); } $this->purgeCache->sendPurgeRequest(implode('|', array_unique($tags))); diff --git a/app/code/Magento/Catalog/Model/Product.php b/app/code/Magento/Catalog/Model/Product.php index adeb3ad14f2d7..0c651799f1c7f 100644 --- a/app/code/Magento/Catalog/Model/Product.php +++ b/app/code/Magento/Catalog/Model/Product.php @@ -307,6 +307,11 @@ class Product extends \Magento\Catalog\Model\AbstractModel implements */ protected $_productIdCached; + /** + * @var \Magento\Framework\App\State + */ + private $appState; + /** * List of attributes in ProductInterface * @var array @@ -2263,6 +2268,9 @@ public function getIdentities() $identities[] = self::CACHE_PRODUCT_CATEGORY_TAG . '_' . $categoryId; } } + if ($this->getAppState()->getAreaCode() === 'frontend') { + $identities[] = self::CACHE_TAG; + } return array_unique($identities); } @@ -2548,4 +2556,31 @@ public function setId($value) { return $this->setData('entity_id', $value); } + + /** + * Get application state + * + * @return \Magento\Framework\App\State + */ + private function getAppState() + { + if (!$this->appState instanceof \Magento\Framework\App\State) { + return \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\State'); + } else { + return $this->appState; + } + } + + /** + * Set application state + * + * @deprecated + * @param \Magento\Framework\App\State $appState + * @return $this + */ + public function setAppState(\Magento\Framework\App\State $appState) + { + $this->appState = $appState; + return $this; + } } diff --git a/app/code/Magento/PageCache/Observer/FlushCacheByTags.php b/app/code/Magento/PageCache/Observer/FlushCacheByTags.php index 116162c5047b5..f76205f057198 100644 --- a/app/code/Magento/PageCache/Observer/FlushCacheByTags.php +++ b/app/code/Magento/PageCache/Observer/FlushCacheByTags.php @@ -53,9 +53,6 @@ public function execute(\Magento\Framework\Event\Observer $observer) $object = $observer->getEvent()->getObject(); if ($object instanceof \Magento\Framework\DataObject\IdentityInterface) { $tags = $object->getIdentities(); - foreach ($tags as $tag) { - $tags[] = preg_replace("~_\\d+$~", '', $tag); - } if (!empty($tags)) { $this->getCache()->clean(\Zend_Cache::CLEANING_MODE_ALL, array_unique($tags)); } From 0a667f049e7c8f726b4b2af0a9d6f88a9e7ec9d0 Mon Sep 17 00:00:00 2001 From: Cari Spruiell Date: Mon, 21 Mar 2016 10:38:59 -0500 Subject: [PATCH 02/25] MAGETWO-50202: [GitHub] Couldn't save shipment data #527 - fix test --- .../testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php index 8c1ed948b84d3..2566b9c09412a 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php @@ -85,6 +85,7 @@ public function testInvoke() 'carrier_code' => 'UPS', 'order_id' => $order->getId(), 'title' => 'ground', + 'description' => null, 'track_number' => '12345678' ] ], From 17a571b0b199cb37074030faac607d3323be3fd3 Mon Sep 17 00:00:00 2001 From: Cari Spruiell Date: Mon, 21 Mar 2016 12:35:54 -0500 Subject: [PATCH 03/25] MAGETWO-50202: [GitHub] Couldn't save shipment data #527 - fix test --- .../Magento/Sales/Service/V1/ShipmentCreateTest.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php index 14c94d4851d76..8e21322d548c8 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php @@ -87,7 +87,12 @@ public function testInvoke() 'order_id' => $order->getId(), 'title' => 'ground', 'description' => null, - 'track_number' => '12345678' + 'track_number' => '12345678', + 'parent_id' => null, + 'created_at' => null, + 'updated_at' => null, + 'qty' => null, + 'weight' => null ] ], 'items' => $items, From aded675dc252e5709c69ba053cd9dbebfb2ffeeb Mon Sep 17 00:00:00 2001 From: Cari Spruiell Date: Mon, 21 Mar 2016 15:36:08 -0500 Subject: [PATCH 04/25] MAGETWO-50202: [GitHub] Couldn't save shipment data #527 - restore fixes to branch and fix test --- app/code/Magento/Sales/Model/Order/Shipment/Track.php | 10 +++++++++- .../Model/ResourceModel/Order/Shipment/Relation.php | 2 ++ .../ResourceModel/Order/Shipment/RelationTest.php | 2 +- .../Shipping/Test/Unit/Model/Order/TrackTest.php | 2 +- .../Magento/Sales/Service/V1/ShipmentCreateTest.php | 6 ++++-- 5 files changed, 17 insertions(+), 5 deletions(-) diff --git a/app/code/Magento/Sales/Model/Order/Shipment/Track.php b/app/code/Magento/Sales/Model/Order/Shipment/Track.php index cac8ea3dfcf3b..34c97f4d80245 100644 --- a/app/code/Magento/Sales/Model/Order/Shipment/Track.php +++ b/app/code/Magento/Sales/Model/Order/Shipment/Track.php @@ -6,6 +6,7 @@ namespace Magento\Sales\Model\Order\Shipment; use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Exception\LocalizedException; use Magento\Sales\Api\Data\ShipmentTrackInterface; use Magento\Sales\Model\AbstractModel; @@ -137,11 +138,16 @@ public function setShipment(\Magento\Sales\Model\Order\Shipment $shipment) * Retrieve Shipment instance * * @return \Magento\Sales\Model\Order\Shipment + * @throws \Magento\Framework\Exception\LocalizedException */ public function getShipment() { if (!$this->_shipment instanceof \Magento\Sales\Model\Order\Shipment) { - $this->_shipment = $this->shipmentRepository->get($this->getParentId()); + if ($this->getParentId()) { + $this->_shipment = $this->shipmentRepository->get($this->getParentId()); + } else { + throw new LocalizedException(__("Parent shipment cannot be loaded for track object.")); + } } return $this->_shipment; @@ -208,6 +214,7 @@ public function addData(array $data) } //@codeCoverageIgnoreStart + /** * Returns track_number * @@ -408,5 +415,6 @@ public function setExtensionAttributes(\Magento\Sales\Api\Data\ShipmentTrackExte { return $this->_setExtensionAttributes($extensionAttributes); } + //@codeCoverageIgnoreEnd } diff --git a/app/code/Magento/Sales/Model/ResourceModel/Order/Shipment/Relation.php b/app/code/Magento/Sales/Model/ResourceModel/Order/Shipment/Relation.php index 39fb499455fda..6a47b80c15f6e 100644 --- a/app/code/Magento/Sales/Model/ResourceModel/Order/Shipment/Relation.php +++ b/app/code/Magento/Sales/Model/ResourceModel/Order/Shipment/Relation.php @@ -64,11 +64,13 @@ public function processRelation(\Magento\Framework\Model\AbstractModel $object) } if (null !== $object->getTracks()) { foreach ($object->getTracks() as $track) { + $track->setParentId($object->getId()); $this->shipmentTrackResource->save($track); } } if (null !== $object->getComments()) { foreach ($object->getComments() as $comment) { + $comment->setParentId($object->getId()); $this->shipmentCommentResource->save($comment); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/RelationTest.php b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/RelationTest.php index 3b618f4057229..98d83011853bd 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/RelationTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/ResourceModel/Order/Shipment/RelationTest.php @@ -111,7 +111,7 @@ protected function setUp() public function testProcessRelations() { - $this->shipmentMock->expects($this->once()) + $this->shipmentMock->expects($this->exactly(3)) ->method('getId') ->willReturn('shipment-id-value'); $this->shipmentMock->expects($this->exactly(2)) diff --git a/app/code/Magento/Shipping/Test/Unit/Model/Order/TrackTest.php b/app/code/Magento/Shipping/Test/Unit/Model/Order/TrackTest.php index b41d31be4d9c0..3dec36fefa1eb 100644 --- a/app/code/Magento/Shipping/Test/Unit/Model/Order/TrackTest.php +++ b/app/code/Magento/Shipping/Test/Unit/Model/Order/TrackTest.php @@ -52,7 +52,7 @@ public function testLookup() 'Magento\Shipping\Model\Order\Track', ['carrierFactory' => $carrierFactory, 'shipmentRepository' => $shipmentRepository] ); - + $model->setParentId(1); $this->assertEquals('trackingInfo', $model->getNumberDetail()); } } diff --git a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php index 8e21322d548c8..9929fbeff374b 100644 --- a/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php @@ -79,7 +79,6 @@ public function testInvoke() 'increment_id' => null, 'created_at' => null, 'updated_at' => null, -// 'packages' => null, 'shipping_label' => null, 'tracks' => [ [ @@ -98,7 +97,10 @@ public function testInvoke() 'items' => $items, 'comments' => [ [ - 'comment' => 'Shipment-related comment.' + 'comment' => 'Shipment-related comment.', + 'is_customer_notified' => null, + 'is_visible_on_front' => null, + 'parent_id' => null ] ], ]; From a19a8d92814dd17950b7320ef1b467ac456fde75 Mon Sep 17 00:00:00 2001 From: Hayder Sharhan Date: Mon, 21 Mar 2016 18:13:20 -0500 Subject: [PATCH 05/25] MAGETWO-50611: [Github][Security] WebAPIs allow anonymous access - Added restriction on some of the services to not allow anonymous access. - Added new module that would allow administrators to loosen this security from the backend. --- app/code/Magento/Catalog/etc/webapi.xml | 42 +++++------ .../Magento/CatalogInventory/etc/webapi.xml | 2 +- app/code/Magento/Cms/etc/webapi.xml | 4 +- .../ConfigurableProduct/etc/webapi.xml | 6 +- app/code/Magento/Store/etc/webapi.xml | 8 +- app/code/Magento/WebapiSecurity/LICENSE.txt | 48 ++++++++++++ .../Magento/WebapiSecurity/LICENSE_AFL.txt | 48 ++++++++++++ .../Plugin/AnonymousResourceSecurity.php | 73 +++++++++++++++++++ .../Model/Plugin/CacheInvalidator.php | 36 +++++++++ app/code/Magento/WebapiSecurity/README.md | 5 ++ app/code/Magento/WebapiSecurity/composer.json | 23 ++++++ .../WebapiSecurity/etc/Adminhtml/system.xml | 19 +++++ app/code/Magento/WebapiSecurity/etc/di.xml | 53 ++++++++++++++ .../Magento/WebapiSecurity/etc/module.xml | 8 ++ .../Magento/WebapiSecurity/registration.php | 11 +++ 15 files changed, 355 insertions(+), 31 deletions(-) create mode 100644 app/code/Magento/WebapiSecurity/LICENSE.txt create mode 100644 app/code/Magento/WebapiSecurity/LICENSE_AFL.txt create mode 100644 app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php create mode 100644 app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php create mode 100644 app/code/Magento/WebapiSecurity/README.md create mode 100644 app/code/Magento/WebapiSecurity/composer.json create mode 100644 app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml create mode 100644 app/code/Magento/WebapiSecurity/etc/di.xml create mode 100644 app/code/Magento/WebapiSecurity/etc/module.xml create mode 100644 app/code/Magento/WebapiSecurity/registration.php diff --git a/app/code/Magento/Catalog/etc/webapi.xml b/app/code/Magento/Catalog/etc/webapi.xml index 2dbaff9694bcd..462df42a288e9 100644 --- a/app/code/Magento/Catalog/etc/webapi.xml +++ b/app/code/Magento/Catalog/etc/webapi.xml @@ -30,13 +30,13 @@ - + - + @@ -49,7 +49,7 @@ - + @@ -97,19 +97,19 @@ - + - + - + @@ -133,7 +133,7 @@ - + @@ -151,7 +151,7 @@ - + @@ -175,7 +175,7 @@ - + @@ -193,13 +193,13 @@ - + - + @@ -223,7 +223,7 @@ - + @@ -231,7 +231,7 @@ - + @@ -256,7 +256,7 @@ - + @@ -268,7 +268,7 @@ - + @@ -294,13 +294,13 @@ - + - + @@ -326,19 +326,19 @@ - + - + - + @@ -364,7 +364,7 @@ - + diff --git a/app/code/Magento/CatalogInventory/etc/webapi.xml b/app/code/Magento/CatalogInventory/etc/webapi.xml index 79677cfdfd6b4..ef2d2c89b3ff1 100644 --- a/app/code/Magento/CatalogInventory/etc/webapi.xml +++ b/app/code/Magento/CatalogInventory/etc/webapi.xml @@ -28,7 +28,7 @@ - + diff --git a/app/code/Magento/Cms/etc/webapi.xml b/app/code/Magento/Cms/etc/webapi.xml index d1bf5bff39a3f..3da517e7b2c0f 100644 --- a/app/code/Magento/Cms/etc/webapi.xml +++ b/app/code/Magento/Cms/etc/webapi.xml @@ -11,7 +11,7 @@ - + @@ -42,7 +42,7 @@ - + diff --git a/app/code/Magento/ConfigurableProduct/etc/webapi.xml b/app/code/Magento/ConfigurableProduct/etc/webapi.xml index 0deb5150906f4..aa8103da274ac 100644 --- a/app/code/Magento/ConfigurableProduct/etc/webapi.xml +++ b/app/code/Magento/ConfigurableProduct/etc/webapi.xml @@ -10,7 +10,7 @@ - + @@ -34,13 +34,13 @@ - + - + diff --git a/app/code/Magento/Store/etc/webapi.xml b/app/code/Magento/Store/etc/webapi.xml index 5ee8e0c67668e..78fd0cfdcf9a8 100644 --- a/app/code/Magento/Store/etc/webapi.xml +++ b/app/code/Magento/Store/etc/webapi.xml @@ -11,7 +11,7 @@ - + @@ -19,7 +19,7 @@ - + @@ -27,7 +27,7 @@ - + @@ -35,7 +35,7 @@ - + diff --git a/app/code/Magento/WebapiSecurity/LICENSE.txt b/app/code/Magento/WebapiSecurity/LICENSE.txt new file mode 100644 index 0000000000000..49525fd99da9c --- /dev/null +++ b/app/code/Magento/WebapiSecurity/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/WebapiSecurity/LICENSE_AFL.txt b/app/code/Magento/WebapiSecurity/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php new file mode 100644 index 0000000000000..edaa1f0c39795 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php @@ -0,0 +1,73 @@ +backendConfig = $backendConfig; + $this->resources = $resources; + } + + public function afterConvert( + Converter $subject, + $nodes + ) { + if (empty($nodes)) { + return $nodes; + } + $useInsecure = $this->backendConfig->isSetFlag(self::XML_ALLOW_INSECURE); + if ($useInsecure) { + foreach ($this->resources as $route => $requestType) { + if ($result = $this->getNode($route, $requestType, $nodes["routes"])) { + if (isset($result[$requestType]['resources'])) { + $result[$requestType]['resources'] = ['anonymous' => true]; + $nodes['routes'][$route] = $result; + } + + if (isset($result[$requestType]['service']['class']) + && isset($result[$requestType]['service']['method']) + ) { + $serviceName = $result[$requestType]['service']['class']; + $serviceMethod = $result[$requestType]['service']['method']; + $nodes['services'][$serviceName]['V1']['methods'][$serviceMethod]['resources'] = ['anonymous']; + } + } + } + } + + return $nodes; + } + + private function getNode($route, $requestType, $source) + { + if (isset($source[$route][$requestType])) { + return $source[$route]; + } + return null; + } +} diff --git a/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php b/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php new file mode 100644 index 0000000000000..72fe04c0bf7fa --- /dev/null +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php @@ -0,0 +1,36 @@ +cacheTypeList = $cacheTypeList; + } + + public function afterAfterSave( + \Magento\Framework\App\Config\Value $subject, + $result + ) + { + if ($result->getPath() == "system/webapisecurity/allow_insecure" && $result->isValueChanged()) { + $this->cacheTypeList->invalidate(\Magento\Webapi\Model\Cache\Type\Webapi::TYPE_IDENTIFIER); + } + + return $result; + } +} diff --git a/app/code/Magento/WebapiSecurity/README.md b/app/code/Magento/WebapiSecurity/README.md new file mode 100644 index 0000000000000..1772524e47379 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/README.md @@ -0,0 +1,5 @@ +# WebapiSecurity + +**WebapiSecurity** enables access management of some webapi resources. +Allowing them to be accessed by anyone. These resources are outlined in di.xml +If anonymous access checkbox is enabled in backend, these resources' security is loosened. diff --git a/app/code/Magento/WebapiSecurity/composer.json b/app/code/Magento/WebapiSecurity/composer.json new file mode 100644 index 0000000000000..292a544ba88b3 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/composer.json @@ -0,0 +1,23 @@ +{ + "name": "magento/module-webapisecurity", + "description": "WebapiSecurity module provides option to loosen security on some webapi resources.", + "require": { + "php": "~5.5.22|~5.6.0|~7.0.0", + "magento/module-backend": "100.0.*", + "magento/framework": "100.0.*" + }, + "type": "magento2-module", + "version": "100.0.2", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\WebapiSecurity\\": "" + } + } +} diff --git a/app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml b/app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml new file mode 100644 index 0000000000000..34249a7e46d2a --- /dev/null +++ b/app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml @@ -0,0 +1,19 @@ + + + + +
+ + + + + Magento\Config\Model\Config\Source\Yesno + Full list can be viewed at Magento/app/code/Magento/WebapiSecurity/etc/di.xml + + +
+
+
diff --git a/app/code/Magento/WebapiSecurity/etc/di.xml b/app/code/Magento/WebapiSecurity/etc/di.xml new file mode 100644 index 0000000000000..8b5b42a6fca2c --- /dev/null +++ b/app/code/Magento/WebapiSecurity/etc/di.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + GET + + + + diff --git a/app/code/Magento/WebapiSecurity/etc/module.xml b/app/code/Magento/WebapiSecurity/etc/module.xml new file mode 100644 index 0000000000000..9966c999c7aa7 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/etc/module.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/app/code/Magento/WebapiSecurity/registration.php b/app/code/Magento/WebapiSecurity/registration.php new file mode 100644 index 0000000000000..b12004c6ab4cf --- /dev/null +++ b/app/code/Magento/WebapiSecurity/registration.php @@ -0,0 +1,11 @@ + Date: Tue, 22 Mar 2016 10:42:41 -0500 Subject: [PATCH 06/25] MAGETWO-50202: [GitHub] Couldn't save shipment data #527 - fix integration test --- .../integration/testsuite/Magento/Shipping/Helper/DataTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dev/tests/integration/testsuite/Magento/Shipping/Helper/DataTest.php b/dev/tests/integration/testsuite/Magento/Shipping/Helper/DataTest.php index b3ea35059f18d..22e438f6d5b00 100644 --- a/dev/tests/integration/testsuite/Magento/Shipping/Helper/DataTest.php +++ b/dev/tests/integration/testsuite/Magento/Shipping/Helper/DataTest.php @@ -45,6 +45,9 @@ public function testGetTrackingPopupUrlBySalesModel($modelName, $getIdMethod, $e if ('Magento\Sales\Model\Order' == $modelName) { $model->setProtectCode($code); } + if ('Magento\Sales\Model\Order\Shipment\Track' == $modelName) { + $model->setParentId(1); + } $actual = $this->_helper->getTrackingPopupUrlBySalesModel($model); $this->assertEquals($expected, $actual); From 45797b920765f3e1890ab5506266c73810a0cf54 Mon Sep 17 00:00:00 2001 From: Cari Spruiell Date: Tue, 22 Mar 2016 11:09:43 -0500 Subject: [PATCH 07/25] MAGETWO-50789: Fix incorrect getter methods - correct method implementations --- app/code/Magento/Backend/Helper/Dashboard/Order.php | 12 ++++++++---- .../Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php | 10 +++++++--- .../Adminhtml/Promo/Quote/Edit/Tab/Conditions.php | 10 +++++++--- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/app/code/Magento/Backend/Helper/Dashboard/Order.php b/app/code/Magento/Backend/Helper/Dashboard/Order.php index e01fd8943d65f..6eaeae4c18342 100644 --- a/app/code/Magento/Backend/Helper/Dashboard/Order.php +++ b/app/code/Magento/Backend/Helper/Dashboard/Order.php @@ -35,14 +35,18 @@ public function __construct( } /** - * @return \Magento\SalesRule\Model\RuleFactory + * The getter function to get the new StoreManager dependency + * + * @return \Magento\Store\Model\StoreManagerInterface + * * @deprecated */ - public function getStoreManager() + private function getStoreManager() { - if ($this->_storeManager instanceof \Magento\Store\Model\StoreManagerInterface) { - $this->_storeManager = ObjectManager::getInstance()->get('\Magento\Store\Model\StoreManagerInterface'); + if ($this->_storeManager === null) { + $this->_storeManager = ObjectManager::getInstance()->get('Magento\Store\Model\StoreManagerInterface'); } + return $this->_storeManager; } /** diff --git a/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php index 830c9cfb439c2..03ae3b8ce9691 100644 --- a/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php +++ b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php @@ -65,14 +65,18 @@ public function __construct( } /** + * The getter function to get the new RuleFactory dependency + * * @return \Magento\SalesRule\Model\RuleFactory + * * @deprecated */ - public function getRuleFactory() + private function getRuleFactory() { - if ($this->ruleFactory instanceof \Magento\SalesRule\Model\RuleFactory) { - $this->ruleFactory = ObjectManager::getInstance()->get('\Magento\SalesRule\Model\RuleFactory'); + if ($this->ruleFactory === null) { + $this->ruleFactory = ObjectManager::getInstance()->get('Magento\SalesRule\Model\RuleFactory'); } + return $this->ruleFactory; } /** diff --git a/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php index 7a1ee091008e9..74fc7689b6d4f 100644 --- a/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php +++ b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php @@ -56,14 +56,18 @@ public function __construct( } /** + * The getter function to get the new RuleFactory dependency + * * @return \Magento\SalesRule\Model\RuleFactory + * * @deprecated */ - public function getRuleFactory() + private function getRuleFactory() { - if ($this->ruleFactory instanceof \Magento\SalesRule\Model\RuleFactory) { - $this->ruleFactory = ObjectManager::getInstance()->get('\Magento\SalesRule\Model\RuleFactory'); + if ($this->ruleFactory === null) { + $this->ruleFactory = ObjectManager::getInstance()->get('Magento\SalesRule\Model\RuleFactory'); } + return $this->ruleFactory; } /** From 5add1110b822f6b39ff3ef78838905f7baaf3e6b Mon Sep 17 00:00:00 2001 From: Cari Spruiell Date: Tue, 22 Mar 2016 11:39:05 -0500 Subject: [PATCH 08/25] MAGETWO-50789: Fix incorrect getter methods - correct method implementations --- app/code/Magento/Backend/Helper/Dashboard/Order.php | 6 +++--- .../Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php | 2 +- .../Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/code/Magento/Backend/Helper/Dashboard/Order.php b/app/code/Magento/Backend/Helper/Dashboard/Order.php index 6eaeae4c18342..59855b1d2b884 100644 --- a/app/code/Magento/Backend/Helper/Dashboard/Order.php +++ b/app/code/Magento/Backend/Helper/Dashboard/Order.php @@ -61,15 +61,15 @@ protected function _initCollection() if ($this->getParam('store')) { $this->_collection->addFieldToFilter('store_id', $this->getParam('store')); } elseif ($this->getParam('website')) { - $storeIds = $this->_storeManager->getWebsite($this->getParam('website'))->getStoreIds(); + $storeIds = $this->getStoreManager()->getWebsite($this->getParam('website'))->getStoreIds(); $this->_collection->addFieldToFilter('store_id', ['in' => implode(',', $storeIds)]); } elseif ($this->getParam('group')) { - $storeIds = $this->_storeManager->getGroup($this->getParam('group'))->getStoreIds(); + $storeIds = $this->getStoreManager()->getGroup($this->getParam('group'))->getStoreIds(); $this->_collection->addFieldToFilter('store_id', ['in' => implode(',', $storeIds)]); } elseif (!$this->_collection->isLive()) { $this->_collection->addFieldToFilter( 'store_id', - ['eq' => $this->_storeManager->getStore(\Magento\Store\Model\Store::ADMIN_CODE)->getId()] + ['eq' => $this->getStoreManager()->getStore(\Magento\Store\Model\Store::ADMIN_CODE)->getId()] ); } $this->_collection->load(); diff --git a/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php index 03ae3b8ce9691..ec23aa0f54070 100644 --- a/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php +++ b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php @@ -169,7 +169,7 @@ protected function addTabToForm($model, $fieldsetId = 'actions_fieldset', $formN { if (!$model) { $id = $this->getRequest()->getParam('id'); - $model = $this->ruleFactory->create(); + $model = $this->getRuleFactory()->create(); $model->load($id); } diff --git a/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php index 74fc7689b6d4f..365c617345d60 100644 --- a/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php +++ b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Conditions.php @@ -160,7 +160,7 @@ protected function addTabToForm($model, $fieldsetId = 'conditions_fieldset', $fo { if (!$model) { $id = $this->getRequest()->getParam('id'); - $model = $this->ruleFactory->create(); + $model = $this->getRuleFactory()->create(); $model->load($id); } $conditionsFieldSetId = $model->getConditionsFieldSetId($formName); From 24d79692c95316e4a479c805429f387d76aaba1d Mon Sep 17 00:00:00 2001 From: Hayder Sharhan Date: Tue, 22 Mar 2016 11:50:11 -0500 Subject: [PATCH 09/25] MAGETWO-50611: [Github][Security] WebAPIs allow anonymous access - Revised README - Added config file to define default value of checkbox. - Changed location of checkbox in backend. - Changed text of label. --- app/code/Magento/Store/etc/webapi.xml | 8 ++--- .../Plugin/AnonymousResourceSecurity.php | 35 ++++++++++++------- .../Model/Plugin/CacheInvalidator.php | 15 +++++--- app/code/Magento/WebapiSecurity/README.md | 7 ++-- .../WebapiSecurity/etc/Adminhtml/system.xml | 8 ++--- .../Magento/WebapiSecurity/etc/config.xml | 16 +++++++++ composer.json | 1 + composer.lock | 12 +++---- 8 files changed, 68 insertions(+), 34 deletions(-) create mode 100644 app/code/Magento/WebapiSecurity/etc/config.xml diff --git a/app/code/Magento/Store/etc/webapi.xml b/app/code/Magento/Store/etc/webapi.xml index 78fd0cfdcf9a8..a344ea26a0b94 100644 --- a/app/code/Magento/Store/etc/webapi.xml +++ b/app/code/Magento/Store/etc/webapi.xml @@ -11,7 +11,7 @@ - + @@ -19,7 +19,7 @@ - + @@ -27,7 +27,7 @@ - + @@ -35,7 +35,7 @@ - + diff --git a/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php index edaa1f0c39795..8c9a7ac865823 100644 --- a/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php @@ -9,38 +9,41 @@ class AnonymousResourceSecurity { - const XML_ALLOW_INSECURE = 'system/webapisecurity/allow_insecure'; + const XML_ALLOW_INSECURE = 'webapi/webapisecurity/allow_insecure'; /** - * @var \Magento\Backend\App\ConfigInterface + * @var \Magento\Framework\App\Config\ReinitableConfigInterface */ - protected $backendConfig; + protected $config; /** - * @var string + * @var array */ protected $resources; /** * AnonymousResourceSecurity constructor. * - * @param \Magento\Backend\App\ConfigInterface $backendConfig - * @param $resources + * @param \Magento\Framework\App\Config\ReinitableConfigInterface $config + * @param array $resources */ - public function __construct(\Magento\Backend\App\ConfigInterface $backendConfig, $resources) + public function __construct(\Magento\Framework\App\Config\ReinitableConfigInterface $config, $resources) { - $this->backendConfig = $backendConfig; + $this->config = $config; $this->resources = $resources; } - public function afterConvert( - Converter $subject, - $nodes - ) { + /** + * @param Converter $subject + * @param array $nodes + * @return array + */ + public function afterConvert(Converter $subject, $nodes) + { if (empty($nodes)) { return $nodes; } - $useInsecure = $this->backendConfig->isSetFlag(self::XML_ALLOW_INSECURE); + $useInsecure = $this->config->getValue(self::XML_ALLOW_INSECURE); if ($useInsecure) { foreach ($this->resources as $route => $requestType) { if ($result = $this->getNode($route, $requestType, $nodes["routes"])) { @@ -63,6 +66,12 @@ public function afterConvert( return $nodes; } + /** + * @param string $route + * @param string $requestType + * @param array $source + * @return array|null + */ private function getNode($route, $requestType, $source) { if (isset($source[$route][$requestType])) { diff --git a/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php b/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php index 72fe04c0bf7fa..5fe32670c974b 100644 --- a/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php @@ -22,12 +22,19 @@ public function __construct(\Magento\Framework\App\Cache\TypeListInterface $cach $this->cacheTypeList = $cacheTypeList; } + /** + * @param \Magento\Framework\App\Config\Value $subject + * @param \Magento\Framework\App\Config\Value $result + * + * @return \Magento\Framework\App\Config\Value + */ public function afterAfterSave( \Magento\Framework\App\Config\Value $subject, - $result - ) - { - if ($result->getPath() == "system/webapisecurity/allow_insecure" && $result->isValueChanged()) { + \Magento\Framework\App\Config\Value $result + ) { + if ($result->getPath() == \Magento\WebapiSecurity\Model\Plugin\AnonymousResourceSecurity::XML_ALLOW_INSECURE + && $result->isValueChanged() + ) { $this->cacheTypeList->invalidate(\Magento\Webapi\Model\Cache\Type\Webapi::TYPE_IDENTIFIER); } diff --git a/app/code/Magento/WebapiSecurity/README.md b/app/code/Magento/WebapiSecurity/README.md index 1772524e47379..df9f68d3a27dc 100644 --- a/app/code/Magento/WebapiSecurity/README.md +++ b/app/code/Magento/WebapiSecurity/README.md @@ -1,5 +1,6 @@ # WebapiSecurity -**WebapiSecurity** enables access management of some webapi resources. -Allowing them to be accessed by anyone. These resources are outlined in di.xml -If anonymous access checkbox is enabled in backend, these resources' security is loosened. +**WebapiSecurity** enables access management of some Web API resources. +If checkbox is enabled in backend through: Stores -> Configuration -> Services -> Magento Web API -> Web Api Security +then the security of all of the services outlined in app/code/Magento/WebapiSecurity/etc/di.xml would be loosened. You may modify these services to customize. +By loosening the security, these services would allow access anonymously (by anyone). diff --git a/app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml b/app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml index 34249a7e46d2a..3d701f1a5b08a 100644 --- a/app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml +++ b/app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml @@ -5,13 +5,13 @@ --> -
+
- + - + Magento\Config\Model\Config\Source\Yesno - Full list can be viewed at Magento/app/code/Magento/WebapiSecurity/etc/di.xml + Anonymous access would be provided for some CMS, Catalog and Store services
diff --git a/app/code/Magento/WebapiSecurity/etc/config.xml b/app/code/Magento/WebapiSecurity/etc/config.xml new file mode 100644 index 0000000000000..df03d23d607be --- /dev/null +++ b/app/code/Magento/WebapiSecurity/etc/config.xml @@ -0,0 +1,16 @@ + + + + + + + 0 + + + + diff --git a/composer.json b/composer.json index 8663b04426e4b..9fccc6d304bf0 100644 --- a/composer.json +++ b/composer.json @@ -172,6 +172,7 @@ "magento/module-vault": "100.0.2", "magento/module-version": "100.0.2", "magento/module-webapi": "100.0.2", + "magento/module-webapisecurity": "100.0.2", "magento/module-weee": "100.0.2", "magento/module-widget": "100.0.2", "magento/module-wishlist": "100.0.2", diff --git a/composer.lock b/composer.lock index 50b6d95197998..fd0eb17375c07 100644 --- a/composer.lock +++ b/composer.lock @@ -4,8 +4,8 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "29f28ff365f5657ea2d0bb7bafe4bd8d", - "content-hash": "39b0f42124f853baedc0207867d2fa71", + "hash": "dff3ec54fe7fce445c95ec3f33524455", + "content-hash": "6a50f51375ee96fbf7459ce1bbb0d41c", "packages": [ { "name": "braintree/braintree_php", @@ -110,7 +110,7 @@ "require": { "colinmollenhour/credis": "1.6", "magento/zendframework1": "1.12.16", - "php": "~5.5.0|~5.6.0|~7.0.0" + "php": "~5.5.22|~5.6.0|~7.0.0" }, "type": "library", "autoload": { @@ -562,12 +562,12 @@ "source": { "type": "git", "url": "https://github.com/magento/zf1.git", - "reference": "dbdf178992bfa52d6e978e62131162301ff6b76f" + "reference": "c9d607bfd9454bc18b9deff737ccd5d044e2ab10" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/magento/zf1/zipball/c9d607bfd9454bc18b9deff737ccd5d044e2ab10", - "reference": "dbdf178992bfa52d6e978e62131162301ff6b76f", + "reference": "c9d607bfd9454bc18b9deff737ccd5d044e2ab10", "shasum": "" }, "require": { @@ -601,7 +601,7 @@ "ZF1", "framework" ], - "time": "2015-09-30 13:04:03" + "time": "2015-10-29 14:34:55" }, { "name": "monolog/monolog", From 220e251a684ca8eb4b40c5763cd6b4618a671eda Mon Sep 17 00:00:00 2001 From: Alexander Paliarush Date: Mon, 21 Mar 2016 15:07:35 -0500 Subject: [PATCH 10/25] MAGETWO-50608: [Github][Security] Able to brute force API token access --- .../Integration/Model/AdminTokenService.php | 23 ++++ .../Model/CustomerTokenService.php | 29 ++++- .../Model/Oauth/Token/RequestLog/Config.php | 49 ++++++++ .../Token/RequestLog/ReaderInterface.php | 22 ++++ .../Token/RequestLog/WriterInterface.php | 38 +++++++ .../Model/Oauth/Token/RequestThrottler.php | 100 ++++++++++++++++ .../ResourceModel/Oauth/Token/RequestLog.php | 107 ++++++++++++++++++ .../Integration/Setup/UpgradeSchema.php | 65 +++++++++++ app/code/Magento/Integration/etc/config.xml | 4 + app/code/Magento/Integration/etc/module.xml | 2 +- 10 files changed, 437 insertions(+), 2 deletions(-) create mode 100644 app/code/Magento/Integration/Model/Oauth/Token/RequestLog/Config.php create mode 100644 app/code/Magento/Integration/Model/Oauth/Token/RequestLog/ReaderInterface.php create mode 100644 app/code/Magento/Integration/Model/Oauth/Token/RequestLog/WriterInterface.php create mode 100644 app/code/Magento/Integration/Model/Oauth/Token/RequestThrottler.php create mode 100644 app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php create mode 100644 app/code/Magento/Integration/Setup/UpgradeSchema.php diff --git a/app/code/Magento/Integration/Model/AdminTokenService.php b/app/code/Magento/Integration/Model/AdminTokenService.php index beb82ce8c02ff..e5c8fbfc56085 100644 --- a/app/code/Magento/Integration/Model/AdminTokenService.php +++ b/app/code/Magento/Integration/Model/AdminTokenService.php @@ -13,6 +13,7 @@ use Magento\Integration\Model\Oauth\TokenFactory as TokenModelFactory; use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory as TokenCollectionFactory; use Magento\User\Model\User as UserModel; +use Magento\Integration\Model\Oauth\Token\RequestThrottler; /** * Class to handle token generation for Admins @@ -46,6 +47,11 @@ class AdminTokenService implements \Magento\Integration\Api\AdminTokenServiceInt */ private $tokenModelCollectionFactory; + /** + * @var RequestThrottler + */ + private $requestThrottler; + /** * Initialize service * @@ -72,8 +78,10 @@ public function __construct( public function createAdminAccessToken($username, $password) { $this->validatorHelper->validate($username, $password); + $this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_ADMIN); $this->userModel->login($username, $password); if (!$this->userModel->getId()) { + $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_ADMIN); /* * This message is same as one thrown in \Magento\Backend\Model\Auth to keep the behavior consistent. * Constant cannot be created in Auth Model since it uses legacy translation that doesn't support it. @@ -83,6 +91,7 @@ public function createAdminAccessToken($username, $password) __('You did not sign in correctly or your account is temporarily disabled.') ); } + $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_ADMIN); return $this->tokenModelFactory->create()->createAdminToken($this->userModel->getId())->getToken(); } @@ -104,4 +113,18 @@ public function revokeAdminAccessToken($adminId) } return true; } + + /** + * Get request throttler instance + * + * @return RequestThrottler + * @deprecated + */ + private function getRequestThrottler() + { + if (!$this->requestThrottler instanceof RequestThrottler) { + return \Magento\Framework\App\ObjectManager::getInstance()->get(RequestThrottler::class); + } + return $this->requestThrottler; + } } diff --git a/app/code/Magento/Integration/Model/CustomerTokenService.php b/app/code/Magento/Integration/Model/CustomerTokenService.php index 1402f4c2b2368..128d5e49ed822 100644 --- a/app/code/Magento/Integration/Model/CustomerTokenService.php +++ b/app/code/Magento/Integration/Model/CustomerTokenService.php @@ -12,6 +12,7 @@ use Magento\Integration\Model\Oauth\Token as Token; use Magento\Integration\Model\Oauth\TokenFactory as TokenModelFactory; use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory as TokenCollectionFactory; +use Magento\Integration\Model\Oauth\Token\RequestThrottler; class CustomerTokenService implements \Magento\Integration\Api\CustomerTokenServiceInterface { @@ -41,6 +42,11 @@ class CustomerTokenService implements \Magento\Integration\Api\CustomerTokenServ */ private $tokenModelCollectionFactory; + /** + * @var RequestThrottler + */ + private $requestThrottler; + /** * Initialize service * @@ -67,7 +73,14 @@ public function __construct( public function createCustomerAccessToken($username, $password) { $this->validatorHelper->validate($username, $password); - $customerDataObject = $this->accountManagement->authenticate($username, $password); + $this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER); + try { + $customerDataObject = $this->accountManagement->authenticate($username, $password); + } catch (\Exception $e) { + $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER); + throw $e; + } + $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER); return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken(); } @@ -89,4 +102,18 @@ public function revokeCustomerAccessToken($customerId) } return true; } + + /** + * Get request throttler instance + * + * @return RequestThrottler + * @deprecated + */ + private function getRequestThrottler() + { + if (!$this->requestThrottler instanceof RequestThrottler) { + return \Magento\Framework\App\ObjectManager::getInstance()->get(RequestThrottler::class); + } + return $this->requestThrottler; + } } diff --git a/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/Config.php b/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/Config.php new file mode 100644 index 0000000000000..da80eeeca8846 --- /dev/null +++ b/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/Config.php @@ -0,0 +1,49 @@ +storeConfig = $storeConfig; + } + + /** + * Get maximum allowed authentication failures count before account is locked. + * + * @return int + */ + public function getMaxFailuresCount() + { + return (int)$this->storeConfig->getValue('oauth/authentication_lock/max_failures_count'); + } + + /** + * Get period of time in seconds after which account will be unlocked. + * + * @return int + */ + public function getLockTimeout() + { + return (int)$this->storeConfig->getValue('oauth/authentication_lock/timeout'); + } +} \ No newline at end of file diff --git a/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/ReaderInterface.php b/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/ReaderInterface.php new file mode 100644 index 0000000000000..9727464c93b14 --- /dev/null +++ b/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/ReaderInterface.php @@ -0,0 +1,22 @@ +requestLogReader = $requestLogReader; + $this->requestLogWriter = $requestLogWriter; + $this->requestLogConfig = $requestLogConfig; + } + + /** + * Throw exception if user account is currently locked because of too many failed authentication attempts. + * + * @param string $userName + * @param int $userType + * @return void + * @throws AuthenticationException + */ + public function throttle($userName, $userType) + { + $count = $this->requestLogReader->getFailuresCount($userName, $userType); + if ($count >= $this->requestLogConfig->getMaxFailuresCount()) { + throw new AuthenticationException(__('Provided credentials are invalid or user account is locked.')); + } + } + + /** + * Reset count of failed authentication attempts. + * + * Unlock user account and make generation of OAuth tokens possible for this account again. + * + * @param string $userName + * @param int $userType + * @return void + */ + public function resetAuthenticationFailuresCount($userName, $userType) + { + $this->requestLogWriter->resetFailuresCount($userName, $userType); + } + + /** + * Increment authentication failures count and lock user account if the limit is reached. + * + * Account will be locked until lock expires. + * + * @param string $userName + * @param int $userType + * @return void + */ + public function logAuthenticationFailure($userName, $userType) + { + $this->requestLogWriter->incrementFailuresCount($userName, $userType); + } +} diff --git a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php new file mode 100644 index 0000000000000..359865d02b6e0 --- /dev/null +++ b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php @@ -0,0 +1,107 @@ +dateTime = $dateTime; + $this->requestLogConfig = $requestLogConfig; + } + + /** + * {@inheritdoc} + */ + protected function _construct() + { + $this->_init('oauth_token_request_log', 'entity_id'); + } + + /** + * {@inheritdoc} + */ + public function getFailuresCount($userName, $userType) + { + $select = $this->getConnection()->select(); + $select->columns('failures_count') + ->from($this->getMainTable()) + ->where('user_login = ? AND user_type = ?', [$userName, $userType]); + + return (int)$this->getConnection()->fetchOne($select); + } + + /** + * {@inheritdoc} + */ + public function resetFailuresCount($userName, $userType) + { + $this->getConnection()->delete( + $this->getMainTable(), + ['user_login = ?' => $userName, 'user_type = ?' => $userType] + ); + } + + /** + * {@inheritdoc} + */ + public function incrementFailuresCount($userName, $userType) + { + $date = (new \DateTime())->setTimestamp($this->dateTime->gmtTimestamp()); + $date->add(new \DateInterval('PT' . $this->requestLogConfig->getLockTimeout() . 'S')); + $this->getConnection()->insertOnDuplicate( + $this->getMainTable(), + [ + 'user_login' => $userName, + 'user_type' => $userType, + 'failures_count' => 1, + 'lock_expires_at' => $date + ], + ['failures_count' => new \Zend_Db_Expr('failures_count+1'), 'lock_expires_at' => $date] + ); + } + + /** + * {@inheritdoc} + */ + public function clearExpiredFailures() + { + $select = $this->getConnection()->select(); + $select->from($this->getMainTable())->where('lock_expires_at <= ?', $this->dateTime->gmtTimestamp()); + $this->getConnection()->delete($select); + } +} diff --git a/app/code/Magento/Integration/Setup/UpgradeSchema.php b/app/code/Magento/Integration/Setup/UpgradeSchema.php new file mode 100644 index 0000000000000..2e91b8e90d90a --- /dev/null +++ b/app/code/Magento/Integration/Setup/UpgradeSchema.php @@ -0,0 +1,65 @@ +startSetup(); + + if (version_compare($context->getVersion(), '2.0.1', '<')) { + /** + * Create table 'oauth_token_request_log' + */ + $table = $setup->getConnection()->newTable( + $setup->getTable('oauth_token_request_log') + )->addColumn( + 'user_login', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 255, + ['nullable' => false, 'primary' => true], + 'Customer email or admin login' + )->addColumn( + 'user_type', + \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, + null, + ['unsigned' => true, 'nullable' => false], + 'User type (admin or customer)' + )->addColumn( + 'failures_count', + \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, + null, + ['unsigned' => true, 'nullable' => true, 'default' => 0], + 'Number of failed authentication attempts in a row' + )->addColumn( + 'lock_expires_at', + \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + null, + [], + 'Lock expiration time' + )->addIndex( + $setup->getIdxName('oauth_token_request_log', ['user_login', 'user_type']), + ['user_login', 'user_type'] + )->setComment( + 'Log of token request authentication failures.' + ); + $setup->getConnection()->createTable($table); + } + + $setup->endSetup(); + } +} diff --git a/app/code/Magento/Integration/etc/config.xml b/app/code/Magento/Integration/etc/config.xml index ac5ff7cd8bd25..19341af43ba99 100644 --- a/app/code/Magento/Integration/etc/config.xml +++ b/app/code/Magento/Integration/etc/config.xml @@ -17,6 +17,10 @@ 0 5 + + 6 + 1800 + diff --git a/app/code/Magento/Integration/etc/module.xml b/app/code/Magento/Integration/etc/module.xml index be193fa8120f0..e7fff2f2804d6 100644 --- a/app/code/Magento/Integration/etc/module.xml +++ b/app/code/Magento/Integration/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + From 3f0667bc071d2b4cf675e58b96a8b21b03864cba Mon Sep 17 00:00:00 2001 From: Oleksii Korshenko Date: Mon, 21 Mar 2016 16:12:14 -0500 Subject: [PATCH 11/25] MAGETWO-50608: [Github][Security] Able to brute force API token access --- .../ResourceModel/Oauth/Token/RequestLog.php | 24 ++++++++++++------- .../Integration/Setup/UpgradeSchema.php | 21 ++++++++++++---- app/code/Magento/Integration/etc/di.xml | 2 ++ 3 files changed, 33 insertions(+), 14 deletions(-) diff --git a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php index 359865d02b6e0..d6babd42eac16 100644 --- a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php +++ b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php @@ -58,11 +58,10 @@ protected function _construct() public function getFailuresCount($userName, $userType) { $select = $this->getConnection()->select(); - $select->columns('failures_count') - ->from($this->getMainTable()) - ->where('user_login = ? AND user_type = ?', [$userName, $userType]); + $select->from($this->getMainTable(), 'failures_count') + ->where('user_name = :user_name AND user_type = :user_type'); - return (int)$this->getConnection()->fetchOne($select); + return (int)$this->getConnection()->fetchOne($select, ['user_name' => $userName, 'user_type' => $userType]); } /** @@ -72,7 +71,7 @@ public function resetFailuresCount($userName, $userType) { $this->getConnection()->delete( $this->getMainTable(), - ['user_login = ?' => $userName, 'user_type = ?' => $userType] + ['user_name = ?' => $userName, 'user_type = ?' => $userType] ); } @@ -83,15 +82,20 @@ public function incrementFailuresCount($userName, $userType) { $date = (new \DateTime())->setTimestamp($this->dateTime->gmtTimestamp()); $date->add(new \DateInterval('PT' . $this->requestLogConfig->getLockTimeout() . 'S')); + $dateTime = $date->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); + $this->getConnection()->insertOnDuplicate( $this->getMainTable(), [ - 'user_login' => $userName, + 'user_name' => $userName, 'user_type' => $userType, 'failures_count' => 1, - 'lock_expires_at' => $date + 'lock_expires_at' => $dateTime ], - ['failures_count' => new \Zend_Db_Expr('failures_count+1'), 'lock_expires_at' => $date] + [ + 'failures_count' => new \Zend_Db_Expr('failures_count+1'), + 'lock_expires_at' => new \Zend_Db_Expr("'" . $dateTime . "'") + ] ); } @@ -100,8 +104,10 @@ public function incrementFailuresCount($userName, $userType) */ public function clearExpiredFailures() { + $date = (new \DateTime())->setTimestamp($this->dateTime->gmtTimestamp()); + $dateTime = $date->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); $select = $this->getConnection()->select(); - $select->from($this->getMainTable())->where('lock_expires_at <= ?', $this->dateTime->gmtTimestamp()); + $select->from($this->getMainTable())->where('lock_expires_at <= ?', $dateTime); $this->getConnection()->delete($select); } } diff --git a/app/code/Magento/Integration/Setup/UpgradeSchema.php b/app/code/Magento/Integration/Setup/UpgradeSchema.php index 2e91b8e90d90a..6d755bb12fd24 100644 --- a/app/code/Magento/Integration/Setup/UpgradeSchema.php +++ b/app/code/Magento/Integration/Setup/UpgradeSchema.php @@ -28,10 +28,16 @@ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $con $table = $setup->getConnection()->newTable( $setup->getTable('oauth_token_request_log') )->addColumn( - 'user_login', + 'log_id', + \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + null, + ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], + 'Log Id' + )->addColumn( + 'user_name', \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 255, - ['nullable' => false, 'primary' => true], + ['nullable' => false], 'Customer email or admin login' )->addColumn( 'user_type', @@ -49,11 +55,16 @@ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $con 'lock_expires_at', \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, null, - [], + ['nullable' => false], 'Lock expiration time' )->addIndex( - $setup->getIdxName('oauth_token_request_log', ['user_login', 'user_type']), - ['user_login', 'user_type'] + $setup->getIdxName( + 'oauth_token_request_log', + ['user_name', 'user_type'], + \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE + ), + ['user_name', 'user_type'], + ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE] )->setComment( 'Log of token request authentication failures.' ); diff --git a/app/code/Magento/Integration/etc/di.xml b/app/code/Magento/Integration/etc/di.xml index e062831a396ca..8b0e04be8cbf5 100644 --- a/app/code/Magento/Integration/etc/di.xml +++ b/app/code/Magento/Integration/etc/di.xml @@ -14,6 +14,8 @@ + + Magento\Framework\Stdlib\DateTime\DateTime\Proxy From cb3f2134d3b194b7bc1a4d7bf27dbb23f65f0a61 Mon Sep 17 00:00:00 2001 From: Alexander Paliarush Date: Mon, 21 Mar 2016 16:47:13 -0500 Subject: [PATCH 12/25] MAGETWO-50608: [Github][Security] Able to brute force API token access --- .../CleanExpiredAuthenticationFailures.php | 40 +++++++++++++++++++ .../Model/CustomerTokenService.php | 5 ++- .../Model/Oauth/Token/RequestThrottler.php | 4 +- app/code/Magento/Integration/etc/crontab.xml | 14 +++++++ 4 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 app/code/Magento/Integration/Cron/CleanExpiredAuthenticationFailures.php create mode 100644 app/code/Magento/Integration/etc/crontab.xml diff --git a/app/code/Magento/Integration/Cron/CleanExpiredAuthenticationFailures.php b/app/code/Magento/Integration/Cron/CleanExpiredAuthenticationFailures.php new file mode 100644 index 0000000000000..f6dc059b339a7 --- /dev/null +++ b/app/code/Magento/Integration/Cron/CleanExpiredAuthenticationFailures.php @@ -0,0 +1,40 @@ +requestLogWriter = $requestLogWriter; + } + + /** + * Clearing log of outdated token request authentication failures. + * + * @return void + */ + public function execute() + { + $this->requestLogWriter->clearExpiredFailures(); + } +} diff --git a/app/code/Magento/Integration/Model/CustomerTokenService.php b/app/code/Magento/Integration/Model/CustomerTokenService.php index 128d5e49ed822..d4e495a6720dd 100644 --- a/app/code/Magento/Integration/Model/CustomerTokenService.php +++ b/app/code/Magento/Integration/Model/CustomerTokenService.php @@ -13,6 +13,7 @@ use Magento\Integration\Model\Oauth\TokenFactory as TokenModelFactory; use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory as TokenCollectionFactory; use Magento\Integration\Model\Oauth\Token\RequestThrottler; +use Magento\Framework\Exception\AuthenticationException; class CustomerTokenService implements \Magento\Integration\Api\CustomerTokenServiceInterface { @@ -78,7 +79,9 @@ public function createCustomerAccessToken($username, $password) $customerDataObject = $this->accountManagement->authenticate($username, $password); } catch (\Exception $e) { $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER); - throw $e; + throw new AuthenticationException( + __('You did not sign in correctly or your account is temporarily disabled.') + ); } $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER); return $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken(); diff --git a/app/code/Magento/Integration/Model/Oauth/Token/RequestThrottler.php b/app/code/Magento/Integration/Model/Oauth/Token/RequestThrottler.php index 6db21364e474b..59ffd26de71d1 100644 --- a/app/code/Magento/Integration/Model/Oauth/Token/RequestThrottler.php +++ b/app/code/Magento/Integration/Model/Oauth/Token/RequestThrottler.php @@ -66,7 +66,9 @@ public function throttle($userName, $userType) { $count = $this->requestLogReader->getFailuresCount($userName, $userType); if ($count >= $this->requestLogConfig->getMaxFailuresCount()) { - throw new AuthenticationException(__('Provided credentials are invalid or user account is locked.')); + throw new AuthenticationException( + __('You did not sign in correctly or your account is temporarily disabled.') + ); } } diff --git a/app/code/Magento/Integration/etc/crontab.xml b/app/code/Magento/Integration/etc/crontab.xml new file mode 100644 index 0000000000000..37440713cdce3 --- /dev/null +++ b/app/code/Magento/Integration/etc/crontab.xml @@ -0,0 +1,14 @@ + + + + + + 0 1 * * * + + + From e2c9fc4b3ead919033bead0d58ee04232ab2a093 Mon Sep 17 00:00:00 2001 From: Alexander Paliarush Date: Mon, 21 Mar 2016 17:29:56 -0500 Subject: [PATCH 13/25] MAGETWO-50608: [Github][Security] Able to brute force API token access --- .../Model/ResourceModel/Oauth/Token/RequestLog.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php index d6babd42eac16..115968682e6fa 100644 --- a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php +++ b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php @@ -106,8 +106,6 @@ public function clearExpiredFailures() { $date = (new \DateTime())->setTimestamp($this->dateTime->gmtTimestamp()); $dateTime = $date->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); - $select = $this->getConnection()->select(); - $select->from($this->getMainTable())->where('lock_expires_at <= ?', $dateTime); - $this->getConnection()->delete($select); + $this->getConnection()->delete($this->getMainTable(), ['lock_expires_at <= ?' => $dateTime]); } } From f92932b83d9b6fe53f4328c9e634d2e6170470c1 Mon Sep 17 00:00:00 2001 From: Alexander Paliarush Date: Tue, 22 Mar 2016 11:55:15 -0500 Subject: [PATCH 14/25] MAGETWO-50608: [Github][Security] Able to brute force API token access --- .../Model/AdminTokenServiceTest.php | 158 ++++++++++++++-- .../Model/CustomerTokenServiceTest.php | 176 +++++++++++++++--- .../Customer/_files/customer_rollback.php | 7 + .../User/_files/user_with_role_rollback.php | 18 ++ 4 files changed, 323 insertions(+), 36 deletions(-) create mode 100644 dev/tests/integration/testsuite/Magento/User/_files/user_with_role_rollback.php diff --git a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php index bf8c2bf3e5d05..6af8713db6151 100644 --- a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php @@ -12,6 +12,7 @@ use Magento\TestFramework\TestCase\WebapiAbstract; use Magento\User\Model\User as UserModel; use Magento\Framework\Webapi\Exception as HTTPExceptionCodes; +use Magento\Integration\Model\Oauth\Token\RequestLog\Config as TokenThrottlerConfig; /** * api-functional test for \Magento\Integration\Model\AdminTokenService. @@ -21,7 +22,6 @@ class AdminTokenServiceTest extends WebapiAbstract const SERVICE_NAME = "integrationAdminTokenServiceV1"; const SERVICE_VERSION = "V1"; const RESOURCE_PATH_ADMIN_TOKEN = "/V1/integration/admin/token"; - const RESOURCE_PATH_CUSTOMER_TOKEN = "/V1/integration/customer/token"; /** * @var \Magento\Integration\Api\AdminTokenServiceInterface @@ -38,6 +38,11 @@ class AdminTokenServiceTest extends WebapiAbstract */ private $userModel; + /** + * @var int + */ + private $attemptsCountToLockAccount; + /** * Setup AdminTokenService */ @@ -47,6 +52,9 @@ public function setUp() $this->tokenService = Bootstrap::getObjectManager()->get('Magento\Integration\Model\AdminTokenService'); $this->tokenModel = Bootstrap::getObjectManager()->get('Magento\Integration\Model\Oauth\Token'); $this->userModel = Bootstrap::getObjectManager()->get('Magento\User\Model\User'); + /** @var TokenThrottlerConfig $tokenThrottlerConfig */ + $tokenThrottlerConfig = Bootstrap::getObjectManager()->get(TokenThrottlerConfig::class); + $this->attemptsCountToLockAccount = $tokenThrottlerConfig->getMaxFailuresCount(); } /** @@ -67,13 +75,7 @@ public function testCreateAdminAccessToken() 'password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD, ]; $accessToken = $this->_webApiCall($serviceInfo, $requestData); - - $adminUserId = $this->userModel->loadByUsername($adminUserNameFromFixture)->getId(); - /** @var $token TokenModel */ - $token = $this->tokenModel - ->loadByAdminId($adminUserId) - ->getToken(); - $this->assertEquals($accessToken, $token); + $this->assertToken($adminUserNameFromFixture, $accessToken); } /** @@ -81,6 +83,7 @@ public function testCreateAdminAccessToken() */ public function testCreateAdminAccessTokenEmptyOrNullCredentials() { + $noExceptionOccurred = false; try { $serviceInfo = [ 'rest' => [ @@ -90,30 +93,36 @@ public function testCreateAdminAccessTokenEmptyOrNullCredentials() ]; $requestData = ['username' => '', 'password' => '']; $this->_webApiCall($serviceInfo, $requestData); + $noExceptionOccurred = true; } catch (\Exception $e) { $this->assertInputExceptionMessages($e); } + if ($noExceptionOccurred) { + $this->fail("Exception was expected to be thrown when provided credentials are invalid."); + } } - public function testCreateAdminAccessTokenInvalidCustomer() + public function testCreateAdminAccessTokenInvalidCredentials() { $customerUserName = 'invalid'; $password = 'invalid'; + $noExceptionOccurred = false; try { $serviceInfo = [ 'rest' => [ - 'resourcePath' => self::RESOURCE_PATH_CUSTOMER_TOKEN, + 'resourcePath' => self::RESOURCE_PATH_ADMIN_TOKEN, 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, ], ]; $requestData = ['username' => $customerUserName, 'password' => $password]; $this->_webApiCall($serviceInfo, $requestData); + $noExceptionOccurred = true; } catch (\Exception $e) { - $this->assertEquals(HTTPExceptionCodes::HTTP_UNAUTHORIZED, $e->getCode()); - $exceptionData = $this->processRestExceptionResult($e); - $expectedExceptionData = ['message' => 'Invalid login or password.']; + $this->assertInvalidCredentialsException($e); + } + if ($noExceptionOccurred) { + $this->fail("Exception was expected to be thrown when provided credentials are invalid."); } - $this->assertEquals($expectedExceptionData, $exceptionData); } /** @@ -129,6 +138,96 @@ public function validationDataProvider() ]; } + /** + * @magentoApiDataFixture Magento/User/_files/user_with_role.php + */ + public function testThrottlingMaxAttempts() + { + $adminUserNameFromFixture = 'adminUser'; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH_ADMIN_TOKEN, + 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + ], + ]; + $invalidCredentials = [ + 'username' => $adminUserNameFromFixture, + 'password' => 'invalid', + ]; + $validCredentials = [ + 'username' => $adminUserNameFromFixture, + 'password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD, + ]; + + /* Try to get token using invalid credentials for 5 times (account is locked after 6 attempts) */ + $noExceptionOccurred = false; + for ($i = 0; $i < ($this->attemptsCountToLockAccount - 1); $i++) { + try { + $this->_webApiCall($serviceInfo, $invalidCredentials); + $noExceptionOccurred = true; + } catch (\Exception $e) { + } + } + if ($noExceptionOccurred) { + $this->fail( + "Precondition failed: exception should have occurred when token was requested with invalid credentials." + ); + } + + /** On 6th attempt it still should be possible to get token if valid credentials are specified */ + $accessToken = $this->_webApiCall($serviceInfo, $validCredentials); + $this->assertToken($adminUserNameFromFixture, $accessToken); + } + + /** + * @magentoApiDataFixture Magento/User/_files/user_with_role.php + */ + public function testThrottlingAccountLockout() + { + $adminUserNameFromFixture = 'adminUser'; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH_ADMIN_TOKEN, + 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + ], + ]; + $invalidCredentials = [ + 'username' => $adminUserNameFromFixture, + 'password' => 'invalid', + ]; + $validCredentials = [ + 'username' => $adminUserNameFromFixture, + 'password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD, + ]; + + /* Try to get token using invalid credentials for 5 times (account would be locked after 6 attempts) */ + $noExceptionOccurred = false; + for ($i = 0; $i < $this->attemptsCountToLockAccount; $i++) { + try { + $this->_webApiCall($serviceInfo, $invalidCredentials); + $noExceptionOccurred = true; + } catch (\Exception $e) { + $this->assertInvalidCredentialsException($e); + } + if ($noExceptionOccurred) { + $this->fail("Exception was expected to be thrown when provided credentials are invalid."); + } + } + + $noExceptionOccurred = false; + try { + $this->_webApiCall($serviceInfo, $validCredentials); + $noExceptionOccurred = true; + } catch (\Exception $e) { + $this->assertInvalidCredentialsException($e); + } + if ($noExceptionOccurred) { + $this->fail("Exception was expected to be thrown because account should have been locked at this point."); + } + } + /** * Assert for presence of Input exception messages * @@ -157,4 +256,35 @@ private function assertInputExceptionMessages($e) ]; $this->assertEquals($expectedExceptionData, $exceptionData); } + + /** + * Make sure that status code and message are correct in case of authentication failure. + * + * @param \Exception $e + */ + private function assertInvalidCredentialsException($e) + { + $this->assertEquals(HTTPExceptionCodes::HTTP_UNAUTHORIZED, $e->getCode(), "Response HTTP code is invalid."); + $exceptionData = $this->processRestExceptionResult($e); + $expectedExceptionData = [ + 'message' => 'You did not sign in correctly or your account is temporarily disabled.' + ]; + $this->assertEquals($expectedExceptionData, $exceptionData, "Exception message is invalid."); + } + + /** + * Make sure provided token is valid and belongs to the specified user. + * + * @param string $username + * @param string $accessToken + */ + private function assertToken($username, $accessToken) + { + $adminUserId = $this->userModel->loadByUsername($username)->getId(); + /** @var $token TokenModel */ + $token = $this->tokenModel + ->loadByAdminId($adminUserId) + ->getToken(); + $this->assertEquals($accessToken, $token); + } } diff --git a/dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php b/dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php index d1f072e6a2d5c..f04f1472e0f58 100644 --- a/dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php @@ -14,6 +14,8 @@ use Magento\User\Model\User as UserModel; use Magento\Framework\Webapi\Exception as HTTPExceptionCodes; use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory; +use Magento\Integration\Model\Oauth\Token\RequestLog\Config as TokenThrottlerConfig; +use Magento\Integration\Api\CustomerTokenServiceInterface; /** * api-functional test for \Magento\Integration\Model\CustomerTokenService. @@ -23,7 +25,6 @@ class CustomerTokenServiceTest extends WebapiAbstract const SERVICE_NAME = "integrationCustomerTokenServiceV1"; const SERVICE_VERSION = "V1"; const RESOURCE_PATH_CUSTOMER_TOKEN = "/V1/integration/customer/token"; - const RESOURCE_PATH_ADMIN_TOKEN = "/V1/integration/admin/token"; /** * @var CustomerTokenServiceInterface @@ -45,6 +46,11 @@ class CustomerTokenServiceTest extends WebapiAbstract */ private $userModel; + /** + * @var int + */ + private $attemptsCountToLockAccount; + /** * Setup CustomerTokenService */ @@ -60,6 +66,9 @@ public function setUp() ); $this->tokenCollection = $tokenCollectionFactory->create(); $this->userModel = Bootstrap::getObjectManager()->get('Magento\User\Model\User'); + /** @var TokenThrottlerConfig $tokenThrottlerConfig */ + $tokenThrottlerConfig = Bootstrap::getObjectManager()->get(TokenThrottlerConfig::class); + $this->attemptsCountToLockAccount = $tokenThrottlerConfig->getMaxFailuresCount(); } /** @@ -67,9 +76,8 @@ public function setUp() */ public function testCreateCustomerAccessToken() { - $customerUserName = 'customer@example.com'; + $userName = 'customer@example.com'; $password = 'password'; - $isTokenCorrect = false; $serviceInfo = [ 'rest' => [ @@ -77,29 +85,18 @@ public function testCreateCustomerAccessToken() 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, ], ]; - $requestData = ['username' => $customerUserName, 'password' => $password]; + $requestData = ['username' => $userName, 'password' => $password]; $accessToken = $this->_webApiCall($serviceInfo, $requestData); - $customerData = $this->customerAccountManagement->authenticate($customerUserName, $password); - - /** @var $this->tokenCollection \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection */ - $this->tokenCollection->addFilterByCustomerId($customerData->getId()); - - foreach ($this->tokenCollection->getItems() as $item) { - /** @var $item TokenModel */ - if ($item->getToken() == $accessToken) { - $isTokenCorrect = true; - } - } - $this->assertTrue($isTokenCorrect); + $this->assertToken($accessToken, $userName, $password); } /** * @dataProvider validationDataProvider - * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function testCreateCustomerAccessTokenEmptyOrNullCredentials($username, $password) { + $noExceptionOccurred = false; try { $serviceInfo = [ 'rest' => [ @@ -107,17 +104,22 @@ public function testCreateCustomerAccessTokenEmptyOrNullCredentials($username, $ 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, ], ]; - $requestData = ['username' => '', 'password' => '']; + $requestData = ['username' => $username, 'password' => $password]; $this->_webApiCall($serviceInfo, $requestData); + $noExceptionOccurred = true; } catch (\Exception $e) { $this->assertInputExceptionMessages($e); } + if ($noExceptionOccurred) { + $this->fail("Exception was expected to be thrown when provided credentials are invalid."); + } } public function testCreateCustomerAccessTokenInvalidCustomer() { $customerUserName = 'invalid'; $password = 'invalid'; + $noExceptionOccurred = false; try { $serviceInfo = [ 'rest' => [ @@ -127,12 +129,13 @@ public function testCreateCustomerAccessTokenInvalidCustomer() ]; $requestData = ['username' => $customerUserName, 'password' => $password]; $this->_webApiCall($serviceInfo, $requestData); + $noExceptionOccurred = true; } catch (\Exception $e) { - $this->assertEquals(HTTPExceptionCodes::HTTP_UNAUTHORIZED, $e->getCode()); - $exceptionData = $this->processRestExceptionResult($e); - $expectedExceptionData = ['message' => 'Invalid login or password.']; + $this->assertInvalidCredentialsException($e); + } + if ($noExceptionOccurred) { + $this->fail("Exception was expected to be thrown when provided credentials are invalid."); } - $this->assertEquals($expectedExceptionData, $exceptionData); } /** @@ -176,4 +179,133 @@ private function assertInputExceptionMessages($e) ]; $this->assertEquals($expectedExceptionData, $exceptionData); } + + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + */ + public function testThrottlingMaxAttempts() + { + $userNameFromFixture = 'customer@example.com'; + $passwordFromFixture = 'password'; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH_CUSTOMER_TOKEN, + 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + ], + ]; + $invalidCredentials = [ + 'username' => $userNameFromFixture, + 'password' => 'invalid', + ]; + $validCredentials = [ + 'username' => $userNameFromFixture, + 'password' => $passwordFromFixture, + ]; + + /* Try to get token using invalid credentials for 5 times (account is locked after 6 attempts) */ + $noExceptionOccurred = false; + for ($i = 0; $i < ($this->attemptsCountToLockAccount - 1); $i++) { + try { + $this->_webApiCall($serviceInfo, $invalidCredentials); + $noExceptionOccurred = true; + } catch (\Exception $e) { + } + } + if ($noExceptionOccurred) { + $this->fail( + "Precondition failed: exception should have occurred when token was requested with invalid credentials." + ); + } + + /** On 6th attempt it still should be possible to get token if valid credentials are specified */ + $accessToken = $this->_webApiCall($serviceInfo, $validCredentials); + $this->assertToken($accessToken, $userNameFromFixture, $passwordFromFixture); + } + + /** + * @magentoApiDataFixture Magento/Customer/_files/customer.php + */ + public function testThrottlingAccountLockout() + { + $userNameFromFixture = 'customer@example.com'; + $passwordFromFixture = 'password'; + + $serviceInfo = [ + 'rest' => [ + 'resourcePath' => self::RESOURCE_PATH_CUSTOMER_TOKEN, + 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST, + ], + ]; + $invalidCredentials = [ + 'username' => $userNameFromFixture, + 'password' => 'invalid', + ]; + $validCredentials = [ + 'username' => $userNameFromFixture, + 'password' => $passwordFromFixture, + ]; + + /* Try to get token using invalid credentials for 5 times (account would be locked after 6 attempts) */ + $noExceptionOccurred = false; + for ($i = 0; $i < $this->attemptsCountToLockAccount; $i++) { + try { + $this->_webApiCall($serviceInfo, $invalidCredentials); + $noExceptionOccurred = true; + } catch (\Exception $e) { + $this->assertInvalidCredentialsException($e); + } + if ($noExceptionOccurred) { + $this->fail("Exception was expected to be thrown when provided credentials are invalid."); + } + } + + $noExceptionOccurred = false; + try { + $this->_webApiCall($serviceInfo, $validCredentials); + $noExceptionOccurred = true; + } catch (\Exception $e) { + $this->assertInvalidCredentialsException($e); + } + if ($noExceptionOccurred) { + $this->fail("Exception was expected to be thrown because account should have been locked at this point."); + } + } + + /** + * Make sure that status code and message are correct in case of authentication failure. + * + * @param \Exception $e + */ + private function assertInvalidCredentialsException($e) + { + $this->assertEquals(HTTPExceptionCodes::HTTP_UNAUTHORIZED, $e->getCode(), "Response HTTP code is invalid."); + $exceptionData = $this->processRestExceptionResult($e); + $expectedExceptionData = [ + 'message' => 'You did not sign in correctly or your account is temporarily disabled.' + ]; + $this->assertEquals($expectedExceptionData, $exceptionData, "Exception message is invalid."); + } + + /** + * Make sure provided token is valid and belongs to the specified user. + * + * @param string $accessToken + * @param string $userName + * @param string $password + */ + private function assertToken($accessToken, $userName, $password) + { + $customerData = $this->customerAccountManagement->authenticate($userName, $password); + /** @var $this ->tokenCollection \Magento\Integration\Model\ResourceModel\Oauth\Token\Collection */ + $this->tokenCollection->addFilterByCustomerId($customerData->getId()); + $isTokenCorrect = false; + foreach ($this->tokenCollection->getItems() as $item) { + /** @var $item TokenModel */ + if ($item->getToken() == $accessToken) { + $isTokenCorrect = true; + } + } + $this->assertTrue($isTokenCorrect); + } } diff --git a/dev/tests/integration/testsuite/Magento/Customer/_files/customer_rollback.php b/dev/tests/integration/testsuite/Magento/Customer/_files/customer_rollback.php index 0b5fc5e284ece..48089c670cfea 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/_files/customer_rollback.php +++ b/dev/tests/integration/testsuite/Magento/Customer/_files/customer_rollback.php @@ -4,6 +4,8 @@ * See COPYING.txt for license details. */ +use Magento\Integration\Model\Oauth\Token\RequestThrottler; + /** @var \Magento\Framework\Registry $registry */ $registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\Framework\Registry'); $registry->unregister('isSecureArea'); @@ -18,3 +20,8 @@ $registry->unregister('isSecureArea'); $registry->register('isSecureArea', false); + +/* Unlock account if it was locked for tokens retrieval */ +/** @var RequestThrottler $throttler */ +$throttler = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(RequestThrottler::class); +$throttler->resetAuthenticationFailuresCount('customer@example.com', RequestThrottler::USER_TYPE_CUSTOMER); diff --git a/dev/tests/integration/testsuite/Magento/User/_files/user_with_role_rollback.php b/dev/tests/integration/testsuite/Magento/User/_files/user_with_role_rollback.php new file mode 100644 index 0000000000000..ceccfdb71976d --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/User/_files/user_with_role_rollback.php @@ -0,0 +1,18 @@ +create('Magento\User\Model\User'); +$userName = 'adminUser'; +$model->load($userName, 'username'); +$model->delete(); + +/* Unlock account if it was locked */ +/** @var RequestThrottler $throttler */ +$throttler = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(RequestThrottler::class); +$throttler->resetAuthenticationFailuresCount($userName, RequestThrottler::USER_TYPE_ADMIN); From 631e111120cd5f7880b089dd8a633fb054cba544 Mon Sep 17 00:00:00 2001 From: Hayder Sharhan Date: Tue, 22 Mar 2016 13:22:22 -0500 Subject: [PATCH 15/25] MAGETWO-50551: When saving product or category cache cleared by general tag - Code cleanup. --- .../Observer/InvalidateVarnishObserver.php | 4 +++- app/code/Magento/Catalog/Model/Product.php | 23 +++++-------------- 2 files changed, 9 insertions(+), 18 deletions(-) diff --git a/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php b/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php index eb2ac66f66dc4..bf3adc9fb6168 100644 --- a/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php +++ b/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php @@ -50,7 +50,9 @@ public function execute(\Magento\Framework\Event\Observer $observer) foreach ($object->getIdentities() as $tag) { $tags[] = sprintf($pattern, $tag); } - $this->purgeCache->sendPurgeRequest(implode('|', array_unique($tags))); + if (!empty($tags)) { + $this->purgeCache->sendPurgeRequest(implode('|', array_unique($tags))); + } } } } diff --git a/app/code/Magento/Catalog/Model/Product.php b/app/code/Magento/Catalog/Model/Product.php index 0c651799f1c7f..d519c543636b2 100644 --- a/app/code/Magento/Catalog/Model/Product.php +++ b/app/code/Magento/Catalog/Model/Product.php @@ -2268,7 +2268,7 @@ public function getIdentities() $identities[] = self::CACHE_PRODUCT_CATEGORY_TAG . '_' . $categoryId; } } - if ($this->getAppState()->getAreaCode() === 'frontend') { + if ($this->getAppState()->getAreaCode() === \Magento\Framework\App\Area::AREA_FRONTEND) { $identities[] = self::CACHE_TAG; } return array_unique($identities); @@ -2560,27 +2560,16 @@ public function setId($value) /** * Get application state * + * @deprecated * @return \Magento\Framework\App\State */ private function getAppState() { if (!$this->appState instanceof \Magento\Framework\App\State) { - return \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\State'); - } else { - return $this->appState; + $this->appState = \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\App\State::class + ); } - } - - /** - * Set application state - * - * @deprecated - * @param \Magento\Framework\App\State $appState - * @return $this - */ - public function setAppState(\Magento\Framework\App\State $appState) - { - $this->appState = $appState; - return $this; + return $this->appState; } } From 5b7abf1f0b39e4e03a0857f72eb66b8f1b026f40 Mon Sep 17 00:00:00 2001 From: Oleksii Korshenko Date: Tue, 22 Mar 2016 13:49:15 -0500 Subject: [PATCH 16/25] MAGETWO-50608: [Github][Security] Able to brute force API token access --- .../Integration/Model/Oauth/Token/RequestLog/Config.php | 2 +- .../Model/Oauth/Token/RequestLog/WriterInterface.php | 2 ++ .../Model/ResourceModel/Oauth/Token/RequestLog.php | 4 ++-- .../Model/Plugin/AnonymousResourceSecurity.php | 8 ++++++++ .../WebapiSecurity/Model/Plugin/CacheInvalidator.php | 4 +++- app/code/Magento/WebapiSecurity/composer.json | 3 ++- app/code/Magento/WebapiSecurity/registration.php | 2 +- composer.json | 2 +- composer.lock | 4 ++-- 9 files changed, 22 insertions(+), 9 deletions(-) diff --git a/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/Config.php b/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/Config.php index da80eeeca8846..a4f76565a3bb6 100644 --- a/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/Config.php +++ b/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/Config.php @@ -46,4 +46,4 @@ public function getLockTimeout() { return (int)$this->storeConfig->getValue('oauth/authentication_lock/timeout'); } -} \ No newline at end of file +} diff --git a/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/WriterInterface.php b/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/WriterInterface.php index e42a31a8f8e58..d91051bee286c 100644 --- a/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/WriterInterface.php +++ b/app/code/Magento/Integration/Model/Oauth/Token/RequestLog/WriterInterface.php @@ -17,6 +17,7 @@ interface WriterInterface * @param string $userName * @param int $userType * @param return void + * @return void */ public function resetFailuresCount($userName, $userType); @@ -26,6 +27,7 @@ public function resetFailuresCount($userName, $userType); * @param string $userName * @param int $userType * @param return void + * @return void */ public function incrementFailuresCount($userName, $userType); diff --git a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php index 115968682e6fa..62a4bcb955e25 100644 --- a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php +++ b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php @@ -12,8 +12,8 @@ /** * Resource model for failed authentication attempts to retrieve admin/customer token. */ -class RequestLog extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb - implements ReaderInterface, WriterInterface +class RequestLog extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb implements + ReaderInterface, WriterInterface { /** * @var \Magento\Framework\Stdlib\DateTime\DateTime diff --git a/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php index 8c9a7ac865823..b0371305995b5 100644 --- a/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php @@ -9,6 +9,9 @@ class AnonymousResourceSecurity { + /** + * Config path + */ const XML_ALLOW_INSECURE = 'webapi/webapisecurity/allow_insecure'; /** @@ -34,9 +37,12 @@ public function __construct(\Magento\Framework\App\Config\ReinitableConfigInterf } /** + * Filter config values. + * * @param Converter $subject * @param array $nodes * @return array + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterConvert(Converter $subject, $nodes) { @@ -67,6 +73,8 @@ public function afterConvert(Converter $subject, $nodes) } /** + * Get node by path. + * * @param string $route * @param string $requestType * @param array $source diff --git a/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php b/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php index 5fe32670c974b..7227b508c5593 100644 --- a/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php @@ -23,10 +23,12 @@ public function __construct(\Magento\Framework\App\Cache\TypeListInterface $cach } /** + * Invalidate WebApi cache if needed. + * * @param \Magento\Framework\App\Config\Value $subject * @param \Magento\Framework\App\Config\Value $result - * * @return \Magento\Framework\App\Config\Value + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterAfterSave( \Magento\Framework\App\Config\Value $subject, diff --git a/app/code/Magento/WebapiSecurity/composer.json b/app/code/Magento/WebapiSecurity/composer.json index 292a544ba88b3..e42cf0a056d89 100644 --- a/app/code/Magento/WebapiSecurity/composer.json +++ b/app/code/Magento/WebapiSecurity/composer.json @@ -4,10 +4,11 @@ "require": { "php": "~5.5.22|~5.6.0|~7.0.0", "magento/module-backend": "100.0.*", + "magento/module-webapi": "100.0.*", "magento/framework": "100.0.*" }, "type": "magento2-module", - "version": "100.0.2", + "version": "100.0.0", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/WebapiSecurity/registration.php b/app/code/Magento/WebapiSecurity/registration.php index b12004c6ab4cf..886c73be0a230 100644 --- a/app/code/Magento/WebapiSecurity/registration.php +++ b/app/code/Magento/WebapiSecurity/registration.php @@ -1,6 +1,6 @@ Date: Tue, 22 Mar 2016 14:00:06 -0500 Subject: [PATCH 17/25] MAGETWO-50608: [Github][Security] Able to brute force API token access --- .../Integration/Model/ResourceModel/Oauth/Token/RequestLog.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php index 62a4bcb955e25..ca46c075d4cd5 100644 --- a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php +++ b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php @@ -13,7 +13,8 @@ * Resource model for failed authentication attempts to retrieve admin/customer token. */ class RequestLog extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb implements - ReaderInterface, WriterInterface + ReaderInterface, + WriterInterface { /** * @var \Magento\Framework\Stdlib\DateTime\DateTime From afaefb3aee676300b3a48745a56f4d7320da984d Mon Sep 17 00:00:00 2001 From: Hayder Sharhan Date: Tue, 22 Mar 2016 14:21:47 -0500 Subject: [PATCH 18/25] MAGETWO-50551: When saving product or category cache cleared by general tag - Fix unit test. --- .../Unit/Observer/InvalidateVarnishObserverTest.php | 2 +- app/code/Magento/Catalog/Model/Product.php | 2 +- .../Magento/Catalog/Test/Unit/Model/ProductTest.php | 13 +++++++++++++ .../Test/Unit/Observer/FlushCacheByTagsTest.php | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/app/code/Magento/CacheInvalidate/Test/Unit/Observer/InvalidateVarnishObserverTest.php b/app/code/Magento/CacheInvalidate/Test/Unit/Observer/InvalidateVarnishObserverTest.php index 9b59500a8123f..bc3a752b47479 100644 --- a/app/code/Magento/CacheInvalidate/Test/Unit/Observer/InvalidateVarnishObserverTest.php +++ b/app/code/Magento/CacheInvalidate/Test/Unit/Observer/InvalidateVarnishObserverTest.php @@ -55,7 +55,7 @@ protected function setUp() public function testInvalidateVarnish() { $tags = ['cache_1', 'cache_group']; - $pattern = '((^|,)cache(,|$))|((^|,)cache_1(,|$))|((^|,)cache_group(,|$))'; + $pattern = '((^|,)cache_1(,|$))|((^|,)cache_group(,|$))'; $this->configMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); $this->configMock->expects( diff --git a/app/code/Magento/Catalog/Model/Product.php b/app/code/Magento/Catalog/Model/Product.php index d15342693a5c1..2a2150c79e29a 100644 --- a/app/code/Magento/Catalog/Model/Product.php +++ b/app/code/Magento/Catalog/Model/Product.php @@ -2268,7 +2268,7 @@ public function getIdentities() $identities[] = self::CACHE_PRODUCT_CATEGORY_TAG . '_' . $categoryId; } } - if ($this->getAppState()->getAreaCode() === \Magento\Framework\App\Area::AREA_FRONTEND) { + if ($this->getAppState()->getAreaCode() == \Magento\Framework\App\Area::AREA_FRONTEND) { $identities[] = self::CACHE_TAG; } return array_unique($identities); diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTest.php index 9659cba70131c..2e4a525f12765 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTest.php @@ -166,6 +166,11 @@ class ProductTest extends \PHPUnit_Framework_TestCase /** @var \PHPUnit_Framework_MockObject_MockObject */ protected $mediaConfig; + /** + * @var \Magento\Framework\App\State|\PHPUnit_Framework_MockObject_MockObject + */ + private $appStateMock; + /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ @@ -365,6 +370,14 @@ protected function setUp() ] ); + $this->appStateMock = $this->getMockBuilder(\Magento\Framework\App\State::class) + ->disableOriginalConstructor() + ->setMethods([]) + ->getMock(); + $modelReflection = new \ReflectionClass(get_class($this->model)); + $appStateReflection = $modelReflection->getProperty('appState'); + $appStateReflection->setAccessible(true); + $appStateReflection->setValue($this->model, $this->appStateMock); } public function testGetAttributes() diff --git a/app/code/Magento/PageCache/Test/Unit/Observer/FlushCacheByTagsTest.php b/app/code/Magento/PageCache/Test/Unit/Observer/FlushCacheByTagsTest.php index 1fcbff4fbf9cd..16c3089cc7a18 100644 --- a/app/code/Magento/PageCache/Test/Unit/Observer/FlushCacheByTagsTest.php +++ b/app/code/Magento/PageCache/Test/Unit/Observer/FlushCacheByTagsTest.php @@ -62,7 +62,7 @@ public function testExecute($cacheState) if ($cacheState) { $tags = ['cache_1', 'cache_group']; - $expectedTags = ['cache_1', 'cache_group', 'cache']; + $expectedTags = ['cache_1', 'cache_group']; $eventMock = $this->getMock('Magento\Framework\Event', ['getObject'], [], '', false); $eventMock->expects($this->once())->method('getObject')->will($this->returnValue($observedObject)); From d3eb4d57b448f83b3278f49f305a064bf7444ccd Mon Sep 17 00:00:00 2001 From: Oleksii Korshenko Date: Tue, 22 Mar 2016 14:21:05 -0500 Subject: [PATCH 19/25] MAGETWO-50611: [Github][Security] WebAPIs allow anonymous access --- .../WebapiSecurity/etc/{Adminhtml => Adminhtml-tm}/system.xml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename app/code/Magento/WebapiSecurity/etc/{Adminhtml => Adminhtml-tm}/system.xml (100%) diff --git a/app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml b/app/code/Magento/WebapiSecurity/etc/Adminhtml-tm/system.xml similarity index 100% rename from app/code/Magento/WebapiSecurity/etc/Adminhtml/system.xml rename to app/code/Magento/WebapiSecurity/etc/Adminhtml-tm/system.xml From 94174cd210f7bec352cf4ef709589d098ce14274 Mon Sep 17 00:00:00 2001 From: Oleksii Korshenko Date: Tue, 22 Mar 2016 14:21:26 -0500 Subject: [PATCH 20/25] MAGETWO-50611: [Github][Security] WebAPIs allow anonymous access --- .../WebapiSecurity/etc/{Adminhtml-tm => adminhtml}/system.xml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename app/code/Magento/WebapiSecurity/etc/{Adminhtml-tm => adminhtml}/system.xml (100%) diff --git a/app/code/Magento/WebapiSecurity/etc/Adminhtml-tm/system.xml b/app/code/Magento/WebapiSecurity/etc/adminhtml/system.xml similarity index 100% rename from app/code/Magento/WebapiSecurity/etc/Adminhtml-tm/system.xml rename to app/code/Magento/WebapiSecurity/etc/adminhtml/system.xml From c3ebd109df89f653b4da7b28a695827f6e3a4091 Mon Sep 17 00:00:00 2001 From: Oleksii Korshenko Date: Tue, 22 Mar 2016 14:40:00 -0500 Subject: [PATCH 21/25] MAGETWO-50611: [Github][Security] WebAPIs allow anonymous access --- app/code/Magento/WebapiSecurity/composer.json | 3 +-- composer.json | 2 +- composer.lock | 6 +++--- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/app/code/Magento/WebapiSecurity/composer.json b/app/code/Magento/WebapiSecurity/composer.json index e42cf0a056d89..d07e2e60d9960 100644 --- a/app/code/Magento/WebapiSecurity/composer.json +++ b/app/code/Magento/WebapiSecurity/composer.json @@ -1,9 +1,8 @@ { - "name": "magento/module-webapisecurity", + "name": "magento/module-webapi-security", "description": "WebapiSecurity module provides option to loosen security on some webapi resources.", "require": { "php": "~5.5.22|~5.6.0|~7.0.0", - "magento/module-backend": "100.0.*", "magento/module-webapi": "100.0.*", "magento/framework": "100.0.*" }, diff --git a/composer.json b/composer.json index 1cc4f62f93a94..73115b15a9f32 100644 --- a/composer.json +++ b/composer.json @@ -172,7 +172,7 @@ "magento/module-vault": "100.0.2", "magento/module-version": "100.0.2", "magento/module-webapi": "100.0.2", - "magento/module-webapisecurity": "100.0.0", + "magento/module-webapi-security": "100.0.0", "magento/module-weee": "100.0.2", "magento/module-widget": "100.0.2", "magento/module-wishlist": "100.0.2", diff --git a/composer.lock b/composer.lock index 83491f0fc90b5..4aaae63b403d4 100644 --- a/composer.lock +++ b/composer.lock @@ -4,8 +4,8 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "20f1db43c90fd881c59d8445753e0144", - "content-hash": "11285020a0aef9e36a7023bfe7e50b90", + "hash": "d81a16c234a62403d9b5b06057393d9d", + "content-hash": "cd415001aebab7eb87bb62e2223509fc", "packages": [ { "name": "braintree/braintree_php", @@ -110,7 +110,7 @@ "require": { "colinmollenhour/credis": "1.6", "magento/zendframework1": "1.12.16", - "php": "~5.5.22|~5.6.0|~7.0.0" + "php": "~5.5.0|~5.6.0|~7.0.0" }, "type": "library", "autoload": { From ad35c5076c0c2c5743310342d74e7289fbb11161 Mon Sep 17 00:00:00 2001 From: Hayder Sharhan Date: Tue, 22 Mar 2016 15:38:49 -0500 Subject: [PATCH 22/25] MAGETWO-50611: [Github][Security] WebAPIs allow anonymous access - Changed the way di argument is structured. - Changed the acl node for some services. - Revised README --- app/code/Magento/Catalog/etc/webapi.xml | 10 +-- .../Plugin/AnonymousResourceSecurity.php | 3 +- app/code/Magento/WebapiSecurity/README.md | 2 +- app/code/Magento/WebapiSecurity/etc/di.xml | 62 +++++++++---------- 4 files changed, 39 insertions(+), 38 deletions(-) diff --git a/app/code/Magento/Catalog/etc/webapi.xml b/app/code/Magento/Catalog/etc/webapi.xml index 462df42a288e9..a8dc6ead7975f 100644 --- a/app/code/Magento/Catalog/etc/webapi.xml +++ b/app/code/Magento/Catalog/etc/webapi.xml @@ -97,19 +97,19 @@ - + - + - + @@ -175,7 +175,7 @@ - + @@ -199,7 +199,7 @@ - + diff --git a/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php index b0371305995b5..204ddbdc59906 100644 --- a/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php @@ -51,7 +51,8 @@ public function afterConvert(Converter $subject, $nodes) } $useInsecure = $this->config->getValue(self::XML_ALLOW_INSECURE); if ($useInsecure) { - foreach ($this->resources as $route => $requestType) { + foreach (array_keys($this->resources) as $resource) { + list($route, $requestType) = explode("::", $resource); if ($result = $this->getNode($route, $requestType, $nodes["routes"])) { if (isset($result[$requestType]['resources'])) { $result[$requestType]['resources'] = ['anonymous' => true]; diff --git a/app/code/Magento/WebapiSecurity/README.md b/app/code/Magento/WebapiSecurity/README.md index df9f68d3a27dc..ec5f84d1d14fa 100644 --- a/app/code/Magento/WebapiSecurity/README.md +++ b/app/code/Magento/WebapiSecurity/README.md @@ -2,5 +2,5 @@ **WebapiSecurity** enables access management of some Web API resources. If checkbox is enabled in backend through: Stores -> Configuration -> Services -> Magento Web API -> Web Api Security -then the security of all of the services outlined in app/code/Magento/WebapiSecurity/etc/di.xml would be loosened. You may modify these services to customize. +then the security of all of the services outlined in app/code/Magento/WebapiSecurity/etc/di.xml would be loosened. You may modify this list to customize which services should follow this behavior. By loosening the security, these services would allow access anonymously (by anyone). diff --git a/app/code/Magento/WebapiSecurity/etc/di.xml b/app/code/Magento/WebapiSecurity/etc/di.xml index 8b5b42a6fca2c..88fb85ad1feb9 100644 --- a/app/code/Magento/WebapiSecurity/etc/di.xml +++ b/app/code/Magento/WebapiSecurity/etc/di.xml @@ -16,37 +16,37 @@ - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET - GET + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 0e2a8a7040c7f6b0a0d9d41cef4fcce495499cf7 Mon Sep 17 00:00:00 2001 From: Hayder Sharhan Date: Wed, 23 Mar 2016 10:11:26 -0500 Subject: [PATCH 23/25] MAGETWO-50611: [Github][Security] WebAPIs allow anonymous access - Revise label text. --- app/code/Magento/WebapiSecurity/etc/adminhtml/system.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/WebapiSecurity/etc/adminhtml/system.xml b/app/code/Magento/WebapiSecurity/etc/adminhtml/system.xml index 3d701f1a5b08a..09d6681300b3c 100644 --- a/app/code/Magento/WebapiSecurity/etc/adminhtml/system.xml +++ b/app/code/Magento/WebapiSecurity/etc/adminhtml/system.xml @@ -9,9 +9,9 @@ - + Magento\Config\Model\Config\Source\Yesno - Anonymous access would be provided for some CMS, Catalog and Store services + This feature applies only to CMS, Catalog and Store APIs. Please consult your developers for details on potential security risks.
From 3899b54ad1f8ac0c8beb7d20a8ba7d2c0b23254d Mon Sep 17 00:00:00 2001 From: Oleksii Korshenko Date: Wed, 23 Mar 2016 11:04:14 -0500 Subject: [PATCH 24/25] MAGETWO-50608: [Github][Security] Able to brute force API token access - fixed integration tests --- .../Model/AdminTokenServiceTest.php | 4 ++-- .../Model/CustomerTokenServiceTest.php | 4 ++-- .../Magento/Webapi/_files/webapi_user.php | 24 +++++++++++++++++++ .../_files/webapi_user_rollback.php} | 2 +- 4 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user.php rename dev/tests/integration/testsuite/Magento/{User/_files/user_with_role_rollback.php => Webapi/_files/webapi_user_rollback.php} (96%) diff --git a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php index 6af8713db6151..86b38252d56c7 100644 --- a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php @@ -58,7 +58,7 @@ public function setUp() } /** - * @magentoApiDataFixture Magento/User/_files/user_with_role.php + * @magentoApiDataFixture Magento/Webapi/_files/webapi_user.php */ public function testCreateAdminAccessToken() { @@ -139,7 +139,7 @@ public function validationDataProvider() } /** - * @magentoApiDataFixture Magento/User/_files/user_with_role.php + * @magentoApiDataFixture Magento/Webapi/_files/webapi_user.php */ public function testThrottlingMaxAttempts() { diff --git a/dev/tests/integration/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php b/dev/tests/integration/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php index 8ec860a7ad7d8..221d3c27954c1 100644 --- a/dev/tests/integration/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php +++ b/dev/tests/integration/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php @@ -70,8 +70,8 @@ public function testCreateCustomerAccessTokenEmptyOrNullCredentials($username, $ } /** - * @expectedException \Magento\Framework\Exception\InvalidEmailOrPasswordException - * @expectedExceptionMessage Invalid login or password. + * @expectedException \Magento\Framework\Exception\AuthenticationException + * @expectedExceptionMessage You did not sign in correctly or your account is temporarily disabled. */ public function testCreateCustomerAccessTokenInvalidCustomer() { diff --git a/dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user.php b/dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user.php new file mode 100644 index 0000000000000..2829d92d1b9bb --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user.php @@ -0,0 +1,24 @@ +create('Magento\User\Model\User'); +$model->setFirstname("Web") + ->setLastname("Api") + ->setUsername('webapi_user') + ->setPassword(\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD) + ->setEmail('webapi_user@example.com') + ->setRoleType('G') + ->setResourceId('Magento_Backend::all') + ->setPrivileges("") + ->setAssertId(0) + ->setRoleId(1) + ->setPermission('allow'); +$model->save(); diff --git a/dev/tests/integration/testsuite/Magento/User/_files/user_with_role_rollback.php b/dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user_rollback.php similarity index 96% rename from dev/tests/integration/testsuite/Magento/User/_files/user_with_role_rollback.php rename to dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user_rollback.php index ceccfdb71976d..d500ec4cbe597 100644 --- a/dev/tests/integration/testsuite/Magento/User/_files/user_with_role_rollback.php +++ b/dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user_rollback.php @@ -8,7 +8,7 @@ /** @var $model \Magento\User\Model\User */ $model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\User\Model\User'); -$userName = 'adminUser'; +$userName = 'webapi_user'; $model->load($userName, 'username'); $model->delete(); From 231b34bc89a6dd165e631eced5763627e0453221 Mon Sep 17 00:00:00 2001 From: Oleksii Korshenko Date: Wed, 23 Mar 2016 16:17:46 -0500 Subject: [PATCH 25/25] MAGETWO-50608: [Github][Security] Able to brute force API token access - fixed rest tests --- .../Magento/Integration/Model/AdminTokenServiceTest.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php index 86b38252d56c7..3f0471ba7cee1 100644 --- a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php @@ -62,7 +62,7 @@ public function setUp() */ public function testCreateAdminAccessToken() { - $adminUserNameFromFixture = 'adminUser'; + $adminUserNameFromFixture = 'webapi_user'; $serviceInfo = [ 'rest' => [ @@ -143,7 +143,7 @@ public function validationDataProvider() */ public function testThrottlingMaxAttempts() { - $adminUserNameFromFixture = 'adminUser'; + $adminUserNameFromFixture = 'webapi_user'; $serviceInfo = [ 'rest' => [ @@ -181,11 +181,11 @@ public function testThrottlingMaxAttempts() } /** - * @magentoApiDataFixture Magento/User/_files/user_with_role.php + * @magentoApiDataFixture Magento/Webapi/_files/webapi_user.php */ public function testThrottlingAccountLockout() { - $adminUserNameFromFixture = 'adminUser'; + $adminUserNameFromFixture = 'webapi_user'; $serviceInfo = [ 'rest' => [