package studio.tongtong.remotecompile import com.sun.net.httpserver.HttpsConfigurator import com.sun.net.httpserver.HttpsServer import org.junit.Assert.* import org.junit.Test import java.net.InetSocketAddress import java.net.URI import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.file.Files import java.nio.file.Path import java.security.KeyStore import java.util.concurrent.TimeUnit import javax.net.ssl.KeyManagerFactory import javax.net.ssl.SSLContext class ServerTlsTest { @Test fun trustedLanCertificateWorksAndDifferentCertificateFails() { val root = Files.createTempDirectory("remote-tls-test") var server: HttpsServer? = null try { fun certificate(name: String): Pair { val path = root.resolve("$name.p12") val log = root.resolve("$name.log") val tool = Path.of(System.getProperty("java.home"), "bin", if (System.getProperty("os.name").startsWith("Windows")) "keytool.exe" else "keytool") val process = ProcessBuilder(tool.toString(), "-genkeypair", "-alias", "server", "-keyalg", "EC", "-dname", "CN=localhost", "-ext", "SAN=IP:127.0.0.1,DNS:localhost", "-validity", "2", "-storetype", "PKCS12", "-keystore", path.toString(), "-storepass", "test-password", "-noprompt") .redirectErrorStream(true).redirectOutput(log.toFile()).start() try { assertTrue(process.waitFor(30, TimeUnit.SECONDS)); assertEquals(String(Files.readAllBytes(log), Charsets.ISO_8859_1), 0, process.exitValue()) } finally { if (process.isAlive) process.destroyForcibly() } val store = KeyStore.getInstance("PKCS12").apply { Files.newInputStream(path).use { load(it, "test-password".toCharArray()) } } val cert = root.resolve("$name.crt"); Files.write(cert, store.getCertificate("server").encoded) return store to cert } val (store, cert) = certificate("trusted") val (_, wrong) = certificate("wrong") val managers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(store, "test-password".toCharArray()) } val context = SSLContext.getInstance("TLS").apply { init(managers.keyManagers, null, null) } server = HttpsServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { httpsConfigurator = HttpsConfigurator(context) createContext("/") { exchange -> exchange.sendResponseHeaders(200, 2); exchange.responseBody.use { it.write("ok".toByteArray()) } } start() } val request = HttpRequest.newBuilder(URI("https://127.0.0.1:${server.address.port}/")).build() assertEquals(200, ServerTls.client(cert.toString()).send(request, HttpResponse.BodyHandlers.ofString()).statusCode()) assertTrue(runCatching { ServerTls.client(wrong.toString()).send(request, HttpResponse.BodyHandlers.ofString()) }.isFailure) assertEquals(95, ServerTls.fingerprint(cert.toString()).length) } finally { server?.stop(0); root.toFile().deleteRecursively() } } }