diff --git a/app/code/Magento/Backend/Helper/Dashboard/Order.php b/app/code/Magento/Backend/Helper/Dashboard/Order.php index e01fd8943d65f..59855b1d2b884 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; } /** @@ -57,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/CacheInvalidate/Observer/InvalidateVarnishObserver.php b/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php index e9d0550454d53..44a9317e0b246 100644 --- a/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php +++ b/app/code/Magento/CacheInvalidate/Observer/InvalidateVarnishObserver.php @@ -48,10 +48,11 @@ 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))); + if (!empty($tags)) { + $this->purgeCache->sendPurgeRequest(implode('|', array_unique($tags))); + } } } } 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 af7c2471b90c6..2a2150c79e29a 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() == \Magento\Framework\App\Area::AREA_FRONTEND) { + $identities[] = self::CACHE_TAG; + } return array_unique($identities); } @@ -2548,4 +2556,20 @@ public function setId($value) { return $this->setData('entity_id', $value); } + + /** + * Get application state + * + * @deprecated + * @return \Magento\Framework\App\State + */ + private function getAppState() + { + if (!$this->appState instanceof \Magento\Framework\App\State) { + $this->appState = \Magento\Framework\App\ObjectManager::getInstance()->get( + \Magento\Framework\App\State::class + ); + } + return $this->appState; + } } 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/Catalog/etc/webapi.xml b/app/code/Magento/Catalog/etc/webapi.xml index 2dbaff9694bcd..a8dc6ead7975f 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/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/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..d4e495a6720dd 100644 --- a/app/code/Magento/Integration/Model/CustomerTokenService.php +++ b/app/code/Magento/Integration/Model/CustomerTokenService.php @@ -12,6 +12,8 @@ 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; +use Magento\Framework\Exception\AuthenticationException; class CustomerTokenService implements \Magento\Integration\Api\CustomerTokenServiceInterface { @@ -41,6 +43,11 @@ class CustomerTokenService implements \Magento\Integration\Api\CustomerTokenServ */ private $tokenModelCollectionFactory; + /** + * @var RequestThrottler + */ + private $requestThrottler; + /** * Initialize service * @@ -67,7 +74,16 @@ 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 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(); } @@ -89,4 +105,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..a4f76565a3bb6 --- /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'); + } +} 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( + __('You did not sign in correctly or your account is temporarily disabled.') + ); + } + } + + /** + * 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..ca46c075d4cd5 --- /dev/null +++ b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Token/RequestLog.php @@ -0,0 +1,112 @@ +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->from($this->getMainTable(), 'failures_count') + ->where('user_name = :user_name AND user_type = :user_type'); + + return (int)$this->getConnection()->fetchOne($select, ['user_name' => $userName, 'user_type' => $userType]); + } + + /** + * {@inheritdoc} + */ + public function resetFailuresCount($userName, $userType) + { + $this->getConnection()->delete( + $this->getMainTable(), + ['user_name = ?' => $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')); + $dateTime = $date->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); + + $this->getConnection()->insertOnDuplicate( + $this->getMainTable(), + [ + 'user_name' => $userName, + 'user_type' => $userType, + 'failures_count' => 1, + 'lock_expires_at' => $dateTime + ], + [ + 'failures_count' => new \Zend_Db_Expr('failures_count+1'), + 'lock_expires_at' => new \Zend_Db_Expr("'" . $dateTime . "'") + ] + ); + } + + /** + * {@inheritdoc} + */ + public function clearExpiredFailures() + { + $date = (new \DateTime())->setTimestamp($this->dateTime->gmtTimestamp()); + $dateTime = $date->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); + $this->getConnection()->delete($this->getMainTable(), ['lock_expires_at <= ?' => $dateTime]); + } +} diff --git a/app/code/Magento/Integration/Setup/UpgradeSchema.php b/app/code/Magento/Integration/Setup/UpgradeSchema.php new file mode 100644 index 0000000000000..6d755bb12fd24 --- /dev/null +++ b/app/code/Magento/Integration/Setup/UpgradeSchema.php @@ -0,0 +1,76 @@ +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( + '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], + '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, + ['nullable' => false], + 'Lock expiration time' + )->addIndex( + $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.' + ); + $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/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 * * * + + + 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 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 @@ */ --> - + diff --git a/app/code/Magento/PageCache/Observer/FlushCacheByTags.php b/app/code/Magento/PageCache/Observer/FlushCacheByTags.php index cc5f98bf93313..fbb1faa54f3da 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)); } 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)); 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/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php b/app/code/Magento/SalesRule/Block/Adminhtml/Promo/Quote/Edit/Tab/Actions.php index 830c9cfb439c2..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 @@ -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; } /** @@ -165,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 7a1ee091008e9..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 @@ -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; } /** @@ -156,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); 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/app/code/Magento/Store/etc/webapi.xml b/app/code/Magento/Store/etc/webapi.xml index 5ee8e0c67668e..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/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..204ddbdc59906 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/AnonymousResourceSecurity.php @@ -0,0 +1,91 @@ +config = $config; + $this->resources = $resources; + } + + /** + * Filter config values. + * + * @param Converter $subject + * @param array $nodes + * @return array + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterConvert(Converter $subject, $nodes) + { + if (empty($nodes)) { + return $nodes; + } + $useInsecure = $this->config->getValue(self::XML_ALLOW_INSECURE); + if ($useInsecure) { + 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]; + $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; + } + + /** + * Get node by path. + * + * @param string $route + * @param string $requestType + * @param array $source + * @return array|null + */ + 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..7227b508c5593 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/Model/Plugin/CacheInvalidator.php @@ -0,0 +1,45 @@ +cacheTypeList = $cacheTypeList; + } + + /** + * 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, + \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); + } + + return $result; + } +} diff --git a/app/code/Magento/WebapiSecurity/README.md b/app/code/Magento/WebapiSecurity/README.md new file mode 100644 index 0000000000000..ec5f84d1d14fa --- /dev/null +++ b/app/code/Magento/WebapiSecurity/README.md @@ -0,0 +1,6 @@ +# WebapiSecurity + +**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 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/composer.json b/app/code/Magento/WebapiSecurity/composer.json new file mode 100644 index 0000000000000..d07e2e60d9960 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/composer.json @@ -0,0 +1,23 @@ +{ + "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-webapi": "100.0.*", + "magento/framework": "100.0.*" + }, + "type": "magento2-module", + "version": "100.0.0", + "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..09d6681300b3c --- /dev/null +++ b/app/code/Magento/WebapiSecurity/etc/adminhtml/system.xml @@ -0,0 +1,19 @@ + + + + +
+ + + + + Magento\Config\Model\Config\Source\Yesno + This feature applies only to CMS, Catalog and Store APIs. Please consult your developers for details on potential security risks. + + +
+
+
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/app/code/Magento/WebapiSecurity/etc/di.xml b/app/code/Magento/WebapiSecurity/etc/di.xml new file mode 100644 index 0000000000000..88fb85ad1feb9 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/etc/di.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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..886c73be0a230 --- /dev/null +++ b/app/code/Magento/WebapiSecurity/registration.php @@ -0,0 +1,11 @@ +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(); } /** - * @magentoApiDataFixture Magento/User/_files/user_with_role.php + * @magentoApiDataFixture Magento/Webapi/_files/webapi_user.php */ public function testCreateAdminAccessToken() { - $adminUserNameFromFixture = 'adminUser'; + $adminUserNameFromFixture = 'webapi_user'; $serviceInfo = [ 'rest' => [ @@ -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/Webapi/_files/webapi_user.php + */ + public function testThrottlingMaxAttempts() + { + $adminUserNameFromFixture = 'webapi_user'; + + $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/Webapi/_files/webapi_user.php + */ + public function testThrottlingAccountLockout() + { + $adminUserNameFromFixture = 'webapi_user'; + + $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/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php b/dev/tests/api-functional/testsuite/Magento/Sales/Service/V1/ShipmentCreateTest.php index c6e1077336f05..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,11 +79,30 @@ public function testInvoke() 'increment_id' => null, 'created_at' => null, 'updated_at' => null, -// 'packages' => null, 'shipping_label' => null, - 'tracks' => [], + 'tracks' => [ + [ + 'carrier_code' => 'UPS', + 'order_id' => $order->getId(), + 'title' => 'ground', + 'description' => null, + 'track_number' => '12345678', + 'parent_id' => null, + 'created_at' => null, + 'updated_at' => null, + 'qty' => null, + 'weight' => null + ] + ], 'items' => $items, - 'comments' => [], + 'comments' => [ + [ + 'comment' => 'Shipment-related comment.', + 'is_customer_notified' => null, + 'is_visible_on_front' => null, + 'parent_id' => null + ] + ], ]; $result = $this->_webApiCall($serviceInfo, ['entity' => $data]); $this->assertNotEmpty($result); 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/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/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); 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/Webapi/_files/webapi_user_rollback.php b/dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user_rollback.php new file mode 100644 index 0000000000000..d500ec4cbe597 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Webapi/_files/webapi_user_rollback.php @@ -0,0 +1,18 @@ +create('Magento\User\Model\User'); +$userName = 'webapi_user'; +$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);