Skip to main content

multistore_cf_workers/
cors.rs

1//! CORS header utilities for browser-accessible S3 proxies.
2
3use http::HeaderMap;
4
5/// Set permissive CORS headers suitable for public, browser-accessible
6/// S3-compatible read-only proxies.
7///
8/// Sets:
9/// - `access-control-allow-origin: *`
10/// - `access-control-allow-methods: GET, HEAD, OPTIONS`
11/// - `access-control-allow-headers: *`
12/// - `access-control-expose-headers: *`
13///
14/// Existing CORS headers in the map are overwritten.
15pub fn add_cors_headers(headers: &mut HeaderMap) {
16    let pairs = [
17        ("access-control-allow-origin", "*"),
18        ("access-control-allow-methods", "GET, HEAD, OPTIONS"),
19        ("access-control-allow-headers", "*"),
20        ("access-control-expose-headers", "*"),
21    ];
22    for (name, value) in pairs {
23        if let Ok(v) = value.parse() {
24            headers.insert(name, v);
25        }
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn sets_all_four_cors_headers() {
35        let mut h = HeaderMap::new();
36        add_cors_headers(&mut h);
37        assert_eq!(h.get("access-control-allow-origin").unwrap(), "*");
38        assert_eq!(
39            h.get("access-control-allow-methods").unwrap(),
40            "GET, HEAD, OPTIONS"
41        );
42        assert_eq!(h.get("access-control-allow-headers").unwrap(), "*");
43        assert_eq!(h.get("access-control-expose-headers").unwrap(), "*");
44    }
45
46    #[test]
47    fn overwrites_existing() {
48        let mut h = HeaderMap::new();
49        h.insert(
50            "access-control-allow-origin",
51            "https://example.com".parse().unwrap(),
52        );
53        add_cors_headers(&mut h);
54        assert_eq!(h.get("access-control-allow-origin").unwrap(), "*");
55    }
56}