From 958607eabbfb806ab694da518843c18d6b2ac514 Mon Sep 17 00:00:00 2001 From: Condorra Date: Sat, 7 Sep 2024 16:42:29 +1000 Subject: [PATCH] Check Origin, not CORS (no CORS for WS) --- Cargo.lock | 16 ---------------- Cargo.toml | 1 - src/main.rs | 26 +++++++++++++++----------- 3 files changed, 15 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 217ae5d..71190d3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,21 +19,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "actix-cors" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9e772b3bcafe335042b5db010ab7c09013dad6eac4915c91d8d50902769f331" -dependencies = [ - "actix-utils", - "actix-web", - "derive_more", - "futures-util", - "log", - "once_cell", - "smallvec", -] - [[package]] name = "actix-http" version = "3.9.0" @@ -1736,7 +1721,6 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" name = "worldwideportal-server" version = "0.1.0" dependencies = [ - "actix-cors", "actix-web", "actix-ws", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 713b913..dfad925 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,6 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -actix-cors = "0.7.0" actix-web = { version = "4.9.0", features = ["rustls-0_23"] } actix-ws = "0.3.0" anyhow = "1.0.86" diff --git a/src/main.rs b/src/main.rs index 861115d..72f878a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,8 @@ -use actix_cors::Cors; use actix_web::{ self, - error::InternalError, + error::{ErrorForbidden, InternalError}, get, - http::StatusCode, + http::{header::ORIGIN, StatusCode}, middleware::Logger, rt::{self, net::TcpStream}, web::{self, Data}, @@ -44,6 +43,19 @@ async fn ws( req: HttpRequest, body: web::Payload, ) -> impl Responder { + match req.headers().get(&ORIGIN) { + None => Err(ErrorForbidden("Missing origin"))?, + Some(origin) => { + if !config_data + .allowed_origins + .iter() + .any(|o| o.matches(origin.to_str().unwrap_or("invalid"))) + { + Err(ErrorForbidden("Disallowed origin"))?; + } + } + } + let (response, mut session, stream) = actix_ws::handle(&req, body)?; let mut stream = stream.aggregate_continuations().max_continuation_size(1024); @@ -182,16 +194,8 @@ async fn main() -> anyhow::Result<()> { let server_data = data.clone(); let server = HttpServer::new(move || { let logger = Logger::default(); - let cors_server_data = server_data.clone(); - let cors = Cors::default().allowed_origin_fn(move |origin, _| { - cors_server_data - .allowed_origins - .iter() - .any(|o| o.matches(origin.to_str().unwrap_or("invalid"))) - }); App::new() .wrap(logger) - .wrap(cors) .app_data(server_data.clone()) .service(ws) });