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

check API version #641

Merged
merged 7 commits into from
Dec 19, 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
88 changes: 78 additions & 10 deletions mithril-aggregator/src/http_server/routes/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,16 @@ use crate::DependencyManager;
use mithril_common::MITHRIL_API_VERSION;

use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::StatusCode;
use std::sync::Arc;
use warp::http::Method;
use warp::Filter;
use warp::reject::Reject;
use warp::{Filter, Rejection, Reply};

#[derive(Debug)]
pub struct VersionMismatchError;

impl Reject for VersionMismatchError {}

/// Routes
pub fn routes(
Expand All @@ -24,14 +31,75 @@ pub fn routes(
"mithril-api-version",
HeaderValue::from_static(MITHRIL_API_VERSION),
);
warp::any()
.and(header_must_be())
.and(warp::path(SERVER_BASE_PATH))
.and(
certificate_routes::routes(dependency_manager.clone())
.or(snapshot_routes::routes(dependency_manager.clone()))
.or(signer_routes::routes(dependency_manager.clone()))
.or(signatures_routes::routes(dependency_manager.clone()))
.or(epoch_routes::routes(dependency_manager))
.with(cors),
)
.recover(handle_custom)
.with(warp::reply::with::headers(headers))
}

/// API Version verification
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change the comment according to what the function does

fn header_must_be() -> impl Filter<Extract = (), Error = Rejection> + Copy {
warp::header::optional("mithril-api-version")
.and_then(|maybe_header: Option<String>| async move {
match maybe_header {
None => Ok(()),
Some(version) if version == MITHRIL_API_VERSION => Ok(()),
Some(_version) => Err(warp::reject::custom(VersionMismatchError)),
}
})
.untuple_one()
}

pub async fn handle_custom(reject: Rejection) -> Result<impl Reply, Rejection> {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handle custom rejection codes

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not need to be public

if reject.find::<VersionMismatchError>().is_some() {
Ok(StatusCode::PRECONDITION_FAILED)
} else {
Err(reject)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[tokio::test]
async fn test_no_version() {
let filters = header_must_be();
warp::test::request()
.path("/aggregator/whatever")
.filter(&filters)
.await
.unwrap();
}

#[tokio::test]
async fn test_bad_version() {
let filters = header_must_be();
warp::test::request()
.header("mithril-api-version", "0.0.999")
.path("/aggregator/whatever")
.filter(&filters)
.await
.unwrap_err();
}

warp::any().and(warp::path(SERVER_BASE_PATH)).and(
certificate_routes::routes(dependency_manager.clone())
.or(snapshot_routes::routes(dependency_manager.clone()))
.or(signer_routes::routes(dependency_manager.clone()))
.or(signatures_routes::routes(dependency_manager.clone()))
.or(epoch_routes::routes(dependency_manager))
.with(cors)
.with(warp::reply::with::headers(headers)),
)
#[tokio::test]
async fn test_good_version() {
let filters = header_must_be();
warp::test::request()
.header("mithril-api-version", MITHRIL_API_VERSION)
.path("/aggregator/whatever")
.filter(&filters)
.await
.unwrap();
}
}
100 changes: 99 additions & 1 deletion mithril-client/src/aggregator.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use async_trait::async_trait;
use flate2::read::GzDecoder;
use futures::StreamExt;
use reqwest::{self, StatusCode};
use reqwest::{self, Response, StatusCode};
use reqwest::{Client, RequestBuilder};
use slog_scope::debug;
use std::env;
Expand Down Expand Up @@ -48,6 +48,17 @@ pub enum AggregatorHandlerError {
/// [AggregatorHandler::download_snapshot] beforehand.
#[error("archive not found, did you download it beforehand ? Expected path: '{0}'")]
ArchiveNotFound(PathBuf),

/// Error raised when the server API version mismatch the client API version.
#[error("API version mismatch: {0}")]
ApiVersionMismatch(String),
}

#[cfg(test)]
impl AggregatorHandlerError {
pub fn is_api_version_mismatch(&self) -> bool {
matches!(self, Self::ApiVersionMismatch(_))
}
}

/// AggregatorHandler represents a read interactor with an aggregator
Expand Down Expand Up @@ -128,6 +139,22 @@ impl AggregatorHTTPClient {
)),
}
}

/// API version error handling
fn handle_api_error(&self, response: &Response) -> AggregatorHandlerError {
if let Some(version) = response.headers().get("mithril-api-version") {
AggregatorHandlerError::ApiVersionMismatch(format!(
"server version: '{}', signer version: '{}'",
version.to_str().unwrap(),
MITHRIL_API_VERSION
))
} else {
AggregatorHandlerError::ApiVersionMismatch(format!(
"version precondition failed, sent version '{}'.",
MITHRIL_API_VERSION
))
}
}
}

