1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use std::collections::HashSet;
use crate::{Error, http::{Request, Response, Method}};
use url::{Url, Origin};
/// Handy enum to deal with the * wildcard
enum CorsOriginBuilder {
None,
All,
List(HashSet<String>)
}
impl CorsOriginBuilder {
fn build(self) -> Result<CorsOrigin, Error> {
match self {
CorsOriginBuilder::None => Ok(CorsOrigin::None),
CorsOriginBuilder::All => Ok(CorsOrigin::All),
CorsOriginBuilder::List(origins) => {
Ok(CorsOrigin::List(origins.into_iter().map(|origin| {
Url::parse(&origin)
}).collect::<Result<Vec<_>,_>>().map_err(Error::Url)?
.into_iter().map(|url| url.origin()).collect()))
}
}
}
}
enum CorsOrigin {
None,
All,
List(HashSet<Origin>)
}
/// Cors builder structure
pub struct CorsBuilder {
origins: CorsOriginBuilder,
max_age: Option<usize>,
methods: Option<HashSet<Method>>,
headers: Option<HashSet<String>>
}
impl CorsBuilder {
/// Creates a [CorsBuilder](CorsBuilder) instance
pub fn new() -> CorsBuilder {
CorsBuilder {
origins: CorsOriginBuilder::None,
max_age: None,
methods: None,
headers: None
}
}
/// Adds an allowed origin
///
/// By default, if this method is never called, not a single response will be different from "forbidden"
pub fn origin<A: Into<String>>(mut self, origin: A) -> Self {
let origin: String = origin.into();
match &mut self.origins {
CorsOriginBuilder::All => (),
CorsOriginBuilder::List(origins) => {
if origin == "*" {
self.origins = CorsOriginBuilder::All;
} else {
origins.insert(origin);
}
},
CorsOriginBuilder::None => {
if origin == "*" {
self.origins = CorsOriginBuilder::All;
} else {
self.origins = CorsOriginBuilder::List([origin].into_iter().collect());
}
}
}
self
}
/// Adds an allowed origin
pub fn max_age(mut self, seconds: usize) -> Self {
self.max_age = Some(seconds);
self
}
/// Adds an allowed method to be used for preflight requests
///
/// By default, if no methods are provided, cataclysm will use the callbacks and their methods to construct a response
pub fn allowed_method(mut self, method: Method) -> Self {
self.methods.get_or_insert_with(|| HashSet::new()).insert(method);
self
}
/// Adds an allowed header to be used
///
/// By default, if no header is provided, cataclysm will mirror the headers listed in the `Access-Control-Request-Headers` field. Please use with caution.
pub fn allowed_header<A: Into<String>>(mut self, header: A) -> Self {
self.headers.get_or_insert_with(|| HashSet::new()).insert(header.into());
self
}
/// Builds de cors object
pub fn build(self) -> Result<Cors, Error> {
Ok(Cors {
origins: self.origins.build()?,
max_age: self.max_age,
methods: self.methods,
headers: self.headers
})
}
}
/// Inner cors structure
///
/// This structure cannot be created directly. Use the [CorsBuilder](CorsBuilder) structure.
pub struct Cors {
origins: CorsOrigin,
max_age: Option<usize>,
methods: Option<HashSet<Method>>,
headers: Option<HashSet<String>>
}
impl Cors {
pub(crate) fn apply(&self, request: &Request, response: &mut Response) {
let origin_source = request.headers.get("Origin").map(|o| o.get(0)).flatten().or_else(||
request.headers.get("origin").map(|o| o.get(0)).flatten()
);
let acao = match &self.origins {
CorsOrigin::None => None,
CorsOrigin::All => {
if let Some(origin) = origin_source {
Some(origin.to_string())
} else {
Some("*".to_string())
}
},
CorsOrigin::List(origins) => {
if let Some(origin) = origin_source {
match Url::parse(&origin) {
Ok(url) => {
origins.get(&url.origin()).map(|found_origin| found_origin.ascii_serialization())
},
Err(_e) => {
#[cfg(feature = "full_log")]
log::debug!("{}, when parsing {}", _e, origin);
None
}
}
} else {
#[cfg(feature = "full_log")]
log::debug!("could not find origin header in preflight request");
None
}
}
};
if let Some(acao) = acao {
response.headers.entry("Access-Control-Allow-Origin".to_string()).or_insert_with(|| Vec::new()).push(acao);
if let Some(max_age) = self.max_age {
response.headers.entry("Access-Control-Max-Age".to_string()).or_insert_with(|| Vec::new()).push(format!("{}", max_age));
}
}
}
/// Computed the preflight response
pub(crate) fn preflight(&self, request: &Request, methods: &HashSet<Method>) -> Response {
let origin_source = request.headers.get("Origin").map(|o| o.get(0)).flatten().or_else(||
request.headers.get("origin").map(|o| o.get(0)).flatten()
);
let acao = match &self.origins {
CorsOrigin::None => None,
CorsOrigin::All => {
if let Some(origin) = origin_source {
Some(origin.to_string())
} else {
Some("*".to_string())
}
},
CorsOrigin::List(origins) => {
if let Some(origin) = origin_source {
match Url::parse(&origin) {
Ok(url) => {
origins.get(&url.origin()).map(|found_origin| found_origin.ascii_serialization())
},
Err(_e) => {
#[cfg(feature = "full_log")]
log::debug!("{}, when parsing {}", _e, origin);
None
}
}
} else {
#[cfg(feature = "full_log")]
log::debug!("could not find origin header in preflight request");
None
}
}
};
if let Some(acao) = acao {
// Found allowed origin
let mut response = Response::no_content();
let methods = match request.headers.get("Access-Control-Request-Method") {
Some(_) => {
if let Some(override_methods) = &self.methods {
override_methods.iter()
} else {
methods.iter()
}.map(|m| m.to_str()).collect::<Vec<_>>().join(", ")
},
None => {
#[cfg(feature = "full_log")]
log::debug!("the Access-Control-Request-Method field was not found");
return Response::forbidden()
}
};
let headers = if let Some(override_headers) = &self.headers {
override_headers.iter().cloned().collect::<Vec<_>>().join(", ")
} else {
match request.headers.get("Access-Control-Request-Headers").map(|acrh| acrh.get(0)).flatten() {
Some(headers) => headers.clone(),
None => {
#[cfg(feature = "full_log")]
log::debug!("the Access-Control-Request-Headers field was not found");
return Response::forbidden()
}
}
};
#[cfg(feature = "full_log")]
log::debug!("the preflight request for '{}' is successful, with methods [{}] and headers [{}]", acao, methods, headers);
response = response.header(
"Access-Control-Allow-Origin".to_string(),
acao
);
response = response.header(
"Access-Control-Allow-Methods".to_string(),
methods
);
response = response.header(
"Access-Control-Allow-Headers".to_string(),
headers
);
if let Some(max_age) = self.max_age {
response = response.header(
"Access-Control-Max-Age".to_string(),
format!("{}", max_age)
);
}
response
} else {
Response::forbidden()
}
/*
if let Some(origin) = request.headers.get("Origin").or_else(|| request.headers.get("origin")) {
match Url::parse(&origin) {
Ok(url) => {
let acao = match &self.origins {
CorsOrigin::None => None,
CorsOrigin::All => Some("*".to_string()),
CorsOrigin::List(origins) => {
origins.get(&url.origin()).map(|found_origin| found_origin.ascii_serialization())
}
};
if let Some(acao) = acao {
// Found allowed origin
let mut response = Response::no_content();
// It should reply
response.headers.insert(
"Access-Control-Allow-Origin".to_string(),
acao
);
let methods = if let Some(override_methods) = &self.methods {
override_methods.iter()
} else {
methods.iter()
}.map(|m| m.to_str()).collect::<Vec<_>>().join(", ");
response.headers.insert(
"Access-Control-Allow-Methods".to_string(),
methods
);
if let Some(max_age) = self.max_age {
response.headers.insert(
"Access-Control-Max-Age".to_string(),
format!("{}", max_age)
);
}
return response;
}
},
Err(_e) => {
#[cfg(feature = "full_log")]
log::debug!("{}, when parsing {}", _e, origin);
}
}
}
Response::forbidden()
*/
}
}