From 07e92938eafa66afe158bcf23cf51397da653dea Mon Sep 17 00:00:00 2001 From: Oliver Evans Date: Thu, 29 Aug 2024 03:37:07 -0700 Subject: [PATCH] Only set one CORS allowed origin at a time --- worker/src/cors.rs | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/worker/src/cors.rs b/worker/src/cors.rs index bb4c76aff..a03c6ec74 100644 --- a/worker/src/cors.rs +++ b/worker/src/cors.rs @@ -5,7 +5,7 @@ use crate::{Error, Headers, Method, Result}; pub struct Cors { credentials: bool, max_age: Option, - origins: Vec, + origin: Option, methods: Vec, allowed_headers: Vec, exposed_headers: Vec, @@ -17,7 +17,7 @@ impl Default for Cors { Self { credentials: false, max_age: None, - origins: vec![], + origin: None, methods: vec![], allowed_headers: vec![], exposed_headers: vec![], @@ -44,11 +44,18 @@ impl Cors { } /// Configures which origins are allowed for cors. - pub fn with_origins, V: IntoIterator>(mut self, origins: V) -> Self { - self.origins = origins + /// The actual request origin is also required. + pub fn with_origins, S2: AsRef, V: IntoIterator>( + mut self, + origins: V, + req_origin: S2, + ) -> Self { + let req_origin_str = req_origin.as_ref(); + self.origin = origins .into_iter() .map(|item| item.into()) - .collect::>(); + .filter(|s| s == req_origin_str) + .next(); self } @@ -90,11 +97,8 @@ impl Cors { if let Some(ref max_age) = self.max_age { headers.set("Access-Control-Max-Age", format!("{max_age}").as_str())?; } - if !self.origins.is_empty() { - headers.set( - "Access-Control-Allow-Origin", - concat_vec_to_string(self.origins.as_slice())?.as_str(), - )?; + if let Some(origin) = &self.origin { + headers.set("Access-Control-Allow-Origin", origin)?; } if !self.methods.is_empty() { headers.set(