oxedyne/fe2o3/fe2o3_steel/tests/handler_ctx.rs
11.8 KiB, 6 runs
created by r1870400018:71570, 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 | //! `ApiHandler::handle_ctx` and the loopback plain-HTTP listener, driven through `handle_https` |
| 2 | //! against a real socket. |
| 3 | //! |
| 4 | //! A probe handler owns the prefix route `/edit/*` and answers with what its `HandlerCtx` held: |
| 5 | //! the method, the peer, and whether the vhost's database was there. It declines a path ending |
| 6 | //! `.html`, which must then come from `www/`. The database map is the one Steel fills on unseal, |
| 7 | //! shared with the handler's `VhostDbRef`, so emptying and filling it here is what sealing and |
| 8 | //! unsealing do; the database put in it is opened but never started, since the handler only looks |
| 9 | //! for it. Every request goes through `serve_loopback`, which is also the test of that listener: |
| 10 | //! two vhosts picked by the Host header, no HSTS though the config asks for it, and a bind to an |
| 11 | //! address that is not loopback refused. |
| 12 | //! |
| 13 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 14 | //! Anthropic Claude |
| 15 | |
| 16 | use oxedyne_fe2o3_steel::{ |
| 17 | app::{ |
| 18 | https::{ |
| 19 | AppWebHandler, |
| 20 | VhostDbRef, |
| 21 | }, |
| 22 | server::VhostDb, |
| 23 | }, |
| 24 | srv::{ |
| 25 | api::{ |
| 26 | ApiHandler, |
| 27 | ApiHandlerRegistry, |
| 28 | HandlerCtx, |
| 29 | }, |
| 30 | cfg::{ |
| 31 | ApiRoute, |
| 32 | ServerConfig, |
| 33 | }, |
| 34 | context::{ |
| 35 | self, |
| 36 | Protocol, |
| 37 | ServerContext, |
| 38 | VhostDbs, |
| 39 | VhostRuntime, |
| 40 | }, |
| 41 | id, |
| 42 | loopback, |
| 43 | webhook::WebhookRegistry, |
| 44 | ws::{ |
| 45 | handler::AppWebSocketHandler, |
| 46 | syntax::WebSocketSyntax, |
| 47 | }, |
| 48 | }, |
| 49 | }; |
| 50 | |
| 51 | use oxedyne_fe2o3_core::{ |
| 52 | file::OsPath, |
| 53 | path::NormalPath, |
| 54 | prelude::*, |
| 55 | }; |
| 56 | use oxedyne_fe2o3_jdat::version::SemVer; |
| 57 | use oxedyne_fe2o3_net::http::{ |
| 58 | fields::HeaderFields, |
| 59 | header::HttpMethod, |
| 60 | loc::HttpLocator, |
| 61 | msg::HttpMessage, |
| 62 | status::HttpStatus, |
| 63 | }; |
| 64 | |
| 65 | use std::{ |
| 66 | collections::HashMap, |
| 67 | future::Future, |
| 68 | net::SocketAddr, |
| 69 | path::PathBuf, |
| 70 | pin::Pin, |
| 71 | sync::{ |
| 72 | atomic::AtomicUsize, |
| 73 | Arc, |
| 74 | RwLock, |
| 75 | }, |
| 76 | }; |
| 77 | |
| 78 | use tokio::{ |
| 79 | io::{ |
| 80 | AsyncReadExt, |
| 81 | AsyncWriteExt, |
| 82 | }, |
| 83 | net::TcpStream, |
| 84 | }; |
| 85 | use tokio_rustls::rustls::ClientConfig; |
| 86 | |
| 87 | const HOST: &str = "edit.test"; |
| 88 | const OTHER: &str = "other.test"; |
| 89 | |
| 90 | /// Answers with what its context held, and declines a `.html` path. |
| 91 | struct Probe; |
| 92 | |
| 93 | impl ApiHandler for Probe { |
| 94 | fn handle<'a>( |
| 95 | &'a self, |
| 96 | _route: &'a ApiRoute, |
| 97 | _method: HttpMethod, |
| 98 | _loc: &'a HttpLocator, |
| 99 | _body: &'a [u8], |
| 100 | _req_headers: &'a HeaderFields, |
| 101 | _tls_client: &'a Option<Arc<ClientConfig>>, |
| 102 | _id: &'a str, |
| 103 | ) -> Pin<Box<dyn Future<Output = Outcome<HttpMessage>> + Send + 'a>> { |
| 104 | Box::pin(async move { |
| 105 | Ok(HttpMessage::respond_with_text(HttpStatus::InternalServerError, "handle, not handle_ctx")) |
| 106 | }) |
| 107 | } |
| 108 | |
| 109 | fn handle_ctx<'a>( |
| 110 | &'a self, |
| 111 | ctx: HandlerCtx<'a>, |
| 112 | ) -> Pin<Box<dyn Future<Output = Outcome<Option<HttpMessage>>> + Send + 'a>> { |
| 113 | Box::pin(async move { |
| 114 | let path = ctx.loc.path.as_string().to_string(); |
| 115 | if path.ends_with(".html") { |
| 116 | return Ok(None); |
| 117 | } |
| 118 | Ok(Some(HttpMessage::respond_with_text(HttpStatus::OK, &fmt!( |
| 119 | "probe {} {} db={} peer={} body={}", |
| 120 | ctx.method, path, ctx.db.is_some(), ctx.peer.ip(), |
| 121 | String::from_utf8_lossy(ctx.body), |
| 122 | )))) |
| 123 | }) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | fn www(dir: &PathBuf, files: &[(&str, &str)]) -> Outcome<()> { |
| 128 | for (rel, text) in files { |
| 129 | let p = dir.join(rel); |
| 130 | if let Some(parent) = p.parent() { |
| 131 | res!(std::fs::create_dir_all(parent), IO, File); |
| 132 | } |
| 133 | res!(std::fs::write(&p, text), IO, File); |
| 134 | } |
| 135 | Ok(()) |
| 136 | } |
| 137 | |
| 138 | #[test] |
| 139 | fn handle_ctx_and_the_loopback_listener() -> Outcome<()> { |
| 140 | let runtime = res!(tokio::runtime::Runtime::new(), Init); |
| 141 | runtime.block_on(async { drive().await }) |
| 142 | } |
| 143 | |
| 144 | async fn drive() -> Outcome<()> { |
| 145 | let base = std::env::temp_dir().join(fmt!("steel_handler_ctx_{}", std::process::id())); |
| 146 | let _ = std::fs::remove_dir_all(&base); |
| 147 | let www_edit = base.join("www_edit"); |
| 148 | let www_other = base.join("www_other"); |
| 149 | res!(www(&www_edit, &[("index.html", "edit index"), ("edit/page.html", "static page")])); |
| 150 | res!(www(&www_other, &[("index.html", "other index")])); |
| 151 | |
| 152 | // The map Steel fills on unseal, shared by the context and the handler. |
| 153 | let dbs: VhostDbs<{ id::UID_LEN }, id::Uid, VhostDb> = Arc::new(RwLock::new(HashMap::new())); |
| 154 | |
| 155 | let mut cfg = ServerConfig::default(); |
| 156 | cfg.hsts_max_age_secs = 31_536_000; |
| 157 | let mut registry = ApiHandlerRegistry::new(); |
| 158 | registry.register("probe", Probe); |
| 159 | let registry = Arc::new(registry); |
| 160 | let route = ApiRoute { |
| 161 | path: fmt!("/edit/*"), |
| 162 | upstream_host: None, |
| 163 | upstream_port: None, |
| 164 | upstream_path: None, |
| 165 | upstream_tls: false, |
| 166 | headers: Vec::new(), |
| 167 | handler: Some(fmt!("probe")), |
| 168 | config: Vec::new(), |
| 169 | }; |
| 170 | let web = |dir: &PathBuf, routes: Vec<ApiRoute>, name: &str| |
| 171 | -> AppWebHandler<HashMap<String, OsPath>> |
| 172 | { |
| 173 | AppWebHandler::new( |
| 174 | cfg.clone(), |
| 175 | dir.clone(), |
| 176 | HashMap::new(), |
| 177 | vec![fmt!("index.html")], |
| 178 | true, |
| 179 | routes, |
| 180 | Vec::new(), |
| 181 | Arc::new(WebhookRegistry::new()), |
| 182 | registry.clone(), |
| 183 | None, |
| 184 | None, |
| 185 | None, |
| 186 | None, |
| 187 | None, |
| 188 | Arc::new(Vec::new()), |
| 189 | ).with_vhost_db(VhostDbRef::new(dbs.clone(), name)) |
| 190 | }; |
| 191 | let vhost = |name: &str, web_handler| -> Outcome<Arc<VhostRuntime<_, _>>> { |
| 192 | Ok(Arc::new(VhostRuntime { |
| 193 | hostnames: vec![name.to_string()], |
| 194 | web_handler, |
| 195 | ws_handler: AppWebSocketHandler::new(None), |
| 196 | ws_syntax: res!(WebSocketSyntax::new("steel_ws", &SemVer::new(0, 1, 0), "Ctx test")), |
| 197 | redirects: Vec::new(), |
| 198 | proxy_routes: Vec::new(), |
| 199 | ws_routes: Vec::new(), |
| 200 | term_manager: None, |
| 201 | uses_sessions: false, |
| 202 | permissions_policy: None, |
| 203 | tiles: None, |
| 204 | access_log: false, |
| 205 | response_headers: Vec::new(), |
| 206 | path_headers: Vec::new(), |
| 207 | })) |
| 208 | }; |
| 209 | let mut vhosts = HashMap::new(); |
| 210 | vhosts.insert(HOST.to_string(), res!(vhost(HOST, web(&www_edit, vec![route], HOST)))); |
| 211 | vhosts.insert(OTHER.to_string(), res!(vhost(OTHER, web(&www_other, Vec::new(), OTHER)))); |
| 212 | let protocol = Protocol::Web { |
| 213 | vhosts: Arc::new(vhosts), |
| 214 | default_vhost: HOST.to_string(), |
| 215 | dev_mode: true, |
| 216 | }; |
| 217 | let root = std::env::temp_dir().normalise().absolute(); |
| 218 | let context = ServerContext::new(cfg.clone(), root, dbs.clone(), Vec::new(), protocol, |
| 219 | None, None); |
| 220 | |
| 221 | // A bind anywhere but loopback is refused, and a loopback one is served. |
| 222 | for addr in ["0.0.0.0:0", "192.0.2.1:0", "[::]:0"] { |
| 223 | let addr: SocketAddr = res!(addr.parse(), Invalid); |
| 224 | assert!(loopback::bind_loopback(addr).await.is_err(), "{} was bound", addr); |
| 225 | } |
| 226 | let listener = res!(loopback::bind_loopback(res!("127.0.0.1:0".parse(), Invalid)).await); |
| 227 | let addr = res!(listener.local_addr(), Network, Init); |
| 228 | let inflight = Arc::new(AtomicUsize::new(0)); |
| 229 | let server = tokio::spawn(context.clone().serve_loopback(listener, inflight)); |
| 230 | |
| 231 | // One request on a fresh connection: the head, lower cased, and the body. |
| 232 | let fetch = async |host: &str, method: &str, path: &str, body: &str| |
| 233 | -> Outcome<(String, String)> |
| 234 | { |
| 235 | let mut tcp = res!(TcpStream::connect(addr).await, Network, Init); |
| 236 | let request = fmt!("{} {} HTTP/1.1\r\nHost: {}\r\nContent-Length: {}\r\n\ |
| 237 | Connection: close\r\n\r\n{}", method, path, host, body.len(), body); |
| 238 | res!(tcp.write_all(request.as_bytes()).await, Network, Write); |
| 239 | let mut reply = Vec::new(); |
| 240 | let mut chunk = [0u8; 4096]; |
| 241 | loop { |
| 242 | if let Some(i) = reply.windows(4).position(|w| w == b"\r\n\r\n") { |
| 243 | let head = String::from_utf8_lossy(&reply[..i]).to_lowercase(); |
| 244 | let want = head.lines() |
| 245 | .filter_map(|l| l.strip_prefix("content-length:")) |
| 246 | .filter_map(|v| v.trim().parse::<usize>().ok()) |
| 247 | .next() |
| 248 | .unwrap_or(0); |
| 249 | if reply.len() >= i + 4 + want { |
| 250 | break; |
| 251 | } |
| 252 | } |
| 253 | match tcp.read(&mut chunk).await { |
| 254 | Ok(0) | Err(_) => break, |
| 255 | Ok(n) => reply.extend_from_slice(&chunk[..n]), |
| 256 | } |
| 257 | } |
| 258 | let split = match reply.windows(4).position(|w| w == b"\r\n\r\n") { |
| 259 | Some(i) => i, |
| 260 | None => return Err(err!("No complete response to {} {}: {:?}.", method, path, |
| 261 | String::from_utf8_lossy(&reply); Test)), |
| 262 | }; |
| 263 | Ok(( |
| 264 | String::from_utf8_lossy(&reply[..split]).to_lowercase(), |
| 265 | String::from_utf8_lossy(&reply[split + 4..]).to_string(), |
| 266 | )) |
| 267 | }; |
| 268 | |
| 269 | // Sealed: the handler runs with the peer set and no database. |
| 270 | let (head, body) = res!(fetch(HOST, "GET", "/edit/doc", "").await); |
| 271 | assert!(head.starts_with("http/1.1 200"), "{}", head); |
| 272 | assert_eq!(body, "probe GET /edit/doc db=false peer=127.0.0.1 body="); |
| 273 | // Over plain HTTP no HSTS is sent, though the config asks for it. |
| 274 | assert!(!head.contains("strict-transport-security"), "{}", head); |
| 275 | |
| 276 | // A handler that declines a GET leaves the path to www/. |
| 277 | let (head, body) = res!(fetch(HOST, "GET", "/edit/page.html", "").await); |
| 278 | assert!(head.starts_with("http/1.1 200"), "{}", head); |
| 279 | assert_eq!(body, "static page"); |
| 280 | |
| 281 | // Unsealed: the database the map now holds reaches the handler. |
| 282 | let db_dir = base.join("db"); |
| 283 | res!(std::fs::create_dir_all(&db_dir), IO, File); |
| 284 | let db = res!(context::new_db(&db_dir, &[7u8; 32], false)); |
| 285 | { |
| 286 | let mut g = res!(dbs.write().map_err(|_| err!("The db map lock is poisoned."; Test))); |
| 287 | g.insert(HOST.to_string(), (Arc::new(RwLock::new(db)), id::Uid::default())); |
| 288 | } |
| 289 | let (_, body) = res!(fetch(HOST, "GET", "/edit/doc", "").await); |
| 290 | assert_eq!(body, "probe GET /edit/doc db=true peer=127.0.0.1 body="); |
| 291 | |
| 292 | // PUT and DELETE reach the handler route, the body with them. |
| 293 | let (head, body) = res!(fetch(HOST, "PUT", "/edit/doc", "new text").await); |
| 294 | assert!(head.starts_with("http/1.1 200"), "{}", head); |
| 295 | assert_eq!(body, "probe PUT /edit/doc db=true peer=127.0.0.1 body=new text"); |
| 296 | let (_, body) = res!(fetch(HOST, "DELETE", "/edit/a/b", "").await); |
| 297 | assert_eq!(body, "probe DELETE /edit/a/b db=true peer=127.0.0.1 body="); |
| 298 | |
| 299 | // Elsewhere, and for a method no route takes, a 405 that says what is allowed. |
| 300 | for (method, path) in [("PUT", "/index.html"), ("DELETE", "/elsewhere"), ("OPTIONS", "/edit/doc")] { |
| 301 | let (head, _) = res!(fetch(HOST, method, path, "").await); |
| 302 | assert!(head.starts_with("http/1.1 405"), "{} {}: {}", method, path, head); |
| 303 | assert!(head.contains("allow: get, head, post"), "{} {}: {}", method, path, head); |
| 304 | } |
| 305 | |
| 306 | // The Host header picks the vhost on a plain connection. |
| 307 | let (_, body) = res!(fetch(OTHER, "GET", "/", "").await); |
| 308 | assert_eq!(body, "other index"); |
| 309 | let (_, body) = res!(fetch(&fmt!("{}:{}", HOST, addr.port()), "GET", "/", "").await); |
| 310 | assert_eq!(body, "edit index"); |
| 311 | // The other vhost has no handler route, so its /edit is no handler's. |
| 312 | let (head, _) = res!(fetch(OTHER, "PUT", "/edit/doc", "x").await); |
| 313 | assert!(head.starts_with("http/1.1 405"), "{}", head); |
| 314 | |
| 315 | server.abort(); |
| 316 | { |
| 317 | let mut g = res!(dbs.write().map_err(|_| err!("The db map lock is poisoned."; Test))); |
| 318 | g.clear(); |
| 319 | } |
| 320 | let _ = std::fs::remove_dir_all(&base); |
| 321 | Ok(()) |
| 322 | } |