|
| 1 | +use axum::http::Method; |
| 2 | +use http::HeaderMap; |
| 3 | +use http::HeaderValue; |
| 4 | +use http::header; |
| 5 | +use std::time::Duration; |
| 6 | +use tower_http::cors::{AllowOrigin, CorsLayer}; |
| 7 | + |
| 8 | +const CORS_MAX_AGE: Duration = Duration::from_secs(3600); |
| 9 | +const S3_ALLOWED_METHODS: &str = "GET,HEAD,PUT,POST,DELETE,OPTIONS"; |
| 10 | +const S3_DEFAULT_ALLOWED_HEADERS: &str = "authorization,content-type,content-md5,range,\ |
| 11 | + x-amz-content-sha256,x-amz-date,x-amz-security-token,x-amz-user-agent"; |
| 12 | +const S3_EXPOSED_HEADERS: &str = "etag,content-range,accept-ranges,content-length,last-modified,\ |
| 13 | + x-amz-request-id,x-amz-version-id,x-amz-delete-marker,aruna-source-content-type,\ |
| 14 | + aruna-source-etag,aruna-source-last-modified,aruna-last-refresh"; |
| 15 | + |
| 16 | +/// Allowed cross-origin request origins, shared by the REST and S3 interfaces. |
| 17 | +/// An empty configuration denies all cross-origin access (no CORS headers are |
| 18 | +/// emitted); a literal `*` entry allows every origin. |
| 19 | +#[derive(Clone, Debug, Default)] |
| 20 | +pub struct CorsConfig { |
| 21 | + allowed_origins: Vec<String>, |
| 22 | + allow_any: bool, |
| 23 | +} |
| 24 | + |
| 25 | +impl CorsConfig { |
| 26 | + pub fn new(origins: impl IntoIterator<Item = String>) -> Self { |
| 27 | + let mut allowed_origins = Vec::new(); |
| 28 | + let mut allow_any = false; |
| 29 | + for origin in origins { |
| 30 | + let origin = origin.trim().trim_end_matches('/'); |
| 31 | + if origin.is_empty() { |
| 32 | + continue; |
| 33 | + } |
| 34 | + if origin == "*" { |
| 35 | + allow_any = true; |
| 36 | + } else { |
| 37 | + allowed_origins.push(origin.to_string()); |
| 38 | + } |
| 39 | + } |
| 40 | + Self { |
| 41 | + allowed_origins, |
| 42 | + allow_any, |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + pub fn is_enabled(&self) -> bool { |
| 47 | + self.allow_any || !self.allowed_origins.is_empty() |
| 48 | + } |
| 49 | + |
| 50 | + pub fn allows(&self, origin: &HeaderValue) -> bool { |
| 51 | + if self.allow_any { |
| 52 | + return true; |
| 53 | + } |
| 54 | + origin |
| 55 | + .to_str() |
| 56 | + .map(|origin| { |
| 57 | + self.allowed_origins |
| 58 | + .iter() |
| 59 | + .any(|allowed| allowed == origin.trim_end_matches('/')) |
| 60 | + }) |
| 61 | + .unwrap_or(false) |
| 62 | + } |
| 63 | + |
| 64 | + pub fn rest_layer(&self) -> Option<CorsLayer> { |
| 65 | + if !self.is_enabled() { |
| 66 | + return None; |
| 67 | + } |
| 68 | + let allow_origin = if self.allow_any { |
| 69 | + AllowOrigin::any() |
| 70 | + } else { |
| 71 | + AllowOrigin::list( |
| 72 | + self.allowed_origins |
| 73 | + .iter() |
| 74 | + .filter_map(|origin| origin.parse().ok()), |
| 75 | + ) |
| 76 | + }; |
| 77 | + Some( |
| 78 | + CorsLayer::new() |
| 79 | + .allow_origin(allow_origin) |
| 80 | + .allow_methods([ |
| 81 | + Method::GET, |
| 82 | + Method::POST, |
| 83 | + Method::PUT, |
| 84 | + Method::PATCH, |
| 85 | + Method::DELETE, |
| 86 | + Method::HEAD, |
| 87 | + Method::OPTIONS, |
| 88 | + ]) |
| 89 | + .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]) |
| 90 | + .max_age(CORS_MAX_AGE), |
| 91 | + ) |
| 92 | + } |
| 93 | + |
| 94 | + fn allow_origin_value(&self, origin: &HeaderValue) -> HeaderValue { |
| 95 | + if self.allow_any { |
| 96 | + HeaderValue::from_static("*") |
| 97 | + } else { |
| 98 | + origin.clone() |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + /// Headers for an S3 preflight response. Returns `None` when the origin is |
| 103 | + /// not allowed; the preflight is then answered without CORS headers. |
| 104 | + pub fn s3_preflight_headers( |
| 105 | + &self, |
| 106 | + origin: &HeaderValue, |
| 107 | + requested_headers: Option<&HeaderValue>, |
| 108 | + ) -> Option<HeaderMap> { |
| 109 | + if !self.allows(origin) { |
| 110 | + return None; |
| 111 | + } |
| 112 | + let mut headers = HeaderMap::new(); |
| 113 | + headers.insert( |
| 114 | + header::ACCESS_CONTROL_ALLOW_ORIGIN, |
| 115 | + self.allow_origin_value(origin), |
| 116 | + ); |
| 117 | + headers.insert( |
| 118 | + header::ACCESS_CONTROL_ALLOW_METHODS, |
| 119 | + HeaderValue::from_static(S3_ALLOWED_METHODS), |
| 120 | + ); |
| 121 | + headers.insert( |
| 122 | + header::ACCESS_CONTROL_ALLOW_HEADERS, |
| 123 | + requested_headers |
| 124 | + .cloned() |
| 125 | + .unwrap_or_else(|| HeaderValue::from_static(S3_DEFAULT_ALLOWED_HEADERS)), |
| 126 | + ); |
| 127 | + headers.insert( |
| 128 | + header::ACCESS_CONTROL_MAX_AGE, |
| 129 | + HeaderValue::from(CORS_MAX_AGE.as_secs()), |
| 130 | + ); |
| 131 | + headers.insert(header::VARY, HeaderValue::from_static("origin")); |
| 132 | + Some(headers) |
| 133 | + } |
| 134 | + |
| 135 | + /// Adds CORS headers to a normal (non-preflight) S3 response when the |
| 136 | + /// request origin is allowed. |
| 137 | + pub fn apply_s3_response_headers(&self, origin: Option<&HeaderValue>, headers: &mut HeaderMap) { |
| 138 | + let Some(origin) = origin else { |
| 139 | + return; |
| 140 | + }; |
| 141 | + if !self.allows(origin) { |
| 142 | + return; |
| 143 | + } |
| 144 | + headers.insert( |
| 145 | + header::ACCESS_CONTROL_ALLOW_ORIGIN, |
| 146 | + self.allow_origin_value(origin), |
| 147 | + ); |
| 148 | + headers.insert( |
| 149 | + header::ACCESS_CONTROL_EXPOSE_HEADERS, |
| 150 | + HeaderValue::from_static(S3_EXPOSED_HEADERS), |
| 151 | + ); |
| 152 | + headers.append(header::VARY, HeaderValue::from_static("origin")); |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +#[cfg(test)] |
| 157 | +mod tests { |
| 158 | + use super::*; |
| 159 | + |
| 160 | + #[test] |
| 161 | + fn empty_config_denies_everything() { |
| 162 | + let config = CorsConfig::default(); |
| 163 | + assert!(!config.is_enabled()); |
| 164 | + assert!(!config.allows(&HeaderValue::from_static("http://portal.test"))); |
| 165 | + assert!(config.rest_layer().is_none()); |
| 166 | + assert!( |
| 167 | + config |
| 168 | + .s3_preflight_headers(&HeaderValue::from_static("http://portal.test"), None) |
| 169 | + .is_none() |
| 170 | + ); |
| 171 | + let mut headers = HeaderMap::new(); |
| 172 | + config.apply_s3_response_headers( |
| 173 | + Some(&HeaderValue::from_static("http://portal.test")), |
| 174 | + &mut headers, |
| 175 | + ); |
| 176 | + assert!(headers.is_empty()); |
| 177 | + } |
| 178 | + |
| 179 | + #[test] |
| 180 | + fn listed_origin_is_allowed_and_reflected() { |
| 181 | + let config = CorsConfig::new(vec!["http://portal.test".to_string()]); |
| 182 | + let origin = HeaderValue::from_static("http://portal.test"); |
| 183 | + assert!(config.allows(&origin)); |
| 184 | + assert!(!config.allows(&HeaderValue::from_static("http://evil.test"))); |
| 185 | + |
| 186 | + let headers = config.s3_preflight_headers(&origin, None).unwrap(); |
| 187 | + assert_eq!( |
| 188 | + headers.get(header::ACCESS_CONTROL_ALLOW_ORIGIN).unwrap(), |
| 189 | + &origin |
| 190 | + ); |
| 191 | + |
| 192 | + let mut response_headers = HeaderMap::new(); |
| 193 | + config.apply_s3_response_headers(Some(&origin), &mut response_headers); |
| 194 | + assert_eq!( |
| 195 | + response_headers |
| 196 | + .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) |
| 197 | + .unwrap(), |
| 198 | + &origin |
| 199 | + ); |
| 200 | + assert!( |
| 201 | + response_headers |
| 202 | + .get(header::ACCESS_CONTROL_EXPOSE_HEADERS) |
| 203 | + .unwrap() |
| 204 | + .to_str() |
| 205 | + .unwrap() |
| 206 | + .contains("etag") |
| 207 | + ); |
| 208 | + } |
| 209 | + |
| 210 | + #[test] |
| 211 | + fn wildcard_allows_any_origin() { |
| 212 | + let config = CorsConfig::new(vec!["*".to_string()]); |
| 213 | + let origin = HeaderValue::from_static("http://anywhere.test"); |
| 214 | + assert!(config.allows(&origin)); |
| 215 | + let headers = config.s3_preflight_headers(&origin, None).unwrap(); |
| 216 | + assert_eq!( |
| 217 | + headers.get(header::ACCESS_CONTROL_ALLOW_ORIGIN).unwrap(), |
| 218 | + "*" |
| 219 | + ); |
| 220 | + } |
| 221 | + |
| 222 | + #[test] |
| 223 | + fn preflight_echoes_requested_headers() { |
| 224 | + let config = CorsConfig::new(vec!["http://portal.test".to_string()]); |
| 225 | + let requested = HeaderValue::from_static("authorization,x-amz-meta-custom"); |
| 226 | + let headers = config |
| 227 | + .s3_preflight_headers( |
| 228 | + &HeaderValue::from_static("http://portal.test"), |
| 229 | + Some(&requested), |
| 230 | + ) |
| 231 | + .unwrap(); |
| 232 | + assert_eq!( |
| 233 | + headers.get(header::ACCESS_CONTROL_ALLOW_HEADERS).unwrap(), |
| 234 | + &requested |
| 235 | + ); |
| 236 | + } |
| 237 | +} |
0 commit comments