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 9 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
88 changes: 88 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
93 changes: 93 additions & 0 deletions tests/UnifiedSpecTests/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@

use LogicException;
use MongoDB\Client;
use MongoDB\Driver\ClientEncryption;
use MongoDB\Driver\ServerApi;
use MongoDB\Model\BSONArray;
use MongoDB\Tests\FunctionalTestCase;
use MongoDB\Tests\SpecTests\ClientSideEncryptionSpecTest;
use PHPUnit\Framework\Assert;
use stdClass;

use function array_key_exists;
use function array_map;
use function current;
use function explode;
use function getenv;
use function key;
use function PHPUnit\Framework\assertArrayHasKey;
use function PHPUnit\Framework\assertCount;
Expand All @@ -24,6 +28,7 @@
use function PHPUnit\Framework\assertNotEmpty;
use function PHPUnit\Framework\assertNotSame;
use function PHPUnit\Framework\assertSame;
use function sprintf;

/**
* Execution context for spec tests.
Expand Down Expand Up @@ -108,6 +113,10 @@ public function createEntities(array $entities): void
$this->createClient($id, $def);
break;

case 'clientEncryption':
$this->createClientEncryption($id, $def);
break;

case 'database':
$this->createDatabase($id, $def);
break;
Expand Down Expand Up @@ -316,6 +325,79 @@ private function createClient(string $id, stdClass $o): void
$this->entityMap->set($id, FunctionalTestCase::createTestClient($uri, $uriOptions, $driverOptions));
}

private function createClientEncryption(string $id, stdClass $o): void
{
Util::assertHasOnlyKeys($o, [
'id',
'clientEncryptionOpts',
]);

$clientEncryptionOpts = [];
$clientId = null;

if (isset($o->clientEncryptionOpts)) {
assertIsObject($o->clientEncryptionOpts);
$clientEncryptionOpts = (array) $o->clientEncryptionOpts;
}

if (isset($clientEncryptionOpts['keyVaultClient'])) {
assertIsString($clientEncryptionOpts['keyVaultClient']);
/* Record the keyVaultClient's ID, which we'll later use to track
* the parent client in the entity map. */
$clientId = $clientEncryptionOpts['keyVaultClient'];
$clientEncryptionOpts['keyVaultClient'] = $this->entityMap->getClient($clientId)->getManager();
}

if (isset($clientEncryptionOpts['kmsProviders'])) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Noting for the benefit of @levon80999 and others that may want to run these tests: I suggest defining these secrets in a phpunit.xml file based on phpunit.xml.dist. This file takes precedence over the dist file and is in gitignore, allowing your own configuration to be added.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was actually helpful for me as well. I was previously using a shell script to export the environment variables before calling vendor/bin/simple-phpunit, but phpunit.xml is much nicer.

assertIsObject($clientEncryptionOpts['kmsProviders']);

if (isset($clientEncryptionOpts['kmsProviders']->aws->accessKeyId->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->aws->accessKeyId = static::getEnv('AWS_ACCESS_KEY_ID');
}

if (isset($clientEncryptionOpts['kmsProviders']->aws->secretAccessKey->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->aws->secretAccessKey = static::getEnv('AWS_SECRET_ACCESS_KEY');
}

if (isset($clientEncryptionOpts['kmsProviders']->azure->clientId->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->azure->clientId = static::getEnv('AZURE_CLIENT_ID');
}

if (isset($clientEncryptionOpts['kmsProviders']->azure->clientSecret->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->azure->clientSecret = static::getEnv('AZURE_CLIENT_SECRET');
}

if (isset($clientEncryptionOpts['kmsProviders']->azure->tenantId->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->azure->tenantId = static::getEnv('AZURE_TENANT_ID');
}

if (isset($clientEncryptionOpts['kmsProviders']->gcp->email->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->gcp->email = static::getEnv('GCP_EMAIL');
}

if (isset($clientEncryptionOpts['kmsProviders']->gcp->privateKey->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->gcp->privateKey = static::getEnv('GCP_PRIVATE_KEY');
}

if (isset($clientEncryptionOpts['kmsProviders']->kmip->endpoint->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->kmip->endpoint = static::getEnv('KMIP_ENDPOINT');
}

if (isset($clientEncryptionOpts['kmsProviders']->local->key->{'$$placeholder'})) {
$clientEncryptionOpts['kmsProviders']->local->key = ClientSideEncryptionSpecTest::LOCAL_MASTERKEY;
}
}

if (isset($clientEncryptionOpts['kmsProviders']->kmip->endpoint)) {
$clientEncryptionOpts['tlsOptions']['kmip'] = [
'tlsCAFile' => static::getEnv('KMS_TLS_CA_FILE'),
'tlsCertificateKeyFile' => static::getEnv('KMS_TLS_CERTIFICATE_KEY_FILE'),
];
}

$this->entityMap->set($id, new ClientEncryption($clientEncryptionOpts), $clientId);
}

private function createEntityCollector(string $clientId, stdClass $o): void
{
Util::assertHasOnlyKeys($o, ['id', 'events']);
Expand Down Expand Up @@ -411,6 +493,17 @@ private function createBucket(string $id, stdClass $o): void
$this->entityMap->set($id, $database->selectGridFSBucket($options), $databaseId);
}

private static function getEnv(string $name): string
{
$value = getenv($name);

if ($value === false) {
Assert::markTestSkipped(sprintf('Environment variable "%s" is not defined', $name));
}

return $value;
}

private static function prepareCollectionOrDatabaseOptions(array $options): array
{
Util::assertHasOnlyKeys($options, ['readConcern', 'readPreference', 'writeConcern']);
Expand Down
2 changes: 2 additions & 0 deletions tests/UnifiedSpecTests/EntityMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use MongoDB\Client;
use MongoDB\Collection;
use MongoDB\Database;
use MongoDB\Driver\ClientEncryption;
use MongoDB\Driver\Cursor;
use MongoDB\Driver\Session;
use MongoDB\GridFS\Bucket;
Expand Down Expand Up @@ -182,6 +183,7 @@ private static function isSupportedType(): Constraint
if (self::$isSupportedType === null) {
self::$isSupportedType = logicalOr(
isInstanceOf(Client::class),
isInstanceOf(ClientEncryption::class),
isInstanceOf(Database::class),
isInstanceOf(Collection::class),
isInstanceOf(Session::class),
Expand Down
Loading