Skip to content
Open
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
86 changes: 86 additions & 0 deletions io/js/src/test/scala/fs2/io/JsCertificateProvider.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* 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
import fs2.io.file.Files
import scodec.bits.ByteVector
import scala.concurrent.duration._

/** Platform-specific implementation for JS platform using OpenSSL.
*/
private[io] object PlatformSpecificCertificateProvider {

def create: IO[TestCertificateProvider] = IO.pure(new JsCertificateProvider)

private class JsCertificateProvider extends TestCertificateProvider {

def getCertificatePair: IO[TestCertificateProvider.CertificatePair] =
Files[IO].tempDirectory.use { tempDir =>
val certPath = tempDir / "cert.pem"
val keyPath = tempDir / "key.pem"

val cmd = List(
"openssl",
"req",
"-x509",
"-newkey",
"rsa:2048",
"-keyout",
keyPath.toString,
"-out",
certPath.toString,
"-days",
"365",
"-nodes",
"-subj",
"/CN=localhost/O=FS2 Tests",
"-addext",
"subjectAltName=DNS:localhost,IP:127.0.0.1",
"-sha256"
)

def run(cmd: List[String]): IO[Unit] =
fs2.io.process.ProcessBuilder(cmd.head, cmd.tail: _*).spawn[IO].use { p =>
p.exitValue.flatMap {
case 0 => IO.unit
case n =>
IO.raiseError(new RuntimeException(s"Command ${cmd.head} failed with exit code $n"))
}
}

for {
_ <- run(cmd)
_ <- IO.sleep(1.second)
cert <- Files[IO].readAll(certPath).compile.to(ByteVector)
key <- Files[IO].readAll(keyPath).compile.to(ByteVector)
certString <- Files[IO].readAll(certPath).through(fs2.text.utf8.decode).compile.string
keyString <- Files[IO].readAll(keyPath).through(fs2.text.utf8.decode).compile.string
} yield TestCertificateProvider.CertificatePair(
certificate = cert,
privateKey = key,
certificateString = certString,
privateKeyString = keyString
)
}
}
}
27 changes: 7 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,43 +26,30 @@ 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.getCachedProvider.flatMap { provider =>
provider.getCertificatePair.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.certificateString.asRight).some,
cert = List(certPair.certificateString.asRight).some,
key =
if (privateKey) List(SecureContext.Key(certKey.key.asRight, "password".some)).some
if (privateKey)
List(SecureContext.Key(certPair.privateKeyString.asRight, "password".some)).some
else None
)
)
}
}

val logger = TLSLogger.Disabled
// 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)
}
}
}
94 changes: 94 additions & 0 deletions io/jvm/src/test/scala/fs2/io/JvmJsCertificateProvider.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* 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
import fs2.io.file.Files
import scodec.bits.ByteVector
import scala.concurrent.duration._

/** Platform-specific implementation for JVM platform using OpenSSL.
*/
private[io] object PlatformSpecificCertificateProvider {

def create: IO[TestCertificateProvider] = IO.pure(new JvmCertificateProvider)

private class JvmCertificateProvider extends TestCertificateProvider {

def getCertificatePair: IO[TestCertificateProvider.CertificatePair] =
Files[IO].tempDirectory.use { tempDir =>
val certPath = tempDir / "cert.pem"
val keyPath = tempDir / "key.pem"

val cmd = List(
"openssl",
"req",
"-x509",
"-newkey",
"rsa:2048",
"-keyout",
keyPath.toString,
"-out",
certPath.toString,
"-days",
"365",
"-nodes",
"-subj",
"/CN=localhost/O=FS2 Tests",
"-addext",
"subjectAltName=DNS:localhost,IP:127.0.0.1",
"-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 {
_ <- run(cmd)
_ <- IO.sleep(1.second)
cert <- Files[IO].readAll(certPath).compile.to(ByteVector)
key <- Files[IO].readAll(keyPath).compile.to(ByteVector)
certString <- Files[IO].readAll(certPath).through(fs2.text.utf8.decode).compile.string
keyString <- Files[IO].readAll(keyPath).through(fs2.text.utf8.decode).compile.string
} yield TestCertificateProvider.CertificatePair(
certificate = cert,
privateKey = key,
certificateString = certString,
privateKeyString = keyString
)
}
}
}
37 changes: 30 additions & 7 deletions io/jvm/src/test/scala/fs2/io/net/tls/TLSSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,36 @@ package tls
import cats.effect.IO

abstract class TLSSuite extends Fs2Suite {
def testTlsContext: IO[TLSContext[IO]] =
Network[IO].tlsContext
.fromKeyStoreResource(
"keystore.jks",
"password".toCharArray,
"password".toCharArray
)
def testTlsContext: IO[TLSContext[IO]] = TestCertificateProvider.getCachedProvider.flatMap {
provider =>
provider.getCertificatePair.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.certificate.toArray)
)

val keyFactory = java.security.KeyFactory.getInstance("RSA")
val keyPem = certPair.privateKeyString
.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
Loading