swadhinbiswas πŸš€ release: 2.0.8 β€” write-path fix (ADR-080), fork-safe GIL pool (ADR-081), HTTP/3 (ADR-082), Security DI fix, docs honesty pass Β· 8/6/2026
731fffe
281 lines Β· 9.8 KB
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
//! Testing utilities β€” `TestClient` for in-process request/response.
//!
//! Uses a tokio duplex pipe to send raw HTTP bytes through the hyper HTTP/1.1
//! parser, producing real `Incoming` bodies without a TCP socket.

use hyper::{Method, Request};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

use hyper_util::rt::TokioIo;

use crate::middleware::HandlerFn;
use tracing;

/// An in-memory HTTP test response.
#[derive(Debug, Clone)]
pub struct TestResponse {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

/// A test client that sends requests through the full JustAPI pipeline
/// without opening a TCP socket.
#[derive(Clone)]
pub struct TestClient {
    handler: HandlerFn,
}

impl TestClient {
    pub fn new(handler: HandlerFn) -> Self {
        Self { handler }
    }

    pub async fn get(&self, path: &str) -> Result<TestResponse, anyhow::Error> {
        self.request(Method::GET, path, Vec::new(), &[]).await
    }

    /// GET with extra request headers (e.g. to exercise header-aware routing
    /// or coalescing keys).
    pub async fn get_with(
        &self,
        path: &str,
        headers: &[(&str, &str)],
    ) -> Result<TestResponse, anyhow::Error> {
        self.request(Method::GET, path, Vec::new(), headers).await
    }

    pub async fn post(&self, path: &str, body: Vec<u8>) -> Result<TestResponse, anyhow::Error> {
        self.request(Method::POST, path, body, &[]).await
    }

    /// POST with extra request headers (e.g. a `Content-Type` carrying the
    /// `multipart/form-data` boundary for file-upload tests).
    pub async fn post_with(
        &self,
        path: &str,
        body: Vec<u8>,
        headers: &[(&str, &str)],
    ) -> Result<TestResponse, anyhow::Error> {
        self.request(Method::POST, path, body, headers).await
    }

    pub async fn put(&self, path: &str, body: Vec<u8>) -> Result<TestResponse, anyhow::Error> {
        self.request(Method::PUT, path, body, &[]).await
    }

    pub async fn patch(&self, path: &str, body: Vec<u8>) -> Result<TestResponse, anyhow::Error> {
        self.request(Method::PATCH, path, body, &[]).await
    }

    pub async fn delete(&self, path: &str) -> Result<TestResponse, anyhow::Error> {
        self.request(Method::DELETE, path, Vec::new(), &[]).await
    }

    /// Send an HTTP QUERY request (RFC 10008) with a body. QUERY is safe and
    /// idempotent like GET but carries a request body like POST, so client
    /// helpers mirror the POST shape.
    pub async fn query(&self, path: &str, body: Vec<u8>) -> Result<TestResponse, anyhow::Error> {
        self.query_with(path, body, &[]).await
    }

    /// QUERY with extra request headers (RFC 10008 requires a Content-Type).
    pub async fn query_with(
        &self,
        path: &str,
        body: Vec<u8>,
        headers: &[(&str, &str)],
    ) -> Result<TestResponse, anyhow::Error> {
        let method = crate::query_method();
        self.request(method, path, body, headers).await
    }

