#![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"),
(
"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"),
("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>"));
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"));
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");
let r = get(&h, "http://evil.example/about").await;
assert_eq!(r.status, StatusCode::PERMANENT_REDIRECT);
assert!(!r.header("location").contains("evil.example"));
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"), "/");
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() {
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"));
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);
}