rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! nextstatic 端到端用例, 与 Go 版 nextstatic_test.go 一一对应
#![cfg(feature = "nextstatic")]

use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use bytes::Bytes;
use http::{Request, Response, StatusCode};
use http_body_util::BodyExt;
use rust_web_utils::nextstatic::{Body, Config, NextStatic, RSC_CACHE_CONTROL, RSC_VARY};
use tempfile::TempDir;

const TREE: &[(&str, &str)] = &[
    ("index.html", "<html><head>__SEO_TITLE__</head><body>home</body></html>"),
    ("index.txt", "rsc:home"),
    ("404.html", "<html><body>not found page</body></html>"),
    ("robots.txt", "User-agent: *"),
    ("sw.js", "self.addEventListener('fetch',()=>{})"),
    ("about/index.html", "<html>about</html>"),
    ("about/__next._index.txt", "rsc:about"),
    (
        "voddetail/_/index.html",
        "<html><head>__SEO_TITLE__</head><body>vod</body></html>",
    ),
    ("voddetail/_/__next._index.txt", "rsc:vod-template"),
    // Next 16 route group 磁盘布局 (点号请求需还原成此结构)
    (
        "admin/users/__next.!KGNvbnNvbGUp/admin/users/__PAGE__.txt",
        "rsc:admin-users",
    ),
    // 动态详情导出在父级
    ("app/index.html", "<html>app-detail-shell</html>"),
    ("app/index.txt", "rsc:app-shell"),
    // trailingSlash: false 形态
    ("pricing.html", "<html>pricing</html>"),
    ("_next/static/chunks/app.js", "console.log(1)"),
];

fn write(root: &Path, rel: &str, content: &str) {
    let full = root.join(rel);
    fs::create_dir_all(full.parent().unwrap()).unwrap();
    fs::write(full, content).unwrap();
}

fn tree() -> TempDir {
    let dir = TempDir::new().unwrap();
    for (rel, content) in TREE {
        write(dir.path(), rel, content);
    }
    dir
}

fn handler(cfg: Config) -> NextStatic {
    NextStatic::new(cfg).unwrap()
}

struct Got {
    status: StatusCode,
    headers: http::HeaderMap,
    body: String,
}

impl Got {
    fn header(&self, name: &str) -> &str {
        self.headers.get(name).map(|v| v.to_str().unwrap()).unwrap_or("")
    }
}

async fn collect(resp: Response<Body>) -> Got {
    let (parts, body) = resp.into_parts();
    let bytes = body.collect().await.unwrap().to_bytes();
    Got {
        status: parts.status,
        headers: parts.headers,
        body: String::from_utf8_lossy(&bytes).into_owned(),
    }
}

async fn request(h: &NextStatic, method: &str, uri: &str) -> Got {
    collect(
        h.handle(Request::builder().method(method).uri(uri).body(()).unwrap())
            .await,
    )
    .await
}

async fn get(h: &NextStatic, uri: &str) -> Got {
    request(h, "GET", uri).await
}

#[test]
fn new_validates_root() {
    assert!(NextStatic::new(Config::new("/not/exist/dir")).is_err());
    let dir = tree();
    assert!(NextStatic::new(Config::new(dir.path().join("index.html"))).is_err());
}

#[tokio::test]
async fn static_pages() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });

    let r = get(&h, "/").await;
    assert_eq!(r.status, 200);
    assert!(r.body.contains("home"));
    assert_eq!(r.header("content-type"), "text/html; charset=utf-8");
    assert!(r.header("cache-control").contains("no-store"));

    let r = get(&h, "/about/").await;
    assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, "<html>about</html>"));

    // HEAD 不带响应体
    let r = request(&h, "HEAD", "/about/").await;
    assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, ""));
    assert_eq!(r.header("content-length"), "18");
}

#[tokio::test]
async fn dot_html_form() {
    let dir = tree();
    let h = handler(Config::new(dir.path()));
    let r = get(&h, "/pricing").await;
    assert_eq!(r.status, 200);
    assert!(r.body.contains("pricing"));

    // 直接请求 .html 也走 HTML 通道
    let r = get(&h, "/pricing.html").await;
    assert_eq!(r.status, 200);
    assert!(r.header("cache-control").contains("no-store"));
}