    async fn request(
        &self,
        method: Method,
        path: &str,
        body: Vec<u8>,
        headers: &[(&str, &str)],
    ) -> Result<TestResponse, anyhow::Error> {
        let handler = self.handler.clone();
        let (mut client, server) = tokio::io::duplex(65536);

        // Spawn the server side: feed the handler through hyper HTTP/1.1
        tokio::spawn(async move {
            let svc = hyper::service::service_fn(move |req: Request<hyper::body::Incoming>| {
                let handler = handler.clone();
                async move { handler(req).await }
            });
            let io = TokioIo::new(server);
            match hyper::server::conn::http1::Builder::new().serve_connection(io, svc).await {
                Ok(()) => {}
                Err(e) => {
                    // A body-stream error (e.g. a validated stream aborting on an
                    // invalid item) surfaces here as a connection-level error. That
                    // is expected application behavior, not a harness bug, so log it
                    // instead of panicking β€” panicking aborts the whole test process
                    // under `panic = "abort"`.
                    tracing::debug!("Test server connection closed with error: {}", e);
                }
            }
        });

        // Build and send the raw HTTP request with Connection: close
        let method_str = method.to_string();
        let body_len = body.len();
        let mut request_bytes =
            format!("{} {} HTTP/1.1\r\nHost: test\r\nConnection: close\r\n", method_str, path,)
                .into_bytes();
        for (name, value) in headers {
            request_bytes.extend_from_slice(format!("{}: {}\r\n", name, value).as_bytes());
        }
        request_bytes.extend_from_slice(format!("Content-Length: {}\r\n\r\n", body_len).as_bytes());
        if body_len > 0 {
            request_bytes.extend_from_slice(&body);
        }

        client.write_all(&request_bytes).await?;

        // Wait for the server to process the request and write the response.
        // The server end of the duplex is dropped when serve_connection returns,
        // which signals EOF on our read half.
        let mut buf = Vec::new();
        client.read_to_end(&mut buf).await?;

        // Parse the raw HTTP response
        parse_response(&buf)
    }
}

fn parse_response(raw: &[u8]) -> Result<TestResponse, anyhow::Error> {
    let header_end = find_double_crlf(raw)
        .ok_or_else(|| anyhow::anyhow!("No header/body separator found in response"))?;

    let header_section = &raw[..header_end];
    let body = &raw[header_end + 4..];

    let header_str = std::str::from_utf8(header_section)
        .map_err(|e| anyhow::anyhow!("Invalid UTF-8 in response headers: {}", e))?;

    let mut lines = header_str.lines();

    // Parse status line: "HTTP/1.1 200 OK"
    let status_line = lines.next().unwrap_or("");
    let status: u16 = status_line.split_whitespace().nth(1).unwrap_or("500").parse().unwrap_or(500);

    // Parse headers
    let headers: Vec<(String, String)> = lines
        .filter(|l| !l.is_empty())
        .filter_map(|l| {
            let mut parts = l.splitn(2, ": ");
            let name = parts.next()?.to_string();
            let value = parts.next().unwrap_or("").to_string();
            Some((name, value))
        })
        .collect();

    let is_chunked = headers.iter().any(|(k, v)| {
        k.eq_ignore_ascii_case("transfer-encoding") && v.eq_ignore_ascii_case("chunked")
    });

    let body = if is_chunked { decode_chunked(body)? } else { body.to_vec() };

    Ok(TestResponse { status, headers, body })
}

/// Decode RFC 9112 chunked-transfer-encoding framing into the raw body bytes.
fn decode_chunked(body: &[u8]) -> Result<Vec<u8>, anyhow::Error> {
    let mut out = Vec::new();
    let mut pos = 0;
    while pos < body.len() {
        // Find the end of the chunk-size line (terminated by \r\n or \n).
        let line_end = body[pos..]
            .iter()
            .position(|&b| b == b'\n')
            .map(|i| pos + i)
            .ok_or_else(|| anyhow::anyhow!("Truncated chunked body"))?;
        let size_line = &body[pos..line_end];
        // Strip a trailing \r if present.
        let size_line = if size_line.last() == Some(&b'\r') {
            &size_line[..size_line.len() - 1]
        } else {
            size_line
        };
        let size_str = std::str::from_utf8(size_line)
            .map_err(|e| anyhow::anyhow!("Invalid chunk size: {}", e))?;
        // Allow optional chunk-ext after a ';'.
        let size_hex = size_str.split(';').next().unwrap_or("").trim();
        let size: usize = usize::from_str_radix(size_hex, 16)
            .map_err(|e| anyhow::anyhow!("Invalid chunk size: {}", e))?;
        if size == 0 {
            break;
        }
        let data_start = line_end + 1;
        let data_end = data_start + size;
        if data_end > body.len() {
            return Err(anyhow::anyhow!("Chunk claims more data than available"));
        }
        out.extend_from_slice(&body[data_start..data_end]);
        // Skip the chunk-data trailing CRLF.
        pos = data_end + if body[data_end..].starts_with(b"\r\n") { 2 } else { 1 };
    }
    Ok(out)
}

fn find_double_crlf(data: &[u8]) -> Option<usize> {
    data.windows(4).position(|w| w == b"\r\n\r\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::json_response;
    use crate::middleware::HandlerFn;
    use hyper::StatusCode;

    fn ok_handler() -> HandlerFn {
        std::sync::Arc::new(|_req| {
            Box::pin(async move { Ok(json_response(StatusCode::OK, r#"{"status":"ok"}"#)) })
        })
    }

    #[tokio::test]
    async fn test_test_client_get() {
        let client = TestClient::new(ok_handler());
        let resp = client.get("/test").await.unwrap();
        assert_eq!(resp.status, 200);
        assert_eq!(resp.body, br#"{"status":"ok"}"#);
    }

    #[tokio::test]
    async fn test_test_client_post() {
        let client = TestClient::new(ok_handler());
        let resp = client.post("/test", b"{}".to_vec()).await.unwrap();
        assert_eq!(resp.status, 200);
    }

    #[tokio::test]
    async fn test_test_client_query() {
        let client = TestClient::new(ok_handler());
        let resp = client.query("/test", b"{}".to_vec()).await.unwrap();
        assert_eq!(resp.status, 200);
        let resp = client
            .query_with("/test", b"{}".to_vec(), &[("Content-Type", "application/json")])
            .await
            .unwrap();
        assert_eq!(resp.status, 200);
    }

    #[tokio::test]
    async fn test_test_client_404() {
        let handler: HandlerFn = std::sync::Arc::new(|_req| {
            Box::pin(
                async move { Ok(json_response(StatusCode::NOT_FOUND, r#"{"error":"not found"}"#)) },
            )
        });
        let client = TestClient::new(handler);
        let resp = client.get("/nonexistent").await.unwrap();
        assert_eq!(resp.status, 404);
    }
}