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
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import sttp.monad.syntax._

import java.io.{ByteArrayInputStream, IOException, InputStream, UnsupportedEncodingException}
import java.net.{ConnectException, MalformedURLException, SocketTimeoutException, UnknownHostException}
import java.nio.file.Files
import java.nio.file.{Files, Path}

import scala.collection.immutable.Seq
import scala.collection.mutable.ArrayBuffer
Expand All @@ -29,6 +29,20 @@ import scala.scalanative.unsigned._
abstract class AbstractCurlBackend[F[_]](_monad: MonadError[F], verbose: Boolean) extends GenericBackend[F, Any] {
override implicit def monad: MonadError[F] = _monad

protected def caFile: Option[Path] = None

private def configureCaFile(curl: CurlHandle, path: Path)(implicit z: Zone): CurlCode =
curl.option(CaInfo, path.toString) match {
case CurlCode.Ok =>
// Clear the compiled-in CA directory to avoid adding its trust anchors alongside the bundle.
// NOT_BUILT_IN means the TLS backend has no CA directory to clear.
curl.option(Capath, null: Ptr[Byte]) match {
case CurlCode.NotBuiltIn => CurlCode.Ok
case other => other
}
case error => error
}

/** Given a [[CurlHandle]], perform the request and return a [[CurlCode]]. */
protected def performCurl(c: CurlHandle): F[CurlCode]

Expand Down Expand Up @@ -104,16 +118,8 @@ abstract class AbstractCurlBackend[F[_]](_monad: MonadError[F], verbose: Boolean
*/
override def send[T](request: GenericRequest[T, R]): F[Response[T]] =
adjustExceptions(request) {
def perform(implicit ctx: Context): F[Response[T]] = {
def sendRequest(curl: CurlHandle)(implicit ctx: Context): F[Response[T]] = {
implicit val z = ctx.zone
val curl = CurlApi.init
if (verbose) {
curl.option(Verbose, parameter = true)
}
if (request.attributes.nonEmpty) {
return monad.error(new UnsupportedOperationException("Attributes are not supported"))
}

val reqHeaders = collection.mutable.ListBuffer[Header](request.headers*)

request.body match {
Expand Down Expand Up @@ -152,7 +158,24 @@ abstract class AbstractCurlBackend[F[_]](_monad: MonadError[F], verbose: Boolean
}

// F may be evaluated many times (e.g. retries); each evaluation needs its own zone
monad.suspend(Context.evaluateUsing(ctx => perform(using ctx)))
monad.suspend {
if (request.attributes.nonEmpty) monad.error(new UnsupportedOperationException("Attributes are not supported"))
else
Context.evaluateUsing { implicit ctx =>
implicit val z = ctx.zone
val curl = CurlApi.init
if (verbose) {
val _ = curl.option(Verbose, parameter = true)
}
val caResult = caFile.fold[CurlCode](CurlCode.Ok)(path => configureCaFile(curl, path))
caResult match {
case CurlCode.Ok => sendRequest(curl)
case code =>
curl.cleanup()
monad.error(AbstractCurlBackend.transferException(code.id, null))
}
}
}
}

private def adjustExceptions[T](request: GenericRequest[?, ?])(t: => F[T]): F[T] =
Expand Down
29 changes: 25 additions & 4 deletions core/src/main/scalanative/sttp/client4/curl/CurlBackends.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,39 @@ import sttp.client4._
import sttp.client4.wrappers.FollowRedirectsBackend
import sttp.monad.{IdentityMonad, TryMonad}

import java.nio.file.Path
import scala.util.Try

// Curl supports redirects, but it doesn't store the history, so using FollowRedirectsBackend is more convenient

private class CurlBackend(verbose: Boolean) extends AbstractSyncCurlBackend(IdentityMonad, verbose) with SyncBackend {}
private class CurlBackend(verbose: Boolean, override protected val caFile: Option[Path])
extends AbstractSyncCurlBackend(IdentityMonad, verbose)
with SyncBackend {}

object CurlBackend {
def apply(verbose: Boolean = false): SyncBackend = FollowRedirectsBackend(new CurlBackend(verbose))

/** @param caFile
* A PEM file to use as libcurl's CA bundle, instead of the default one.
*/
def apply(verbose: Boolean = false, caFile: Option[Path] = None): SyncBackend =
FollowRedirectsBackend(new CurlBackend(verbose, caFile))

// binary compatibility
private[curl] def apply(verbose: Boolean): SyncBackend = apply(verbose, None)
}

private class CurlTryBackend(verbose: Boolean) extends AbstractSyncCurlBackend(TryMonad, verbose) with Backend[Try] {}
private class CurlTryBackend(verbose: Boolean, override protected val caFile: Option[Path])
extends AbstractSyncCurlBackend(TryMonad, verbose)
with Backend[Try] {}

object CurlTryBackend {
def apply(verbose: Boolean = false): Backend[Try] = FollowRedirectsBackend(new CurlTryBackend(verbose))

/** @param caFile
* A PEM file to use as libcurl's CA bundle, instead of the default one.
*/
def apply(verbose: Boolean = false, caFile: Option[Path] = None): Backend[Try] =
FollowRedirectsBackend(new CurlTryBackend(verbose, caFile))

// binary compatibility
private[curl] def apply(verbose: Boolean): Backend[Try] = apply(verbose, None)
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ class CurlBackendHttpTest extends HttpTest[Identity] {

"when streaming the response" in {
checkConnectionRefused(
basicRequest.get(uri"http://localhost:7918").response(asInputStreamAlways(is => new String(is.readAllBytes())))
basicRequest
.get(uri"http://localhost:7918")
.response(asInputStreamAlways(is => new String(is.readAllBytes())))
)
}

Expand Down
123 changes: 123 additions & 0 deletions core/src/test/scalanative/sttp/client4/CurlCaFileTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package sttp.client4
package curl

import org.scalatest.BeforeAndAfterAll
import org.scalatest.TryValues._
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import sttp.model.StatusCode

import java.io.{BufferedReader, InputStreamReader}
import java.nio.charset.StandardCharsets.UTF_8
import java.nio.file.Files
import scala.util.Try

class CurlCaFileTest extends AnyFreeSpec with Matchers with BeforeAndAfterAll {
// Exercise a CA file whose absolute path contains spaces.
private lazy val dir = Files.createTempDirectory("sttp curl ca ")
private def caFile = dir.resolve("ca.pem")
private var server: Option[Process] = None
private var port = 0
private var unsupportedOpenssl: Option[String] = None

private def request = {
unsupportedOpenssl.foreach(cancel(_))
basicRequest.get(uri"https://127.0.0.1:$port/")
}

"a curl backend configured with a CA file" - {
"trusts the server with its CA using CurlBackend" in {
request.send(CurlBackend(caFile = Some(caFile))).code shouldBe StatusCode.Ok
}

"trusts the server with its CA using CurlTryBackend" in {
request.send(CurlTryBackend(caFile = Some(caFile))).success.value.code shouldBe StatusCode.Ok
}

"rejects an unrelated CA" in {
val backend = CurlTryBackend(caFile = Some(dir.resolve("other.pem")))
request.send(backend).failure.exception.getCause.getMessage should include("(PEER_FAILED_VERIFICATION)")
}

"rejects the server without a CA file" in {
val r = request // outside intercept, so that a cancellation isn't caught
val error = intercept[SttpClientException.ReadException](r.send(CurlBackend()))
error.getCause.getMessage should include("(PEER_FAILED_VERIFICATION)")
}

"rejects a hostname mismatch" in {
val wrongHost = request.get(uri"https://localhost:$port/")
val error = intercept[SttpClientException.ReadException](wrongHost.send(CurlBackend(caFile = Some(caFile))))
error.getCause.getMessage should include("(PEER_FAILED_VERIFICATION)")
}

"applies the CA file to a streamed InputStream response" in {
request.response(asInputStreamAlways(_.read())).send(CurlBackend(caFile = Some(caFile))).body should be >= 0
}
}

private def openssl(args: Seq[String]): ProcessBuilder =
new ProcessBuilder(("openssl" +: args)*).directory(dir.toFile)

private def run(args: Seq[String]): Unit = {
val exit = openssl(args).redirectError(ProcessBuilder.Redirect.INHERIT).start().waitFor()
if (exit != 0) fail(s"openssl ${args.head} exited with $exit")
}

private def requestCertificate(name: String, output: String, options: Seq[String]): Unit = {
val key = Seq("-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes")
val files = Seq("-subj", s"/CN=$name", "-keyout", s"$name.key", "-out", output)
run(Seq("req") ++ key ++ files ++ options)
}

override protected def beforeAll(): Unit = {
super.beforeAll()
unsupportedOpenssl = checkOpenssl()
if (unsupportedOpenssl.isEmpty) startServer()
}

/** The setup relies on OpenSSL 1.1.1+ command-line options, which e.g. LibreSSL doesn't support. */
private def checkOpenssl(): Option[String] =
Try {
val process = openssl(Seq("version")).start()
val version = new BufferedReader(new InputStreamReader(process.getInputStream, UTF_8)).readLine()
val _ = process.waitFor()
version
}.toOption.flatMap(Option(_)) match {
case Some(v) if v.startsWith("OpenSSL ") && !v.startsWith("OpenSSL 1.0") && !v.startsWith("OpenSSL 1.1.0") => None
case other => Some(s"Requires OpenSSL 1.1.1+ on PATH, found: ${other.getOrElse("none")}")
}

private def startServer(): Unit = {
val root = Seq("-x509", "-days", "1", "-addext", "basicConstraints=critical,CA:TRUE")
requestCertificate("ca", "ca.pem", root)
requestCertificate("other", "other.pem", root)
requestCertificate("server", "server.csr", Nil)
val _ = Files.write(dir.resolve("extensions"), "subjectAltName=IP:127.0.0.1\n".getBytes(UTF_8))
val issuer = Seq("-CA", "ca.pem", "-CAkey", "ca.key", "-set_serial", "1", "-days", "1")
run(Seq("x509", "-req", "-in", "server.csr") ++ issuer ++ Seq("-extfile", "extensions", "-out", "server.pem"))

val listen = Seq("s_server", "-accept", "127.0.0.1:0", "-www", "-no_dhe", "-ign_eof")
val process = openssl(listen ++ Seq("-cert", "server.pem", "-key", "server.key"))
.redirectError(dir.resolve("server.log").toFile)
.start()
server = Some(process)
val reader = new BufferedReader(new InputStreamReader(process.getInputStream, UTF_8))
val listening =
Option(reader.readLine()).getOrElse(fail(new String(Files.readAllBytes(dir.resolve("server.log")), UTF_8)))
port = listening.stripPrefix("ACCEPT 127.0.0.1:").toInt
}

override protected def afterAll(): Unit =
try {
server.foreach { process =>
val _ = process.destroyForcibly().waitFor()
process.getInputStream.close()
}
} finally {
try {
dir.toFile.listFiles().foreach(f => Files.delete(f.toPath))
Files.delete(dir)
} finally super.afterAll()
}
}
17 changes: 17 additions & 0 deletions docs/backends/native/curl.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ val tryBackend = CurlTryBackend()
You need to have an environment with Scala Native [setup](https://scala-native.readthedocs.io/en/latest/user/setup.html)
with additionally installed `libcrypto` (included in OpenSSL) and `curl` in version `7.56.0` or newer.

## Custom CA bundle

To verify a service using a private CA, pass a PEM bundle to the backend. This file replaces libcurl's default
CA bundle. Some TLS implementations, including Apple's system libcurl, may still consult the operating system's
trust store.

```scala
import java.nio.file.Paths
import sttp.client4.curl.CurlBackend

val backend = CurlBackend(caFile = Some(Paths.get("service-ca.pem")))
```

`CurlTryBackend`, `CurlCatsBackend` and `CurlZioBackend` accept the same `caFile` parameter. The setting applies to
every request sent using that backend. The backend also clears the compiled-in CA directory where supported. Peer and
hostname verification remain enabled.

## scala-cli example

Try the following example:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import sttp.client4.impl.cats.CatsMonadError
import sttp.client4.wrappers.FollowRedirectsBackend
import sttp.client4.Backend

class CurlCatsBackend[F[_]: Sync] private (verbose: Boolean)
import java.nio.file.Path

class CurlCatsBackend[F[_]: Sync] private (verbose: Boolean, override protected val caFile: Option[Path])
extends AbstractSyncCurlBackend[F](new CatsMonadError[F], verbose)
with Backend[F]

Expand All @@ -16,9 +18,14 @@ object CurlCatsBackend {
*
* @param verbose
* If true, logs request and response summary to the console.
* @param caFile
* A PEM file to use as libcurl's CA bundle, instead of the default one.
* @return
* A backend that uses the Sync type class for effects.
*/
def apply[F[_]: Sync](verbose: Boolean = false): Backend[F] =
FollowRedirectsBackend(new CurlCatsBackend[F](verbose))
def apply[F[_]: Sync](verbose: Boolean = false, caFile: Option[Path] = None): Backend[F] =
FollowRedirectsBackend(new CurlCatsBackend[F](verbose, caFile))

// binary compatibility
private[curl] def apply[F[_]: Sync](verbose: Boolean): Backend[F] = apply[F](verbose, None)
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,25 @@ import sttp.client4.Backend
import sttp.client4.impl.zio.RIOMonadAsyncError
import sttp.client4.wrappers.FollowRedirectsBackend

class CurlZioBackend private (verbose: Boolean)
import java.nio.file.Path

class CurlZioBackend private (verbose: Boolean, override protected val caFile: Option[Path])
extends sttp.client4.curl.AbstractSyncCurlBackend[Task](RIOMonadAsyncError[Any], verbose)
with Backend[Task]

/** In all factory methods, `caFile` is a PEM file to use as libcurl's CA bundle, instead of the default one. */
object CurlZioBackend {
def apply(verbose: Boolean = false): Backend[Task] = FollowRedirectsBackend(new CurlZioBackend(verbose))
def apply(verbose: Boolean = false, caFile: Option[Path] = None): Backend[Task] =
FollowRedirectsBackend(new CurlZioBackend(verbose, caFile))

def layer(verbose: Boolean = false, caFile: Option[Path] = None): ZLayer[Any, Throwable, Backend[Task]] =
ZLayer.scoped(scoped(verbose, caFile))

def layer(verbose: Boolean = false): ZLayer[Any, Throwable, Backend[Task]] =
ZLayer.scoped(scoped(verbose))
def scoped(verbose: Boolean = false, caFile: Option[Path] = None): ZIO[Scope, Throwable, Backend[Task]] =
ZIO.acquireRelease(ZIO.attempt(apply(verbose, caFile)))(_.close().ignore)

def scoped(verbose: Boolean = false): ZIO[Scope, Throwable, Backend[Task]] =
ZIO.acquireRelease(ZIO.attempt(apply(verbose)))(_.close().ignore)
// binary compatibility
private[curl] def apply(verbose: Boolean): Backend[Task] = apply(verbose, None)
private[curl] def layer(verbose: Boolean): ZLayer[Any, Throwable, Backend[Task]] = layer(verbose, None)
private[curl] def scoped(verbose: Boolean): ZIO[Scope, Throwable, Backend[Task]] = scoped(verbose, None)
}
Loading