feat(middleware): add middleware to attach default response headers (#824)

This commit is contained in:
Sanchith Hegde
2023-04-04 11:26:05 +05:30
committed by GitHub
parent 35d3e27724
commit 6d7b11a0f0
9 changed files with 23 additions and 49 deletions

View File

@ -25,8 +25,6 @@ impl actix_web::ResponseError for ApiErrorResponse {
actix_web::HttpResponseBuilder::new(self.status_code()) actix_web::HttpResponseBuilder::new(self.status_code())
.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
.insert_header((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000"))
.insert_header((header::VIA, "Juspay_Router"))
.body(self.to_string()) .body(self.to_string())
} }
} }

View File

@ -522,12 +522,8 @@ impl actix_web::ResponseError for StripeErrorCode {
fn error_response(&self) -> actix_web::HttpResponse { fn error_response(&self) -> actix_web::HttpResponse {
use actix_web::http::header; use actix_web::http::header;
use crate::consts;
actix_web::HttpResponseBuilder::new(self.status_code()) actix_web::HttpResponseBuilder::new(self.status_code())
.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
.insert_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE))
.insert_header((header::VIA, "Juspay_Router"))
.body(self.to_string()) .body(self.to_string())
} }
} }

View File

@ -24,6 +24,3 @@ pub(crate) const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose =
pub(crate) const API_KEY_LENGTH: usize = 64; pub(crate) const API_KEY_LENGTH: usize = 64;
pub(crate) const PUB_SUB_CHANNEL: &str = "hyperswitch_invalidate"; pub(crate) const PUB_SUB_CHANNEL: &str = "hyperswitch_invalidate";
/// Max age of 1 year in seconds. Which is `60*60*24*365`
pub(crate) const HSTS_HEADER_VALUE: &str = "max-age=31536000";

View File

@ -153,14 +153,8 @@ impl From<ConfigError> for ApplicationError {
} }
fn error_response<T: Display>(err: &T) -> actix_web::HttpResponse { fn error_response<T: Display>(err: &T) -> actix_web::HttpResponse {
use actix_web::http::header;
use crate::consts;
actix_web::HttpResponse::BadRequest() actix_web::HttpResponse::BadRequest()
.append_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE)) .content_type(mime::APPLICATION_JSON)
.append_header((header::VIA, "Juspay_Router"))
.content_type("application/json")
.body(format!(r#"{{ "error": {{ "message": "{err}" }} }}"#)) .body(format!(r#"{{ "error": {{ "message": "{err}" }} }}"#))
} }

View File

@ -263,12 +263,8 @@ impl actix_web::ResponseError for ApiErrorResponse {
fn error_response(&self) -> actix_web::HttpResponse { fn error_response(&self) -> actix_web::HttpResponse {
use actix_web::http::header; use actix_web::http::header;
use crate::consts;
actix_web::HttpResponseBuilder::new(self.status_code()) actix_web::HttpResponseBuilder::new(self.status_code())
.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
.insert_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE))
.insert_header((header::VIA, "Juspay_Router"))
.body(self.to_string()) .body(self.to_string())
} }
} }

View File

@ -162,13 +162,10 @@ pub fn get_application_builder(
let json_cfg = actix_web::web::JsonConfig::default() let json_cfg = actix_web::web::JsonConfig::default()
.limit(request_body_limit) .limit(request_body_limit)
.content_type_required(true) .content_type_required(true)
.content_type(|mime| mime == mime::APPLICATION_JSON) // FIXME: This doesn't seem to be enforced.
.error_handler(utils::error_parser::custom_json_error_handler); .error_handler(utils::error_parser::custom_json_error_handler);
actix_web::App::new() actix_web::App::new()
.app_data(json_cfg) .app_data(json_cfg)
.wrap(middleware::RequestId)
.wrap(router_env::tracing_actix_web::TracingLogger::default())
.wrap(ErrorHandlers::new().handler( .wrap(ErrorHandlers::new().handler(
StatusCode::NOT_FOUND, StatusCode::NOT_FOUND,
errors::error_handlers::custom_error_handlers, errors::error_handlers::custom_error_handlers,
@ -177,5 +174,8 @@ pub fn get_application_builder(
StatusCode::METHOD_NOT_ALLOWED, StatusCode::METHOD_NOT_ALLOWED,
errors::error_handlers::custom_error_handlers, errors::error_handlers::custom_error_handlers,
)) ))
.wrap(middleware::default_response_headers())
.wrap(cors::cors()) .wrap(cors::cors())
.wrap(middleware::RequestId)
.wrap(router_env::tracing_actix_web::TracingLogger::default())
} }

