rws-server 18.29.0

The server layer of rust-web-server (internal: use the rust-web-server crate).
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Tests for the outbound HTTP client.
//!
//! All tests spin up an in-process `TcpListener` bound to a random ephemeral
//! port and act as a fake HTTP server — no real network access required.

#[cfg(test)]
mod tests {
    use std::io::{Read, Write};
    use std::net::TcpListener;

    use crate::http_client::{Client, HttpClientError};

    // ── helpers ───────────────────────────────────────────────────────────────

    /// Spawn a fake HTTP server that handles **one** connection.
    ///
    /// `handler` receives the raw request text and returns the raw response
    /// bytes that should be sent back.  Returns the base URL of the server.
    fn start_fake_server(handler: impl Fn(String) -> String + Send + 'static) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = vec![0u8; 4096];
                let n = stream.read(&mut buf).unwrap_or(0);
                let req = String::from_utf8_lossy(&buf[..n]).to_string();
                let resp = handler(req);
                stream.write_all(resp.as_bytes()).ok();
            }
        });
        format!("http://127.0.0.1:{}", addr.port())
    }

    // ── URL parsing ───────────────────────────────────────────────────────────

    #[test]
    fn parse_url_http() {
        // Access private ParsedUrl via the public API behaviour — we parse a
        // constructed URL by making a request to a fake server on the port it
        // resolves to. Alternatively, expose ParsedUrl through a test helper.
        // Here we test via the public `send()` path: a 200 response proves
        // the URL was parsed correctly.
        let base = start_fake_server(|_req| {
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nbody".to_string()
        });
        // Build a URL with path + query
        let url = format!("{}/path?q=1", base);
        let resp = Client::new().get(&url).send().unwrap();
        assert_eq!(200, resp.status());
        assert_eq!(b"body", resp.bytes());
    }

    #[test]
    fn parse_url_https_custom_port() {
        // We test URL parsing directly via the private ParsedUrl struct
        // using a module-level re-export trick only available in the same crate.
        // The cleanest cross-boundary test is to verify `HttpClientError` is
        // returned for bad URLs and success for well-formed ones.
        // For HTTPS we cannot spin up a TLS server easily, so we just verify
        // parsing by attempting a connection that fails at the TLS layer — the
        // error must NOT say "unsupported or missing URL scheme".
        let result = Client::new()
            .get("https://127.0.0.1:19999/v1")
            .timeout_ms(200)
            .send();
        match result {
            Err(HttpClientError(msg)) => {
                assert!(
                    !msg.contains("missing URL scheme"),
                    "URL was not parsed (got: {msg})"
                );
            }
            Ok(_) => { /* unexpected success is also fine for this parse-only test */ }
        }
    }

    #[test]
    fn parse_url_missing_scheme_returns_error() {
        let result = Client::new().get("example.com/path").timeout_ms(100).send();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.0.contains("missing URL scheme") || err.0.contains("unsupported"),
            "expected scheme error, got: {}",
            err.0
        );
    }

    // ── Plain HTTP requests ───────────────────────────────────────────────────

    #[test]
    fn get_plain_http() {
        let base = start_fake_server(|_req| {
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nbody".to_string()
        });
        let resp = Client::new().get(&base).send().unwrap();
        assert_eq!(200, resp.status());
        assert_eq!("body", resp.text().unwrap());
    }

    #[test]
    fn post_with_body() {
        // The fake server echoes "received" so we just check the request was
        // sent with the right Content-Length (by inspecting its echo).
        let base = start_fake_server(|req| {
            // req should contain "Content-Length: 5"
            let has_len = req.contains("Content-Length: 5");
            let has_body = req.contains("hello");
            let status = if has_len && has_body { "200" } else { "400" };
            format!("HTTP/1.1 {status} OK\r\nContent-Length: 2\r\n\r\nok")
        });
        let resp = Client::new()
            .post(&base)
            .body(b"hello".to_vec())
            .send()
            .unwrap();
        assert_eq!(200, resp.status());
    }

    #[test]
    fn response_with_chunked_encoding() {
        // Server sends chunked body: "Hello, " + "World!"
        let base = start_fake_server(|_req| {
            "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n7\r\nHello, \r\n6\r\nWorld!\r\n0\r\n\r\n".to_string()
        });
        let resp = Client::new().get(&base).send().unwrap();
        assert_eq!(200, resp.status());
        assert_eq!("Hello, World!", resp.text().unwrap());
    }

    // ── Response helpers ──────────────────────────────────────────────────────

    #[test]
    fn is_success_true_for_200_range() {
        let base = start_fake_server(|_| {
            "HTTP/1.1 201 Created\r\nContent-Length: 0\r\n\r\n".to_string()
        });
        let resp = Client::new().get(&base).send().unwrap();
        assert!(resp.is_success());
    }

    #[test]
    fn is_success_false_for_404() {
        let base = start_fake_server(|_| {
            "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n".to_string()
        });
        let resp = Client::new().get(&base).send().unwrap();
        assert!(!resp.is_success());
    }

    #[test]
    fn header_lookup_case_insensitive() {
        let base = start_fake_server(|_| {
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}".to_string()
        });
        let resp = Client::new().get(&base).send().unwrap();
        assert_eq!(Some("application/json"), resp.header("content-type"));
        assert_eq!(Some("application/json"), resp.header("Content-Type"));
        assert_eq!(Some("application/json"), resp.header("CONTENT-TYPE"));
    }

    // ── Redirect following ────────────────────────────────────────────────────

    #[test]
    fn redirect_followed() {
        // First connection: 301 → /new
        // Second connection: 200 OK
        // We need two servers because the client opens a new TCP connection for
        // each hop.

        // Start the final destination server first so we know its port
        let dest = start_fake_server(|_| {
            "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndone".to_string()
        });

        // Start the redirect server that sends Location pointing at dest
        let dest_url = dest.clone();
        let redir = start_fake_server(move |_| {
            format!(
                "HTTP/1.1 301 Moved Permanently\r\nLocation: {dest_url}\r\nContent-Length: 0\r\n\r\n"
            )
        });

        let resp = Client::new().get(&redir).send().unwrap();
        assert_eq!(200, resp.status());
        assert_eq!("done", resp.text().unwrap());
    }

    #[test]
    fn max_redirects_exceeded_returns_last_response() {
        // Build a chain of 3 servers each 301-ing to the next, with the last
        // one also returning 301 (no final 200). With max_redirects=2 the
        // client should stop after 2 follows and return the last 301 response.

        // Server C — always returns 301 back to itself (loop), but client
        // should stop before reaching it a third time.
        let server_c = start_fake_server(|_| {
            "HTTP/1.1 301 Moved\r\nLocation: http://127.0.0.1:1\r\nContent-Length: 0\r\n\r\n"
                .to_string()
        });

        let c_url = server_c.clone();
        let server_b = start_fake_server(move |_| {
            format!(
                "HTTP/1.1 301 Moved\r\nLocation: {c_url}\r\nContent-Length: 0\r\n\r\n"
            )
        });

        let b_url = server_b.clone();
        let server_a = start_fake_server(move |_| {
            format!(
                "HTTP/1.1 301 Moved\r\nLocation: {b_url}\r\nContent-Length: 0\r\n\r\n"
            )
        });

        // max_redirects=2 means we follow at most 2 redirects (A→B, B→C)
        // then return C's response (301) without an error
        let resp = Client::new()
            .max_redirects(2)
            .get(&server_a)
            .send()
            .unwrap();
        // The client must return the last response it received, even if it's a redirect
        assert!(resp.is_redirect());
    }

    // ── Custom headers ────────────────────────────────────────────────────────

    #[test]
    fn custom_header_sent() {
        let base = start_fake_server(|req| {
            // Echo whether the header was present
            let found = req.contains("X-Custom: value");
            let body = if found { "yes" } else { "no" };
            format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", body.len(), body)
        });
        let resp = Client::new()
            .get(&base)
            .header("X-Custom", "value")
            .send()
            .unwrap();
        assert_eq!("yes", resp.text().unwrap());
    }

    // ── Timeout ───────────────────────────────────────────────────────────────

    #[test]
    fn timeout_returns_error() {
        // Accept the connection but never write anything back — triggers a
        // read timeout on the client.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((_stream, _)) = listener.accept() {
                // hold the connection open without sending anything
                std::thread::sleep(std::time::Duration::from_secs(5));
            }
        });
        let url = format!("http://127.0.0.1:{}", addr.port());
        let result = Client::new().timeout_ms(150).get(&url).send();
        assert!(
            result.is_err(),
            "expected timeout error but got a response"
        );
    }

    // ── DELETE method ─────────────────────────────────────────────────────────

    #[test]
    fn delete_method_sent_correctly() {
        let base = start_fake_server(|req| {
            let is_delete = req.starts_with("DELETE ");
            let body = if is_delete { "deleted" } else { "wrong" };
            format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
                body.len(),
                body
            )
        });
        let resp = Client::new().delete(&base).send().unwrap();
        assert_eq!(200, resp.status());
        assert_eq!("deleted", resp.text().unwrap());
    }

    // ── form encoding ─────────────────────────────────────────────────────────

    #[test]
    fn form_sets_content_type_and_urlencoded_body() {
        let base = start_fake_server(|req| {
            let has_ct = req.contains("Content-Type: application/x-www-form-urlencoded");
            let has_body = req.contains("grant_type=authorization_code&code=abc%20123");
            let status = if has_ct && has_body { "200" } else { "400" };
            format!("HTTP/1.1 {status} OK\r\nContent-Length: 2\r\n\r\nok")
        });
        let resp = Client::new()
            .post(&base)
            .form(&[("grant_type", "authorization_code"), ("code", "abc 123")])
            .send()
            .unwrap();
        assert_eq!(200, resp.status());
    }

    #[test]
    fn form_encodes_reserved_characters_in_keys_and_values() {
        let base = start_fake_server(|req| {
            let has_body = req.contains("redirect_uri=https%3A%2F%2Fexample.com%2Fcb%3Fx%3D1");
            let status = if has_body { "200" } else { "400" };
            format!("HTTP/1.1 {status} OK\r\nContent-Length: 2\r\n\r\nok")
        });
        let resp = Client::new()
            .post(&base)
            .form(&[("redirect_uri", "https://example.com/cb?x=1")])
            .send()
            .unwrap();
        assert_eq!(200, resp.status());
    }

    #[test]
    fn form_empty_pairs_sends_content_type_with_empty_body() {
        // An empty body never gets a Content-Length header (pre-existing
        // build_request_bytes behavior, unrelated to .form()) — just confirm
        // the Content-Type header is still set and nothing sent for the body.
        let base = start_fake_server(|req| {
            let has_ct = req.contains("Content-Type: application/x-www-form-urlencoded");
            let ends_with_headers = req.ends_with("\r\n\r\n");
            let status = if has_ct && ends_with_headers { "200" } else { "400" };
            format!("HTTP/1.1 {status} OK\r\nContent-Length: 2\r\n\r\nok")
        });
        let resp = Client::new().post(&base).form(&[]).send().unwrap();
        assert_eq!(200, resp.status());
    }

    #[test]
    fn inside_a_traced_request_the_trace_context_is_sent() {
        crate::otel::setup(crate::otel::TracingConfig { exporter: crate::otel::ExporterConfig::Discard, ..Default::default() });
        let (tx, rx) = std::sync::mpsc::channel();
        let base = start_fake_server(move |req| {
            tx.send(req).unwrap();
            "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n".to_string()
        });
        std::thread::spawn(move || {
            let root = crate::otel::span("request");
            crate::otel::set_baggage("tenant", "acme");
            let resp = Client::new().get(&format!("{base}/x")).send().unwrap();
            assert_eq!(200, resp.status());
            let sent = rx.recv().unwrap();
            let trace = root.trace_id().iter().map(|b| format!("{b:02x}")).collect::<String>();
            assert!(sent.contains(&format!("traceparent: 00-{trace}-")), "{sent}");
            assert!(!sent.contains(&root.span_id().iter().map(|b| format!("{b:02x}")).collect::<String>()), "a client span is the parent: {sent}");
            assert!(sent.contains("baggage: tenant=acme\r\n"), "{sent}");
        })
        .join()
        .unwrap();
    }
}