#[tokio::test]
async fn trailing_slash_redirect() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });

    let r = get(&h, "/about").await;
    assert_eq!(r.status, StatusCode::PERMANENT_REDIRECT);
    assert_eq!(r.header("location"), "/about/");

    let r = get(&h, "/about?x=1&y=2").await;
    assert_eq!(r.header("location"), "/about/?x=1&y=2");

    // absolute-form 请求携带外部 Host, Location 必须为相对路径
    let r = get(&h, "http://evil.example/about").await;
    assert_eq!(r.status, StatusCode::PERMANENT_REDIRECT);
    assert!(!r.header("location").contains("evil.example"));

    // 非 ASCII 路径转义
    let r = get(&h, "/%E4%B8%AD%E6%96%87").await;
    assert_eq!(r.header("location"), "/%E4%B8%AD%E6%96%87/");
}

#[tokio::test]
async fn rsc_headers() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });

    let r = get(&h, "/about/__next._index.txt").await;
    assert_eq!(r.status, 200);
    assert_eq!(r.header("content-type"), "text/x-component; charset=utf-8");
    assert_eq!(r.header("vary"), RSC_VARY);
    assert_eq!(r.header("cache-control"), RSC_CACHE_CONTROL);

    let r = get(&h, "/index.txt").await;
    assert_eq!(r.header("content-type"), "text/x-component; charset=utf-8");

    let r = get(&h, "/robots.txt").await;
    assert!(r.header("content-type").starts_with("text/plain"));
    assert!(!r.header("vary").contains("RSC"));
}

#[tokio::test]
async fn route_group_dot_path_restore() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });
    let r = get(&h, "/admin/users/__next.!KGNvbnNvbGUp.admin.users.__PAGE__.txt").await;
    assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, "rsc:admin-users"));
    assert_eq!(r.header("content-type"), "text/x-component; charset=utf-8");
}

#[tokio::test]
async fn immutable_and_sw() {
    let dir = tree();
    let h = handler(Config::new(dir.path()));

    assert!(
        get(&h, "/_next/static/chunks/app.js")
            .await
            .header("cache-control")
            .contains("immutable")
    );

    let r = get(&h, "/sw.js").await;
    assert_eq!(r.status, 200);
    assert_eq!(r.header("cache-control"), "no-cache");
    assert_eq!(r.header("service-worker-allowed"), "/");

    // sw.js 缺失时必须 404, 绝不回退 HTML
    let empty = TempDir::new().unwrap();
    write(empty.path(), "index.html", "<html>x</html>");
    let h2 = handler(Config {
        spa_fallback: true,
        ..Config::new(empty.path())
    });
    let r = get(&h2, "/sw.js").await;
    assert_eq!(r.status, 404);
    assert!(!r.body.contains("<html>"));
    assert_eq!(r.header("cache-control"), "no-store");
}

#[tokio::test]
async fn range_and_conditional() {
    let dir = tree();
    let h = handler(Config::new(dir.path()));
    let req = Request::builder()
        .uri("/_next/static/chunks/app.js")
        .header("range", "bytes=0-6")
        .body(())
        .unwrap();
    let r = collect(h.handle(req).await).await;
    assert_eq!((r.status, r.body.as_str()), (StatusCode::PARTIAL_CONTENT, "console"));
    assert!(r.header("cache-control").contains("immutable"));

    let last_modified = get(&h, "/sw.js").await.header("last-modified").to_owned();
    assert!(!last_modified.is_empty());
    let req = Request::builder()
        .uri("/sw.js")
        .header("if-modified-since", &last_modified)
        .body(())
        .unwrap();
    assert_eq!(collect(h.handle(req).await).await.status, StatusCode::NOT_MODIFIED);
}

#[tokio::test]
async fn dynamic_route_fallback() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });

    let r = get(&h, "/voddetail/123/").await;
    assert_eq!(r.status, 200);
    assert!(r.body.contains("vod"));

    let r = get(&h, "/voddetail/123/__next._index.txt").await;
    assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, "rsc:vod-template"));
    assert_eq!(r.header("content-type"), "text/x-component; charset=utf-8");
}

#[tokio::test]
async fn parent_dir_fallback() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });

    let r = get(&h, "/app/12345/").await;
    assert_eq!(r.status, 200);
    assert!(r.body.contains("app-detail-shell"));

    let r = get(&h, "/app/12345/index.txt").await;
    assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, "rsc:app-shell"));
}

#[tokio::test]
async fn seo_inject() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        seo_inject: Some(Arc::new(|parts, html| {
            assert_eq!(parts.uri.path(), "/voddetail/123/");
            Bytes::from(String::from_utf8_lossy(&html).replace("__SEO_TITLE__", "<title>注入标题</title>"))
        })),
        ..Config::new(dir.path())
    });
    assert!(
        get(&h, "/voddetail/123/")
            .await
            .body
            .contains("<title>注入标题</title>")
    );
}

#[tokio::test]
async fn seo_inject_keeps_cache_intact() {
    let dir = tree();
    let n = Arc::new(AtomicUsize::new(0));
    let counter = n.clone();
    let h = handler(Config {
        trailing_slash: true,
        seo_inject: Some(Arc::new(move |_parts, html| {
            let k = counter.fetch_add(1, Ordering::SeqCst) + 1;
            let mut out = html.to_vec();
            out.extend_from_slice(format!("<!--{}-->", "x".repeat(k)).as_bytes());
            Bytes::from(out)
        })),
        ..Config::new(dir.path())
    });
    assert_eq!(get(&h, "/about/").await.body, "<html>about</html><!--x-->");
    assert_eq!(get(&h, "/about/").await.body, "<html>about</html><!--xx-->");
}

#[tokio::test]
async fn not_found_defaults_to_404_page() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });

    let r = get(&h, "/no-such-page/").await;
    assert_eq!(r.status, 404);
    assert!(r.body.contains("not found page"));
    assert!(r.header("cache-control").contains("no-store"));

    let r = get(&h, "/no-such-asset.js").await;
    assert_eq!(r.status, 404);
    assert!(!r.body.contains("<html>"));
}

#[tokio::test]
async fn not_found_fallbacks_without_404_html() {
    let dir = TempDir::new().unwrap();
    write(dir.path(), "index.html", "<html>root</html>");
    let h = handler(Config::new(dir.path()));
    let r = get(&h, "/missing").await;
    assert_eq!(
        (r.status, r.body.as_str()),
        (StatusCode::NOT_FOUND, "<html>root</html>")
    );

    let bare = TempDir::new().unwrap();
    let h = handler(Config::new(bare.path()));
    let r = get(&h, "/missing").await;
    assert_eq!(
        (r.status, r.body.as_str()),
        (StatusCode::NOT_FOUND, "404 page not found\n")
    );
    assert_eq!(get(&h, "/").await.status, 404);
}

#[tokio::test]
async fn custom_not_found() {
    let dir = tree();
    let h = handler(Config {
        not_found: Some(Arc::new(|parts| {
            let mut r = Response::new(Bytes::from(format!("custom {}", parts.uri.path())));
            *r.status_mut() = StatusCode::NOT_FOUND;
            r
        })),
        ..Config::new(dir.path())
    });
    let r = get(&h, "/nope").await;
    assert_eq!((r.status, r.body.as_str()), (StatusCode::NOT_FOUND, "custom /nope"));
    let r = get(&h, "/nope.js").await;
    assert_eq!(r.body, "custom /nope.js");
    assert_eq!(r.header("cache-control"), "no-store");
}

#[tokio::test]
async fn spa_fallback_mode() {
    let dir = tree();
    let h = handler(Config {
        spa_fallback: true,
        ..Config::new(dir.path())
    });
    let r = get(&h, "/no-such-page").await;
    assert_eq!(r.status, 200);
    assert!(r.body.contains("home"));
}

#[tokio::test]
async fn api_prefix_json_404() {
    let dir = tree();
    let h = handler(Config::new(dir.path()));
    let r = get(&h, "/api/not-registered").await;
    assert_eq!(r.status, 404);
    assert!(r.header("content-type").starts_with("application/json"));
    assert_eq!(r.body, r#"{"code":404,"data":{},"msg":"not found"}"#);

    let h2 = handler(Config {
        api_prefixes: Some(vec![]),
        spa_fallback: true,
        ..Config::new(dir.path())
    });
    let r = get(&h2, "/api/not-registered").await;
    assert!(!r.header("content-type").starts_with("application/json"));
}

#[tokio::test]
async fn path_traversal_blocked() {
    let dir = tree();
    let h = handler(Config::new(dir.path()));

    let r = get(&h, "/../../etc/passwd").await;
    assert!(!(r.status == 200 && r.body.contains("root:")));

    let r = get(&h, "/%2e%2e/%2e%2e/etc/passwd").await;
    assert_ne!(r.status, 200);

    let r = get(&h, "/..%5C..%5Cwindows%5Cwin.ini").await;
    assert_eq!(r.status, StatusCode::BAD_REQUEST);

    let r = get(&h, "/a%00b").await;
    assert_eq!(r.status, StatusCode::BAD_REQUEST);

    let r = get(&h, "/%FF").await;
    assert_eq!(r.status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn drive_letter_cannot_escape_root() {
    // 在导出目录旁放一个"根外"文件, 用绝对路径 (Windows 带盘符) 尝试读取
    let outside = TempDir::new().unwrap();
    write(outside.path(), "secret.txt", "top-secret");
    let abs = outside.path().join("secret.txt");
    let abs = abs.to_str().unwrap().replace('\\', "/");
    let dir = tree();
    for disable_cache in [false, true] {
        let h = handler(Config {
            disable_cache,
            ..Config::new(dir.path())
        });
        for uri in [format!("/{abs}"), format!("/{}", abs.replace('/', "%2F"))] {
            let r = get(&h, &uri).await;
            assert!(
                !r.body.contains("top-secret"),
                "disable_cache={disable_cache} uri={uri}"
            );
        }
        assert!(!get(&h, "/C:/Windows/win.ini").await.body.contains("[fonts]"));
    }
}

#[tokio::test]
async fn method_not_allowed() {
    let dir = tree();
    let h = handler(Config::new(dir.path()));
    let r = request(&h, "POST", "/").await;
    assert_eq!(r.status, StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(r.header("allow"), "GET, HEAD");
}

#[tokio::test]
async fn snapshot_needs_reload() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });
    assert!(get(&h, "/about/").await.body.contains("about")); // 预热 HTML 缓存

    write(dir.path(), "new/index.html", "<html>new-page</html>");
    write(dir.path(), "about/index.html", "<html>changed</html>");
    write(dir.path(), "fresh.js", "console.log(2)");

    assert_eq!(get(&h, "/new/").await.status, 404);
    assert_eq!(get(&h, "/fresh.js").await.status, 404);
    assert!(get(&h, "/about/").await.body.contains("about"));

    h.reload().unwrap();
    let r = get(&h, "/new/").await;
    assert_eq!(r.status, 200);
    assert!(r.body.contains("new-page"));
    assert_eq!(get(&h, "/fresh.js").await.status, 200);
    assert!(get(&h, "/about/").await.body.contains("changed"));
}

#[tokio::test]
async fn disable_cache_reads_disk() {
    let dir = tree();
    let h = handler(Config {
        trailing_slash: true,
        disable_cache: true,
        ..Config::new(dir.path())
    });
    get(&h, "/about/").await;
    write(dir.path(), "new/index.html", "<html>new-page</html>");
    write(dir.path(), "about/index.html", "<html>changed</html>");
    let r = get(&h, "/new/").await;
    assert_eq!(r.status, 200);
    assert!(r.body.contains("new-page"));
    assert!(get(&h, "/about/").await.body.contains("changed"));
}

#[tokio::test]
async fn html_cache_limit() {
    for (max, want_cached) in [(0, true), (4, false), (-1, false)] {
        let dir = tree();
        let h = handler(Config {
            trailing_slash: true,
            html_cache_max_bytes: max,
            ..Config::new(dir.path())
        });
        get(&h, "/about/").await;
        write(dir.path(), "about/index.html", "<html>changed</html>");
        let cached = !get(&h, "/about/").await.body.contains("changed");
        assert_eq!(cached, want_cached, "max={max}");
    }
}

#[tokio::test]
async fn index_is_case_sensitive() {
    let dir = tree();
    let h = handler(Config::new(dir.path()));
    assert_eq!(get(&h, "/SW.JS").await.status, 404);
}

#[tokio::test]
async fn works_as_axum_fallback() {
    use axum::Router;
    use axum::routing::get as route_get;
    use tower::ServiceExt;

    let dir = tree();
    let web = handler(Config {
        trailing_slash: true,
        ..Config::new(dir.path())
    });
    let app: Router = Router::new()
        .route("/api/ping", route_get(|| async { "pong" }))
        .fallback_service(web);

    let resp = app
        .clone()
        .oneshot(Request::get("/api/ping").body(axum::body::Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(resp.into_body().collect().await.unwrap().to_bytes(), "pong");

    let resp = app
        .oneshot(Request::get("/about/").body(axum::body::Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}