View File

@ -59,3 +59,14 @@ where
}) })
} }
} }
/// Middleware for attaching default response headers. Headers with the same key already set in a
/// response will not be overwritten.
pub fn default_response_headers() -> actix_web::middleware::DefaultHeaders {
use actix_web::http::header;
actix_web::middleware::DefaultHeaders::new()
// Max age of 1 year in seconds, equal to `60 * 60 * 24 * 365` seconds.
.add((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000"))
.add((header::VIA, "HyperSwitch"))
}

View File

@ -9,7 +9,7 @@ use std::{
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use actix_web::{body, http::header, HttpRequest, HttpResponse, Responder}; use actix_web::{body, HttpRequest, HttpResponse, Responder};
use common_utils::errors::ReportSwitchExt; use common_utils::errors::ReportSwitchExt;
use error_stack::{report, IntoReport, Report, ResultExt}; use error_stack::{report, IntoReport, Report, ResultExt};
use masking::ExposeOptionInterface; use masking::ExposeOptionInterface;
@ -20,7 +20,6 @@ use self::request::{ContentType, HeaderExt, RequestBuilderExt};
pub use self::request::{Method, Request, RequestBuilder}; pub use self::request::{Method, Request, RequestBuilder};
use crate::{ use crate::{
configs::settings::Connectors, configs::settings::Connectors,
consts,
core::{ core::{
errors::{self, CustomResult}, errors::{self, CustomResult},
payments, payments,
@ -604,25 +603,16 @@ where
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse { pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.content_type("application/json") .content_type(mime::APPLICATION_JSON)
.append_header((header::VIA, "Juspay_router"))
.append_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE))
.body(response) .body(response)
} }
pub fn http_response_plaintext<T: body::MessageBody + 'static>(res: T) -> HttpResponse { pub fn http_response_plaintext<T: body::MessageBody + 'static>(res: T) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok().content_type(mime::TEXT_PLAIN).body(res)
.content_type("text/plain")
.append_header((header::VIA, "Juspay_router"))
.append_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE))
.body(res)
} }
pub fn http_response_ok() -> HttpResponse { pub fn http_response_ok() -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok().finish()
.append_header((header::VIA, "Juspay_router"))
.append_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE))
.finish()
} }
pub fn http_redirect_response<T: body::MessageBody + 'static>( pub fn http_redirect_response<T: body::MessageBody + 'static>(
@ -630,22 +620,18 @@ pub fn http_redirect_response<T: body::MessageBody + 'static>(
redirection_response: api::RedirectionResponse, redirection_response: api::RedirectionResponse,
) -> HttpResponse { ) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.content_type("application/json") .content_type(mime::APPLICATION_JSON)
.append_header((header::VIA, "Juspay_router"))
.append_header(( .append_header((
"Location", "Location",
redirection_response.return_url_with_query_params, redirection_response.return_url_with_query_params,
)) ))
.append_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE))
.status(http::StatusCode::FOUND) .status(http::StatusCode::FOUND)
.body(response) .body(response)
} }
pub fn http_response_err<T: body::MessageBody + 'static>(response: T) -> HttpResponse { pub fn http_response_err<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::BadRequest() HttpResponse::BadRequest()
.content_type("application/json") .content_type(mime::APPLICATION_JSON)
.append_header((header::VIA, "Juspay_router"))
.append_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE))
.body(response) .body(response)
} }

View File

@ -51,18 +51,14 @@ pub mod error_parser {
impl ResponseError for CustomJsonError { impl ResponseError for CustomJsonError {
fn status_code(&self) -> StatusCode { fn status_code(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR StatusCode::BAD_REQUEST
} }
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
use actix_web::http::header; use actix_web::http::header;
use crate::consts; actix_web::HttpResponseBuilder::new(self.status_code())
actix_web::HttpResponseBuilder::new(StatusCode::BAD_REQUEST)
.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
.insert_header((header::STRICT_TRANSPORT_SECURITY, consts::HSTS_HEADER_VALUE))
.insert_header((header::VIA, "Juspay_Router"))
.body(self.to_string()) .body(self.to_string())
} }
} }