From 4b3634b8e77b974a0b3f515bbb72c7430f0488fb Mon Sep 17 00:00:00 2001 From: Xavier Vello Date: Tue, 31 Oct 2023 16:32:13 +0100 Subject: [PATCH] add cors support (#43) --- Cargo.toml | 2 +- capture/src/capture.rs | 6 ++++++ capture/src/router.rs | 14 ++++++++++++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b8b4d08..318b180 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,7 @@ serde_json = "1.0.96" governor = "0.5.1" tower_governor = "0.0.4" time = { version = "0.3.20", features = ["formatting", "macros", "parsing", "serde"] } -tower-http = { version = "0.4.0", features = ["trace"] } +tower-http = { version = "0.4.0", features = ["cors", "trace"] } bytes = "1" anyhow = "1.0" flate2 = "1.0" diff --git a/capture/src/capture.rs b/capture/src/capture.rs index 6475940..45fc5f7 100644 --- a/capture/src/capture.rs +++ b/capture/src/capture.rs @@ -104,6 +104,12 @@ pub async fn event( })) } +pub async fn options() -> Result, CaptureError> { + Ok(Json(CaptureResponse { + status: CaptureResponseCode::Ok, + })) +} + pub fn process_single_event( event: &RawEvent, context: &ProcessingContext, diff --git a/capture/src/router.rs b/capture/src/router.rs index 757b975..8fc080d 100644 --- a/capture/src/router.rs +++ b/capture/src/router.rs @@ -1,10 +1,12 @@ use std::future::ready; use std::sync::Arc; +use axum::http::Method; use axum::{ routing::{get, post}, Router, }; +use tower_http::cors::{AllowOrigin, Any, CorsLayer}; use tower_http::trace::TraceLayer; use crate::{billing_limits::BillingLimiter, capture, redis::Client, sink, time::TimeSource}; @@ -41,12 +43,20 @@ pub fn router< billing, }; + // Very permissive CORS policy, as old SDK versions + // and reverse proxies might send funky headers. + let cors = CorsLayer::new() + .allow_methods([Method::GET, Method::POST, Method::OPTIONS]) + .allow_headers(Any) + .allow_origin(AllowOrigin::mirror_request()); + let router = Router::new() // TODO: use NormalizePathLayer::trim_trailing_slash .route("/", get(index)) - .route("/i/v0/e", post(capture::event)) - .route("/i/v0/e/", post(capture::event)) + .route("/i/v0/e", post(capture::event).options(capture::options)) + .route("/i/v0/e/", post(capture::event).options(capture::options)) .layer(TraceLayer::new_for_http()) + .layer(cors) .layer(axum::middleware::from_fn(track_metrics)) .with_state(state);