Search code examples
javascriptkotlinktorkmm

configuration to Ignore self-signed certificate in ktor httpClient(js) JS engine


Kotlin multiplatform library, my setup looks like the following. Obviously, my JS test fails with the error "Error: Fail to fetch" because the Ktor httpClient(JS) was not configured to ignore/Trust Self Signed certificate. and according to the documentation "Js engine has no custom configuration." so my question is there a way to achieve this to make my test pass JS platforms. or do you know of any workaround? or am I missing something here?

expect object Provider {
    fun createClient(): HttpClient
}

//JVM
actual object Provider {
    actual fun createClient(): HttpClient {
        return HttpClient(Apache) {
            install(JsonFeature) {
                serializer = KotlinxSerializer()
            }
            engine {
                customizeClient {
                    setSSLContext(
                        SSLContextBuilder
                            .create()
                            .loadTrustMaterial(TrustSelfSignedStrategy())
                            .build()
                    )
                    setSSLHostnameVerifier(NoopHostnameVerifier())
                }
            }
        }
    }
}

//JS
actual object Provider {
    actual fun createClient(): HttpClient {
        return HttpClient(Js) {
            install(JsonFeature) {
                serializer = KotlinxSerializer()
            }
        }
    }
}

Solution

  • As a workaround, on the Node.js target, you can set the environment variable NODE_TLS_REJECT_UNAUTHORIZED to disable all certificate verification:

    js("process.env.NODE_TLS_REJECT_UNAUTHORIZED = \"0\";")
    val client = HttpClient(Js)
    client.get<String>("https://localhost:8443/")