1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-12-18 09:43:11 +01:00
actix-extras/awc/tests/test_ssl_client.rs

91 lines
3.0 KiB
Rust
Raw Normal View History

2019-11-20 19:35:07 +01:00
#![cfg(feature = "openssl")]
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
use std::io::Result;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use actix_codec::{AsyncRead, AsyncWrite};
use actix_http::HttpService;
2019-11-20 19:35:07 +01:00
use actix_http_test::{block_on, TestServer};
use actix_server::ssl::OpensslAcceptor;
2019-11-20 19:35:07 +01:00
use actix_service::{pipeline_factory, ServiceFactory};
use actix_web::http::Version;
use actix_web::{web, App, HttpResponse};
2019-11-20 19:35:07 +01:00
use futures::future::ok;
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
// load ssl keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
.unwrap();
builder
.set_certificate_chain_file("../tests/cert.pem")
.unwrap();
builder.set_alpn_select_callback(|_, protos| {
const H2: &[u8] = b"\x02h2";
if protos.windows(3).any(|window| window == H2) {
Ok(b"h2")
} else {
2019-11-20 19:35:07 +01:00
Err(open_ssl::ssl::AlpnError::NOACK)
}
});
builder.set_alpn_protos(b"\x02h2")?;
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
}
#[test]
fn test_connection_reuse_h2() {
2019-11-20 19:35:07 +01:00
block_on(async {
let openssl = ssl_acceptor().unwrap();
let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone();
2019-11-20 19:35:07 +01:00
let srv = TestServer::start(move || {
let num2 = num2.clone();
pipeline_factory(move |io| {
num2.fetch_add(1, Ordering::Relaxed);
ok(io)
})
.and_then(
openssl
.clone()
.map_err(|e| println!("Openssl error: {}", e)),
)
.and_then(
HttpService::build()
.h2(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
))
.map_err(|_| ()),
)
});
2019-11-20 19:35:07 +01:00
// disable ssl verification
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
builder.set_verify(SslVerifyMode::NONE);
let _ = builder
.set_alpn_protos(b"\x02h2\x08http/1.1")
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
2019-11-20 19:35:07 +01:00
let client = awc::Client::build()
.connector(awc::Connector::new().ssl(builder.build()).finish())
.finish();
2019-11-20 19:35:07 +01:00
// req 1
let request = client.get(srv.surl("/")).send();
let response = request.await.unwrap();
assert!(response.status().is_success());
2019-11-20 19:35:07 +01:00
// req 2
let req = client.post(srv.surl("/"));
let response = req.send().await.unwrap();
assert!(response.status().is_success());
assert_eq!(response.version(), Version::HTTP_2);
2019-11-20 19:35:07 +01:00
// one connection
assert_eq!(num.load(Ordering::Relaxed), 1);
})
}