#[test]
fn localhost_reaches_a_server_listening_on_ipv4_only() {
    // `localhost` may resolve to ::1 first; every address is tried.
    use std::io::{Read, Write};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    std::thread::spawn(move || {
        if let Ok((mut stream, _)) = listener.accept() {
            let mut buf = [0u8; 1024];
            let _ = stream.read(&mut buf);
            let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");
        }
    });
    let response = crate::http_client::Client::new().get(&format!("http://localhost:{port}/")).send().expect("reached over IPv4");
    assert_eq!((200, "ok"), (response.status(), response.text().unwrap().as_str()));
}

#[test]
fn the_host_header_carries_a_non_default_port() {
    // Servers that build absolute URLs from Host (OIDC discovery documents)
    // need the port; found by the Keycloak end-to-end test (18.21.0).
    use std::io::{Read, Write};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    let seen = std::thread::spawn(move || {
        let (mut stream, _) = listener.accept().unwrap();
        let mut buf = [0u8; 1024];
        let n = stream.read(&mut buf).unwrap();
        let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
        String::from_utf8_lossy(&buf[..n]).to_string()
    });
    crate::http_client::Client::new().get(&format!("http://127.0.0.1:{port}/x")).send().unwrap();
    let request = seen.join().unwrap();
    assert!(request.contains(&format!("Host: 127.0.0.1:{port}\r\n")), "{request}");
}

