Skip to content

PHPLIB-820: Key Management API spec tests #957

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions .evergreen/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -621,22 +621,22 @@ axes:
- id: driver-versions
display_name: Driver Version
values:
# TODO: Update to "1.14.0" once PHPC 1.14.0 is released
# TODO: Update to "1.15.0" once PHPC 1.15.0 is released
- id: "oldest-supported"
# display_name: "1.14.0"
display_name: "PHPC 1.14-dev (master)"
# display_name: "1.15.0"
display_name: "PHPC 1.15-dev (master)"
variables:
# EXTENSION_VERSION: "1.14.0"
# EXTENSION_VERSION: "1.15.0"
EXTENSION_BRANCH: "master"
# TODO: Update to "1.14.x"/"stable" once PHPC 1.14.0 is released
# TODO: Update to "1.15.x"/"stable" once PHPC 1.15.0 is released
- id: "latest-stable"
# display_name: "1.14.x"
display_name: "PHPC 1.14-dev (master)"
# display_name: "1.15.x"
display_name: "PHPC 1.15-dev (master)"
variables:
# EXTENSION_VERSION: "stable"
EXTENSION_BRANCH: "master"
- id: "latest-dev"
display_name: "PHPC 1.14-dev (master)"
display_name: "PHPC 1.15-dev (master)"
variables:
EXTENSION_BRANCH: "master"

Expand Down
32 changes: 16 additions & 16 deletions tests/FunctionalTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,21 @@ public function configureFailPoint($command, ?Server $server = null): void
$this->configuredFailPoints[] = [$command->configureFailPoint, $failPointServer];
}

public static function getModuleInfo(string $row): ?string
{
ob_start();
phpinfo(INFO_MODULES);
$info = ob_get_clean();

$pattern = sprintf('/^%s([\w ]+)$/m', preg_quote($row . ' => '));

if (preg_match($pattern, $info, $matches) !== 1) {
return null;
}

return $matches[1];
}

/**
* Creates the test collection with the specified options.
*
Expand Down Expand Up @@ -512,7 +527,7 @@ protected function skipIfClientSideEncryptionIsNotSupported(): void
$this->markTestSkipped('Client Side Encryption only supported on FCV 4.2 or higher');
}

if ($this->getModuleInfo('libmongocrypt') === 'disabled') {
if (static::getModuleInfo('libmongocrypt') === 'disabled') {
$this->markTestSkipped('Client Side Encryption is not enabled in the MongoDB extension');
}
}
Expand Down Expand Up @@ -598,21 +613,6 @@ private function disableFailPoints(): void
}
}

private function getModuleInfo(string $row): ?string
{
ob_start();
phpinfo(INFO_MODULES);
$info = ob_get_clean();

$pattern = sprintf('/^%s([\w ]+)$/m', preg_quote($row . ' => '));

if (preg_match($pattern, $info, $matches) !== 1) {
return null;
}

return $matches[1];
}

/**
* Checks if the failCommand command is supported on this server version
*
Expand Down
166 changes: 166 additions & 0 deletions tests/SpecTests/ClientSideEncryptionSpecTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use MongoDB\Driver\Exception\ConnectionTimeoutException;
use MongoDB\Driver\Exception\EncryptionException;
use MongoDB\Driver\Exception\RuntimeException;
use MongoDB\Driver\Exception\ServerException;
use MongoDB\Driver\Monitoring\CommandFailedEvent;
use MongoDB\Driver\Monitoring\CommandStartedEvent;
use MongoDB\Driver\Monitoring\CommandSubscriber;
Expand Down Expand Up @@ -1403,6 +1404,93 @@ static function (self $test, ClientEncryption $clientEncryption, Client $encrypt
];
}

/**
* Prose test 13: Unique Index on keyAltNames
*
* @see https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/tests/README.rst#unique-index-on-keyaltnames
* @dataProvider provideUniqueIndexOnKeyAltNamesTests
*/
public function testUniqueIndexOnKeyAltNames(Closure $test): void
{
// Test setup
$client = static::createTestClient();

// Ensure that the key vault is dropped with a majority write concern
self::insertKeyVaultData($client, []);

$client->selectCollection('keyvault', 'datakeys')->createIndex(
['keyAltNames' => 1],
[
'unique' => true,
'partialFilterExpression' => ['keyAltNames' => ['$exists' => true]],
'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
]
);

$clientEncryption = new ClientEncryption([
'keyVaultClient' => $client->getManager(),
'keyVaultNamespace' => 'keyvault.datakeys',
'kmsProviders' => ['local' => ['key' => new Binary(base64_decode(self::LOCAL_MASTERKEY), 0)]],
]);

$clientEncryption->createDataKey('local', ['keyAltNames' => ['def']]);

$test($this, $client, $clientEncryption);
}

