//! 兜底服务(404 / SPA 深链)的行为锁定。
//!
//! ⚠️ **只测兜底服务本身**(对它 `oneshot`),**不接鉴权中间件**
//! (接了就会先吃 401,测不到 404)。
//! ⚠️ 本测试二进制**不需要 PGlite**(兜底不碰 DB)⇒ 不建 PGlite 实例。
use std::path::{Path, PathBuf};
use axum::body::Body;
use axum::http::{header, Request, StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;
use tdc_connector::platform::fallback::spa_fallback;
/// 仓库里的 `static/`(SPA 构建产物)。
fn static_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("static")
}
/// 打一个请求到兜底服务,返回 `(状态码, content-type, body 文本)`。
async fn call(uri: &str) -> (StatusCode, String, String) {
call_dir(&static_dir(), uri).await
}
/// 打一个请求到**指定** web root 的兜底服务,返回 `(状态码, content-type, body 文本)`。
async fn call_dir(dir: &Path, uri: &str) -> (StatusCode, String, String) {
call_dir_with_range(dir, uri, None).await
}
/// 同上,但可带一个 `Range` 头(`range = None` 时不带)。
async fn call_dir_with_range(
dir: &Path,
uri: &str,
range: Option<&str>,
) -> (StatusCode, String, String) {
let svc = spa_fallback(dir);
let mut builder = Request::builder().uri(uri);
if let Some(value) = range {
builder = builder.header(header::RANGE, value);
}
let req = builder.body(Body::empty()).expect("构造请求失败");
let resp = svc.oneshot(req).await.expect("兜底服务不应出错");
let status = resp.status();
let ct = resp
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
let bytes = resp
.into_body()
.collect()
.await
.expect("读取 body 失败")
.to_bytes();
let text = String::from_utf8_lossy(&bytes).to_string();
(status, ct, text)
}
/// `/api/**` 未命中 ⇒ 404 + JSON(**无 `data` 键**)。
///
/// 🔴 附带断言(R2-3):
/// - `/api%2Ffoo`(**编码斜杠**)⇒ 判定前先 percent-decode ⇒ 解码后是 `/api/foo`
/// ⇒ 落在 `/api` 命名空间 ⇒ **404 + JSON**(**不是** SPA 的 HTML);
/// - `/apifoo`(**非** `/api` 命名空间)⇒ **不能**被误吞 ⇒ 仍回 SPA HTML(200 `text/html`)。
#[tokio::test]
async fn api_prefix_returns_404_json_without_data_key() {
let (status, ct, body) = call("/api/anything").await;
assert_eq!(status, StatusCode::NOT_FOUND, "body={}", body);
assert_eq!(ct, "application/json", "body={}", body);
let v: serde_json::Value = serde_json::from_str(&body).expect("body 必须是 JSON");
assert_eq!(v["code"], 404);
assert_eq!(v["msg"], "接口不存在");
assert!(
v.get("data").is_none(),
"404 信封不得有 data 键(与 auth::reject 同族):{:?}",
v
);
// R2-3:编码斜杠 ⇒ 解码后属于 `/api` 命名空间 ⇒ 404 + JSON。
let (status, ct, body) = call("/api%2Ffoo").await;
assert_eq!(status, StatusCode::NOT_FOUND, "body={}", body);
assert_eq!(ct, "application/json", "body={}", body);
let v: serde_json::Value = serde_json::from_str(&body).expect("body 必须是 JSON");
assert_eq!(v["code"], 404);
// R2-3:`/apifoo` 不是 `/api` 命名空间 ⇒ 不能被误吞成 404 JSON。
let (status, ct, _body) = call("/apifoo").await;
assert_eq!(status, StatusCode::OK, "`/apifoo` 不应被误吞");
assert!(ct.starts_with("text/html"), "content-type={:?}", ct);
}
/// `/api/`(**带尾斜杠**)⇒ 404 + JSON。
///
/// 🔴 这条是回归点:matchit 的 `{*rest}` **不匹配空 rest** ⇒ 旧实现里它落到 SPA 兜底回 HTML。
#[tokio::test]
async fn api_prefix_with_trailing_slash_returns_404_json() {
let (status, ct, body) = call("/api/").await;
assert_eq!(status, StatusCode::NOT_FOUND, "body={}", body);
assert_eq!(ct, "application/json", "body={}", body);
let v: serde_json::Value = serde_json::from_str(&body).expect("body 必须是 JSON");
assert_eq!(v["code"], 404);
}
/// `/migrate.sql` ⇒ 404,且**响应体不含 `CREATE TABLE`**(不得泄露 DDL)。
#[tokio::test]
async fn migrate_sql_is_not_downloadable() {
let (status, _ct, body) = call("/migrate.sql").await;
assert_eq!(status, StatusCode::NOT_FOUND, "body={}", body);
assert!(
!body.contains("CREATE TABLE"),
"响应体不得含 DDL:{}",
&body[..body.len().min(200)]
);
}
/// `/MIGRATE.SQL`(**大小写变体**)⇒ 响应体不得含 `CREATE TABLE`。
///
/// 🔴 这条是回归点:macOS 文件系统大小写不敏感 ⇒ 旧实现里它能下到完整 DDL。
#[tokio::test]
async fn migrate_sql_case_variant_is_not_downloadable() {
let (status, _ct, body) = call("/MIGRATE.SQL").await;
assert!(
!body.contains("CREATE TABLE"),
"大小写变体不得泄露 DDL:{}",
&body[..body.len().min(200)]
);
assert_ne!(status, StatusCode::OK, "大小写变体不应 200");
}
/// SPA 深链 ⇒ 200 + `text/html`(内容是上游 SPA 外壳)。
#[tokio::test]
async fn spa_deep_link_returns_index_html() {
let (status, ct, body) = call("/tdc/home").await;
assert_eq!(status, StatusCode::OK, "body={}", body);
assert!(
ct.starts_with("text/html"),
"content-type 应为 text/html,实际 {:?}",
ct
);
assert!(
body.contains("
尚数网可信数据空间(连接器)"),
"应是上游 SPA 外壳:{}",
&body[..body.len().min(200)]
);
}
/// 静态资源(`/assets/*.js`)⇒ 200(由 `ServeDir` 直接出,不走兜底)。
///
/// 🔴 R3-2 补的断言:**content-type 不得以 `text/html` 开头**。
/// 只断言 `status == 200` 时,`ServeDir` 的根目录坏掉(资源不存在)也会绿——
/// 因为请求落到决策层、回的是 `static/index.html`(200 `text/html`)。
/// 加上 content-type 后,「资源被 `ServeDir` 命中」与「回落成 SPA index」才可区分。
#[tokio::test]
async fn static_assets_are_still_served() {
let asset = std::fs::read_dir(static_dir().join("assets"))
.expect("读 static/assets 失败")
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.find(|n| n.starts_with("index-") && n.ends_with(".js"))
.expect("static/assets 里应有 index-*.js");
let (status, ct, body) = call(&format!("/assets/{}", asset)).await;
assert_eq!(
status,
StatusCode::OK,
"body={}",
&body[..body.len().min(200)]
);
assert!(
!ct.starts_with("text/html"),
"静态资源应由 ServeDir 直接出(实测 text/javascript),不该回落成 SPA index.html:ct={:?}",
ct
);
}
/// 在 `temp_dir` 下造一个 web root,写入给定的 `(相对路径, 内容)` 文件对。
///
/// 🔴 名字 = **pid + 纳秒 + 进程内自增序号**:单靠纳秒仍有残余竞争
/// (同进程内两个并发用例可能拿到同一个纳秒 ⇒ 目录名撞车 ⇒
/// 先结束的那个把后者的目录删了 ⇒ 后者读到 `index.html missing`)。
/// 自增序号保证同进程内唯一。
fn tmp_web_root_with_files(files: &[(&str, &str)]) -> PathBuf {
use std::sync::atomic::{AtomicU32, Ordering};
static SEQ: AtomicU32 = AtomicU32::new(0);
let tmp = std::env::temp_dir().join(format!(
"tdc-ddl-guard-{}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0),
SEQ.fetch_add(1, Ordering::Relaxed),
));
std::fs::create_dir_all(&tmp).expect("创建临时 web root 失败");
for (name, content) in files {
let path = tmp.join(name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("创建子目录失败");
}
std::fs::write(&path, content).expect("写临时文件失败");
}
tmp
}
/// 在 `temp_dir` 下造一个「含 `migrate.sql` 的 web root」(并发安全的名字)。
///
/// 内容用**可识别的标记串**(不是真 DDL,避免报告里出现真 DDL 片段)。
fn tmp_web_root_with_ddl() -> PathBuf {
tmp_web_root_with_files(&[
(
"migrate.sql",
"CREATE TABLE tdc_secret (id text);\n-- DDL MUST NOT LEAK\n",
),
("index.html", "tmp"),
])
}
/// 🔴 **回归点(R2-1 / R3-1)**:DDL 文件**就在 web root 里**时,下列**每一条**变体都**必须**下不到。
///
/// 这条测试证明的是「前置守卫 `ddl_guard` 真的跑在 `ServeDir` **之前**」:
/// - 若守卫只在 `ServeDir` 的 decision 层(文件没找到时)判定 ⇒ 这里会 **200 + 完整 DDL**;
/// - 若守卫是前置中间件 ⇒ 无论文件在不在 web root,都是 **404 + JSON**。
///
/// 🔴 R3-2:**每一条**变体都必须同时满足「404 + `application/json` + 响应体不含标记串」。
/// R2 时的变体清单只有 4 条,且**恰好全在旧守卫的判定口径内**(只看末段)
/// ⇒ 用例对「末段带 `.`」那一族(`/migrate.sql/.` 等 24 条)**零敏感**。
/// 现在清单覆盖了复评实测漏网的 24 条 + 回归护栏 ⇒ **任一条漏网即红**。
#[tokio::test]
async fn ddl_in_web_root_is_still_not_downloadable() {
// 在临时目录里造一个「含 migrate.sql 的 web root」。
let tmp = tmp_web_root_with_ddl();
// 变体清单:复评实测漏网的 24 条 + R2 的 4 条 + 尾斜杠 / 编码斜杠 / 尾部空白等护栏
// + R4 的 Unicode casefold 一族(`ſ` 家族:旧守卫用 ASCII 折叠 ⇒ 这一族会漏网)。
const VARIANTS: [&str; 44] = [
// R2 的 4 条(原本就在)
"/migrate.sql",
"/MIGRATE.SQL",
"/migrate%2Esql",
"//migrate.sql",
// 大小写 / 编码变体
"/Migrate.sql",
"/migrate%2esql",
"/%6digrate.sql",
// 尾斜杠 / 编码斜杠
"/migrate.sql/",
"/migrate.sql%2f",
// 末段带 `.` 的一族(R2 漏网 ⇒ R3 的重点)
"/migrate.sql/.",
"/migrate.sql/./",
"/migrate.sql/%2e",
"/migrate.sql/%2E",
"/migrate.sql/%2e%2f",
"/migrate.sql/././.",
"/MIGRATE.SQL/.",
"/MIGRATE.SQL/./",
"/MIGRATE.SQL/%2e",
"/MIGRATE.SQL/%2E",
"/MIGRATE.SQL/%2e%2f",
"/MIGRATE.SQL/././.",
"/migrate%2Esql/.",
"/migrate%2Esql/./",
"/migrate%2Esql/%2e",
"/migrate%2Esql/%2E",
"/migrate%2Esql/%2e%2f",
"/migrate%2Esql/././.",
"/%6digrate.sql/.",
"/%6digrate.sql/./",
"/%6digrate.sql/%2e",
"/%6digrate.sql/%2E",
"/%6digrate.sql/%2e%2f",
"/%6digrate.sql/././.",
// 「任一段」口径的护栏(不止是修 `.` 那一族)
"/migrate.sql/..",
"/schema/migrate.sql",
// 尾部空白(收紧项)
"/migrate.sql%20",
// R4:Unicode casefold 一族(`ſ` = U+017F,APFS 上与 `s` 等价)
"/migrate.%C5%BFql",
"/MIGRATE.%C5%BFQL",
"/migrate.%C5%BFql/.",
"/migrate.%C5%BFql/./",
"/migrate.%C5%BFql%2f",
"/schema/migrate.%C5%BFql",
// 扩展名里的字母被 percent 编码(解码后仍命中)
"/migrate.s%71l",
"/migrate.%73ql",
];
let mut failures: Vec = Vec::new();
for uri in VARIANTS {
let (status, ct, body) = call_dir(&tmp, uri).await;
let head: String = body.chars().take(200).collect();
if status != StatusCode::NOT_FOUND {
failures.push(format!(
"uri={uri} 必须是 404(DDL 在 web root 里也下不到),实际 {status},body={head}"
));
}
if !ct.starts_with("application/json") {
failures.push(format!("uri={uri} 必须是 JSON,实际 {ct},body={head}"));
}
if body.contains("CREATE TABLE") || body.contains("DDL MUST NOT LEAK") {
failures.push(format!("uri={uri} 响应体不得含 DDL:{head}"));
}
}
// 只删**自己**在 temp_dir 下建的那个目录(不碰仓库里任何东西)。
let _ = std::fs::remove_dir_all(&tmp);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// 🔴 **回归点(R3-1)**:「**任意一段**命中」的口径被**单独**钉住。
///
/// 守卫的判据是「路径中任意一段(去尾部空白、忽略大小写)等于 `migrate.sql`」,
/// 而不是「最后一段」。这三条路径分别覆盖:
/// - `/schema/migrate.sql` ⇒ DDL 文件名在**中间**一段(不是末段);
/// - `/migrate.sql/..` ⇒ 末段是 `..`,DDL 文件名在**前一段**;
/// - `/migrate.sql/.` ⇒ 末段是 `.`(`ServeDir` 归一化时会被**丢弃**,
/// 于是它把 `migrate.sql` 当成末段文件直接吐出 ⇒ 这条是 R2 漏网的那一族)。
///
/// 三条都必须是 **404 + JSON + 响应体不含标记串**。
#[tokio::test]
async fn ddl_is_blocked_by_any_path_segment() {
let tmp = tmp_web_root_with_ddl();
let mut failures: Vec = Vec::new();
for uri in ["/schema/migrate.sql", "/migrate.sql/..", "/migrate.sql/."] {
let (status, ct, body) = call_dir(&tmp, uri).await;
let head: String = body.chars().take(200).collect();
if status != StatusCode::NOT_FOUND {
failures.push(format!("uri={uri} 必须是 404,实际 {status},body={head}"));
}
if !ct.starts_with("application/json") {
failures.push(format!("uri={uri} 必须是 JSON,实际 {ct},body={head}"));
}
if body.contains("CREATE TABLE") || body.contains("DDL MUST NOT LEAK") {
failures.push(format!("uri={uri} 响应体不得含 DDL:{head}"));
}
}
let _ = std::fs::remove_dir_all(&tmp);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// 🔴 **回归点(R4-1)**:**Unicode casefold** 家族(`ſ` = U+017F)**必须**下不到。
///
/// macOS APFS 的文件名比较用的是 **Unicode casefold**(不是 ASCII 折叠)⇒
/// 磁盘上叫 `migrate.sql` 的文件,用 `migrate.ſql` 也能打开
/// (**本机实测**:12 种扩展名拼法 `s∈{s,S,ſ} × q∈{q,Q} × l∈{l,L}` 全部命中同一个文件)。
///
/// 旧守卫用 `eq_ignore_ascii_case` ⇒ 只能覆盖 1536 种拼法里的 1024 种
/// ⇒ 含 `ſ` 的 512 种**全部漏网** ⇒ 这一族是 R3 复评的 Critical。
/// 新守卫用「扩展名 + **Unicode 大写折叠**」⇒ 覆盖 1536 / 1536。
#[tokio::test]
async fn ddl_unicode_casefold_variants_are_not_downloadable() {
let tmp = tmp_web_root_with_ddl();
const VARIANTS: [&str; 8] = [
"/migrate.%C5%BFql",
"/MIGRATE.%C5%BFQL",
"/migrate.%C5%BFql/.",
"/migrate.%C5%BFql/./",
"/migrate.%C5%BFql%2f",
"/schema/migrate.%C5%BFql",
"/migrate.s%71l",
"/migrate.%73ql",
];
let mut failures: Vec = Vec::new();
for uri in VARIANTS {
let (status, ct, body) = call_dir(&tmp, uri).await;
let head: String = body.chars().take(200).collect();
if status != StatusCode::NOT_FOUND {
failures.push(format!(
"uri={uri} 必须是 404(Unicode casefold 变体同样下不到 DDL),实际 {status},body={head}"
));
}
if !ct.starts_with("application/json") {
failures.push(format!("uri={uri} 必须是 JSON,实际 {ct},body={head}"));
}
if body.contains("CREATE TABLE") || body.contains("DDL MUST NOT LEAK") {
failures.push(format!("uri={uri} 响应体不得含 DDL:{head}"));
}
}
let _ = std::fs::remove_dir_all(&tmp);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// 🔴 **回归点(R4-2)**:**改了名**、但内容**逐字节相同**的 DDL 副本**必须**下不到。
///
/// 路径级守卫只认**扩展名** ⇒ `schema.txt` 不在它的射程内
/// ⇒ 由**内容级**兜底(与**内嵌** DDL 逐字节比较)拦住。
///
/// 🔴 同时钉住**反向护栏**:**长度与 DDL 相同、但内容不同**的文件**必须**照常吐出
/// (否则说明兜底是按「长度」而不是按「内容」判的 ⇒ 会误伤一切等长文件)。
#[tokio::test]
async fn ddl_content_guard_blocks_renamed_copy() {
/// 仓库里的真 DDL(与 lib 里 `include_str!` 内嵌的是**同一个文件** ⇒ 逐字节相同)。
const DDL: &str = include_str!("../schema/migrate.sql");
// 等长但内容不同的对照文件。
let same_length_other = "x".repeat(DDL.len());
let tmp = tmp_web_root_with_files(&[
("schema.txt", DDL),
("other.txt", same_length_other.as_str()),
("index.html", "tmp"),
]);
let mut failures: Vec = Vec::new();
// ① 改名副本(内容逐字节相同)⇒ 404 + JSON,且响应体不含 DDL。
let (status, ct, body) = call_dir(&tmp, "/schema.txt").await;
if status != StatusCode::NOT_FOUND {
failures.push(format!(
"/schema.txt(改名但内容相同)必须是 404,实际 {status},body={}",
&body[..body.len().min(200)]
));
}
if !ct.starts_with("application/json") {
failures.push(format!("/schema.txt 必须是 JSON,实际 {ct}"));
}
if body.contains("CREATE TABLE") {
failures.push(format!(
"/schema.txt 响应体不得含 DDL:{}",
&body[..body.len().min(200)]
));
}
// ② 等长但内容不同 ⇒ 照常吐出(证明兜底比的是**内容**不是长度)。
let (status, ct, body) = call_dir(&tmp, "/other.txt").await;
if status != StatusCode::OK {
failures.push(format!(
"/other.txt(等长不同内容)应当照常吐出,实际 {status},body={}",
&body[..body.len().min(200)]
));
}
if body.len() != DDL.len() {
failures.push(format!(
"/other.txt 响应体长度应为 {},实际 {}",
DDL.len(),
body.len()
));
}
if ct.starts_with("text/html") {
failures.push(format!("/other.txt 不应回落成 SPA index.html,ct={ct}"));
}
// ③ **整份 Range**(`bytes=0-`)⇒ `Content-Length` 仍等于整份长度
// ⇒ 同样必须拿不到 DDL(否则 Range 就成了绕过口)。
let (status, ct, body) = call_dir_with_range(&tmp, "/schema.txt", Some("bytes=0-")).await;
if body.contains("CREATE TABLE") {
failures.push(format!(
"/schema.txt(整份 Range)响应体不得含 DDL:{}",
&body[..body.len().min(200)]
));
}
if status != StatusCode::NOT_FOUND {
failures.push(format!(
"/schema.txt(整份 Range)必须是 404,实际 {status},body={}",
&body[..body.len().min(200)]
));
}
if !ct.starts_with("application/json") {
failures.push(format!("/schema.txt(整份 Range)必须是 JSON,实际 {ct}"));
}
// ④ **片段 Range**(`bytes=0-1000`)⇒ 响应体只有 1001 字节(`Content-Length` ≠ DDL 长度)
// ⇒ 只按「整份长度」比对会放行 ⇒ 而逐段请求能把整份 DDL **拼回来** ⇒ 必须拦。
let (status, ct, body) = call_dir_with_range(&tmp, "/schema.txt", Some("bytes=0-1000")).await;
if status != StatusCode::NOT_FOUND {
failures.push(format!(
"/schema.txt(片段 Range)必须是 404,实际 {status},body={}",
&body[..body.len().min(200)]
));
}
if !ct.starts_with("application/json") {
failures.push(format!("/schema.txt(片段 Range)必须是 JSON,实际 {ct}"));
}
if body.contains("CREATE TABLE") {
failures.push(format!(
"/schema.txt(片段 Range)响应体不得含 DDL:{}",
&body[..body.len().min(200)]
));
}
// ⑤ **中段 Range**(`bytes=5000-6000`)⇒ 比的是**同偏移**的 DDL 片段 ⇒ 同样拦。
let (status, _ct, body) =
call_dir_with_range(&tmp, "/schema.txt", Some("bytes=5000-6000")).await;
if status != StatusCode::NOT_FOUND {
failures.push(format!(
"/schema.txt(中段 Range)必须是 404,实际 {status},body={}",
&body[..body.len().min(200)]
));
}
if body.contains("CREATE TABLE") {
failures.push(format!(
"/schema.txt(中段 Range)响应体不得含 DDL:{}",
&body[..body.len().min(200)]
));
}
// ⑥ **片段 Range 打在等长不同内容的文件上** ⇒ 放行(206 + 该片段)
// ⇒ 证明分段兜底比的是**内容**(同偏移逐字节),不是长度。
let (status, _ct, body) = call_dir_with_range(&tmp, "/other.txt", Some("bytes=0-1000")).await;
if status != StatusCode::PARTIAL_CONTENT {
failures.push(format!(
"/other.txt(片段 Range)应当是 206,实际 {status},body={}",
&body[..body.len().min(200)]
));
}
if body.len() != 1001 {
failures.push(format!(
"/other.txt(片段 Range)响应体长度应为 1001,实际 {}",
body.len()
));
}
let _ = std::fs::remove_dir_all(&tmp);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}