Skip to content

Commit f0da98d

Browse files
authored
Add X509 authentication tests. (#1771)
JAVA-5866
1 parent 5e61b7a commit f0da98d

File tree

5 files changed

+323
-0
lines changed

5 files changed

+323
-0
lines changed

.evergreen/.evg.yml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,17 @@ functions:
232232
cd $DRIVERS_TOOLS/.evergreen/auth_aws
233233
./setup_secrets.sh drivers/aws_auth
234234
235+
"add-atlas-connect-variables-to-file":
236+
- command: shell.exec
237+
type: "test"
238+
params:
239+
include_expansions_in_env: [ "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN" ]
240+
shell: "bash"
241+
working_dir: "src"
242+
script: |
243+
${PREPARE_SHELL}
244+
${DRIVERS_TOOLS}/.evergreen/secrets_handling/setup-secrets.sh drivers/atlas_connect
245+
235246
"start-csfle-servers":
236247
- command: ec2.assume_role
237248
params:
@@ -512,6 +523,16 @@ functions:
512523
# DO NOT ECHO WITH XTRACE (which PREPARE_SHELL does)
513524
JAVA_VERSION="8" MONGODB_URI="${plain_auth_mongodb_uri}" .evergreen/run-plain-auth-test.sh
514525
526+
"run-x509-auth-test":
527+
- command: shell.exec
528+
type: "test"
529+
params:
530+
silent: true
531+
working_dir: "src"
532+
script: |
533+
# DO NOT ECHO WITH XTRACE (which PREPARE_SHELL does)
534+
JAVA_VERSION="8" .evergreen/run-x509-auth-tests.sh
535+
515536
"run-aws-auth-test-with-regular-aws-credentials":
516537
- command: shell.exec
517538
type: "test"
@@ -978,6 +999,13 @@ tasks:
978999
commands:
9791000
- func: "run-plain-auth-test"
9801001

1002+
# Test that x509 auth using server with OpenSSL 3 succeeds.
1003+
- name: "atlas-x509-auth-test-task"
1004+
commands:
1005+
- func: "assume-aws-test-secrets-role"
1006+
- func: "add-atlas-connect-variables-to-file"
1007+
- func: "run-x509-auth-test"
1008+
9811009
- name: "aws-auth-test-with-regular-aws-credentials-task"
9821010
commands:
9831011
- func: "start-mongo-orchestration"
@@ -2254,6 +2282,7 @@ buildvariants:
22542282
- name: "atlas-deployed-task-group"
22552283
- name: "atlas-search-task"
22562284
- name: "atlas-connectivity-task"
2285+
- name: "atlas-x509-auth-test-task"
22572286

22582287
- name: "atlas-data-lake-test"
22592288
display_name: "Atlas Data Lake test"

.evergreen/run-x509-auth-tests.sh

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/bin/bash
2+
3+
# Exit the script with error if any of the commands fail
4+
set -o errexit
5+
6+
# Supported/used environment variables:
7+
# JDK Set the version of java to be used. Java versions can be set from the java toolchain /opt/java
8+
# ATLAS_X509_DEV Set the connection string for the Atlas X509 development cluster.
9+
# 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.
10+
# 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.
11+
12+
RELATIVE_DIR_PATH="$(dirname "${BASH_SOURCE:-$0}")"
13+
. "${RELATIVE_DIR_PATH}/setup-env.bash"
14+
15+
MONGODB_URI=${ATLAS_X509_DEV:-}
16+
echo "$MONGODB_URI"
17+
ATLAS_X509_DEV_CERT_BASE64=${ATLAS_X509_DEV_CERT_BASE64:-}
18+
ATLAS_X509_DEV_CERT_NOUSER_BASE64=${ATLAS_X509_DEV_CERT_NOUSER_BASE64:-}
19+
20+
############################################
21+
# Functions #
22+
############################################
23+
24+
provision_keystores () {
25+
# Base64 decode contents of a PEM holder for client certificate (signed by the mongodb dev CA) and private key
26+
echo "${ATLAS_X509_DEV_CERT_BASE64}" | base64 --decode > ca_and_pk.pem
27+
echo "${ATLAS_X509_DEV_CERT_NOUSER_BASE64}" | base64 --decode > ca_and_pk_no_user.pem
28+
29+
# Build the pkcs12 (keystore). We include the leaf-only certificate (with public key) and private key in the keystore,
30+
# assuming the signed certificate is already trusted by the Atlas as issuer is MongoDB dev CA.
31+
echo "Creating PKCS12 keystore from ca_and_pk.pem"
32+
openssl pkcs12 -export \
33+
-in ca_and_pk.pem \
34+
-out existing_user.p12 \
35+
-password pass:test
36+
37+
echo "Creating PKCS12 keystore from ca_and_pk_no_user.pem"
38+
openssl pkcs12 -export \
39+
-in ca_and_pk_no_user.pem \
40+
-out non_existing_user.p12 \
41+
-password pass:test
42+
}
43+
44+
############################################
45+
# Main Program #
46+
############################################
47+
echo "Running X509 Authentication tests with Java ${JAVA_VERSION}"
48+
49+
# Set up keystores for x509 authentication.
50+
provision_keystores
51+
52+
./gradlew -PjavaVersion=${JAVA_VERSION} -Dorg.mongodb.test.uri=${MONGODB_URI} --info --continue \
53+
-Dorg.mongodb.test.x509.auth.enabled=true \
54+
-Dorg.mongodb.test.x509.auth.keystore.location="$(pwd)" \
55+
driver-sync:test --tests X509AuthenticationTest \
56+
driver-reactive-streams:test --tests X509AuthenticationTest
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Copyright 2008-present MongoDB, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.mongodb.reactivestreams.client;
18+
19+
import com.mongodb.MongoClientSettings;
20+
import com.mongodb.client.auth.AbstractX509AuthenticationTest;
21+
import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient;
22+
23+
public class X509AuthenticationTest extends AbstractX509AuthenticationTest {
24+
@Override
25+
protected com.mongodb.client.MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) {
26+
return new SyncMongoClient(MongoClients.create(mongoClientSettings));
27+
}
28+
}
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
/*
2+
* Copyright 2008-present MongoDB, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.mongodb.client.auth;
18+
19+
import com.mongodb.MongoClientSettings;
20+
import com.mongodb.MongoCommandException;
21+
import com.mongodb.MongoSecurityException;
22+
import com.mongodb.client.Fixture;
23+
import com.mongodb.client.MongoClient;
24+
import com.mongodb.connection.NettyTransportSettings;
25+
import io.netty.handler.ssl.SslContextBuilder;
26+
import io.netty.handler.ssl.SslProvider;
27+
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
28+
import org.junit.jupiter.api.extension.ExecutionCondition;
29+
import org.junit.jupiter.api.extension.ExtendWith;
30+
import org.junit.jupiter.api.extension.ExtensionContext;
31+
import org.junit.jupiter.params.ParameterizedTest;
32+
import org.junit.jupiter.params.provider.Arguments;
33+
import org.junit.jupiter.params.provider.MethodSource;
34+
35+
import javax.net.ssl.KeyManagerFactory;
36+
import javax.net.ssl.SSLContext;
37+
import java.io.File;
38+
import java.io.FileInputStream;
39+
import java.io.IOException;
40+
import java.security.KeyStore;
41+
import java.security.KeyStoreException;
42+
import java.security.NoSuchAlgorithmException;
43+
import java.security.UnrecoverableKeyException;
44+
import java.security.cert.CertificateException;
45+
import java.util.stream.Stream;
46+
47+
import static com.mongodb.AuthenticationMechanism.MONGODB_X509;
48+
import static org.junit.jupiter.api.Assertions.assertEquals;
49+
import static org.junit.jupiter.api.Assertions.assertThrows;
50+
import static org.junit.jupiter.api.Assertions.assertTrue;
51+
52+
@ExtendWith(AbstractX509AuthenticationTest.X509AuthenticationPropertyCondition.class)
53+
public abstract class AbstractX509AuthenticationTest {
54+
55+
private static final String KEYSTORE_PASSWORD = "test";
56+
protected abstract MongoClient createMongoClient(MongoClientSettings mongoClientSettings);
57+
58+
private static Stream<Arguments> shouldAuthenticateWithClientCertificate() throws Exception {
59+
String keystoreFileName = "existing_user.p12";
60+
return getArgumentForKeystore(keystoreFileName);
61+
}
62+
63+
@ParameterizedTest(name = "should authenticate with client certificate. MongoClientSettings: {0}")
64+
@MethodSource
65+
public void shouldAuthenticateWithClientCertificate(final MongoClientSettings mongoClientSettings) {
66+
//given
67+
try (MongoClient client = createMongoClient(mongoClientSettings)) {
68+
69+
//when & then command completes successfully with x509 authentication
70+
client.getDatabase("test").getCollection("test").estimatedDocumentCount();
71+
}
72+
}
73+
74+
private static Stream<Arguments> shouldPassMutualTLSWithClientCertificateAndFailAuthenticateWithAbsentUser() throws Exception {
75+
String keystoreFileName = "non_existing_user.p12";
76+
return getArgumentForKeystore(keystoreFileName);
77+
}
78+
79+
@ParameterizedTest(name = "should pass mutual TLS with client certificate and fail authenticate with absent user. "
80+
+ "MongoClientSettings: {0}")
81+
@MethodSource
82+
public void shouldPassMutualTLSWithClientCertificateAndFailAuthenticateWithAbsentUser(final MongoClientSettings mongoClientSettings) {
83+
// given
84+
try (MongoClient client = createMongoClient(mongoClientSettings)) {
85+
86+
// when & then
87+
MongoSecurityException mongoSecurityException = assertThrows(MongoSecurityException.class,
88+
() -> client.getDatabase("test").getCollection("test").estimatedDocumentCount());
89+
90+
assertTrue(mongoSecurityException.getMessage().contains("Exception authenticating"));
91+
MongoCommandException mongoCommandException = (MongoCommandException) mongoSecurityException.getCause();
92+
93+
assertTrue(mongoCommandException.getMessage().contains("Could not find user"));
94+
assertEquals(11, mongoCommandException.getCode());
95+
}
96+
}
97+
98+
private static Stream<Arguments> getArgumentForKeystore(final String keystoreFileName) throws Exception {
99+
SSLContext context = buildSslContextFromKeyStore(keystoreFileName);
100+
MongoClientSettings.Builder mongoClientSettingsBuilder = Fixture.getMongoClientSettingsBuilder();
101+
verifyX509AuthenticationIsRequired(mongoClientSettingsBuilder);
102+
103+
return Stream.of(
104+
Arguments.of(mongoClientSettingsBuilder
105+
.applyToSslSettings(builder -> builder.context(context))
106+
.build()),
107+
108+
Arguments.of(mongoClientSettingsBuilder
109+
.applyToSslSettings(builder -> builder.context(context))
110+
.transportSettings(NettyTransportSettings.nettyBuilder()
111+
.sslContext(SslContextBuilder.forClient()
112+
.sslProvider(SslProvider.JDK)
113+
.keyManager(getKeyManagerFactory(keystoreFileName))
114+
.build())
115+
.build())
116+
.build()),
117+
118+
Arguments.of(mongoClientSettingsBuilder
119+
.applyToSslSettings(builder -> builder.context(context))
120+
.transportSettings(NettyTransportSettings.nettyBuilder()
121+
.sslContext(SslContextBuilder.forClient()
122+
.sslProvider(SslProvider.OPENSSL)
123+
.keyManager(getKeyManagerFactory(keystoreFileName))
124+
.build())
125+
.build())
126+
.build())
127+
);
128+
}
129+
130+
private static SSLContext buildSslContextFromKeyStore(final String keystoreFileName) throws Exception {
131+
KeyManagerFactory keyManagerFactory = getKeyManagerFactory(keystoreFileName);
132+
SSLContext sslContext = SSLContext.getInstance("TLS");
133+
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
134+
return sslContext;
135+
}
136+
137+
private static KeyManagerFactory getKeyManagerFactory(final String keystoreFileName)
138+
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
139+
KeyStore ks = KeyStore.getInstance("PKCS12");
140+
try (FileInputStream fis = new FileInputStream(getKeystoreLocation() + File.separator + keystoreFileName)) {
141+
ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
142+
}
143+
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
144+
KeyManagerFactory.getDefaultAlgorithm());
145+
keyManagerFactory.init(ks, KEYSTORE_PASSWORD.toCharArray());
146+
return keyManagerFactory;
147+
}
148+
149+
private static String getKeystoreLocation() {
150+
return System.getProperty("org.mongodb.test.x509.auth.keystore.location");
151+
}
152+
153+
/**
154+
* The connection string is sourced from an environment variable populated from Secret Storage.
155+
* We verify it still requires X.509 authentication before running these tests to ensure test invariants.
156+
*/
157+
private static void verifyX509AuthenticationIsRequired(final MongoClientSettings.Builder mongoClientSettingsBuilder) {
158+
com.mongodb.assertions.Assertions.assertTrue(
159+
com.mongodb.assertions.Assertions.assertNotNull(mongoClientSettingsBuilder.build().getCredential())
160+
.getAuthenticationMechanism() == MONGODB_X509);
161+
}
162+
163+
/**
164+
This condition allows to skip initialization of method sources and test execution.
165+
- @EnableIf on the class, assumeTrue in the constructor - do not block method source initialization.
166+
- assumeTrue in the static block - fails the test.
167+
**/
168+
public static class X509AuthenticationPropertyCondition implements ExecutionCondition {
169+
@Override
170+
public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext context) {
171+
if (isX509TestsEnabled()) {
172+
return ConditionEvaluationResult.enabled("Test is enabled because x509 auth configuration exists");
173+
} else {
174+
return ConditionEvaluationResult.disabled("Test is disabled because x509 auth configuration is missing");
175+
}
176+
}
177+
}
178+
179+
private static boolean isX509TestsEnabled() {
180+
return Boolean.parseBoolean(System.getProperty("org.mongodb.test.x509.auth.enabled"));
181+
}
182+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Copyright 2008-present MongoDB, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.mongodb.client.auth;
18+
19+
import com.mongodb.MongoClientSettings;
20+
import com.mongodb.client.MongoClient;
21+
import com.mongodb.client.MongoClients;
22+
23+
public class X509AuthenticationTest extends AbstractX509AuthenticationTest {
24+
@Override
25+
protected MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) {
26+
return MongoClients.create(mongoClientSettings);
27+
}
28+
}

0 commit comments

Comments
 (0)