Skip to content

Commit

Permalink
fix(anubis): configure CORS policy for Rocket
Browse files Browse the repository at this point in the history
  • Loading branch information
WarriorsSami committed Mar 3, 2024
1 parent 13fbc85 commit f25b830
Show file tree
Hide file tree
Showing 14 changed files with 131 additions and 199 deletions.
246 changes: 75 additions & 171 deletions anubis-eval/Cargo.lock

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions anubis-eval/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ edition = "2021"

[dependencies]
url = "2.2.2"
tokio-cron-scheduler = "0.9.4"
tokio-cron-scheduler = "0.10.0"
tokio = { version = "1.11.0", features = ["full"] }
thiserror = "1.0.49"
diesel = { version = "2.1.1", features = ["postgres", "chrono", "r2d2", "uuid", "numeric"] }
Expand All @@ -17,12 +17,12 @@ r2d2-diesel = "1.0.0"
serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0.105"
uuid = { version = "1.4.1", features = ["serde", "v4"] }
rocket = { version = "=0.5.0-rc.3", features = ["json"] }
rocket-validation = "0.1.3"
rocket = { version = "0.5.0", features = ["json"] }
rocket-validation = "0.2.0"
validator = "0.16.1"
rocket_dyn_templates = { version = "=0.1.0-rc.3", features = ["tera"] }
rocket_sync_db_pools = { version = "0.1.0-rc.3", features = ["diesel_postgres_pool"] }
mockall = "0.11.4"
rocket_dyn_templates = { version = "0.1.0", features = ["tera"] }
rocket_sync_db_pools = { version = "0.1.0", features = ["diesel_postgres_pool"] }
mockall = "0.12.1"
lazy_static = "1.4.0"
log4rs = "1.2.0"
jsonwebtoken = "9.0.0"
Expand All @@ -33,4 +33,4 @@ reqwest = { version = "0.11.22", features = ["json"] }
futures = "0.3.28"
cloudevents-sdk = "0.7.0"
anyhow = "1.0.80"
async-scoped = { version = "0.9.0", features = ["use-tokio"] }
async-scoped = { version = "0.9.0", features = ["use-tokio"] }
16 changes: 16 additions & 0 deletions anubis-eval/src/api/catchers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,19 @@ pub fn unauthorized_catcher(req: &rocket::Request) -> Value {
"error": "Access token has expired or is invalid"
})
}

#[catch(404)]
pub fn not_found_catcher(req: &rocket::Request) -> Value {
error!("Not found: {:?}", req);
json!({
"error": "Resource not found"
})
}