#[async_trait]
Expand All @@ -147,6 +174,7 @@ impl AggregatorHandler for AggregatorHTTPClient {
Ok(snapshots) => Ok(snapshots),
Err(err) => Err(AggregatorHandlerError::JsonParseFailed(err.to_string())),
},
StatusCode::PRECONDITION_FAILED => Err(self.handle_api_error(&response)),
status_error => Err(AggregatorHandlerError::RemoteServerTechnical(
status_error.to_string(),
)),
Expand All @@ -172,6 +200,7 @@ impl AggregatorHandler for AggregatorHTTPClient {
Ok(snapshot) => Ok(snapshot),
Err(err) => Err(AggregatorHandlerError::JsonParseFailed(err.to_string())),
},
StatusCode::PRECONDITION_FAILED => Err(self.handle_api_error(&response)),
StatusCode::NOT_FOUND => Err(AggregatorHandlerError::RemoteServerLogical(
"snapshot not found".to_string(),
)),
Expand Down Expand Up @@ -226,6 +255,7 @@ impl AggregatorHandler for AggregatorHTTPClient {
}
Ok(local_path.into_os_string().into_string().unwrap())
}
StatusCode::PRECONDITION_FAILED => Err(self.handle_api_error(&response)),
StatusCode::NOT_FOUND => Err(AggregatorHandlerError::RemoteServerLogical(
"snapshot archive not found".to_string(),
)),
Expand Down Expand Up @@ -352,6 +382,20 @@ mod tests {
assert_eq!(snapshots.unwrap(), snapshots_expected);
}

#[tokio::test]
async fn test_list_snapshots_ko_412() {
let (server, config) = setup_test();
let _snapshots_mock = server.mock(|when, then| {
when.path("/snapshots");
then.status(412).header("mithril-api-version", "0.0.999");
});
let aggregator_client =
AggregatorHTTPClient::new(config.network, config.aggregator_endpoint);
let error = aggregator_client.list_snapshots().await.unwrap_err();

assert!(error.is_api_version_mismatch());
}

#[tokio::test]
async fn test_list_snapshots_ko_500() {
let (server, config) = setup_test();
Expand Down Expand Up @@ -403,6 +447,24 @@ mod tests {
assert!(snapshot.is_err());
}

#[tokio::test]
async fn test_snapshot_details_ko_412() {
let (server, config) = setup_test();
let digest = "digest123";
let _snapshots_mock = server.mock(|when, then| {
when.path(format!("/snapshot/{}", digest));
then.status(412).header("mithril-api-version", "0.0.999");
});
let aggregator_client =
AggregatorHTTPClient::new(config.network, config.aggregator_endpoint);
let error = aggregator_client
.get_snapshot_details(digest)
.await
.unwrap_err();

assert!(error.is_api_version_mismatch());
}

#[tokio::test]
async fn get_snapshot_details_ko_500() {
let digest = "digest123";
Expand Down Expand Up @@ -448,6 +510,26 @@ mod tests {
assert_eq!(data_downloaded, data_expected);
}

#[tokio::test]
async fn test_download_snapshot_ko_412() {
let (server, config) = setup_test();
let digest = "digest123";
let url_path = "/download";
let _snapshots_mock = server.mock(|when, then| {
when.path(url_path.to_string());
then.status(412).header("mithril-api-version", "0.0.999");
});
let aggregator_client =
AggregatorHTTPClient::new(config.network, config.aggregator_endpoint);
let location = server.url(url_path);
let error = aggregator_client
.download_snapshot(digest, &location)
.await
.unwrap_err();

assert!(error.is_api_version_mismatch());
}

#[tokio::test]
async fn get_download_snapshot_ko_unreachable() {
let digest = "digest123";
Expand Down Expand Up @@ -502,6 +584,22 @@ mod tests {
assert!(local_dir_path.is_err());
}

#[tokio::test]
async fn test_certificate_details_412() {
let (server, config) = setup_test();
let certificate_hash = "certificate-hash-123";
let _snapshots_mock = server.mock(|when, then| {
when.path(format!("/certificate/{}", certificate_hash));
then.status(412).header("mithril-api-version", "0.0.999");
});
let aggregator_client =
AggregatorHTTPClient::new(config.network, config.aggregator_endpoint);
let _error = aggregator_client
.get_certificate_details(certificate_hash)
.await
.unwrap_err();
}

#[tokio::test]
async fn get_certificate_details_ok() {
let certificate_hash = "certificate-hash-123";
Expand Down
Loading