Files
tdc-rs/tests/spa_fallback.rs
T
adminandClaude Code 3f66cf2834 fix(fallback): DDL 守卫改「任一段命中」口径,注释只写可证明的规则
影响:
- `is_ddl_path` 从「只看末段」改为「路径中任意一段(去尾部空白、忽略大小写)
  等于 migrate.sql 即命中」。旧口径下 `/migrate.sql/.` 等 24 条变体绕过守卫,
  ServeDir 归一化时丢弃 `Component::CurDir` 后直接把 DDL 文件端出来。
- 变体清单从 4 条扩到 36 条,逐条断言 404 + application/json + 响应体无标记串;
  任何一条漏网即红。另加一条 `ddl_is_blocked_by_any_path_segment` 单独钉住
  「任一段」口径;`static_assets_are_still_served` 补 content-type 断言
  (原来对「ServeDir 根目录坏掉」零区分度)。
- README:系统列改 10 个 / 24 张带齐 / 6 张精简 / 21 个唯一索引含 14 个 partial;
  实体写入能力改「通用读取 + 按实体分档」;动作端点区分两段式 404 与单段式 200。

改动:
- src/routes/fallback.rs:is_ddl_path 改任一段口径;模块语义表、DDL 守卫说明、
  ddl_guard / is_ddl_path 注释按新口径重写,并写清守卫边界(只认这一个文件名,
  根因修复是「DDL 文件不在 web root」);补「只 decode 一层是刻意选择」。
- src/main.rs:装配处两处守卫注释同步为同一口径。
- tests/spa_fallback.rs:36 条变体循环 + 新增任一段用例 + 静态资源 content-type
  断言;临时目录名加进程内自增序号,消除同进程并发用例的目录名撞车。
- README.md:四处按代码实测对齐。

设计:
- 判据取「任一段命中」而不是复刻 ServeDir 的归一化,避免两边口径再对不齐。
- 注释只写能被证明的规则,删掉「任何路径变体都拦」这类全称量词。

Co-Authored-By: Claude Code <[email protected]>
2026-10-25 08:45:57 +08:00

314 lines
13 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 兜底服务(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::routes::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) {
let svc = spa_fallback(dir);
let req = Request::builder()
.uri(uri)
.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("<title>尚数网可信数据空间(连接器)</title>"),
"应是上游 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` 下造一个「含 `migrate.sql` 的 web root」(并发安全的名字)。
///
/// 内容用**可识别的标记串**(不是真 DDL,避免报告里出现真 DDL 片段)。
///
/// 🔴 名字 = **pid + 纳秒 + 进程内自增序号**:单靠纳秒仍有残余竞争
/// (同进程内两个并发用例可能拿到同一个纳秒 ⇒ 目录名撞车 ⇒
/// 先结束的那个把后者的目录删了 ⇒ 后者读到 `index.html missing`)。
/// 自增序号保证同进程内唯一。
fn tmp_web_root_with_ddl() -> 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 失败");
std::fs::write(
tmp.join("migrate.sql"),
"CREATE TABLE tdc_secret (id text);\n-- DDL MUST NOT LEAK\n",
)
.expect("写临时 migrate.sql 失败");
std::fs::write(tmp.join("index.html"), "<title>tmp</title>").expect("写临时 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 条 + 尾斜杠 / 编码斜杠 / 尾部空白等护栏。
const VARIANTS: [&str; 36] = [
// 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",
];
let mut failures: Vec<String> = 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<String> = 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"));
}