public static function provideUniqueIndexOnKeyAltNamesTests()
{
// See: https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/tests/README.rst#case-1-createdatakey
yield 'Case 1: createDataKey()' => [
static function (self $test, Client $client, ClientEncryption $clientEncryption): void {
$clientEncryption->createDataKey('local', ['keyAltNames' => ['abc']]);

try {
$clientEncryption->createDataKey('local', ['keyAltNames' => ['abc']]);
$test->fail('Expected exception to be thrown');
} catch (ServerException $e) {
$test->assertSame(11000 /* DuplicateKey */, $e->getCode());
}

try {
$clientEncryption->createDataKey('local', ['keyAltNames' => ['def']]);
$test->fail('Expected exception to be thrown');
} catch (ServerException $e) {
$test->assertSame(11000 /* DuplicateKey */, $e->getCode());
}
},
];

// See: https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/tests/README.rst#case-2-addkeyaltname
yield 'Case 2: addKeyAltName()' => [
static function (self $test, Client $client, ClientEncryption $clientEncryption): void {
$keyId = $clientEncryption->createDataKey('local');

$keyBeforeUpdate = $clientEncryption->addKeyAltName($keyId, 'abc');
$test->assertObjectNotHasAttribute('keyAltNames', $keyBeforeUpdate);

$keyBeforeUpdate = $clientEncryption->addKeyAltName($keyId, 'abc');
$test->assertObjectHasAttribute('keyAltNames', $keyBeforeUpdate);
$test->assertIsArray($keyBeforeUpdate->keyAltNames);
$test->assertContains('abc', $keyBeforeUpdate->keyAltNames);

try {
$clientEncryption->addKeyAltName($keyId, 'def');
$test->fail('Expected exception to be thrown');
} catch (ServerException $e) {
$test->assertSame(11000 /* DuplicateKey */, $e->getCode());
}

$originalKeyId = $clientEncryption->getKeyByAltName('def')->_id;

$originalKeyBeforeUpdate = $clientEncryption->addKeyAltName($originalKeyId, 'def');
$test->assertObjectHasAttribute('keyAltNames', $originalKeyBeforeUpdate);
$test->assertIsArray($originalKeyBeforeUpdate->keyAltNames);
$test->assertContains('def', $originalKeyBeforeUpdate->keyAltNames);
},
];
}

/**
* Prose test 14: Decryption Events
*
Expand Down Expand Up @@ -1552,6 +1640,84 @@ static function (self $test, Client $setupClient, ClientEncryption $clientEncryp
];
}

/**
* Prose test 16: RewrapManyDataKey
*
* @see https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/tests/README.rst#rewrap
* @dataProvider provideRewrapManyDataKeySrcAndDstProviders
*/
public function testRewrapManyDataKey(string $srcProvider, string $dstProvider): void
{
$providerMasterKeys = [
'aws' => ['region' => 'us-east-1', 'key' => 'arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0'],
'azure' => ['keyVaultEndpoint' => 'key-vault-csfle.vault.azure.net', 'keyName' => 'key-name-csfle'],
'gcp' => ['projectId' => 'devprod-drivers', 'location' => 'global', 'keyRing' => 'key-ring-csfle', 'keyName' => 'key-name-csfle'],
'kmip' => [],
];

// Test setup
$client = static::createTestClient();

// Ensure that the key vault is dropped with a majority write concern
self::insertKeyVaultData($client, []);

$clientEncryptionOpts = [
'keyVaultNamespace' => 'keyvault.datakeys',
'kmsProviders' => [
'aws' => Context::getAWSCredentials(),
'azure' => Context::getAzureCredentials(),
'gcp' => Context::getGCPCredentials(),
'kmip' => ['endpoint' => Context::getKmipEndpoint()],
'local' => ['key' => new Binary(base64_decode(self::LOCAL_MASTERKEY), 0)],
],
'tlsOptions' => [
'kmip' => Context::getKmsTlsOptions(),
],
];

$clientEncryption1 = $client->createClientEncryption($clientEncryptionOpts);

$createDataKeyOpts = [];

if (isset($providerMasterKeys[$srcProvider])) {
$createDataKeyOpts['masterKey'] = $providerMasterKeys[$srcProvider];
}

$keyId = $clientEncryption1->createDataKey($srcProvider, $createDataKeyOpts);

$ciphertext = $clientEncryption1->encrypt('test', ['algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, 'keyId' => $keyId]);

$clientEncryption2 = $client->createClientEncryption($clientEncryptionOpts);

$rewrapManyDataKeyOpts = ['provider' => $dstProvider];

if (isset($providerMasterKeys[$dstProvider])) {
$rewrapManyDataKeyOpts['masterKey'] = $providerMasterKeys[$dstProvider];
}

$result = $clientEncryption2->rewrapManyDataKey([], $rewrapManyDataKeyOpts);

$this->assertObjectHasAttribute('bulkWriteResult', $result);
$this->assertIsObject($result->bulkWriteResult);
// libmongoc uses different field names for its BulkWriteResult
$this->assertObjectHasAttribute('nModified', $result->bulkWriteResult);
$this->assertSame(1, $result->bulkWriteResult->nModified);

$this->assertSame('test', $clientEncryption1->decrypt($ciphertext));
$this->assertSame('test', $clientEncryption2->decrypt($ciphertext));
}

public static function provideRewrapManyDataKeySrcAndDstProviders()
{
$providers = ['aws', 'azure', 'gcp', 'kmip', 'local'];

foreach ($providers as $srcProvider) {
foreach ($providers as $dstProvider) {
yield [$srcProvider, $dstProvider];
}
}
}

private function createInt64(string $value): Int64
{
$array = sprintf('a:1:{s:7:"integer";s:%d:"%s";}', strlen($value), $value);
Expand Down
Loading