Skip to content

Commit

Permalink
Fix CORS checks to allow WebSocket connections
Browse files Browse the repository at this point in the history
Actix' default CORS policy would reject any request with a Origin
header. Updating dependencies thus broke the /api/live endpoint when
used from a browser. This configures Actix to permit requests from a
single configurable origin.
  • Loading branch information
mologie committed Jun 9, 2023
1 parent c4cf148 commit 0d2b657
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Finally we can use [cargo] to download all necessary dependencies, compile the
application and then run it:

```bash
export OGN_CORS_ORIGIN=http:https://localhost
cargo run --release
```

Expand Down
2 changes: 0 additions & 2 deletions src/api/ddb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ pub async fn get(redis: web::Data<Addr<redis::RedisExecutor>>) -> impl Responder
let response = devices
.map_err(ErrorInternalServerError)?
.customize()
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("Access-Control-Allow-Methods", "GET, POST, OPTIONS"))
.insert_header(("Content-Type", "application/json"));

Ok::<_, actix_web::Error>(response)
Expand Down
12 changes: 10 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use actix_cors::Cors;
use actix_files::NamedFile;
use actix_ogn::OGNActor;
use actix_web::middleware::Logger;
use actix_web::{web, App, HttpServer, Responder};
use actix_web::{http, web, App, HttpServer, Responder};
use anyhow::{anyhow, Context, Result};
use clap::{self, value_t, Arg};
use log::debug;
Expand Down Expand Up @@ -89,17 +89,25 @@ async fn main() -> Result<()> {
let gw = gateway.clone();
let _ogn_addr: Addr<_> = Supervisor::start(|_| OGNActor::new(gw.recipient()));

// Origin for WebSocket CORS validation, e.g. https://ogn.cloud
let cors_origin = env::var("OGN_CORS_ORIGIN").context("CORS_ORIGIN must be set a URI")?;

debug!("Listening on {}:{}", listen_host, listen_port);

// Create Http server with websocket support
HttpServer::new(move || {
let cors = Cors::default()
.allowed_origin(&cors_origin)
.allow_any_method()
.allowed_headers(vec![http::header::ACCEPT, http::header::CONTENT_TYPE])
.max_age(3600);
App::new()
.app_data(web::Data::new(gateway.clone()))
.app_data(web::Data::new(redis_executor_addr.clone()))
.wrap(Logger::default())
.service(
web::scope("/api")
.wrap(Cors::default())
.wrap(cors)
.route("/ddb", web::get().to(api::ddb::get))
.route("/status", web::get().to(api::status::get))
.route("/records/{id}", web::get().to(api::records::get))
Expand Down

0 comments on commit 0d2b657

Please sign in to comment.