rust-web-server 18.6.0

Single-binary web server and reverse proxy: automatic HTTPS (Let's Encrypt), HTTP/1.1, HTTP/2 and HTTP/3, load balancing, auth and rate limiting, configured in one TOML file. Also a Rust library: routing, middleware, MCP server, ORM, background jobs. No hyper, no Tower; HTTP/2 and HTTP/3 framing via h2 and quinn.
Documentation
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::sync::Arc;

use crate::application::Application;
use crate::core::New;
use crate::di::Container;
use crate::header::Header;
use crate::http::VERSION;
use crate::mime_type::MimeType;
use crate::range::Range;
use crate::request::{METHOD, Request};
use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
use crate::server::{Address, ConnectionInfo};
use crate::server_config::ServerConfig;
use crate::state::AppWithState;

fn conn() -> ConnectionInfo {
    ConnectionInfo {
        client: Address { ip: "127.0.0.1".to_string(), port: 0 },
        server: Address { ip: "127.0.0.1".to_string(), port: 7878 },
        request_size: 16000,
    sni_hostname: None,
    }
}

fn get(uri: &str) -> Request {
    Request {
        method: METHOD.get.to_string(),
        request_uri: uri.to_string(),
        http_version: VERSION.http_1_1.to_string(),
        headers: vec![],
        body: Default::default(),
    }
}

fn post(uri: &str, body: &[u8]) -> Request {
    Request {
        method: METHOD.post.to_string(),
        request_uri: uri.to_string(),
        http_version: VERSION.http_1_1.to_string(),
        headers: vec![],
        body: body.to_vec().into(),
    }
}

fn ok_text(body: &str) -> Response {
    let mut r = Response::new();
    r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
    r.content_range_list = vec![Range::get_content_range(body.as_bytes().to_vec(), MimeType::TEXT_PLAIN.to_string())];
    r
}

struct State {
    value: String,
    counter: std::sync::atomic::AtomicU32,
}

#[test]
fn state_accessible_in_get_handler() {
    let app = AppWithState::new(State {
        value: "hello".into(),
        counter: std::sync::atomic::AtomicU32::new(0),
    })
    .get("/greet", |_req, _params, _conn, state| {
        state.counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        ok_text(&state.value)
    });

    let resp = app.execute(&get("/greet"), &conn()).unwrap();
    assert_eq!(200, resp.status_code);
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("hello", body);
}

#[test]
fn path_params_and_state_together() {
    let app = AppWithState::new("world".to_string())
        .get("/hello/:name", |_req, params, _conn, state| {
            let name = params.get("name").unwrap_or("?");
            ok_text(&format!("{}, {}!", state, name))
        });

    let resp = app.execute(&get("/hello/alice"), &conn()).unwrap();
    assert_eq!(200, resp.status_code);
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("world, alice!", body);
}

#[test]
fn post_handler_receives_state() {
    let app = AppWithState::new(42u32)
        .post("/echo", |req, _params, _conn, state| {
            let body = format!("state={} body={}", state, String::from_utf8_lossy(&req.body));
            ok_text(&body)
        });

    let resp = app.execute(&post("/echo", b"test"), &conn()).unwrap();
    assert_eq!(200, resp.status_code);
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("state=42 body=test", body);
}

#[test]
fn unmatched_request_falls_through_to_app() {
    let app = AppWithState::new(()).get("/custom", |_, _, _, _| ok_text("custom"));
    // /healthz is served by the built-in HealthController
    let resp = app.execute(&get("/healthz"), &conn()).unwrap();
    assert_eq!(200, resp.status_code);
}

#[test]
fn unmatched_request_returns_404() {
    // Falls through to App's built-in StaticResourceController, whose
    // is_matching now depends on RWS_CONFIG_SPA_FALLBACK.
    let _g = crate::test_env::lock();
    std::env::remove_var("RWS_CONFIG_SPA_FALLBACK");

    let app = AppWithState::new(()).get("/custom", |_, _, _, _| ok_text("custom"));
    let resp = app.execute(&get("/does-not-exist-xyz"), &conn()).unwrap();
    assert_eq!(404, resp.status_code);
}

#[test]
fn first_matching_route_wins() {
    let app = AppWithState::new(())
        .get("/a", |_, _, _, _| ok_text("first"))
        .get("/a", |_, _, _, _| ok_text("second"));

    let resp = app.execute(&get("/a"), &conn()).unwrap();
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("first", body);
}

#[test]
fn wildcard_captures_remaining_path() {
    let app = AppWithState::new(())
        .get("/files/*path", |_, params, _, _| {
            ok_text(params.get("path").unwrap_or(""))
        });

    let resp = app.execute(&get("/files/a/b/c.txt"), &conn()).unwrap();
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("a/b/c.txt", body);
}

#[test]
fn state_accessor_returns_inner_value() {
    let app = AppWithState::new("sentinel".to_string());
    assert_eq!("sentinel", app.state());
}

#[test]
fn state_is_shared_across_concurrent_handlers() {
    use std::sync::atomic::Ordering;
    let app = std::sync::Arc::new(
        AppWithState::new(std::sync::atomic::AtomicU32::new(0))
            .get("/inc", |_, _, _, state| {
                state.fetch_add(1, Ordering::Relaxed);
                ok_text("ok")
            }),
    );

    let mut handles = vec![];
    for _ in 0..8 {
        let app = std::sync::Arc::clone(&app);
        let conn = conn();
        let req = get("/inc");
        handles.push(std::thread::spawn(move || {
            app.execute(&req, &conn).unwrap();
        }));
    }
    for h in handles { h.join().unwrap(); }

    assert_eq!(8, app.state().load(Ordering::Relaxed));
}

#[test]
fn put_patch_delete_are_registered() {
    let app = AppWithState::new(())
        .put("/r", |_, _, _, _| ok_text("put"))
        .patch("/r", |_, _, _, _| ok_text("patch"))
        .delete("/r", |_, _, _, _| ok_text("delete"));

    for (method, expected) in [("PUT", "put"), ("PATCH", "patch"), ("DELETE", "delete")] {
        let req = Request {
            method: method.to_string(),
            request_uri: "/r".to_string(),
            http_version: VERSION.http_1_1.to_string(),
            headers: vec![],
            body: Default::default(),
        };
        let resp = app.execute(&req, &conn()).unwrap();
        let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
        assert_eq!(expected, body, "method={}", method);
    }
}

// ── di::Container as AppWithState's state ───────────────────────────────────────
//
// `Container` needs no special-cased integration: it's `Send + Sync + 'static`
// like any other state type, so `AppWithState::new(container)` (not
// `container.into_arc()`, which would double-wrap in `Arc`) works directly.
// These tests exist so that claim is verified, not just documented.

#[test]
fn container_resolves_concrete_service_through_a_request() {
    struct Greeting(String);

    let mut container = Container::new();
    container.register(Greeting("hello from the container".to_string()));

    let app = AppWithState::new(container).get("/greet", |_req, _params, _conn, state| {
        let greeting = state.get::<Greeting>().unwrap();
        ok_text(&greeting.0)
    });

    let resp = app.execute(&get("/greet"), &conn()).unwrap();
    assert_eq!(200, resp.status_code);
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("hello from the container", body);
}

#[test]
fn container_resolves_trait_object_service_through_a_request() {
    trait Greeter: Send + Sync {
        fn greet(&self) -> String;
    }
    struct EnglishGreeter;
    impl Greeter for EnglishGreeter {
        fn greet(&self) -> String {
            "hi".to_string()
        }
    }

    let mut container = Container::new();
    container.provide::<dyn Greeter>(Arc::new(EnglishGreeter));

    let app = AppWithState::new(container).get("/greet", |_req, _params, _conn, state| {
        ok_text(&state.get::<dyn Greeter>().unwrap().greet())
    });

    let resp = app.execute(&get("/greet"), &conn()).unwrap();
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("hi", body);
}

#[test]
fn container_resolution_miss_does_not_panic_the_handler() {
    let app = AppWithState::new(Container::new()).get("/x", |_req, _params, _conn, state| {
        match state.get::<u32>() {
            Some(_) => ok_text("found"),
            None => ok_text("missing"),
        }
    });

    let resp = app.execute(&get("/x"), &conn()).unwrap();
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("missing", body);
}

// ── with_config: fallback App pinned to an explicit ServerConfig ───────────────
//
// No env writes here — App::with_config's whole point is to avoid them — so
// these run safely without test_env::lock(), unlike a test that touched
// RWS_CONFIG_* directly.

#[test]
fn with_config_pins_cors_denial_on_fallback_request() {
    // Falls through to App's built-in StaticResourceController, whose
    // is_matching now depends on RWS_CONFIG_SPA_FALLBACK.
    let _g = crate::test_env::lock();
    std::env::remove_var("RWS_CONFIG_SPA_FALLBACK");

    let config = ServerConfig {
        cors_allow_all: false,
        cors_allow_origins: String::new(), // no allowed origins -> CORS denied
        ..ServerConfig::default()
    };
    // No routes registered, so every request falls through to the built-in App.
    let app = AppWithState::new(()).with_config(config);

    let mut req = get("/does-not-exist");
    req.headers.push(Header {
        name: Header::_ORIGIN.into(),
        value: "https://evil.example.com".into(),
    });

    let resp = app.execute(&req, &conn()).unwrap();
    assert!(resp._get_header(Header::_ACCESS_CONTROL_ALLOW_ORIGIN.to_string()).is_none());
}

#[test]
fn with_config_allows_cors_for_configured_origin_on_fallback_request() {
    let _g = crate::test_env::lock();
    std::env::remove_var("RWS_CONFIG_SPA_FALLBACK");

    let config = ServerConfig {
        cors_allow_all: false,
        cors_allow_origins: "https://trusted.example.com".to_string(),
        ..ServerConfig::default()
    };
    let app = AppWithState::new(()).with_config(config);

    let mut req = get("/does-not-exist");
    req.headers.push(Header {
        name: Header::_ORIGIN.into(),
        value: "https://trusted.example.com".into(),
    });

    let resp = app.execute(&req, &conn()).unwrap();
    let acao = resp._get_header(Header::_ACCESS_CONTROL_ALLOW_ORIGIN.to_string()).unwrap();
    assert_eq!("https://trusted.example.com", acao.value);
}

#[test]
fn own_routes_still_take_priority_over_fallback_when_config_is_pinned() {
    let config = ServerConfig { cors_allow_all: false, ..ServerConfig::default() };
    let app = AppWithState::new(())
        .with_config(config)
        .get("/greet", |_req, _params, _conn, _state| ok_text("hi"));

    let resp = app.execute(&get("/greet"), &conn()).unwrap();
    let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
    assert_eq!("hi", body);
}

// ── openapi() ────────────────────────────────────────────────────────────────

#[cfg(feature = "openapi")]
mod openapi_tests {
    use super::*;
    use crate::openapi::OpenApiConfig;

    #[test]
    fn openapi_json_serves_a_spec_covering_registered_routes() {
        let app = AppWithState::new(())
            .get("/users", |_req, _params, _conn, _state| ok_text("users"))
            .get("/users/:id", |_req, _params, _conn, _state| ok_text("user"))
            .openapi(OpenApiConfig::new("My API", "1.0.0"));

        let resp = app.execute(&get("/openapi.json"), &conn()).unwrap();
        assert_eq!(200, resp.status_code);
        assert_eq!(
            Some("application/json"),
            resp.content_range_list.first().map(|c| c.content_type.as_str())
        );
        let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
        assert!(body.contains(r#""title":"My API""#));
        assert!(body.contains(r#""/users":"#));
        assert!(body.contains(r#""/users/{id}":"#));
    }

    #[test]
    fn docs_serves_swagger_ui_html() {
        let app = AppWithState::new(())
            .get("/users", |_req, _params, _conn, _state| ok_text("users"))
            .openapi(OpenApiConfig::new("My API", "1.0.0"));

        let resp = app.execute(&get("/docs"), &conn()).unwrap();
        assert_eq!(200, resp.status_code);
        assert_eq!(
            Some("text/html"),
            resp.content_range_list.first().map(|c| c.content_type.as_str())
        );
        let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
        assert!(body.contains("swagger-ui"));
        assert!(body.contains("/openapi.json"));
    }

    #[test]
    fn own_routes_are_unaffected_after_calling_openapi() {
        let app = AppWithState::new(())
            .get("/users", |_req, _params, _conn, _state| ok_text("users"))
            .openapi(OpenApiConfig::new("My API", "1.0.0"));

        let resp = app.execute(&get("/users"), &conn()).unwrap();
        let body = String::from_utf8(resp.content_range_list[0].body.clone()).unwrap();
        assert_eq!("users", body);
    }

    #[test]
    fn routes_registered_after_openapi_still_work_but_are_not_in_the_spec() {
        let app = AppWithState::new(())
            .get("/users", |_req, _params, _conn, _state| ok_text("users"))
            .openapi(OpenApiConfig::new("My API", "1.0.0"))
            .get("/posts", |_req, _params, _conn, _state| ok_text("posts"));

        let resp = app.execute(&get("/posts"), &conn()).unwrap();
        assert_eq!(200, resp.status_code);

        let spec_resp = app.execute(&get("/openapi.json"), &conn()).unwrap();
        let spec = String::from_utf8(spec_resp.content_range_list[0].body.clone()).unwrap();
        assert!(!spec.contains("/posts"));
    }
}

#[test]
fn stream_body_marks_only_its_routes() {
    use crate::application::Application;
    let app = crate::app::App::with_state(())
        .put("/upload/:name", |_r, _p, _c, _s| Response::new())
        .post("/form", |_r, _p, _c, _s| Response::new())
        .stream_body("PUT", "/upload/:name");
    let conn = crate::server::ConnectionInfo {
        client: crate::server::Address { ip: "127.0.0.1".into(), port: 1 },
        server: crate::server::Address { ip: "127.0.0.1".into(), port: 2 },
        request_size: 0,
        sni_hostname: None,
    };
    let request = |method: &str, uri: &str| Request {
        method: method.into(), request_uri: uri.into(), http_version: "HTTP/1.1".into(), headers: vec![], body: Default::default(),
    };
    assert!(app.streams_body(&request("PUT", "/upload/a.bin"), &conn));
    assert!(!app.streams_body(&request("POST", "/upload/a.bin"), &conn));
    assert!(!app.streams_body(&request("POST", "/form"), &conn));
}