Skip to content
This repository has been archived by the owner on Feb 11, 2024. It is now read-only.

Commit

Permalink
fix: fix CORS headers (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
Xavier Basty authored Jul 10, 2023
1 parent 14bbb36 commit 02b668f
Show file tree
Hide file tree
Showing 6 changed files with 17 additions and 48 deletions.
3 changes: 0 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,5 @@ MONGO_ADDRESS=mongodb://admin:admin@localhost:27017/gilgamesh?authSource=admin
# HTTP clients e.g. curl, insomnia, postman, etc
VALIDATE_SIGNATURES=false

# CORS
CORS_ALLOWED_ORIGINS=*

# Telemetry
TELEMETRY_PROMETHEUS_PORT=3001
11 changes: 0 additions & 11 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const DEFAULT_PORT_NUMBER: u16 = 3001;
const DEFAULT_LOG_LEVEL: &str = "WARN";
const DEFAULT_RELAY_URL: &str = "https://relay.walletconnect.com";
const DEFAULT_VALIDATE_SIGNATURES: bool = true;
const DEFAULT_CORS_ALLOWED_ORIGINS: &[&str] = &["*"];

/// The server configuration.
#[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
Expand All @@ -26,9 +25,6 @@ pub struct Configuration {
/// An internal flag to disable logging, cannot be defined by user.
#[serde(default = "default_is_test", skip)]
pub is_test: bool,
// CORS
#[serde(default = "default_cors_allowed_origins")]
pub cors_allowed_origins: Vec<String>,

pub otel_exporter_otlp_endpoint: Option<String>,
pub telemetry_prometheus_port: Option<u16>,
Expand Down Expand Up @@ -65,13 +61,6 @@ fn default_is_test() -> bool {
false
}

fn default_cors_allowed_origins() -> Vec<String> {
DEFAULT_CORS_ALLOWED_ORIGINS
.iter()
.map(|s| s.to_string())
.collect::<Vec<String>>()
}

/// Create a new configuration from the environment variables.
pub fn get_config() -> error::Result<Configuration> {
let config = envy::from_env::<Configuration>()?;
Expand Down
48 changes: 17 additions & 31 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use {
state::{MessagesStorageArc, RegistrationStorageArc},
},
axum::{
http::{HeaderValue, Method},
http,
routing::{get, post},
Router,
},
Expand All @@ -16,7 +16,7 @@ use {
tokio::{select, sync::broadcast},
tower::ServiceBuilder,
tower_http::{
cors::{AllowOrigin, CorsLayer},
cors::{Any, CorsLayer},
trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer},
},
};
Expand Down Expand Up @@ -92,37 +92,22 @@ pub async fn bootstrap(
let port = state.config.port;
let private_port = state.config.telemetry_prometheus_port.unwrap_or(3001);

let allowed_origins = state.config.cors_allowed_origins.clone();

let state_arc = Arc::new(state);

let global_middleware = ServiceBuilder::new()
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().include_headers(true))
.on_request(DefaultOnRequest::new().level(config.log_level()))
.on_response(
DefaultOnResponse::new()
.level(config.log_level())
.include_headers(true),
),
)
.layer(if allowed_origins == vec!["*".to_string()] {
info!("CORS is disabled");
CorsLayer::new()
.allow_methods([Method::GET, Method::POST, Method::DELETE])
.allow_origin(AllowOrigin::any())
} else {
info!("CORS is enabled for {:?}", allowed_origins);
CorsLayer::new()
.allow_methods([Method::GET, Method::POST, Method::DELETE])
.allow_origin(
allowed_origins
.iter()
.map(|v| v.parse::<HeaderValue>().unwrap())
.collect::<Vec<HeaderValue>>(),
)
});
let global_middleware = ServiceBuilder::new().layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().include_headers(true))
.on_request(DefaultOnRequest::new().level(config.log_level()))
.on_response(
DefaultOnResponse::new()
.level(config.log_level())
.include_headers(true),
),
);

let cors = CorsLayer::new()
.allow_origin(Any)
.allow_headers([http::header::CONTENT_TYPE, http::header::AUTHORIZATION]);

let app = Router::new()
.route("/health", get(handlers::health::handler))
Expand All @@ -131,6 +116,7 @@ pub async fn bootstrap(
.route("/register", get(handlers::get_registration::handler))
.route("/register", post(handlers::register::handler))
.layer(global_middleware)
.layer(cors)
.with_state(state_arc.clone());

let private_app = Router::new()
Expand Down
1 change: 0 additions & 1 deletion terraform/ecs/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ resource "aws_ecs_task_definition" "app_task_definition" {
{ name = "PUBLIC_URL", value = "http://localhost:8080" }, // TODO: Change this to the actual public URL
{ name = "LOG_LEVEL", value = var.log_level },
{ name = "MONGO_ADDRESS", value = var.docdb-connection_url },
{ name = "CORS_ALLOWED_ORIGINS", value = "*" },
{ name = "TELEMETRY_PROMETHEUS_PORT", value = "8081" }
],
dependsOn = [
Expand Down
1 change: 0 additions & 1 deletion tests/context/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ impl Gilgamesh {
validate_signatures: false,
mongo_address,
is_test: true,
cors_allowed_origins: vec!["*".to_string()],
otel_exporter_otlp_endpoint: None,
telemetry_prometheus_port: Some(get_random_port()),
};
Expand Down
1 change: 0 additions & 1 deletion tests/context/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ impl PersistentStorage {
validate_signatures: false,
mongo_address,
is_test: true,
cors_allowed_origins: vec!["*".to_string()],
otel_exporter_otlp_endpoint: None,
telemetry_prometheus_port: Some(get_random_port()),
};
Expand Down

0 comments on commit 02b668f

Please sign in to comment.