Skip to content

Commit

Permalink
feat(api): update axum to 0.6 (#948)
Browse files Browse the repository at this point in the history
* Update axum to 0.6

* Fix docs

Co-authored-by: Jochen Görtler <jochen.goertler@iota.org>
  • Loading branch information
Alexandcoats and grtlr authored Dec 12, 2022
1 parent 5a533bd commit f77ccfa
Show file tree
Hide file tree
Showing 13 changed files with 428 additions and 451 deletions.
284 changes: 119 additions & 165 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ influxdb = { version = "0.5", default-features = false, features = [ "use-serde"

# API
auth-helper = { version = "0.3", default-features = false, optional = true }
axum = { version = "0.5", default-features = false, features = [ "http1", "json", "query", "original-uri", "headers" ], optional = true }
axum = { version = "0.6", default-features = false, features = [ "http1", "json", "query", "original-uri", "headers" ], optional = true }
ed25519 = { version = "1.5", default-features = false, features = [ "alloc", "pkcs8", "pem" ], optional = true }
ed25519-dalek = { version = "1.0", default-features = false, features = [ "u64_backend" ], optional = true }
hex = { version = "0.4", default-features = false, optional = true }
Expand Down
17 changes: 10 additions & 7 deletions src/bin/inx-chronicle/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,33 @@
use async_trait::async_trait;
use auth_helper::jwt::{BuildValidation, JsonWebToken, Validation};
use axum::{
extract::{FromRequest, OriginalUri},
extract::{FromRef, FromRequestParts, OriginalUri},
headers::{authorization::Bearer, Authorization},
Extension, TypedHeader,
TypedHeader,
};

use super::{config::ApiData, error::RequestError, ApiError, AuthError};

pub struct Auth;

#[async_trait]
impl<B: Send> FromRequest<B> for Auth {
impl<S: Send + Sync> FromRequestParts<S> for Auth
where
ApiData: FromRef<S>,
{
type Rejection = ApiError;

async fn from_request(req: &mut axum::extract::RequestParts<B>) -> Result<Self, Self::Rejection> {
async fn from_request_parts(req: &mut axum::http::request::Parts, state: &S) -> Result<Self, Self::Rejection> {
// Unwrap: <OriginalUri as FromRequest>::Rejection = Infallable
let OriginalUri(uri) = OriginalUri::from_request(req).await.unwrap();
let OriginalUri(uri) = OriginalUri::from_request_parts(req, state).await.unwrap();

let Extension(config) = Extension::<ApiData>::from_request(req).await?;
let config = ApiData::from_ref(state);

if config.public_routes.is_match(&uri.to_string()) {
return Ok(Auth);
}

let TypedHeader(Authorization(bearer)) = TypedHeader::<Authorization<Bearer>>::from_request(req)
let TypedHeader(Authorization(bearer)) = TypedHeader::<Authorization<Bearer>>::from_request_parts(req, state)
.await
.map_err(RequestError::from)?;
let jwt = JsonWebToken(bearer.token().to_string());
Expand Down
49 changes: 22 additions & 27 deletions src/bin/inx-chronicle/api/extractors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

use async_trait::async_trait;
use axum::{
extract::{FromRequest, Query},
Extension,
};
use axum::extract::{FromRef, FromRequestParts, Query};
use serde::Deserialize;

use super::{
Expand All @@ -31,14 +28,17 @@ impl Default for Pagination {
}

#[async_trait]
impl<B: Send> FromRequest<B> for Pagination {
impl<S: Send + Sync> FromRequestParts<S> for Pagination
where
ApiData: FromRef<S>,
{
type Rejection = ApiError;

async fn from_request(req: &mut axum::extract::RequestParts<B>) -> Result<Self, Self::Rejection> {
let Query(mut pagination) = Query::<Pagination>::from_request(req)
async fn from_request_parts(req: &mut axum::http::request::Parts, state: &S) -> Result<Self, Self::Rejection> {
let Query(mut pagination) = Query::<Pagination>::from_request_parts(req, state)
.await
.map_err(RequestError::from)?;
let Extension(config) = Extension::<ApiData>::from_request(req).await?;
let config = ApiData::from_ref(state);
pagination.page_size = pagination.page_size.min(config.max_page_size);
Ok(pagination)
}
Expand All @@ -51,11 +51,11 @@ pub struct ListRoutesQuery {
}

#[async_trait]
impl<B: Send> FromRequest<B> for ListRoutesQuery {
impl<S: Send + Sync> FromRequestParts<S> for ListRoutesQuery {
type Rejection = ApiError;

async fn from_request(req: &mut axum::extract::RequestParts<B>) -> Result<Self, Self::Rejection> {
let Query(query) = Query::<ListRoutesQuery>::from_request(req)
async fn from_request_parts(req: &mut axum::http::request::Parts, state: &S) -> Result<Self, Self::Rejection> {
let Query(query) = Query::<ListRoutesQuery>::from_request_parts(req, state)
.await
.map_err(RequestError::from)?;
Ok(query)
Expand Down Expand Up @@ -83,14 +83,14 @@ mod stardust {
}

#[async_trait]
impl<B: Send> FromRequest<B> for TimeRange {
impl<S: Send + Sync> FromRequestParts<S> for TimeRange {
type Rejection = ApiError;

async fn from_request(req: &mut axum::extract::RequestParts<B>) -> Result<Self, Self::Rejection> {
async fn from_request_parts(req: &mut axum::http::request::Parts, state: &S) -> Result<Self, Self::Rejection> {
let Query(TimeRangeQuery {
start_timestamp,
end_timestamp,
}) = Query::<TimeRangeQuery>::from_request(req)
}) = Query::<TimeRangeQuery>::from_request_parts(req, state)
.await
.map_err(RequestError::from)?;
if matches!((start_timestamp, end_timestamp), (Some(start), Some(end)) if end < start) {
Expand All @@ -110,26 +110,21 @@ pub use stardust::*;

#[cfg(test)]
mod test {
use axum::{
extract::{FromRequest, RequestParts},
http::Request,
};
use axum::{extract::FromRequest, http::Request};

use super::*;
use crate::api::ApiConfig;

#[tokio::test]
async fn page_size_clamped() {
let mut req = RequestParts::new(
Request::builder()
.method("GET")
.uri("/?pageSize=9999999")
.extension(ApiData::try_from(ApiConfig::default()).unwrap())
.body(())
.unwrap(),
);
let config = ApiData::try_from(ApiConfig::default()).unwrap();
let req = Request::builder()
.method("GET")
.uri("/?pageSize=9999999")
.body(())
.unwrap();
assert_eq!(
Pagination::from_request(&mut req).await.unwrap(),
Pagination::from_request(req, &config).await.unwrap(),
Pagination {
page_size: 1000,
..Default::default()
Expand Down
10 changes: 4 additions & 6 deletions src/bin/inx-chronicle/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@ mod config;
mod router;
mod routes;

use axum::{Extension, Server};
use chronicle::db::MongoDb;
use futures::Future;
use hyper::Method;
use hyper::{Method, Server};
use tower_http::{
catch_panic::CatchPanicLayer,
cors::{Any, CorsLayer},
Expand All @@ -39,7 +38,7 @@ pub use self::{
pub const DEFAULT_PAGE_SIZE: usize = 100;

/// The Chronicle API actor
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct ApiWorker {
db: MongoDb,
api_data: ApiData,
Expand All @@ -58,9 +57,8 @@ impl ApiWorker {
info!("Starting API server on port `{}`", self.api_data.port);

let port = self.api_data.port;
let routes = routes()
.layer(Extension(self.db.clone()))
.layer(Extension(self.api_data.clone()))
let routes = routes(self.api_data.clone())
.with_state(self.clone())
.layer(CatchPanicLayer::new())
.layer(TraceLayer::new_for_http())
.layer(
Expand Down
Loading

0 comments on commit f77ccfa

Please sign in to comment.