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(server): add --cors argument to enable cors for all workers #202

Merged
Merged
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
20 changes: 18 additions & 2 deletions crates/server/src/handlers/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ use super::{assets::handle_assets, not_found::handle_not_found};
use crate::DataConnectors;
use actix_web::{
http::StatusCode,
web::{Bytes, Data},
web::{self, Bytes, Data},
HttpRequest, HttpResponse,
};
use std::{fs::File, io::Write, sync::RwLock};
use wws_router::Routes;
use wws_worker::io::WasmOutput;

const CORS_HEADER: &str = "Access-Control-Allow-Origin";

/// Process an HTTP request by passing it to the right Runner. The Runner
/// will prepare the WASI environment and call the Wasm module with the data.
///
Expand All @@ -29,7 +31,11 @@ use wws_worker::io::WasmOutput;
///
/// For these reasons, we are selecting the right handler at this point and not
/// allowing Actix to select it for us.
pub async fn handle_worker(req: HttpRequest, body: Bytes) -> HttpResponse {
pub async fn handle_worker(
req: HttpRequest,
body: Bytes,
cors_origins: web::Data<Option<Vec<String>>>,
) -> HttpResponse {
let routes = req.app_data::<Data<Routes>>().unwrap();
let stderr_file = req.app_data::<Data<Option<File>>>().unwrap();
let data_connectors = req
Expand Down Expand Up @@ -97,6 +103,16 @@ pub async fn handle_worker(req: HttpRequest, body: Bytes) -> HttpResponse {
// Default content type
builder.insert_header(("Content-Type", "text/html"));

// Check if cors config has any origins to register
if let Some(origins) = cors_origins.as_ref() {
// Check if worker has overridden the header, if not
if !handler_result.headers.contains_key(CORS_HEADER) {
// insert those origins in 'Access-Control-Allow-Origin' header
let header_value = origins.join(",");
builder.insert_header((CORS_HEADER, header_value));
}
}

for (key, val) in handler_result.headers.iter() {
// Note that QuickJS is replacing the "-" character
// with "_" on property keys. Here, we rollback it
Expand Down
6 changes: 5 additions & 1 deletion crates/server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub async fn serve(
port: u16,
panel: bool,
stderr: Option<&Path>,
cors_origins: Option<Vec<String>>,
) -> Result<Server> {
// Initializes the data connectors. For now, just KV
let data = Data::new(RwLock::new(DataConnectors::default()));
Expand All @@ -53,6 +54,8 @@ pub async fn serve(
stderr_file = Data::new(None);
}

let cors_data = Data::new(cors_origins);

let server = HttpServer::new(move || {
let mut app = App::new()
// enable logger
Expand All @@ -62,7 +65,8 @@ pub async fn serve(
.app_data(Data::clone(&routes))
.app_data(Data::clone(&data))
.app_data(Data::clone(&root_path))
.app_data(Data::clone(&stderr_file));
.app_data(Data::clone(&stderr_file))
.app_data(Data::clone(&cors_data));

// Configure panel
if panel {
Expand Down
5 changes: 5 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ pub struct Args {
/// Manage language runtimes in your project
#[command(subcommand)]
commands: Option<Main>,

/// CORS headers to add to all workers if not already set by the worker
#[arg(long)]
cors: Option<Vec<String>>,
}

#[actix_web::main]
Expand Down Expand Up @@ -198,6 +202,7 @@ async fn main() -> std::io::Result<()> {
args.port,
args.enable_panel,
None,
args.cors,
)
.await
.map_err(|err| Error::new(ErrorKind::AddrInUse, err))?;
Expand Down