/// `Client::ca_file`: an HTTPS server whose certificate a private CA signed
/// is trusted with that CA, and refused with the public roots.
#[test]
#[cfg(any(feature = "http-client", feature = "http2"))] // `ca_file` and TLS need one of them
fn a_private_ca_is_trusted_with_ca_file() {
    use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair};
    use std::io::{Read, Write};
    let ca_key = KeyPair::generate().unwrap();
    let mut ca_params = CertificateParams::new(Vec::<String>::new()).unwrap();
    ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
    let ca_cert = ca_params.self_signed(&ca_key).unwrap();
    let issuer = Issuer::new(ca_params, ca_key);
    let server_key = KeyPair::generate().unwrap();
    let server_cert = CertificateParams::new(vec!["localhost".to_string()]).unwrap().signed_by(&server_key, &issuer).unwrap();

    let config = std::sync::Arc::new(
        rustls::ServerConfig::builder_with_provider(std::sync::Arc::new(crate::crypto_provider()))
            .with_safe_default_protocol_versions()
            .unwrap()
            .with_no_client_auth()
            .with_single_cert(vec![server_cert.der().clone()], rustls::pki_types::PrivateKeyDer::try_from(server_key.serialize_der()).unwrap())
            .unwrap(),
    );
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    std::thread::spawn(move || {
        for stream in listener.incoming().take(2) {
            let Ok(tcp) = stream else { continue };
            let conn = rustls::ServerConnection::new(config.clone()).unwrap();
            let mut tls = rustls::StreamOwned::new(conn, tcp);
            let mut buf = [0u8; 1024];
            if tls.read(&mut buf).is_ok() {
                let _ = tls.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\nprivate");
                let _ = tls.flush();
            }
        }
    });
    let url = format!("https://localhost:{port}/");
    assert!(crate::http_client::Client::new().get(&url).send().is_err(), "the public roots don't know this CA");
    let ca = crate::test_env::TempPath::new("http-client-ca.pem");
    std::fs::write(&*ca, ca_cert.pem()).unwrap();
    let client = crate::http_client::Client::new().ca_file(&ca.to_string_lossy()).unwrap();
    assert_eq!("private", client.get(&url).send().unwrap().text().unwrap());
    assert!(crate::http_client::Client::new().ca_file("/nonexistent.pem").is_err());
}