-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Add X509 authentication tests. #1771
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
Open
vbabanin
wants to merge
6
commits into
mongodb:main
Choose a base branch
from
vbabanin:JAVA-5866
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e7014ad
Add X509 authentication tests.
vbabanin cc3e759
Remove valueOf.
vbabanin f876032
Add execution condition.
vbabanin da96e3f
Fix checkstyle.
vbabanin 75b7dc4
Change javadoc.
vbabanin 222541c
Move method down.
vbabanin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
#!/bin/bash | ||
|
||
# Exit the script with error if any of the commands fail | ||
set -o errexit | ||
|
||
# Supported/used environment variables: | ||
# JDK Set the version of java to be used. Java versions can be set from the java toolchain /opt/java | ||
# ATLAS_X509_DEV Set the connection string for the Atlas X509 development cluster. | ||
# ATLAS_X509_DEV_CERT_BASE64 Set the base64 encoded contents of a PEM file containing the client certificate (signed by the mongodb dev CA) and client private key for the X509 authentication on development cluster. | ||
# ATLAS_X509_DEV_CERT_NOUSER_BASE64 Set the base64 encoded contents of a PEM file containing the client certificate (signed by the mongodb dev CA) and client private key for the X509 authentication on development cluster with the subject name that does not exist on the server/cluster. | ||
|
||
RELATIVE_DIR_PATH="$(dirname "${BASH_SOURCE:-$0}")" | ||
. "${RELATIVE_DIR_PATH}/setup-env.bash" | ||
|
||
MONGODB_URI=${ATLAS_X509_DEV:-} | ||
echo "$MONGODB_URI" | ||
ATLAS_X509_DEV_CERT_BASE64=${ATLAS_X509_DEV_CERT_BASE64:-} | ||
ATLAS_X509_DEV_CERT_NOUSER_BASE64=${ATLAS_X509_DEV_CERT_NOUSER_BASE64:-} | ||
|
||
############################################ | ||
# Functions # | ||
############################################ | ||
|
||
provision_keystores () { | ||
# Base64 decode contents of a PEM holder for client certificate (signed by the mongodb dev CA) and private key | ||
echo "${ATLAS_X509_DEV_CERT_BASE64}" | base64 --decode > ca_and_pk.pem | ||
echo "${ATLAS_X509_DEV_CERT_NOUSER_BASE64}" | base64 --decode > ca_and_pk_no_user.pem | ||
|
||
# Build the pkcs12 (keystore). We include the leaf-only certificate (with public key) and private key in the keystore, | ||
# assuming the signed certificate is already trusted by the Atlas as issuer is MongoDB dev CA. | ||
echo "Creating PKCS12 keystore from ca_and_pk.pem" | ||
openssl pkcs12 -export \ | ||
-in ca_and_pk.pem \ | ||
-out existing_user.p12 \ | ||
-password pass:test | ||
|
||
echo "Creating PKCS12 keystore from ca_and_pk_no_user.pem" | ||
openssl pkcs12 -export \ | ||
-in ca_and_pk_no_user.pem \ | ||
-out non_existing_user.p12 \ | ||
-password pass:test | ||
} | ||
|
||
############################################ | ||
# Main Program # | ||
############################################ | ||
echo "Running X509 Authentication tests with Java ${JAVA_VERSION}" | ||
|
||
# Set up keystores for x509 authentication. | ||
provision_keystores | ||
|
||
./gradlew -PjavaVersion=${JAVA_VERSION} -Dorg.mongodb.test.uri=${MONGODB_URI} --info --continue \ | ||
-Dorg.mongodb.test.x509.auth=true \ | ||
-Dorg.mongodb.test.x509.auth.keystore.location="$(pwd)" \ | ||
driver-sync:test --tests X509AuthenticationTest \ | ||
driver-reactive-streams:test --tests X509AuthenticationTest |
28 changes: 28 additions & 0 deletions
28
...treams/src/test/functional/com/mongodb/reactivestreams/client/X509AuthenticationTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
/* | ||
* Copyright 2008-present MongoDB, Inc. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.mongodb.reactivestreams.client; | ||
|
||
import com.mongodb.MongoClientSettings; | ||
import com.mongodb.client.auth.AbstractX509AuthenticationTest; | ||
import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; | ||
|
||
public class X509AuthenticationTest extends AbstractX509AuthenticationTest { | ||
@Override | ||
protected com.mongodb.client.MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) { | ||
return new SyncMongoClient(MongoClients.create(mongoClientSettings)); | ||
} | ||
} |
167 changes: 167 additions & 0 deletions
167
driver-sync/src/test/functional/com/mongodb/client/auth/AbstractX509AuthenticationTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
/* | ||
* Copyright 2008-present MongoDB, Inc. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.mongodb.client.auth; | ||
|
||
import com.mongodb.MongoClientSettings; | ||
import com.mongodb.MongoCommandException; | ||
import com.mongodb.MongoSecurityException; | ||
import com.mongodb.client.Fixture; | ||
import com.mongodb.client.MongoClient; | ||
import com.mongodb.connection.NettyTransportSettings; | ||
import io.netty.handler.ssl.SslContextBuilder; | ||
import io.netty.handler.ssl.SslProvider; | ||
import org.junit.jupiter.params.ParameterizedTest; | ||
import org.junit.jupiter.params.provider.Arguments; | ||
import org.junit.jupiter.params.provider.MethodSource; | ||
|
||
import javax.net.ssl.KeyManagerFactory; | ||
import javax.net.ssl.SSLContext; | ||
import java.io.File; | ||
import java.io.FileInputStream; | ||
import java.io.IOException; | ||
import java.security.KeyStore; | ||
import java.security.KeyStoreException; | ||
import java.security.NoSuchAlgorithmException; | ||
import java.security.UnrecoverableKeyException; | ||
import java.security.cert.CertificateException; | ||
import java.util.stream.Stream; | ||
|
||
import static com.mongodb.AuthenticationMechanism.MONGODB_X509; | ||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import static org.junit.jupiter.api.Assertions.assertThrows; | ||
import static org.junit.jupiter.api.Assertions.assertTrue; | ||
import static org.junit.jupiter.api.Assumptions.assumeTrue; | ||
|
||
public abstract class AbstractX509AuthenticationTest { | ||
|
||
private static final String KEYSTORE_PASSWORD = "test"; | ||
|
||
protected abstract MongoClient createMongoClient(MongoClientSettings mongoClientSettings); | ||
|
||
protected AbstractX509AuthenticationTest() { | ||
assumeTrue(isX509TestsEnabled(), "X509 authentication tests are disabled"); | ||
} | ||
|
||
private static Stream<Arguments> shouldAuthenticateWithClientCertificate() throws Exception { | ||
String keystoreFileName = "existing_user.p12"; | ||
return getArgumentForKeystore(keystoreFileName); | ||
} | ||
|
||
@ParameterizedTest(name = "should authenticate with client certificate. MongoClientSettings: {0}") | ||
@MethodSource | ||
public void shouldAuthenticateWithClientCertificate(final MongoClientSettings mongoClientSettings) { | ||
//given | ||
try (MongoClient client = createMongoClient(mongoClientSettings)) { | ||
|
||
//when & then command completes successfully with x509 authentication | ||
client.getDatabase("test").getCollection("test").estimatedDocumentCount(); | ||
} | ||
} | ||
|
||
private static Stream<Arguments> shouldPassMutualTLSWithClientCertificateAndFailAuthenticateWithAbsentUser() throws Exception { | ||
String keystoreFileName = "non_existing_user.p12"; | ||
return getArgumentForKeystore(keystoreFileName); | ||
} | ||
|
||
@ParameterizedTest(name = "should pass mutual TLS with client certificate and fail authenticate with absent user. " | ||
+ "MongoClientSettings: {0}") | ||
@MethodSource | ||
public void shouldPassMutualTLSWithClientCertificateAndFailAuthenticateWithAbsentUser(final MongoClientSettings mongoClientSettings) { | ||
// given | ||
try (MongoClient client = createMongoClient(mongoClientSettings)) { | ||
|
||
// when & then | ||
MongoSecurityException mongoSecurityException = assertThrows(MongoSecurityException.class, | ||
() -> client.getDatabase("test").getCollection("test").estimatedDocumentCount()); | ||
|
||
assertTrue(mongoSecurityException.getMessage().contains("Exception authenticating")); | ||
MongoCommandException mongoCommandException = (MongoCommandException) mongoSecurityException.getCause(); | ||
|
||
assertTrue(mongoCommandException.getMessage().contains("Could not find user")); | ||
assertEquals(11, mongoCommandException.getCode()); | ||
} | ||
} | ||
|
||
private static Stream<Arguments> getArgumentForKeystore(final String keystoreFileName) throws Exception { | ||
SSLContext context = buildSslContextFromKeyStore(keystoreFileName); | ||
MongoClientSettings.Builder mongoClientSettingsBuilder = Fixture.getMongoClientSettingsBuilder(); | ||
verifyX509AuthenticationIsRequired(mongoClientSettingsBuilder); | ||
|
||
return Stream.of( | ||
Arguments.of(mongoClientSettingsBuilder | ||
.applyToSslSettings(builder -> builder.context(context)) | ||
.build()), | ||
|
||
Arguments.of(mongoClientSettingsBuilder | ||
.applyToSslSettings(builder -> builder.context(context)) | ||
.transportSettings(NettyTransportSettings.nettyBuilder() | ||
.sslContext(SslContextBuilder.forClient() | ||
.sslProvider(SslProvider.valueOf("JDK")) | ||
vbabanin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.keyManager(getKeyManagerFactory(keystoreFileName)) | ||
.build()) | ||
.build()) | ||
.build()), | ||
|
||
Arguments.of(mongoClientSettingsBuilder | ||
.applyToSslSettings(builder -> builder.context(context)) | ||
.transportSettings(NettyTransportSettings.nettyBuilder() | ||
.sslContext(SslContextBuilder.forClient() | ||
.sslProvider(SslProvider.valueOf("OPENSSL")) | ||
vbabanin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.keyManager(getKeyManagerFactory(keystoreFileName)) | ||
.build()) | ||
.build()) | ||
.build()) | ||
); | ||
} | ||
|
||
private static SSLContext buildSslContextFromKeyStore(final String keystoreFileName) throws Exception { | ||
KeyManagerFactory keyManagerFactory = getKeyManagerFactory(keystoreFileName); | ||
SSLContext sslContext = SSLContext.getInstance("TLS"); | ||
sslContext.init(keyManagerFactory.getKeyManagers(), null, null); | ||
return sslContext; | ||
} | ||
|
||
private static KeyManagerFactory getKeyManagerFactory(final String keystoreFileName) | ||
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException { | ||
KeyStore ks = KeyStore.getInstance("PKCS12"); | ||
try (FileInputStream fis = new FileInputStream(getKeystoreLocation() + File.separator + keystoreFileName)) { | ||
ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); | ||
} | ||
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( | ||
KeyManagerFactory.getDefaultAlgorithm()); | ||
keyManagerFactory.init(ks, KEYSTORE_PASSWORD.toCharArray()); | ||
return keyManagerFactory; | ||
} | ||
|
||
private static boolean isX509TestsEnabled() { | ||
return Boolean.parseBoolean(System.getProperty("org.mongodb.test.x509.auth")); | ||
} | ||
|
||
private static String getKeystoreLocation() { | ||
return System.getProperty("org.mongodb.test.x509.auth.keystore.location"); | ||
} | ||
|
||
/** | ||
* The connection string is sourced from an environment variable (Secret Storage). | ||
* We verify it still requires X.509 authentication before running these tests to ensure correctness. | ||
*/ | ||
private static void verifyX509AuthenticationIsRequired(final MongoClientSettings.Builder mongoClientSettingsBuilder) { | ||
com.mongodb.assertions.Assertions.assertTrue( | ||
com.mongodb.assertions.Assertions.assertNotNull(mongoClientSettingsBuilder.build().getCredential()) | ||
.getAuthenticationMechanism() == MONGODB_X509); | ||
} | ||
} |
28 changes: 28 additions & 0 deletions
28
driver-sync/src/test/functional/com/mongodb/client/auth/X509AuthenticationTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
/* | ||
* Copyright 2008-present MongoDB, Inc. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.mongodb.client.auth; | ||
|
||
import com.mongodb.MongoClientSettings; | ||
import com.mongodb.client.MongoClient; | ||
import com.mongodb.client.MongoClients; | ||
|
||
public class X509AuthenticationTest extends AbstractX509AuthenticationTest { | ||
@Override | ||
protected MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) { | ||
return MongoClients.create(mongoClientSettings); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.