This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,26 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\EncryptionKey\Block\Adminhtml\Crypt\Key;
class EditTest extends \PHPUnit\Framework\TestCase
{
/**
* Test edit block
*/
public function testEditBlock()
{
/**
* @var \Magento\EncryptionKey\Block\Adminhtml\Crypt\Key\Edit
*/
$block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\EncryptionKey\Block\Adminhtml\Crypt\Key\Edit::class
);
$this->assertEquals('Encryption Key', $block->getHeaderText());
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\EncryptionKey\Block\Adminhtml\Crypt\Key;
/**
* Test class for \Magento\EncryptionKey\Block\Adminhtml\Crypt\Key\Form
* @magentoAppArea adminhtml
*/
class FormTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppIsolation enabled
*/
public function testPrepareForm()
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\View\DesignInterface::class)
->setArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE)
->setDefaultDesignTheme();
$block = $objectManager->get(\Magento\Framework\View\LayoutInterface::class)
->createBlock(\Magento\EncryptionKey\Block\Adminhtml\Crypt\Key\Form::class);
$prepareFormMethod = new \ReflectionMethod(
\Magento\EncryptionKey\Block\Adminhtml\Crypt\Key\Form::class,
'_prepareForm'
);
$prepareFormMethod->setAccessible(true);
$prepareFormMethod->invoke($block);
$form = $block->getForm();
$this->assertEquals('edit_form', $form->getId());
$this->assertEquals('post', $form->getMethod());
foreach (['enc_key_note', 'generate_random', 'crypt_key', 'main_fieldset'] as $id) {
$element = $form->getElement($id);
$this->assertNotNull($element);
}
$generateRandomField = $form->getElement('generate_random');
$this->assertEquals('select', $generateRandomField->getType());
$this->assertEquals([ 0 => 'No', 1 => 'Yes'], $generateRandomField->getOptions());
$cryptKeyField = $form->getElement('crypt_key');
$this->assertEquals('text', $cryptKeyField->getType());
$this->assertEquals('crypt_key', $cryptKeyField->getName());
}
}
@@ -0,0 +1,20 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key;
class IndexTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Test index action
*/
public function testIndexAction()
{
$this->dispatch('backend/admin/crypt_key/index');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('<h1 class="page-title">Encryption Key</h1>', $body);
}
}
@@ -0,0 +1,116 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key;
use Magento\Framework\App\Request\Http as HttpRequest;
/**
* Test for Magento\EncryptionKey\Controller\Adminhtml\Crypt\Key\Save
*/
class SaveTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Test save action with empty encryption key
* @return void
*/
public function testSaveActionWithEmptyKey():void
{
// data set with no random encryption key and no provided encryption key
$ifGenerateRandom = '0';
$encryptionKey = '';
$request = $this->getRequest();
$request->setMethod(HttpRequest::METHOD_POST);
$request
->setPostValue('generate_random', $ifGenerateRandom)
->setPostValue('crypt_key', $encryptionKey);
$this->dispatch('backend/admin/crypt_key/save');
$this->assertSessionMessages(
$this->containsEqual('Please enter an encryption key.'),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
}
/**
* Test save action with provided encryption key
*
* @magentoDbIsolation enabled
* @return void
*/
public function testSaveActionWithProvidedKey():void
{
$this->markTestSkipped('Test is blocked by MAGETWO-33612.');
// data set with provided encryption key
$ifGenerateRandom = '0';
$encryptionKey = 'foo_encryption_key';
$request = $this->getRequest();
$request
->setPostValue('generate_random', $ifGenerateRandom)
->setPostValue('crypt_key', $encryptionKey);
$this->dispatch('backend/admin/crypt_key/save');
$this->assertRedirect();
$this->assertSessionMessages(
$this->containsEqual('The encryption key has been changed.'),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
}
/**
* Test save action with invalid encryption key
* @return void
*/
public function testSaveActionWithInvalidKey():void
{
// data set with provided encryption key
$ifGenerateRandom = '0';
$encryptionKey = 'invalid key';
$params = [
'generate_random' => $ifGenerateRandom,
'crypt_key' => $encryptionKey,
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($params);
$this->dispatch('backend/admin/crypt_key/save');
$this->assertRedirect();
$this->assertSessionMessages(
$this->containsEqual('Encryption key must be 32 character string without any white space.'),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
}
/**
* Test save action with randomly generated key
*
* @magentoDbIsolation enabled
* @return void
*/
public function testSaveActionWithRandomKey():void
{
$this->markTestSkipped('Test is blocked by MAGETWO-33612.');
// data set with random encryption key
$ifGenerateRandom = '1';
$encryptionKey = '';
$request = $this->getRequest();
$request
->setPostValue('generate_random', $ifGenerateRandom)
->setPostValue('crypt_key', $encryptionKey);
$this->dispatch('backend/admin/crypt_key/save');
$this->assertRedirect();
$this->assertSessionMessages(
$this->containsEqual('The encryption key has been changed.'),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
}
}
@@ -0,0 +1,235 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\EncryptionKey\Model\Data\ReEncryptorList\ReEncryptor;
use PHPUnit\Framework\TestCase;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\App\ResourceConnection;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\EncryptionKey\Test\Fixture\TableWithEncryptedData;
use Magento\EncryptionKey\Model\Data\ReEncryptorList\ReEncryptor\Handler\ErrorFactory;
/**
* Test for the Simple Re-encryption Handler.
*/
class SimpleHandlerTest extends TestCase
{
/**
* @var ErrorFactory|null
*/
private ?ErrorFactory $errorFactory;
/**
* @var EncryptorInterface|null
*/
private ?EncryptorInterface $encryptor;
/**
* @var ResourceConnection|null
*/
private ?ResourceConnection $resourceConnection;
protected function setUp(): void
{
$this->errorFactory = Bootstrap::getObjectManager()->get(
ErrorFactory::class
);
$this->encryptor = Bootstrap::getObjectManager()->get(
EncryptorInterface::class
);
$this->resourceConnection = Bootstrap::getObjectManager()->get(
ResourceConnection::class
);
}
/**
* Tests data re-encryption.
*/
#[
DataFixture(TableWithEncryptedData::class)
]
public function testReEncrypt()
{
/** @var SimpleHandler $testDataReEncryptionHandler */
$testDataReEncryptionHandler = Bootstrap::getObjectManager()->create(
SimpleHandler::class,
[
"tableName" => "test_table_with_encrypted_data",
"identifierField" => "id",
"fieldsToReEncrypt" => ["enc_column_1", "enc_column_2"]
]
);
$tableName = $this->resourceConnection->getTableName(
"test_table_with_encrypted_data"
);
$connection = $this->resourceConnection->getConnection();
$select = $connection->select()->from(
$tableName,
["id", "not_enc_column_1", "enc_column_1", "enc_column_2"]
)->order(
"id ASC"
);
$dataBeforeReEncryption = $connection->fetchAll($select);
try {
$errors = $testDataReEncryptionHandler->reEncrypt();
} catch (\Throwable $e) {
$this->fail(
sprintf(
'Re-encryption failed: %s',
$e->getMessage()
)
);
}
$expectedErrors[] = $this->errorFactory->create(
"id",
4,
"Not supported cipher version"
);
$this->assertEquals($expectedErrors, $errors);
$dataAfterReEncryption = $connection->fetchAll($select);
$this->assertRowOne($dataBeforeReEncryption, $dataAfterReEncryption);
$this->assertRowTwo($dataBeforeReEncryption, $dataAfterReEncryption);
$this->assertRowThree($dataBeforeReEncryption, $dataAfterReEncryption);
$this->assertRowFour($dataBeforeReEncryption, $dataAfterReEncryption);
}
/**
* Asserts changes done by re-encryption to the first DB row.
*
* @param array $dataBeforeReEncryption
* @param array $dataAfterReEncryption
*
* @return void
*/
private function assertRowOne(array $dataBeforeReEncryption, array $dataAfterReEncryption): void
{
// Fields not supposed to be affected should stay unchanged.
$this->assertEquals(
$dataBeforeReEncryption[0]["not_enc_column_1"],
$dataAfterReEncryption[0]["not_enc_column_1"]
);
// Empty or NULL fields should stay unchanged.
$this->assertEmpty($dataAfterReEncryption[0]["enc_column_1"]);
$this->assertEmpty($dataAfterReEncryption[0]["enc_column_2"]);
}
/**
* Asserts changes done by re-encryption to the second DB row.
*
* @param array $dataBeforeReEncryption
* @param array $dataAfterReEncryption
*
* @return void
*/
private function assertRowTwo(array $dataBeforeReEncryption, array $dataAfterReEncryption): void
{
// Fields not supposed to be affected should stay unchanged.
$this->assertEquals(
$dataBeforeReEncryption[1]["not_enc_column_1"],
$dataAfterReEncryption[1]["not_enc_column_1"]
);
// Encrypted fields that were not empty should not be empty.
$this->assertNotEmpty($dataAfterReEncryption[1]["enc_column_1"]);
// Empty or NULL fields should stay unchanged.
$this->assertEmpty($dataAfterReEncryption[1]["enc_column_2"]);
// Encrypted fields should be changed.
$this->assertNotEquals(
$dataBeforeReEncryption[1]["enc_column_1"],
$dataAfterReEncryption[1]["enc_column_1"]
);
// It still should be possible to decrypt encrypted fields.
$this->assertEquals(
"Encrypted Column Value",
$this->encryptor->decrypt($dataAfterReEncryption[1]["enc_column_1"])
);
}
/**
* Asserts changes done by re-encryption to the third DB row.
*
* @param array $dataBeforeReEncryption
* @param array $dataAfterReEncryption
*
* @return void
*/
private function assertRowThree(array $dataBeforeReEncryption, array $dataAfterReEncryption): void
{
// Fields not supposed to be affected should stay unchanged.
$this->assertEquals(
$dataBeforeReEncryption[2]["not_enc_column_1"],
$dataAfterReEncryption[2]["not_enc_column_1"]
);
// Encrypted fields that were not empty should not be empty.
$this->assertNotEmpty($dataAfterReEncryption[2]["enc_column_1"]);
$this->assertNotEmpty($dataAfterReEncryption[2]["enc_column_2"]);
// Encrypted fields should be changed.
$this->assertNotEquals(
$dataBeforeReEncryption[2]["enc_column_1"],
$dataAfterReEncryption[2]["enc_column_1"]
);
$this->assertNotEquals(
$dataBeforeReEncryption[2]["enc_column_2"],
$dataAfterReEncryption[2]["enc_column_2"]
);
// It still should be possible to decrypt encrypted fields.
$this->assertEquals(
"Encrypted Column Value",
$this->encryptor->decrypt($dataAfterReEncryption[2]["enc_column_1"])
);
$this->assertEquals(
"Encrypted Column Value",
$this->encryptor->decrypt($dataAfterReEncryption[2]["enc_column_2"])
);
}
/**
* Asserts changes done by re-encryption to the forth DB row.
*
* @param array $dataBeforeReEncryption
* @param array $dataAfterReEncryption
*
* @return void
*/
private function assertRowFour(array $dataBeforeReEncryption, array $dataAfterReEncryption): void
{
// Fields not supposed to be affected should stay unchanged.
$this->assertEquals(
$dataBeforeReEncryption[3]["not_enc_column_1"],
$dataAfterReEncryption[3]["not_enc_column_1"]
);
// Encrypted fields should stay unchanged if DB row level error occurred.
$this->assertEquals(
$dataBeforeReEncryption[3]["enc_column_1"],
$dataAfterReEncryption[3]["enc_column_1"]
);
// Empty or NULL fields should stay unchanged.
$this->assertEmpty($dataAfterReEncryption[3]["enc_column_2"]);
}
}
@@ -0,0 +1,103 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\EncryptionKey\Model\ResourceModel\Key;
class ChangeTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
protected function setup(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
*/
public function testChangeEncryptionKeyConfigNotWritable()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Deployment configuration file is not writable');
$writerMock = $this->createMock(\Magento\Framework\App\DeploymentConfig\Writer::class);
$writerMock->expects($this->once())->method('checkIfWritable')->willReturn(false);
/** @var \Magento\EncryptionKey\Model\ResourceModel\Key\Change $keyChangeModel */
$keyChangeModel = $this->objectManager->create(
\Magento\EncryptionKey\Model\ResourceModel\Key\Change::class,
['writer' => $writerMock]
);
$keyChangeModel->changeEncryptionKey();
}
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/EncryptionKey/_files/payment_info.php
*/
public function testChangeEncryptionKey()
{
$testPath = 'test/config';
$testValue = 'test';
$writerMock = $this->createMock(\Magento\Framework\App\DeploymentConfig\Writer::class);
$writerMock->expects($this->once())->method('checkIfWritable')->willReturn(true);
$structureMock = $this->createMock(\Magento\Config\Model\Config\Structure::class);
$structureMock->expects($this->once())
->method('getFieldPathsByAttribute')
->willReturn([$testPath]);
/** @var \Magento\EncryptionKey\Model\ResourceModel\Key\Change $keyChangeModel */
$keyChangeModel = $this->objectManager->create(
\Magento\EncryptionKey\Model\ResourceModel\Key\Change::class,
['structure' => $structureMock, 'writer' => $writerMock]
);
$configModel = $this->objectManager->create(
\Magento\Config\Model\ResourceModel\Config::class
);
$configModel->saveConfig($testPath, 'test', 'default', 0);
$this->assertNotNull($keyChangeModel->changeEncryptionKey());
$connection = $keyChangeModel->getConnection();
// Verify that the config value has been encrypted
$values1 = $connection->fetchPairs(
$connection->select()->from(
$keyChangeModel->getTable('core_config_data'),
['config_id', 'value']
)->where(
'path IN (?)',
[$testPath]
)->where(
'value NOT LIKE ?',
''
)
);
$this->assertNotContains($testValue, $values1);
$this->assertMatchesRegularExpression('|([0-9]+:)([0-9]+:)([a-zA-Z0-9+/]+=*)|', current($values1));
// Verify that the credit card number has been encrypted
$values2 = $connection->fetchPairs(
$connection->select()->from(
$keyChangeModel->getTable('sales_order_payment'),
['entity_id', 'cc_number_enc']
)
);
$this->assertNotContains('1111111111', $values2);
$this->assertMatchesRegularExpression('|([0-9]+:)([0-9]+:)([a-zA-Z0-9+/]+=*)|', current($values2));
/** clean up */
$select = $connection->select()->from($configModel->getMainTable())->where('path=?', $testPath);
$this->assertNotEmpty($connection->fetchRow($select));
$configModel->deleteConfig($testPath, 'default', 0);
$this->assertEmpty($connection->fetchRow($select));
}
}
@@ -0,0 +1,123 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\EncryptionKey\Setup\Patch\Data;
use Magento\Framework\Config\ConfigOptionsListConstants;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\Encryption\Encryptor;
/**
* Class SodiumChachaPatch library test
*/
class SodiumChachaPatchTest extends \PHPUnit\Framework\TestCase
{
private const PATH_KEY = 'crypt/key';
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var DeploymentConfig
*/
private $deployConfig;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->deployConfig = $this->objectManager->get(DeploymentConfig::class);
}
public function testChangeEncryptionKey()
{
$testPath = 'test/config';
$testValue = 'test';
$structureMock = $this->createMock(
// phpstan:ignore "Class Magento\Config\Model\Config\Structure\Proxy not found."
\Magento\Config\Model\Config\Structure\Proxy::class
);
$structureMock->expects($this->once())
->method('getFieldPathsByAttribute')
->willReturn([$testPath]);
$structureMock->expects($this->once())
->method('getFieldPaths')
->willReturn([]);
/** @var \Magento\Config\Model\ResourceModel\Config $configModel */
$configModel = $this->objectManager->create(\Magento\Config\Model\ResourceModel\Config::class);
$configModel->saveConfig($testPath, $this->legacyEncrypt($testValue), 'default', 0);
/** @var \Magento\EncryptionKey\Setup\Patch\Data\SodiumChachaPatch $patch */
$patch = $this->objectManager->create(
\Magento\EncryptionKey\Setup\Patch\Data\SodiumChachaPatch::class,
[
'structure' => $structureMock,
]
);
$patch->apply();
$connection = $configModel->getConnection();
$values = $connection->fetchPairs(
$connection->select()->from(
$configModel->getMainTable(),
['config_id', 'value']
)->where(
'path IN (?)',
[$testPath]
)->where(
'value NOT LIKE ?',
''
)
);
/** @var \Magento\Framework\Encryption\EncryptorInterface $encyptor */
$encyptor = $this->objectManager->get(\Magento\Framework\Encryption\EncryptorInterface::class);
$rawConfigValue = array_pop($values);
$this->assertNotEquals($testValue, $rawConfigValue);
$this->assertStringStartsWith('0:' . Encryptor::CIPHER_LATEST . ':', $rawConfigValue);
$this->assertEquals($testValue, $encyptor->decrypt($rawConfigValue));
}
private function legacyEncrypt(string $data): string
{
// @codingStandardsIgnoreStart
$handle = @mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
$initVectorSize = @mcrypt_enc_get_iv_size($handle);
$initVector = str_repeat("\0", $initVectorSize);
@mcrypt_generic_init($handle, $this->getEncryptionKey(), $initVector);
$encrpted = @mcrypt_generic($handle, $data);
@mcrypt_generic_deinit($handle);
@mcrypt_module_close($handle);
// @codingStandardsIgnoreEnd
return '0:' . Encryptor::CIPHER_RIJNDAEL_256 . ':' . base64_encode($encrpted);
}
/**
* Get Encryption key
*
* @return string
* @throws \Magento\Framework\Exception\FileSystemException
* @throws \Magento\Framework\Exception\RuntimeException
*/
private function getEncryptionKey(): string
{
$key = $this->deployConfig->get(static::PATH_KEY);
return (str_starts_with($key, ConfigOptionsListConstants::STORE_KEY_ENCODED_RANDOM_STRING_PREFIX)) ?
base64_decode(substr($key, strlen(ConfigOptionsListConstants::STORE_KEY_ENCODED_RANDOM_STRING_PREFIX))) :
$key;
}
}
@@ -0,0 +1,20 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Sales\Model\Order\Payment $paymentInfo */
$paymentInfo = $objectManager->create(\Magento\Sales\Model\Order\Payment::class);
$paymentInfo->setMethod('Cc')->setData('cc_number_enc', '1111111111');
/** @var \Magento\Sales\Model\Order $order */
$order = $objectManager->create(\Magento\Sales\Model\Order::class);
$order->setIncrementId(
'100000001'
)->setPayment(
$paymentInfo
);
$order->save();