Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 6 additions & 20 deletions io/js/src/test/scala/fs2/io/net/tls/TLSSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,23 @@ package tls

import cats.effect.IO
import cats.syntax.all._
import fs2.io.file.Files
import fs2.io.file.Path

import scala.scalajs.js

abstract class TLSSuite extends Fs2Suite {

def testTlsContext(
privateKey: Boolean,
version: Option[SecureContext.SecureVersion] = None
): IO[TLSContext[IO]] = Files[IO]
.readAll(Path("io/shared/src/test/resources/keystore.json"))
.through(text.utf8.decode)
.compile
.string
.flatMap(s => IO(js.JSON.parse(s).asInstanceOf[js.Dictionary[CertKey]]("server")))
.map { certKey =>
): IO[TLSContext[IO]] =
TestCertificateProvider.getCertificateAndPrivateKey.map { certPair =>
Network[IO].tlsContext.fromSecureContext(
SecureContext(
minVersion = version,
maxVersion = version,
ca = List(certKey.cert.asRight).some,
cert = List(certKey.cert.asRight).some,
ca = List(certPair.certificatePem.asRight).some,
cert = List(certPair.certificatePem.asRight).some,
key =
if (privateKey) List(SecureContext.Key(certKey.key.asRight, "password".some)).some
if (privateKey)
List(SecureContext.Key(certPair.privateKeyPem.asRight, None)).some
else None
)
)
Expand All @@ -60,9 +52,3 @@ abstract class TLSSuite extends Fs2Suite {
// val logger = TLSLogger.Enabled(msg => IO(println(s"\u001b[33m${msg}\u001b[0m")))

}

@js.native
trait CertKey extends js.Object {
def cert: String = js.native
def key: String = js.native
}
4 changes: 2 additions & 2 deletions io/jvm/src/test/scala/fs2/io/IoPlatformSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,8 @@ class IoPlatformSuite extends Fs2Suite {
bar.assertEquals("bar")
}
test("classloader") {
val size = readClassLoaderResource[IO]("keystore.jks", 8192).as(1L).compile.foldMonoid
size.assertEquals(2591L)
val size = readClassLoaderResource[IO]("fs2/io/foo", 8192).as(1L).compile.foldMonoid
size.assertEquals(3L)
}
}
}
35 changes: 29 additions & 6 deletions io/jvm/src/test/scala/fs2/io/net/tls/TLSSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,35 @@ import cats.effect.IO

abstract class TLSSuite extends Fs2Suite {
def testTlsContext: IO[TLSContext[IO]] =
Network[IO].tlsContext
.fromKeyStoreResource(
"keystore.jks",
"password".toCharArray,
"password".toCharArray
)
TestCertificateProvider.getCertificateAndPrivateKey.flatMap { certPair =>
IO.blocking {
val keyStore = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType)
keyStore.load(null, null)

val certFactory = java.security.cert.CertificateFactory.getInstance("X.509")
val cert = certFactory.generateCertificate(
new java.io.ByteArrayInputStream(
certPair.certificatePem.getBytes(java.nio.charset.StandardCharsets.UTF_8)
)
)

val keyFactory = java.security.KeyFactory.getInstance("RSA")
val keyPem = certPair.privateKeyPem
.replaceAll("-----BEGIN (.*)-----", "")
.replaceAll("-----END (.*)-----", "")
.replaceAll("\\s", "")
val keyBytes = java.util.Base64.getDecoder.decode(keyPem)
val keySpec = new java.security.spec.PKCS8EncodedKeySpec(keyBytes)
val key = keyFactory.generatePrivate(keySpec)

keyStore.setKeyEntry("alias", key, "password".toCharArray, Array(cert))
keyStore.setCertificateEntry("ca", cert)

keyStore
}.flatMap { ks =>
Network[IO].tlsContext.fromKeyStore(ks, "password".toCharArray)
}
}

