oxedyne/fe2o3/fe2o3_steel/tests/response_headers.rs
7.0 KiB, 7 runs
created by r1870400018:72035, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! A vhost's `response_headers` reach every response it sends, a static file, a 404 and a |
| 2 | //! redirect alike, each as the one field of its name: Steel's baseline `Referrer-Policy` is |
| 3 | //! replaced, not joined, since a browser given two takes the laxer. A vhost that sets none still |
| 4 | //! gets the baseline. The key is read from config with its names lower-cased, and a name that is |
| 5 | //! not a token, a value with a line break, or a field that frames the message is refused. |
| 6 | //! |
| 7 | //! The server's HSTS, like the baseline, fills only an empty field: a handler that sends its own |
| 8 | //! `Strict-Transport-Security` is not given a second one beside it. |
| 9 | //! |
| 10 | //! `ServerConfig::binds_loopback_only` says whether every listener a config opens is loopback. |
| 11 | //! |
| 12 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 13 | //! Anthropic Claude |
| 14 | |
| 15 | mod vhost_rig; |
| 16 | |
| 17 | use vhost_rig::{ |
| 18 | Reply, |
| 19 | Rig, |
| 20 | Scratch, |
| 21 | Site, |
| 22 | }; |
| 23 | |
| 24 | use oxedyne_fe2o3_core::prelude::*; |
| 25 | use oxedyne_fe2o3_jdat::prelude::*; |
| 26 | use oxedyne_fe2o3_net::http::{ |
| 27 | fields::{ |
| 28 | HeaderFieldValue, |
| 29 | HeaderFields, |
| 30 | HeaderName, |
| 31 | }, |
| 32 | header::HttpMethod, |
| 33 | loc::HttpLocator, |
| 34 | msg::HttpMessage, |
| 35 | status::HttpStatus, |
| 36 | }; |
| 37 | use oxedyne_fe2o3_steel::srv::{ |
| 38 | api::ApiHandler, |
| 39 | cfg::{ |
| 40 | ApiRoute, |
| 41 | ServerConfig, |
| 42 | VhostConfig, |
| 43 | }, |
| 44 | }; |
| 45 | |
| 46 | use std::{ |
| 47 | future::Future, |
| 48 | pin::Pin, |
| 49 | sync::Arc, |
| 50 | }; |
| 51 | |
| 52 | use tokio_rustls::rustls::ClientConfig; |
| 53 | |
| 54 | const SET: &str = "private.test"; |
| 55 | const BARE: &str = "plain.test"; |
| 56 | |
| 57 | fn count(r: &Reply, name: &str) -> usize { |
| 58 | let want = fmt!("{}:", name); |
| 59 | r.head.lines().skip(1).filter(|l| l.to_lowercase().starts_with(&want)).count() |
| 60 | } |
| 61 | |
| 62 | #[test] |
| 63 | fn every_response_carries_the_vhost_headers_once() -> Outcome<()> { |
| 64 | let web = res!(Scratch::new("resp_headers")); |
| 65 | res!(web.put("index.html", "<p>home</p>")); |
| 66 | res!(web.put("a.css", "p{}")); |
| 67 | res!(web.dir("sub")); |
| 68 | let mut set = Site::new(SET, &web.0); |
| 69 | set.response_headers = vec![ |
| 70 | (fmt!("referrer-policy"), fmt!("no-referrer")), |
| 71 | (fmt!("x-robots-tag"), fmt!("noindex")), |
| 72 | (fmt!("content-security-policy"), fmt!("default-src 'self'")), |
| 73 | ]; |
| 74 | let bare = Site::new(BARE, &web.0); |
| 75 | let rig = res!(Rig::new(vec![set, bare])); |
| 76 | let runtime = res!(vhost_rig::runtime()); |
| 77 | runtime.block_on(async { |
| 78 | for path in ["/", "/index.html", "/a.css", "/missing.html", "/sub"] { |
| 79 | let r = res!(rig.fetch(SET, "GET", path, &[], "").await); |
| 80 | assert_eq!(r.field("referrer-policy").as_deref(), Some("no-referrer"), |
| 81 | "GET {}: {:?}", path, r); |
| 82 | assert_eq!(count(&r, "referrer-policy"), 1, "GET {} doubled the field: {:?}", path, r); |
| 83 | assert_eq!(r.field("x-robots-tag").as_deref(), Some("noindex"), "GET {}: {:?}", path, r); |
| 84 | assert_eq!(r.field("content-security-policy").as_deref(), Some("default-src 'self'"), |
| 85 | "GET {}: {:?}", path, r); |
| 86 | // The rest of the baseline is untouched. |
| 87 | assert_eq!(r.field("x-content-type-options").as_deref(), Some("nosniff"), |
| 88 | "GET {}: {:?}", path, r); |
| 89 | } |
| 90 | let r = res!(rig.fetch(BARE, "GET", "/index.html", &[], "").await); |
| 91 | assert_eq!(r.field("referrer-policy").as_deref(), Some("strict-origin-when-cross-origin"), |
| 92 | "{:?}", r); |
| 93 | assert_eq!(r.field("x-robots-tag"), None, "{:?}", r); |
| 94 | Ok(()) |
| 95 | }) |
| 96 | } |
| 97 | |
| 98 | const OWN_HSTS: &str = "max-age=60"; |
| 99 | |
| 100 | /// Answers with a policy of its own. |
| 101 | struct OwnHsts; |
| 102 | |
| 103 | impl ApiHandler for OwnHsts { |
| 104 | fn handle<'a>( |
| 105 | &'a self, |
| 106 | _route: &'a ApiRoute, |
| 107 | _method: HttpMethod, |
| 108 | _loc: &'a HttpLocator, |
| 109 | _body: &'a [u8], |
| 110 | _req_headers: &'a HeaderFields, |
| 111 | _tls_client: &'a Option<Arc<ClientConfig>>, |
| 112 | _id: &'a str, |
| 113 | ) -> Pin<Box<dyn Future<Output = Outcome<HttpMessage>> + Send + 'a>> { |
| 114 | Box::pin(async move { |
| 115 | let mut msg = HttpMessage::respond_with_text(HttpStatus::OK, "own"); |
| 116 | msg.header.fields.insert( |
| 117 | HeaderName::StrictTransportSecurity, |
| 118 | HeaderFieldValue::Generic(OWN_HSTS.to_string()), |
| 119 | None, |
| 120 | ); |
| 121 | Ok(msg) |
| 122 | }) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | #[test] |
| 127 | fn a_handlers_own_hsts_is_not_doubled() -> Outcome<()> { |
| 128 | let web = res!(Scratch::new("resp_hsts")); |
| 129 | res!(web.put("index.html", "<p>home</p>")); |
| 130 | let mut site = Site::new(SET, &web.0); |
| 131 | site.api_routes = vec![ApiRoute { |
| 132 | path: fmt!("/api/own"), |
| 133 | upstream_host: None, |
| 134 | upstream_port: None, |
| 135 | upstream_path: None, |
| 136 | upstream_tls: false, |
| 137 | headers: Vec::new(), |
| 138 | handler: Some(fmt!("own_hsts")), |
| 139 | config: Vec::new(), |
| 140 | }]; |
| 141 | site.handlers.register("own_hsts", OwnHsts); |
| 142 | let mut cfg = ServerConfig::default(); |
| 143 | cfg.hsts_max_age_secs = 31_536_000; |
| 144 | let rig = res!(Rig::with_config(vec![site], cfg)); |
| 145 | let runtime = res!(vhost_rig::runtime()); |
| 146 | runtime.block_on(async { |
| 147 | let r = res!(rig.fetch(SET, "GET", "/api/own", &[], "").await); |
| 148 | assert_eq!(r.body, "own", "{:?}", r); |
| 149 | assert_eq!(count(&r, "strict-transport-security"), 1, "{:?}", r); |
| 150 | assert_eq!(r.field("strict-transport-security").as_deref(), Some(OWN_HSTS), "{:?}", r); |
| 151 | // A response that sets none is given the server's, once. |
| 152 | let r = res!(rig.fetch(SET, "GET", "/index.html", &[], "").await); |
| 153 | assert_eq!(count(&r, "strict-transport-security"), 1, "{:?}", r); |
| 154 | assert_eq!(r.field("strict-transport-security").as_deref(), |
| 155 | Some("max-age=31536000; includeSubDomains"), "{:?}", r); |
| 156 | Ok(()) |
| 157 | }) |
| 158 | } |
| 159 | |
| 160 | fn vhost(headers: &str) -> Outcome<VhostConfig> { |
| 161 | let text = fmt!("{{\"hostnames\": [\"a.test\"], \"response_headers\": {}}}", headers); |
| 162 | let dat = res!(Dat::decode_string(&text)); |
| 163 | match dat { |
| 164 | Dat::Map(m) => VhostConfig::from_datmap(&m), |
| 165 | _ => Err(err!("Not a map."; Invalid, Input)), |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | #[test] |
| 170 | fn the_key_is_read_and_checked() -> Outcome<()> { |
| 171 | let v = res!(vhost("{\"X-Robots-Tag\": \"noindex\"}")); |
| 172 | assert_eq!(v.response_headers, vec![(fmt!("x-robots-tag"), fmt!("noindex"))]); |
| 173 | assert!(res!(vhost("{}")).response_headers.is_empty()); |
| 174 | for bad in [ |
| 175 | "{\"bad name\": \"x\"}", |
| 176 | "{\"x-a\": \"one\\r\\nSet-Cookie: s=1\"}", |
| 177 | "{\"Content-Length\": \"3\"}", |
| 178 | "{\"set-cookie\": \"s=1\"}", |
| 179 | "{\"x-a\": 1}", |
| 180 | "[\"x-a\"]", |
| 181 | ] { |
| 182 | assert!(vhost(bad).is_err(), "{} must be refused", bad); |
| 183 | } |
| 184 | Ok(()) |
| 185 | } |
| 186 | |
| 187 | #[test] |
| 188 | fn loopback_only_is_the_server_address() -> Outcome<()> { |
| 189 | let mut cfg = ServerConfig::default(); |
| 190 | for (addr, want) in [("127.0.0.1", true), ("::1", true), ("0.0.0.0", false), |
| 191 | ("192.168.1.2", false)] |
| 192 | { |
| 193 | cfg.server_address = addr.to_string(); |
| 194 | assert_eq!(res!(cfg.binds_loopback_only()), want, "{}", addr); |
| 195 | } |
| 196 | cfg.server_address = fmt!("localhost"); |
| 197 | assert!(cfg.binds_loopback_only().is_err()); |
| 198 | Ok(()) |
| 199 | } |