Skip to content

Instantly share code, notes, and snippets.

@DoZator
Last active October 2, 2023 07:54
Show Gist options
  • Save DoZator/7bdd1b258db5f6214ff478d0cda620b7 to your computer and use it in GitHub Desktop.
Save DoZator/7bdd1b258db5f6214ff478d0cda620b7 to your computer and use it in GitHub Desktop.
DocumentDB configuration example
@Slf4j
@Configuration
@RequiredArgsConstructor
public class DocumentDBConfig extends AbstractMongoClientConfiguration {
private static final String CERT_FILE_PATH = "document-db-certs/rds-combined-ca-bundle.pem";
private static final String END_OF_CERTIFICATE_DELIMITER = "-----END CERTIFICATE-----";
private static final String CERTIFICATE_TYPE = "X.509";
private static final String TLS_PROTOCOL = "TLS";
// mongodb://%s:%s@%s:%s/%s?directConnection=true&serverSelectionTimeoutMS=2000&tlsAllowInvalidHostnames=true&tls=true
@Value("${documentDb.connectionStringTemplate}")
private String connectionStringTemplate;
@Value("${documentDb.port}")
private String port;
@Value("${documentDb.name}")
private String dbName;
@Value("${documentDb.host}")
private String host;
@Value("${documentDb.user}")
private String user;
@Value("${documentDb.password}")
private String password;
@Override
protected String getDatabaseName() {
return this.dbName;
}
@Override
protected void configureClientSettings(MongoClientSettings.Builder builder) {
builder.applyConnectionString(new ConnectionString(getConnectionString()));
builder.applyToSslSettings(ssl -> ssl.enabled(true).context(createSSLConfiguration()));
}
@SneakyThrows
private SSLContext createSSLConfiguration() {
ClassPathResource cpr = new ClassPathResource(CERT_FILE_PATH);
String certContent = Files.readString(cpr.getFile().toPath());
Set<String> allCertificates = Stream.of(certContent
.split(END_OF_CERTIFICATE_DELIMITER)).filter(line -> !line.isBlank())
.map(line -> line + END_OF_CERTIFICATE_DELIMITER)
.collect(Collectors.toUnmodifiableSet());
CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
int certNumber = 1;
for (String cert : allCertificates) {
Certificate caCert = certificateFactory.generateCertificate(new ByteArrayInputStream(cert.getBytes()));
keyStore.setCertificateEntry(String.format("AWS-certificate-%s", certNumber++), caCert);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance(TLS_PROTOCOL);
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
return sslContext;
}
private String getConnectionString() {
return String.format(this.connectionStringTemplate,
this.user,
this.password,
this.host,
this.port,
this.getDatabaseName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment