liburlx 0.2.2

A memory-safe URL transfer library — idiomatic Rust reimplementation of libcurl
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! Integration tests for basic HTTP operations using a real test server.

#![allow(clippy::unwrap_used, unused_results, clippy::significant_drop_tightening)]

mod common;

use std::io::Write as _;
use std::sync::Arc;

use common::TestServer;
use http_body_util::Full;
use hyper::body::Bytes;
use hyper::Response;

#[tokio::test]
async fn get_returns_200_with_body() {
    let server = TestServer::start(|_req| {
        Response::builder().status(200).body(Full::new(Bytes::from("hello world"))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(resp.body_str().unwrap(), "hello world");
}

#[tokio::test]
async fn get_returns_404() {
    let server = TestServer::start(|_req| {
        Response::builder().status(404).body(Full::new(Bytes::from("not found"))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/missing")).unwrap();
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 404);
    assert_eq!(resp.body_str().unwrap(), "not found");
}

#[tokio::test]
async fn post_with_body() {
    let server = TestServer::start(|req| {
        let method = req.method().to_string();
        let has_content_length = req.headers().contains_key("content-length");
        let body_info = format!("method={method}, has_cl={has_content_length}");
        Response::builder().status(200).body(Full::new(Bytes::from(body_info))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/submit")).unwrap();
    easy.method("POST");
    easy.body(b"test data");
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    let body = resp.body_str().unwrap();
    assert!(body.contains("method=POST"), "body was: {body}");
    assert!(body.contains("has_cl=true"), "body was: {body}");
}

#[tokio::test]
async fn put_request() {
    let server = TestServer::start(|req| {
        let method = req.method().to_string();
        Response::builder().status(200).body(Full::new(Bytes::from(method))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/resource")).unwrap();
    easy.method("PUT");
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.body_str().unwrap(), "PUT");
}

#[tokio::test]
async fn delete_request() {
    let server = TestServer::start(|req| {
        let method = req.method().to_string();
        Response::builder().status(200).body(Full::new(Bytes::from(method))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/resource")).unwrap();
    easy.method("DELETE");
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.body_str().unwrap(), "DELETE");
}

#[tokio::test]
async fn head_request_returns_no_body() {
    let server = TestServer::start(|_req| {
        Response::builder()
            .status(200)
            .header("content-length", "1000")
            .body(Full::new(Bytes::new()))
            .unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    easy.method("HEAD");
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    assert!(resp.body().is_empty());
}

#[tokio::test]
async fn custom_headers_are_sent() {
    let server = TestServer::start(|req| {
        let custom = req.headers().get("x-custom").map_or("missing", |v| v.to_str().unwrap_or(""));
        Response::builder().status(200).body(Full::new(Bytes::from(custom.to_string()))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    easy.header("X-Custom", "test-value-123");
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.body_str().unwrap(), "test-value-123");
}

#[tokio::test]
async fn redirect_301_is_followed() {
    let redirect_count = Arc::new(std::sync::atomic::AtomicU32::new(0));
    let redirect_count_clone = redirect_count.clone();

    let server = TestServer::start(move |req| {
        let path = req.uri().path().to_string();
        if path == "/start" {
            redirect_count_clone.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            Response::builder()
                .status(301)
                .header("location", "/end")
                .body(Full::new(Bytes::new()))
                .unwrap()
        } else {
            Response::builder().status(200).body(Full::new(Bytes::from("final"))).unwrap()
        }
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/start")).unwrap();
    easy.follow_redirects(true);
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(resp.body_str().unwrap(), "final");
    assert_eq!(redirect_count.load(std::sync::atomic::Ordering::Relaxed), 1);
}

#[tokio::test]
async fn redirect_302_is_followed() {
    let server = TestServer::start(|req| {
        if req.uri().path() == "/old" {
            Response::builder()
                .status(302)
                .header("location", "/new")
                .body(Full::new(Bytes::new()))
                .unwrap()
        } else {
            Response::builder().status(200).body(Full::new(Bytes::from("arrived"))).unwrap()
        }
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/old")).unwrap();
    easy.follow_redirects(true);
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(resp.body_str().unwrap(), "arrived");
}

#[tokio::test]
async fn redirect_not_followed_by_default() {
    let server = TestServer::start(|_req| {
        Response::builder()
            .status(301)
            .header("location", "/other")
            .body(Full::new(Bytes::new()))
            .unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/start")).unwrap();
    // follow_redirects is false by default
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 301);
}

#[tokio::test]
async fn redirect_max_exceeded() {
    let server = TestServer::start(|_req| {
        Response::builder()
            .status(302)
            .header("location", "/loop")
            .body(Full::new(Bytes::new()))
            .unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/loop")).unwrap();
    easy.follow_redirects(true);
    easy.max_redirects(3);
    let result = easy.perform_async().await;

    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("too many redirects") || err.contains("redirects followed"),
        "error was: {err}"
    );
}

#[tokio::test]
async fn redirect_303_changes_post_to_get() {
    let request_methods: Arc<std::sync::Mutex<Vec<String>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));
    let methods_clone = request_methods.clone();

    let server = TestServer::start(move |req| {
        let method = req.method().to_string();
        methods_clone.lock().unwrap().push(method);

        if req.uri().path() == "/submit" {
            Response::builder()
                .status(303)
                .header("location", "/result")
                .body(Full::new(Bytes::new()))
                .unwrap()
        } else {
            Response::builder().status(200).body(Full::new(Bytes::from("done"))).unwrap()
        }
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/submit")).unwrap();
    easy.method("POST");
    easy.follow_redirects(true);
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    let methods = request_methods.lock().unwrap();
    assert_eq!(methods[0], "POST");
    assert_eq!(methods[1], "GET"); // 303 changes to GET
}

#[tokio::test]
async fn redirect_307_preserves_method() {
    let request_methods: Arc<std::sync::Mutex<Vec<String>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));
    let methods_clone = request_methods.clone();

    let server = TestServer::start(move |req| {
        let method = req.method().to_string();
        methods_clone.lock().unwrap().push(method);

        if req.uri().path() == "/submit" {
            Response::builder()
                .status(307)
                .header("location", "/submit2")
                .body(Full::new(Bytes::new()))
                .unwrap()
        } else {
            Response::builder().status(200).body(Full::new(Bytes::from("done"))).unwrap()
        }
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/submit")).unwrap();
    easy.method("PUT");
    easy.follow_redirects(true);
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    let methods = request_methods.lock().unwrap();
    assert_eq!(methods[0], "PUT");
    assert_eq!(methods[1], "PUT"); // 307 preserves method
}

#[tokio::test]
async fn connection_refused() {
    let mut easy = liburlx::Easy::new();
    // Use a port that's (almost certainly) not listening
    easy.url("http://127.0.0.1:1").unwrap();
    let result = easy.perform_async().await;
    assert!(result.is_err());
}

#[tokio::test]
async fn empty_response_body() {
    let server = TestServer::start(|_req| {
        Response::builder().status(204).body(Full::new(Bytes::new())).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 204);
    assert!(resp.body().is_empty());
}

#[tokio::test]
async fn redirect_with_absolute_url() {
    let server = TestServer::start(|req| {
        let path = req.uri().path().to_string();
        if path == "/start" {
            // Use the Host header to construct the absolute redirect URL
            let host = req.headers().get("host").unwrap().to_str().unwrap().to_string();
            Response::builder()
                .status(302)
                .header("location", format!("http://{host}/end"))
                .body(Full::new(Bytes::new()))
                .unwrap()
        } else {
            Response::builder()
                .status(200)
                .body(Full::new(Bytes::from("final destination")))
                .unwrap()
        }
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/start")).unwrap();
    easy.follow_redirects(true);
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(resp.body_str().unwrap(), "final destination");
}

#[tokio::test]
async fn chunked_response_is_decoded() {
    let server = TestServer::start(|_req| {
        // hyper uses chunked encoding when Content-Length is not set and body is non-empty
        Response::builder()
            .status(200)
            .body(Full::new(Bytes::from("chunked body content")))
            .unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(resp.body_str().unwrap(), "chunked body content");
}

#[tokio::test]
async fn gzip_decompression() {
    let server = TestServer::start(|req| {
        // Only compress if client accepts gzip
        let accepts_gzip = req
            .headers()
            .get("accept-encoding")
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.contains("gzip"));

        if accepts_gzip {
            let mut encoder =
                flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
            encoder.write_all(b"compressed content").unwrap();
            let compressed = encoder.finish().unwrap();

            Response::builder()
                .status(200)
                .header("content-encoding", "gzip")
                .header("content-length", compressed.len().to_string())
                .body(Full::new(Bytes::from(compressed)))
                .unwrap()
        } else {
            Response::builder()
                .status(200)
                .header("content-length", "18")
                .body(Full::new(Bytes::from("compressed content")))
                .unwrap()
        }
    })
    .await;

    // With accept_encoding enabled, response should be decompressed
    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    easy.accept_encoding(true);
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(resp.body_str().unwrap(), "compressed content");
}

#[tokio::test]
async fn no_decompression_without_accept_encoding() {
    let server = TestServer::start(|_req| {
        Response::builder().status(200).body(Full::new(Bytes::from("plain content"))).unwrap()
    })
    .await;

    // Without accept_encoding, no Accept-Encoding header is sent
    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.body_str().unwrap(), "plain content");
}

#[tokio::test]
async fn connect_timeout_triggers() {
    let mut easy = liburlx::Easy::new();
    // 10.255.255.1 is non-routable, should timeout
    easy.url("http://10.255.255.1:1234").unwrap();
    easy.connect_timeout(std::time::Duration::from_millis(100));
    let result = easy.perform_async().await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("timeout") || err.contains("Timeout"), "error was: {err}");
}

#[tokio::test]
async fn total_timeout_triggers() {
    let server = TestServer::start(|_req| {
        // Server responds instantly, but we'll use the timeout anyway
        Response::builder().status(200).body(Full::new(Bytes::from("ok"))).unwrap()
    })
    .await;

    // A very generous timeout should succeed
    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    easy.timeout(std::time::Duration::from_secs(10));
    let resp = easy.perform_async().await.unwrap();
    assert_eq!(resp.status(), 200);
}

#[tokio::test]
async fn basic_auth_header_sent() {
    let server = TestServer::start(|req| {
        let auth = req
            .headers()
            .get("authorization")
            .map_or_else(|| "none".to_string(), |v| v.to_str().unwrap_or("").to_string());
        Response::builder().status(200).body(Full::new(Bytes::from(auth))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    easy.basic_auth("admin", "secret");
    let resp = easy.perform_async().await.unwrap();

    // base64("admin:secret") = "YWRtaW46c2VjcmV0"
    assert_eq!(resp.body_str().unwrap(), "Basic YWRtaW46c2VjcmV0");
}

#[tokio::test]
async fn bearer_token_header_sent() {
    let server = TestServer::start(|req| {
        let auth = req
            .headers()
            .get("authorization")
            .map_or_else(|| "none".to_string(), |v| v.to_str().unwrap_or("").to_string());
        Response::builder().status(200).body(Full::new(Bytes::from(auth))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    easy.bearer_token("my-api-token");
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.body_str().unwrap(), "Bearer my-api-token");
}

#[tokio::test]
async fn transfer_info_is_populated() {
    let server = TestServer::start(|_req| {
        Response::builder().status(200).body(Full::new(Bytes::from("info test"))).unwrap()
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/")).unwrap();
    let resp = easy.perform_async().await.unwrap();

    let info = resp.transfer_info();
    assert!(info.time_total.as_nanos() > 0, "time_total should be > 0");
    assert_eq!(info.num_redirects, 0);
    assert_eq!(resp.size_download(), 9); // "info test" = 9 bytes
}

#[tokio::test]
async fn transfer_info_counts_redirects() {
    let server = TestServer::start(|req| {
        if req.uri().path() == "/start" {
            Response::builder()
                .status(302)
                .header("location", "/end")
                .body(Full::new(Bytes::new()))
                .unwrap()
        } else {
            Response::builder().status(200).body(Full::new(Bytes::from("done"))).unwrap()
        }
    })
    .await;

    let mut easy = liburlx::Easy::new();
    easy.url(&server.url("/start")).unwrap();
    easy.follow_redirects(true);
    let resp = easy.perform_async().await.unwrap();

    assert_eq!(resp.transfer_info().num_redirects, 1);
}