#[catch(500)]
pub fn internal_error_catcher(req: &rocket::Request) -> Value {
error!("Internal error: {:?}", req);
json!({
"error": "Internal server error"
})
}
2 changes: 1 addition & 1 deletion anubis-eval/src/api/create_submission_endpoint.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::application::auth::JwtContext;
use crate::api::middleware::auth::JwtContext;
use crate::application::dapr_client::DaprClient;
use crate::config::di::CONFIG;
use crate::contracts::create_submission_dtos::CreateSubmissionResponseDto;
Expand Down
2 changes: 1 addition & 1 deletion anubis-eval/src/api/get_highest_score_submissions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::application::auth::JwtContext;
use crate::api::middleware::auth::JwtContext;
use crate::contracts::get_highest_score_submissions_dtos::GetHighestScoreSubmissionsDto;
use crate::domain::application_error::ApplicationError;
use crate::domain::submission::Submission;
Expand Down
2 changes: 1 addition & 1 deletion anubis-eval/src/api/get_submission_endpoint.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::application::auth::JwtContext;
use crate::api::middleware::auth::JwtContext;
use crate::application::dapr_client::DaprClient;
use crate::contracts::get_submission_dtos::GetSubmissionWithTestCasesDto;
use crate::domain::application_error::ApplicationError;
Expand Down
2 changes: 1 addition & 1 deletion anubis-eval/src/api/get_submissions_endpoint.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::application::auth::JwtContext;
use crate::api::middleware::auth::JwtContext;
use crate::contracts::fps_dtos::FpsSubmissionDto;
use crate::contracts::get_submissions_dtos::GetSubmissionsDto;
use crate::domain::application_error::ApplicationError;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,28 @@ impl<'r> FromRequest<'r> for JwtContext {
match req.headers().get_one("authorization") {
None => {
let response = String::from("Error validating JWT token - No token provided");
Outcome::Failure((Status::Unauthorized, ApplicationError::AuthError(response)))
Outcome::Error((Status::Unauthorized, ApplicationError::AuthError(response)))
}
Some(key) => match is_valid(key) {
Ok(claims) => Outcome::Success(JwtContext { claims }),
Err(err) => match &err.kind() {
ErrorKind::ExpiredSignature => {
let response = String::from("Error validating JWT token - Expired Token");
Outcome::Failure((
Outcome::Error((
Status::Unauthorized,
ApplicationError::AuthError(response),
))
}
ErrorKind::InvalidToken => {
let response = String::from("Error validating JWT token - Invalid Token");
Outcome::Failure((
Outcome::Error((
Status::Unauthorized,
ApplicationError::AuthError(response),
))
}
_ => {
let response = format!("Error validating JWT token - {}", err);
Outcome::Failure((
Outcome::Error((
Status::Unauthorized,
ApplicationError::AuthError(response),
))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::config::di::CONFIG;
use rocket::fairing::Fairing;
use rocket::http::{Method, Status};

pub struct Cors;

Expand All @@ -14,7 +15,7 @@ impl Fairing for Cors {

async fn on_response<'r>(
&self,
_request: &'r rocket::Request<'_>,
request: &'r rocket::Request<'_>,
response: &mut rocket::Response<'r>,
) {
let allowed_origins = CONFIG
Expand All @@ -23,18 +24,26 @@ impl Fairing for Cors {
.map(String::from)
.collect::<Vec<String>>();

if request.method() == Method::Options {
response.set_status(Status::NoContent);
response.set_header(rocket::http::Header::new(
"Access-Control-Allow-Methods",
"POST, GET, OPTIONS",
));
response.set_header(rocket::http::Header::new(
"Access-Control-Allow-Headers",
"Access-Control-Allow-Headers, \
Origin,Accept, X-Requested-With, \
Content-Type, \
Access-Control-Request-Method, \
Access-Control-Request-Headers",
));
response.remove_header("Content-Type");
}
response.set_header(rocket::http::Header::new(
"Access-Control-Allow-Origin",
allowed_origins.join(","),
));
response.set_header(rocket::http::Header::new(
"Access-Control-Allow-Methods",
"POST, GET, OPTIONS",
));
response.set_header(rocket::http::Header::new(
"Access-Control-Allow-Headers",
"*",
));
response.set_header(rocket::http::Header::new(
"Access-Control-Allow-Credentials",
"true",
Expand Down
2 changes: 2 additions & 0 deletions anubis-eval/src/api/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod auth;
pub mod cors;
2 changes: 1 addition & 1 deletion anubis-eval/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
pub mod catchers;
pub mod cors;
pub mod create_submission_endpoint;
pub mod evaluate_submission_job;
pub mod get_highest_score_submissions;
pub mod get_submission_endpoint;
pub mod get_submissions_endpoint;
pub mod health_check_endpoint;
pub mod middleware;
pub mod problem_eval_metadata_upserted_event_handler;
2 changes: 1 addition & 1 deletion anubis-eval/src/application/dapr_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ impl<'r> FromRequest<'r> for DaprClient {
}),
_ => {
let response = String::from("Error initializing http client and/or db connection");
Outcome::Failure((
Outcome::Error((
rocket::http::Status::InternalServerError,
ApplicationError::Unknown(response),
))
Expand Down
1 change: 0 additions & 1 deletion anubis-eval/src/application/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod auth;
pub mod dapr_client;
4 changes: 3 additions & 1 deletion anubis-eval/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::api::cors::Cors;
use crate::api::middleware::cors::Cors;
use crate::config::di::{CONFIG, DAPR_CLIENT, DB_CONN, HTTP_CLIENT};
use crate::config::logger::init_logger;
use crate::infrastructure::db::{run_migrations, Db};
Expand Down Expand Up @@ -68,6 +68,8 @@ async fn rocket() -> _ {
catchers![
rocket_validation::validation_catcher,
api::catchers::unauthorized_catcher,
api::catchers::not_found_catcher,
api::catchers::internal_error_catcher,
],
)
}

0 comments on commit f25b830

Please sign in to comment.