3

I want to post http requests to a secured server with a given ca cert.

I'm using Spray 1.3.1, the code looks something like this:

val is = this.getClass().getResourceAsStream("/cacert.crt")

val cf: CertificateFactory = CertificateFactory.getInstance("X.509")

val caCert: X509Certificate = cf.generateCertificate(is).asInstanceOf[X509Certificate];

val tmf: TrustManagerFactory  = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
val ks: KeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null); 
ks.setCertificateEntry("caCert", caCert);

tmf.init(ks);

implicit val sslContext: SSLContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);

implicit val timeout: Timeout = Timeout(15.seconds)
import spray.httpx.RequestBuilding._

val respFuture = (IO(Http) ? Post( uri=Uri(url), content="my content")).mapTo[HttpResponse]

The problem is that the defined implicit SSLContext is not taken and I'm getting: "unable to find valid certification path to requested target" on runtime.

How can I define a SSLContext to be used with spray client?

joel
  • 61
  • 5

3 Answers3

2

I use the following to define an SSLContext in spray. In my case, I'm using a very permissive context that does not validate the remote server's certificate. Based on the first solution in this post - works for me.

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, X509TrustManager, TrustManager}

import akka.actor.ActorRef
import akka.io.IO
import akka.util.Timeout
import spray.can.Http

import scala.concurrent.Future

trait HttpClient {
  /** For the HostConnectorSetup ask operation. */
  implicit val ImplicitPoolSetupTimeout: Timeout = 30 seconds

  val hostName: String
  val hostPort: Int

  implicit val sslContext = {
    /** Create a trust manager that does not validate certificate chains. */
    val permissiveTrustManager: TrustManager = new X509TrustManager() {
      override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {
      }
      override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {
      }
      override def getAcceptedIssuers(): Array[X509Certificate] = {
        null
      }
    }

    val initTrustManagers = Array(permissiveTrustManager)
    val ctx = SSLContext.getInstance("TLS")
    ctx.init(null, initTrustManagers, new SecureRandom())
    ctx
  }

  def initClientPool(): Future[ActorRef] = {
    val hostPoolFuture = for {
      Http.HostConnectorInfo(connector, _) <- IO(Http) ? Http.HostConnectorSetup(hostName, port = hostPort,
        sslEncryption = true)
    } yield connector
  }
}
Reed Sandberg
  • 671
  • 1
  • 10
  • 18
0

I came up with this replacement for sendReceive which allows passing a custom SSLContext (as an implicit)

def mySendReceive( request: HttpRequest )( implicit uri: spray.http.Uri, ec: ExecutionContext, futureTimeout: Timeout = 60.seconds, sslContext: SSLContext = SSLContext.getDefault): Future[ HttpResponse ] = {

    implicit val clientSSLEngineProvider = ClientSSLEngineProvider { _ =>
        val engine = sslContext.createSSLEngine( )
        engine.setUseClientMode( true )
        engine
    }

    for {
        Http.HostConnectorInfo( connector, _ ) <- IO( Http ) ? Http.HostConnectorSetup( uri.authority.host.address, port = uri.authority.port, sslEncryption = true )
        response <- connector ? request
    } yield response match {
        case x: HttpResponse ⇒ x
        case x: HttpResponsePart ⇒ sys.error( "sendReceive doesn't support chunked responses, try sendTo instead" )
        case x: Http.ConnectionClosed ⇒ sys.error( "Connection closed before reception of response: " + x )
        case x ⇒ sys.error( "Unexpected response from HTTP transport: " + x )
    }
}

Then use it as "usual" (almost see below):

val pipeline: HttpRequest => Future[ HttpResponse ] = mySendReceive
pipeline( Get( uri ) ) map processResponse

There are a couple of things I really do not like though:

  • it is a hack. I would expect spray-client to allow support of a custom SSLContext natively. These are very useful during dev and test, to force custom TrustManagers typically

  • there is an implicit uri: spray.http.Uri parameter to avoid hard coding of the host and port on the connector. So uri must be declared implicit.

Any improvement to this code or even better, a patch to spray-client, is most welcome (externalization of the creation of the SSLEngine being an obvious one)

Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101
0

The shortest I've gotten to work is this:

IO(Http) ! HostConnectorSetup(host = Conf.base.getHost, port = 443, sslEncryption = true)

i.e. what's in @reed-sandberg's answer, but no ask pattern seems to be needed. I don't pass a connection parameter to sendReceive but instead:

// `host` is the host part of the service
//
def addHost = { req: HttpRequest => req.withEffectiveUri(true, Host(host, 443)) }

val pipeline: HttpRequest => Future[Seq[PartitionInfo]] = (
    addHost
    ~> sendReceive
    ~> unmarshal[...]
)

This seems to work, but I would naturally be interested to hear if there are downsides to this approach.

I agree with all spray-client SSL support criticism. It's awkward that something like this is so hard. I probably spent 2 days on it, merging data from various sources (SO, spray documentation, mailing list).

akauppi
  • 17,018
  • 15
  • 95
  • 120