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

feat(error): handle json error as json instead of plaintext #125

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
55 changes: 45 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ vaultrs = { version = "0.7.2", optional = true }

# Tokio Dependencies
tokio = { version = "1.39.3", features = ["macros", "rt-multi-thread"] }
axum = "0.7.5"
axum = { version = "0.7.5", features = ["macros"] }
axum-server = { version = "0.7.1", features = ["tls-rustls"] }
axum-extra = { version = "0.9.4" }
hyper = "1.4.1"
tower = { version = "0.5.0", features = ["limit", "buffer", "load-shed"] }
tower-http = { version = "0.5.2", features = ["trace"] }
Expand Down
4 changes: 3 additions & 1 deletion benches/hashing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ pub fn criterion_hmac_sha512(c: &mut Criterion) {
(1..ITERATION).for_each(|po| {
let max: u64 = (2_u64).pow(po);
let value = (0..max).map(|_| rand::random::<u8>()).collect::<Vec<_>>();
let hashed = algo.encode(value.clone().into()).expect("Failed while hashing");
let hashed = algo
.encode(value.clone().into())
.expect("Failed while hashing");
group.throughput(criterion::Throughput::Bytes(max));
group.bench_with_input(
criterion::BenchmarkId::from_parameter(format!("{}", max)),
Expand Down
57 changes: 33 additions & 24 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ pub mod container;
mod custom_error;
mod transforms;

use axum::extract::rejection::JsonRejection;
use axum::response::IntoResponse;
pub use container::*;
pub use custom_error::*;
use reqwest::StatusCode;
Expand Down Expand Up @@ -419,27 +421,34 @@ impl ApiErrorResponse {
}
}

// pub trait LogReport<T, E> {
// fn report_unwrap(self) -> Result<T, E>;
// }

// impl<T, E1, E2> LogReport<T, E1> for Result<T, Report<E2>>
// where
// E1: Send + Sync + std::error::Error + Copy + 'static,
// E2: Send + Sync + std::error::Error + Copy + 'static,
// E1: From<E2>,
// {
// #[track_caller]
// fn report_unwrap(self) -> Result<T, E1> {
// let output = match self {
// Ok(inner_val) => Ok(inner_val),
// Err(inner_err) => {
// let new_error: E1 = (*inner_err.current_context()).into();
// crate::logger::error!(?inner_err);
// Err(inner_err.change_context(new_error))
// }
// };

// output.map_err(|err| (*err.current_context()))
// }
// }
#[derive(Debug, Clone)]
pub struct JsonError {
message: String,
}

impl From<JsonRejection> for JsonError {
fn from(rejection: JsonRejection) -> Self {
Self {
message: rejection.body_text(),
}
}
}

impl IntoResponse for JsonError {
fn into_response(self) -> axum::response::Response {
crate::logger::error!(?self);
(
hyper::StatusCode::BAD_REQUEST,
axum::Json(ApiErrorResponse::new(
error_codes::TE_03,
self.message,
None,
)),
)
.into_response()
}
}

#[derive(axum::extract::FromRequest)]
#[from_request(via(axum::Json), rejection(JsonError))]
pub struct Json<T>(pub T);
2 changes: 1 addition & 1 deletion src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use josekit::jwe;
pub async fn middleware(
TenantStateResolver(state): TenantStateResolver,
parts: request::Parts,
axum::Json(jwe_body): axum::Json<jw::JweBody>,
error::Json(jwe_body): error::Json<jw::JweBody>,
next: Next,
) -> Result<(response::Parts, axum::Json<jw::JweBody>), ContainerError<error::ApiError>> {
let keys = JWEncryption {
Expand Down
29 changes: 16 additions & 13 deletions src/routes/data.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::Arc;

use axum::{routing::post, Json};
use axum::routing::post;

#[cfg(feature = "limit")]
use axum::{error_handling::HandleErrorLayer, response::IntoResponse};
Expand Down Expand Up @@ -95,8 +95,8 @@ pub fn serve(
/// `/data/add` handling the requirement of storing data
pub async fn add_card(
TenantStateResolver(tenant_app_state): TenantStateResolver,
Json(request): Json<types::StoreCardRequest>,
) -> Result<Json<types::StoreCardResponse>, ContainerError<error::ApiError>> {
error::Json(request): error::Json<types::StoreCardRequest>,
) -> Result<axum::Json<types::StoreCardResponse>, ContainerError<error::ApiError>> {
request.validate()?;

let master_encryption =
Expand Down Expand Up @@ -183,14 +183,17 @@ pub async fn add_card(
}
};

Ok(Json(StoreCardResponse::from((duplication_check, output))))
Ok(axum::Json(StoreCardResponse::from((
duplication_check,
output,
))))
}

/// `/data/delete` handling the requirement of deleting data
pub async fn delete_card(
TenantStateResolver(tenant_app_state): TenantStateResolver,
Json(request): Json<types::DeleteCardRequest>,
) -> Result<Json<types::DeleteCardResponse>, ContainerError<error::ApiError>> {
error::Json(request): error::Json<types::DeleteCardRequest>,
) -> Result<axum::Json<types::DeleteCardResponse>, ContainerError<error::ApiError>> {
let master_key = GcmAes256::new(tenant_app_state.config.tenant_secrets.master_key.clone());

let _merchant = tenant_app_state
Expand All @@ -207,16 +210,16 @@ pub async fn delete_card(
)
.await?;

Ok(Json(types::DeleteCardResponse {
Ok(axum::Json(types::DeleteCardResponse {
status: types::Status::Ok,
}))
}

/// `/data/retrieve` handling the requirement of retrieving data
pub async fn retrieve_card(
TenantStateResolver(tenant_app_state): TenantStateResolver,
Json(request): Json<types::RetrieveCardRequest>,
) -> Result<Json<types::RetrieveCardResponse>, ContainerError<error::ApiError>> {
error::Json(request): error::Json<types::RetrieveCardRequest>,
) -> Result<axum::Json<types::RetrieveCardResponse>, ContainerError<error::ApiError>> {
let master_key = GcmAes256::new(tenant_app_state.config.tenant_secrets.master_key.clone());

let merchant = tenant_app_state
Expand Down Expand Up @@ -257,18 +260,18 @@ pub async fn retrieve_card(
})
.transpose()?;

Ok(Json(card.try_into()?))
Ok(axum::Json(card.try_into()?))
}

/// `/cards/fingerprint` handling the creation and retrieval of card fingerprint
pub async fn get_or_insert_fingerprint(
TenantStateResolver(tenant_app_state): TenantStateResolver,
Json(request): Json<types::FingerprintRequest>,
) -> Result<Json<types::FingerprintResponse>, ContainerError<error::ApiError>> {
error::Json(request): error::Json<types::FingerprintRequest>,
) -> Result<axum::Json<types::FingerprintResponse>, ContainerError<error::ApiError>> {
let fingerprint = tenant_app_state
.db
.get_or_insert_fingerprint(request.data, request.key)
.await?;

Ok(Json(fingerprint.into()))
Ok(axum::Json(fingerprint.into()))
}
10 changes: 6 additions & 4 deletions src/routes/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use crate::{crypto::keymanager, logger, tenant::GlobalAppState};

use axum::{routing::get, Json};
use axum::routing::get;

use crate::{custom_extractors::TenantStateResolver, error, storage::TestInterface};

Expand All @@ -21,9 +21,9 @@ pub struct HealthRespPayload {
}

/// '/health` API handler`
pub async fn health() -> Json<HealthRespPayload> {
pub async fn health() -> axum::Json<HealthRespPayload> {
crate::logger::debug!("Health was called");
Json(HealthRespPayload {
axum::Json(HealthRespPayload {
message: "Health is good".into(),
})
}
Expand Down Expand Up @@ -51,7 +51,9 @@ pub enum HealthState {
}

/// '/health/diagnostics` API handler`
pub async fn diagnostics(TenantStateResolver(state): TenantStateResolver) -> Json<Diagnostics> {
pub async fn diagnostics(
TenantStateResolver(state): TenantStateResolver,
) -> axum::Json<Diagnostics> {
crate::logger::info!("Health diagnostics was called");

let db_test_output = state.db.test().await;
Expand Down
18 changes: 9 additions & 9 deletions src/routes/key_custodian.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::Arc;

use axum::{extract::State, routing::post, Json};
use axum::{extract::State, routing::post};
use error_stack::ResultExt;

use crate::{
Expand Down Expand Up @@ -63,15 +63,15 @@ pub fn serve() -> axum::Router<Arc<GlobalAppState>> {
pub async fn key1(
State(global_app_state): State<Arc<GlobalAppState>>,
TenantId(tenant_id): TenantId,
Json(payload): Json<CustodianReqPayload>,
) -> Json<CustodianRespPayload> {
error::Json(payload): error::Json<CustodianReqPayload>,
) -> axum::Json<CustodianRespPayload> {
let mut key_state = global_app_state.tenants_key_state.write().await;
key_state
.entry(tenant_id.to_string())
.and_modify(|key_state_data| key_state_data.key1 = Some(payload.key));

logger::info!("Received key1");
Json(CustodianRespPayload {
axum::Json(CustodianRespPayload {
message: "Received Key1".into(),
})
}
Expand All @@ -80,15 +80,15 @@ pub async fn key1(
pub async fn key2(
State(global_app_state): State<Arc<GlobalAppState>>,
TenantId(tenant_id): TenantId,
Json(payload): Json<CustodianReqPayload>,
) -> Json<CustodianRespPayload> {
error::Json(payload): error::Json<CustodianReqPayload>,
) -> axum::Json<CustodianRespPayload> {
let mut key_state = global_app_state.tenants_key_state.write().await;
key_state
.entry(tenant_id.to_string())
.and_modify(|key_state_data| key_state_data.key2 = Some(payload.key));

logger::info!("Received key2");
Json(CustodianRespPayload {
axum::Json(CustodianRespPayload {
message: "Received Key2".into(),
})
}
Expand All @@ -97,7 +97,7 @@ pub async fn key2(
pub async fn decrypt(
State(global_app_state): State<Arc<GlobalAppState>>,
TenantId(tenant_id): TenantId,
) -> Result<Json<CustodianRespPayload>, error::ContainerError<error::ApiError>> {
) -> Result<axum::Json<CustodianRespPayload>, error::ContainerError<error::ApiError>> {
let mut key_state_map = global_app_state.tenants_key_state.write().await;
let key_state_for_tenant = key_state_map
.get_mut(&tenant_id.to_string())
Expand Down Expand Up @@ -127,7 +127,7 @@ pub async fn decrypt(
global_app_state.set_app_state(tenant_app_state).await;

logger::info!("Decryption of Custodian key is successful");
Ok(Json(CustodianRespPayload {
Ok(axum::Json(CustodianRespPayload {
message: "Decryption of Custodian key is successful".into(),
}))
}
Expand Down
Loading
Loading