Last active
December 24, 2021 16:53
-
-
Save rescribet/8a710e957151b2aa1e464e32a127f0e9 to your computer and use it in GitHub Desktop.
KMongo certificate from environment
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
import com.mongodb.ConnectionString | |
import com.mongodb.MongoClientSettings | |
import eu.dexes.broker.persistence.sslContextFromCaCert | |
import io.ktor.application.Application | |
import io.ktor.util.InternalAPI | |
import org.litote.kmongo.coroutine.coroutine | |
import org.litote.kmongo.reactivestreams.KMongo | |
@OptIn(InternalAPI::class) | |
@Suppress("unused") // Referenced in application.conf | |
@kotlin.jvm.JvmOverloads | |
fun Application.module(testing: Boolean = false) { | |
val mongoUrl = environment.config.property("mongo_url").getString() | |
val caCert = environment.config.property("mongo_cert").getString() | |
val connect: MongoClientSettings = MongoClientSettings | |
.builder() | |
.applyToSslSettings { | |
it.invalidHostNameAllowed(true) | |
it.context(sslContextFromCaCert(caCert)) | |
} | |
.applyConnectionString(ConnectionString(mongoUrl)) | |
.build() | |
val client = KMongo.createClient(connect).coroutine | |
client.getDatabase("mydb") | |
} |
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
import io.ktor.util.InternalAPI | |
import io.ktor.util.decodeBase64String | |
import java.security.KeyStore | |
import java.security.cert.CertificateFactory | |
import java.security.cert.X509Certificate | |
import javax.net.ssl.SSLContext | |
import javax.net.ssl.TrustManagerFactory | |
// Adapted from https://stackoverflow.com/a/18514628/1630540 | |
// Note: this uses @InternalAPI `decodeBase64String` from ktor, which can be replaced by the java api if needed. | |
@InternalAPI | |
fun sslContextFromCaCert(cert: String): SSLContext { | |
val cf = CertificateFactory.getInstance("X.509") | |
val caCert = cf.generateCertificate(cert.decodeBase64String().byteInputStream()) as X509Certificate | |
val tmf = TrustManagerFactory | |
.getInstance(TrustManagerFactory.getDefaultAlgorithm()) | |
val ks = KeyStore.getInstance(KeyStore.getDefaultType()) | |
// Don't load key from file | |
ks.load(null) | |
ks.setCertificateEntry("caCert", caCert) | |
tmf.init(ks) | |
val sslContext = SSLContext.getInstance("TLS") | |
sslContext.init(null, tmf.trustManagers, null) | |
return sslContext | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment