Skip to content

Commit

Permalink
fix: make tls as optional http-service feature
Browse files Browse the repository at this point in the history
  • Loading branch information
ruslanti committed Jun 17, 2024
1 parent 308239d commit 5567b58
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 17 deletions.
9 changes: 5 additions & 4 deletions crates/http-service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ authors.workspace = true
default = []
metrics = ["runtime/metrics"]
stats = ["runtime/stats"]
tls = ["tokio-rustls", "rustls-pemfile", "hyper-rustls", "rustls"]

[dependencies]
anyhow = { workspace = true }
Expand All @@ -22,10 +23,10 @@ wasmtime-wasi-nn = { workspace = true }
wasi-common = { workspace = true }
tracing = { workspace = true }
smol_str = { workspace = true }
tokio-rustls = "0.24.1"
rustls-pemfile = "1.0.2"
hyper-rustls = "0.24.1"
rustls = "0.21.6"
tokio-rustls = { version = "0.24.1", optional = true}
rustls-pemfile = { version = "1.0.2" , optional = true}
hyper-rustls = { version = "0.24.1", optional = true }
rustls = { version = "0.21.6", optional = true }
reactor = { path = "../reactor" }
runtime = { path = "../runtime" }
http-backend = { path = "../http-backend" }
Expand Down
33 changes: 22 additions & 11 deletions crates/http-service/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
use std::net::SocketAddr;
use std::sync::Arc;

use anyhow::{anyhow, bail, Context, Error, Result};
use anyhow::{ bail, Context, Error, Result};
use http::header::{ACCESS_CONTROL_ALLOW_ORIGIN, CACHE_CONTROL};
use http::{HeaderMap, HeaderName, HeaderValue, Request, Response, StatusCode};
use hyper::client::connect::Connect;
use hyper::server::conn::{AddrIncoming, AddrStream};
use hyper::server::conn::AddrStream;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Server};
use smol_str::SmolStr;
use tokio_rustls::rustls;
use tokio_rustls::rustls::ServerConfig;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error_span, info, info_span, trace, warn, Instrument};
use tracing::{debug, info, info_span, trace, warn, Instrument};
use wasi_common::I32Exit;
use wasmtime::Trap;
use wasmtime_wasi_nn::WasiNnCtx;
Expand All @@ -29,11 +27,14 @@ use crate::executor::{ HttpExecutor};
use runtime::util::stats::StatRow;
use runtime::util::stats::StatsWriter;

#[cfg(feature = "tls")]
use crate::tls::{load_certs, load_private_key, TlsAcceptor, TlsStream};
pub mod executor;

#[cfg(feature = "tls")]
mod tls;

pub mod executor;

pub use crate::executor::ExecutorFactory;

pub(crate) static TRACEPARENT: &str = "traceparent";
Expand All @@ -43,14 +44,18 @@ const FASTEDGE_OUT_OF_MEMORY: u16 = 531;
const FASTEDGE_EXECUTION_TIMEOUT: u16 = 532;
const FASTEDGE_EXECUTION_PANIC: u16 = 533;

#[cfg(feature = "tls")]
#[derive(Default)]
pub struct HttpsConfig {
pub ssl_certs: &'static str,
pub ssl_pkey: &'static str,
}

#[derive(Default)]
pub struct HttpConfig {
pub all_interfaces: bool,
pub port: u16,
#[cfg(feature = "tls")]
pub https: Option<HttpsConfig>,
pub cancel: CancellationToken,
}
Expand Down Expand Up @@ -99,6 +104,8 @@ where
};
let listen_addr = (interface, config.port).into();


#[cfg(feature = "tls")]
if let Some(https) = config.https {
let tls = {
// Load public certificate.
Expand All @@ -110,7 +117,7 @@ where
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(certs, key)
.map_err(|e| anyhow!(format!("{}", e)))?;
.map_err(|e| anyhow::anyhow!(format!("{}", e)))?;
// Configure ALPN to accept HTTP/2, HTTP/1.1 in that order.
cfg.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Arc::new(cfg)
Expand All @@ -120,6 +127,9 @@ where
self.serve(listen_addr).await?
};

#[cfg(not(feature = "tls"))]
self.serve(listen_addr).await?;

Ok(())
}

Expand Down Expand Up @@ -176,7 +186,8 @@ where
Ok(())
}

async fn serve_tls(self, listen_addr: SocketAddr, tls: Arc<ServerConfig>) -> Result<()> {
#[cfg(feature = "tls")]
async fn serve_tls(self, listen_addr: SocketAddr, tls: Arc<rustls::ServerConfig>) -> Result<()> {
let service = Arc::new(self);
let make_service = make_service_fn(|_conn: &TlsStream| {
let service = service.clone();
Expand All @@ -187,15 +198,15 @@ where
async move {
service
.handle_request(req)
.instrument(error_span!("https_handler", request_id))
.instrument(tracing::error_span!("https_handler", request_id))
.await
}
});
Ok::<_, Error>(service)
}
});

let incoming = AddrIncoming::bind(&listen_addr)
let incoming = hyper::server::conn::AddrIncoming::bind(&listen_addr)
.with_context(|| format!("Unable to bind on {}", listen_addr))?;
info!("Listening on https://{}", listen_addr);
Server::builder(TlsAcceptor::new(tls, incoming))
Expand Down Expand Up @@ -500,7 +511,7 @@ fn app_res_headers(app_cfg: App) -> HeaderMap {
headers
}

fn app_req_headers<'a>(geo: impl Iterator<Item = (SmolStr, SmolStr)>) -> HeaderMap {
fn app_req_headers(geo: impl Iterator<Item = (SmolStr, SmolStr)>) -> HeaderMap {
let mut headers = HeaderMap::new();
for (key, value) in geo {
trace!("append new request header {}={}", key, value);
Expand Down
3 changes: 1 addition & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,7 @@ async fn main() -> anyhow::Result<()> {
let http = http.run(HttpConfig {
all_interfaces: false,
port: run.port,
https: None,
cancel: cancel.clone(),
cancel: cancel.clone()
});
tokio::select! {
_ = http => {
Expand Down

0 comments on commit 5567b58

Please sign in to comment.