Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose way for request handlers to determine if the request came over HTTP or HTTPS. #420

Merged
merged 1 commit into from
Aug 12, 2022
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
4 changes: 4 additions & 0 deletions dropshot/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ pub struct DropshotState<C: ServerContext> {
pub log: Logger,
/** bound local address for the server. */
pub local_addr: SocketAddr,
/** are requests served over HTTPS */
pub tls: bool,
}

/**
Expand Down Expand Up @@ -253,6 +255,7 @@ impl<C: ServerContext> InnerHttpServerStarter<C> {
router: api.into_router(),
log: log.new(o!("local_addr" => local_addr)),
local_addr,
tls: false,
});

let make_service = ServerConnectionHandler::new(app_state.clone());
Expand Down Expand Up @@ -503,6 +506,7 @@ impl<C: ServerContext> InnerHttpsServerStarter<C> {
router: api.into_router(),
log: logger,
local_addr,
tls: true,
});

let make_service = ServerConnectionHandler::new(Arc::clone(&app_state));
Expand Down
109 changes: 108 additions & 1 deletion dropshot/tests/test_tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* including certificate loading and supported modes.
*/

use dropshot::{ConfigDropshot, ConfigTls, HttpServerStarter};
use dropshot::{ConfigDropshot, ConfigTls, HttpResponseOk, HttpServerStarter};
use slog::{o, Logger};
use std::convert::TryFrom;
use std::path::Path;
Expand Down Expand Up @@ -241,3 +241,110 @@ async fn test_tls_aborted_negotiation() {

logctx.cleanup_successful();
}

#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct TlsCheckArgs {
tls: bool,
}

/*
* The same handler is used for both an HTTP and HTTPS server.
* Make sure that we can distinguish between the two.
* The intended version is determined by a query parameter
* that varies between both tests.
*/
#[dropshot::endpoint {
method = GET,
path = "/",
}]
async fn tls_check_handler(
rqctx: Arc<dropshot::RequestContext<usize>>,
query: dropshot::Query<TlsCheckArgs>,
) -> Result<HttpResponseOk<()>, dropshot::HttpError> {
if rqctx.server.tls != query.into_inner().tls {
return Err(dropshot::HttpError::for_bad_request(
None,
"mismatch between expected and actual tls state".to_string(),
));
}
Ok(HttpResponseOk(()))
}

#[tokio::test]
async fn test_server_is_https() {
let logctx = create_log_context("test_server_is_https");
let log = logctx.log.new(o!());

// Generate key for the server
let (certs, key) = common::generate_tls_key();
let (cert_file, key_file) = common::tls_key_to_file(&certs, &key);

let config = ConfigDropshot {
bind_address: "127.0.0.1:0".parse().unwrap(),
request_body_max_bytes: 1024,
tls: Some(ConfigTls {
cert_file: cert_file.path().to_path_buf(),
key_file: key_file.path().to_path_buf(),
}),
};
let mut api = dropshot::ApiDescription::new();
api.register(tls_check_handler).unwrap();
let server = HttpServerStarter::new(&config, api, 0, &log).unwrap().start();
let port = server.local_addr().port();

let https_client = make_https_client(make_pki_verifier(&certs));

// Expect request with tls=true to pass with https server
let https_request = hyper::Request::builder()
.method(http::method::Method::GET)
.uri(format!("https://localhost:{}/?tls=true", port))
.body(hyper::Body::empty())
.unwrap();
let res = https_client.request(https_request).await.unwrap();
assert_eq!(res.status(), hyper::StatusCode::OK);

// Expect request with tls=false to fail with https server
let https_request = hyper::Request::builder()
.method(http::method::Method::GET)
.uri(format!("https://localhost:{}/?tls=false", port))
.body(hyper::Body::empty())
.unwrap();
let res = https_client.request(https_request).await.unwrap();
assert_eq!(res.status(), hyper::StatusCode::BAD_REQUEST);

server.close().await.unwrap();

logctx.cleanup_successful();
}

#[tokio::test]
async fn test_server_is_http() {
let mut api = dropshot::ApiDescription::new();
api.register(tls_check_handler).unwrap();

let testctx = common::test_setup("test_server_is_http", api);

// Expect request with tls=false to pass with plain http server
testctx
.client_testctx
.make_request(
hyper::Method::GET,
"/?tls=false",
None as Option<()>,
hyper::StatusCode::OK,
)
.await
.expect("expected success");

// Expect request with tls=true to fail with plain http server
testctx
.client_testctx
.make_request(
hyper::Method::GET,
"/?tls=true",
None as Option<()>,
hyper::StatusCode::BAD_REQUEST,
)
.await
.expect_err("expected failure");
}