val logger = TLSLogger.Disabled
// val logger = TLSLogger.Enabled(msg => IO(println(s"\u001b[33m${msg}\u001b[0m")))
Expand Down
6 changes: 6 additions & 0 deletions io/native/src/main/scala/fs2/io/net/tls/CertChainAndKey.scala
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,10 @@ final class CertChainAndKey private (chainPem: ByteVector, privateKeyPem: ByteVe
object CertChainAndKey {
def apply(chainPem: ByteVector, privateKeyPem: ByteVector): CertChainAndKey =
new CertChainAndKey(chainPem, privateKeyPem)

def apply(chainPem: String, privateKeyPem: String): CertChainAndKey =
new CertChainAndKey(bytesFromPemString(chainPem), bytesFromPemString(privateKeyPem))

private def bytesFromPemString(s: String): ByteVector =
ByteVector.view(s.getBytes(java.nio.charset.StandardCharsets.UTF_8))
}
22 changes: 7 additions & 15 deletions io/native/src/test/scala/fs2/io/net/tls/TLSSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,30 +26,22 @@ package tls

import cats.effect.IO
import cats.effect.kernel.Resource
import fs2.io.file.Files
import fs2.io.file.Path
import scodec.bits.ByteVector

abstract class TLSSuite extends Fs2Suite {
def testTlsContext: Resource[IO, TLSContext[IO]] = for {
cert <- Resource.eval {
Files[IO].readAll(Path("io/shared/src/test/resources/cert.pem")).compile.to(ByteVector)
}
key <- Resource.eval {
Files[IO].readAll(Path("io/shared/src/test/resources/key.pem")).compile.to(ByteVector)
}
certPair <- Resource.eval(TestCertificateProvider.getCertificateAndPrivateKey)
cfg <- S2nConfig.builder
.withCertChainAndKeysToStore(List(CertChainAndKey(cert, key)))
.withPemsToTrustStore(List(cert.decodeAscii.toOption.get))
.withCertChainAndKeysToStore(
List(CertChainAndKey(certPair.certificatePem, certPair.privateKeyPem))
)
.withPemsToTrustStore(List(certPair.certificatePem))
.build[IO]
} yield Network[IO].tlsContext.fromS2nConfig(cfg)

def testClientTlsContext: Resource[IO, TLSContext[IO]] = for {
cert <- Resource.eval {
Files[IO].readAll(Path("io/shared/src/test/resources/cert.pem")).compile.to(ByteVector)
}
certPair <- Resource.eval(TestCertificateProvider.getCertificateAndPrivateKey)
cfg <- S2nConfig.builder
.withPemsToTrustStore(List(cert.decodeAscii.toOption.get))
.withPemsToTrustStore(List(certPair.certificatePem))
.build[IO]
} yield Network[IO].tlsContext.fromS2nConfig(cfg)

Expand Down
21 changes: 0 additions & 21 deletions io/shared/src/test/resources/cert.pem

This file was deleted.

28 changes: 0 additions & 28 deletions io/shared/src/test/resources/key.pem

This file was deleted.

Binary file removed io/shared/src/test/resources/keystore.jks
Binary file not shown.
6 changes: 0 additions & 6 deletions io/shared/src/test/resources/keystore.json

This file was deleted.

120 changes: 120 additions & 0 deletions io/shared/src/test/scala/fs2/io/TestCertificateProvider.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright (c) 2013 Functional Streams for Scala
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package fs2.io

import cats.effect.{IO, Ref, SyncIO}
import cats.effect.std.Mutex
import fs2.Stream
import fs2.io.file.Files

object TestCertificateProvider {

/** Represents a self-signed certificate and private key for testing.
* Both values are PEM encoded.
*/
case class CertificateAndPrivateKey(
certificatePem: String,
privateKeyPem: String
)

private val mutex: Mutex[IO] = Mutex.in[SyncIO, IO].unsafeRunSync()
private val cache: Ref[IO, Option[CertificateAndPrivateKey]] = Ref.unsafe(None)

/** Returns a cached certificate and private key, generating it if necessary.
* The generation happens once per test suite execution using a self-signed certificate.
*/
def getCertificateAndPrivateKey: IO[CertificateAndPrivateKey] =
mutex.lock.surround {
cache.get.flatMap {
case Some(c) => IO.pure(c)
case None => generateCertificateAndPrivateKey.flatTap(c => cache.set(Some(c)))
}
}

private def generateCertificateAndPrivateKey: IO[CertificateAndPrivateKey] =
Files[IO].tempDirectory.use { tempDir =>
val certPath = tempDir / "cert.pem"
val keyPath = tempDir / "key.pem"
val configPath = tempDir / "openssl.cnf"

val config = """[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no

[req_distinguished_name]
CN = localhost
O = FS2 Tests

[v3_req]
subjectAltName = DNS:localhost,IP:127.0.0.1,DNS:Unknown
basicConstraints = critical,CA:TRUE
keyUsage = digitalSignature,keyEncipherment,keyCertSign
extendedKeyUsage = serverAuth,clientAuth
"""

val cmd = List(
"openssl",
"req",
"-x509",
"-newkey",
"rsa:2048",
"-keyout",
keyPath.toString,
"-out",
certPath.toString,
"-days",
"365",
"-nodes",
"-config",
configPath.toString,
"-sha256"
)

def run(cmd: List[String]): IO[Unit] =
fs2.io.process.ProcessBuilder(cmd.head, cmd.tail: _*).spawn[IO].use { p =>
for {
out <- p.stdout.through(fs2.text.utf8.decode).compile.string
err <- p.stderr.through(fs2.text.utf8.decode).compile.string
exitCode <- p.exitValue
_ <-
if (exitCode == 0) IO.unit
else
IO.raiseError(
new RuntimeException(
s"Command ${cmd.mkString(" ")} failed with exit code $exitCode\nStdout: $out\nStderr: $err"
)
)
} yield ()
}

for {
_ <- Stream(config).through(Files[IO].writeUtf8Lines(configPath)).compile.drain
_ <- run(cmd)
certString <- Files[IO].readUtf8(certPath).compile.string
keyString <- Files[IO].readUtf8(keyPath).compile.string
} yield CertificateAndPrivateKey(
certString,
keyString
)
}
}