fix(fallback): DDL 守卫改两层——扩展名类规则 + 内容逐字节兜底

影响:DDL 不再能被任何路径拼法下载。旧守卫只比 ASCII 大小写,
`migrate.ſql`(APFS 上与 `migrate.sql` 是同一个文件)会漏网并吐出 99 KB DDL。
改后路径级判据是「任意一段的扩展名经 Unicode 大写折叠等于 SQL」
(覆盖 `migrate.sql` 的全部 1536 种 casefold 等价拼法),另加一层
「响应体与内嵌 DDL 逐字节相同 ⇒ 404」兜住改了名、但内容没变的副本。

改动:
- src/routes/fallback.rs:is_ddl_path 改为扩展名类规则(Unicode 大写折叠);
  新增 ddl_content_guard(只在 `Content-Length` 等于 DDL 长度时逐字节比对:
  长度缺失 / 片段响应不比,长度与实际不符 ⇒ fail-closed;
  整份 Range(`bytes=0-`)的长度等于整份 ⇒ 同样被拦);
  语义表改为「充分条件」表述,覆盖范围与边界按本机实测写入模块文档。
- src/main.rs:注释同步(守卫已不是「只认一个文件名」的单条规则)。
- tests/spa_fallback.rs:变体清单 36 → 44 条;新增两个用例——Unicode casefold
  一族、以及「改名但内容逐字节相同」的副本(含等长不同内容的反向护栏
  与整份 Range 的绕过口)。
- README.md:单段式动作端点按方法分述(GET 200 业务信封 / POST 405);
  DDL 的两道兜底写进说明。

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
adminandClaude Code committed 2026-10-25 10:39:25 +08:00
1 parent 3f66cf2834
commit 5b0111e7a7
4 files changed
+319 -52

No files matched your search

+6 -2
View File
@@ -30,7 +30,9 @@ PORT=30000 ./target/debug/tdc-connector
- 启动即初始化:Rust 进程内 `PGlite::open(data/tdc.pg)`,若 `tdc_identity` 不存在则执行
内嵌的 `schema/migrate.sql`(`include_str!` 进二进制,**30 张表**,上游 `tdc_*` schema 的生成产物)。
- 数据全部落在 Rust 进程内嵌库;控制台(上游 SPA)通过 `/api/ssw/tdc/*` 读写。
- schema DDL 在 `schema/migrate.sql`(**编译期内嵌**,**刻意不在 web root**)⇒ 不可从 HTTP 下载。
- schema DDL 在 `schema/migrate.sql`(**编译期内嵌**,**刻意不在 web root**)⇒ 不可从 HTTP 下载;
另有**两道兜底**(`src/routes/fallback.rs`):**路径级**(任意一段路径的扩展名经 Unicode
大写折叠后等于 `SQL` ⇒ 404 JSON)+ **内容级**(响应体与内嵌 DDL 逐字节相同 ⇒ 404 JSON)。
## 控制台(前端)
@@ -126,7 +128,9 @@ sccache 0.18 经 `~/.cargo/config.toml` 的 `[build] rustc-wrapper` + `[env] SCC
> 本仓**不提供**这些动作端点的占位实现 ⇒ 请求的实际表现分两种:
> - **两段式**(`/{Entity}/{id}/{Action}`,如 `/api/ssw/tdc/Product/{id}/Offline`)⇒ **404 + JSON**;
> - **单段式**(`/{Entity}/{Action}`,如 `/api/ssw/tdc/Product/publish`)⇒ 被详情路由
> `/{Entity}/{id}` 吃掉,`publish` 被当成 id ⇒ **200** 业务信封『记录不存在或已删除』。
> `/{Entity}/{id}` 吃掉,`publish` 被当成 id ⇒ **GET** 得到 **200** 业务信封
> 『记录不存在或已删除』;**POST** 则该路径只注册了 `GET`/`PUT`/`DELETE`
> ⇒ **405**(由 `src/routes/mw.rs` 改写成业务信封,**保留 `Allow` 头**)。
## 明确不在 MVP 内(原 `ssw-tdc` 的隐私计算作业)
+9 -7
View File
@@ -144,16 +144,18 @@ async fn main() {
// ⇒ **绝不能**从 HTTP 下载(上游部署里 DDL 不在 web root)。
// 🔴 该文件**已移出 web root**(现在在 `schema/`)⇒ ServeDir 根本读不到它;
// 这条字面路由只是**额外**兜住这个字面路径。
// 🔴 **文件名级的前置守卫**是 `routes::fallback::ddl_guard`(**跑在 `ServeDir` 之前**
// 的前置中间件):判据是「路径中**任意一段**(去尾部空白、忽略大小写)
// 等于 `migrate.sql`」⇒ 该文件名不会被 `ServeDir` 吐出。
// ⚠️ 守卫**只认这一个文件名**;web root 里叫别的名字的文件**不拦**
// ⇒ 根因修复是「DDL 文件不在 web root」,守卫只是前置兜底。
// 🔴 **前置守卫**是 `routes::fallback::ddl_guard`(**跑在 `ServeDir` 之前**
// 的前置中间件),**两层**:
// ① 路径级:路径中**任意一段的扩展名**(去尾部空白与尾部 `.`、
// **Unicode 大写折叠**后)等于 `SQL` ⇒ 404 + JSON(**类**规则,`.sql` 全覆盖);
// ② 内容级:响应体与**内嵌 DDL 逐字节相同** ⇒ 404 + JSON(与拼法/大小写无关)。
// ⚠️ 两层都是**兜底**;根因修复是「DDL 文件不在 web root」。
.route("/migrate.sql", any(api_not_found))
// ③ 静态托管挂**根**(vite base 是 `/`,产物引用 `/assets/...`)
// 兜底服务(`routes::fallback::spa_fallback`):
// - **前置守卫** `ddl_guard` ⇒ 路径中任意一段等于 `migrate.sql` 时 404 + JSON
// (先于 ServeDir;守卫只认这一个文件名,别的文件名不拦)
// - **前置守卫** `ddl_guard` ⇒ 路径中任意一段的扩展名(Unicode 大写折叠后)
// 等于 `SQL` 时 404 + JSON(**先于** ServeDir)
// - **内容兜底** `ddl_content_guard` ⇒ 响应体与**内嵌 DDL 逐字节相同** ⇒ 404 + JSON
// - 命中 `static/` 里的真实文件 ⇒ 直接出(`/assets/*.js`、`/logo.png` …)
// - `/api`、`/api/`、`/api/**` ⇒ 404 + JSON(**不是** SPA 的 HTML)
// - 其余(`/tdc/home`、`/login` 等 SPA 深链)⇒ 200 + `index.html`
+126 -27
View File
@@ -5,24 +5,40 @@
//!
//! ## 语义
//!
//! | 请求路径 | 响应 |
//! 下表是**充分条件**(命中即如此),**不是**穷举:
//!
//! | 请求路径 / 响应 | 结果 |
//! |---|---|
//! | `/api`、`/api/`、`/api/**` | **404 + JSON**(`api_not_found()`) |
//! | 路径中**任意一段**(去尾部空白、忽略大小写)等于 `migrate.sql` | **404 + JSON**(**前置守卫** `ddl_guard`) |
//! | 其余(`/tdc/home`、`/login` 等 SPA 深链) | **200 + `text/html`**(`static/index.html`) |
//! | 命中 `static/` 里的真实文件(`/assets/*.js`、`/logo.png` …) | 由 `ServeDir` 直接出 |
//! | 路径中**任意一段**的**扩展名**(去尾部空白与尾部 `.`、**Unicode 大写折叠**后)等于 `SQL` | **404 + JSON**(**前置守卫** `ddl_guard`) |
//! | 命中 `static/` 里的真实文件、且响应体**不**与内嵌 DDL 逐字节相同 | 由 `ServeDir` 直接出 |
//! | 响应体与**内嵌 DDL 逐字节相同**(**不论文件名**) | **404 + JSON**(**内容级兜底** `ddl_content_guard`) |
//! | 其余未命中路径(`/tdc/home`、`/login` 等 SPA 深链) | **200 + `text/html`**(`static/index.html`) |
//!
//! ⚠️ **「不命中上表」不等于「响应形状一定是 200 HTML」**:例如 `/migrate.sql%00`
//! (尾部 NUL)这类**拼法与 DDL 文件名不同**的路径**不**命中守卫
//! ⇒ 交由 `ServeDir` 处理 ⇒ 该文件名不存在 ⇒ 落到 SPA 决策层(200 + `text/html`)。
//! **不会**泄露 DDL(那不是同一个文件名),但**响应形状**与上表不同。
//!
//! ## 为什么 DDL 要单独判
//!
//! 🔴 **根因修复**:DDL 文件**已移出 web root**(现在在 `schema/`,编译期 `include_str!` 内嵌),
//! 所以 `ServeDir` 根本读不到它。
//! 🔴 **前置守卫(文件名级)**:`ddl_guard` 是**跑在 `ServeDir` 之前**的中间件
//! (`Router::layer` 在 axum 0.8.9 会同时包住 `fallback_router` 与 `catch_all_fallback`
//! ⇒ 守卫先于 `ServeDir` 执行)。
//! 它的判据是「**路径中任意一段**(去尾部空白、忽略大小写)等于 `migrate.sql`」。
//! ⚠️ **边界**:守卫**只认这一个文件名**。web root 里若存在**别的** `.sql`
//! (或任何其它名字的文件),守卫**不拦** ⇒ 真正的修复是「DDL 文件不在 web root」,
//! 守卫只是文件名级的前置兜底,不是「web root 里任何文件都吐不出来」。
//! ⚠️ 这才是**根本控制**;下面两道都是**兜底**。
//!
//! 🔴 **兜底 1 · 路径级(`ddl_guard`,跑在 `ServeDir` 之前)**:
//! `Router::layer` 在 axum 0.8.9 会同时包住 `fallback_router` 与 `catch_all_fallback`
//! ⇒ 守卫先于 `ServeDir` 执行。
//! 判据是「**路径中任意一段的扩展名**,经 **Unicode 大写折叠**后等于 `SQL`」
//! ⇒ web root 里**任何** `.sql` 文件都不会被吐出去(**类**规则,不只 `migrate.sql` 这一个名字)。
//!
//! 🔴 **兜底 2 · 内容级(`ddl_content_guard`,跑在 `ServeDir` 之后)**:
//! 「与**内嵌 DDL 逐字节相同**的响应 ⇒ 404 + JSON」。
//! 这条判据**只认内容**,与文件名怎么拼、大小写怎么折叠、路径怎么规范化**全都无关**
//! ⇒ 兜住「改了名字、但内容还是那份 DDL」的副本。
//!
//! ⚠️ **边界**:兜底 1 覆盖 `.sql` 这一**类**扩展名;兜底 2 只覆盖**与内嵌 DDL 逐字节相同**的内容
//! (**改过一个字节**的副本不覆盖)⇒ 真正的控制仍然是「DDL 文件不在 web root」。
//!
//! ## 为什么 `/api` 用「精确前缀」而不是裸 `starts_with`
//!
@@ -50,8 +66,23 @@ use axum::Router;
use serde_json::json;
use tower_http::services::ServeDir;
/// schema DDL 的文件名(**绝不能**从 web root 下载)。
const DDL_FILENAME: &str = "migrate.sql";
/// DDL 的**扩展名**(判定用,见 [`is_ddl_path`])。
///
/// 🔴 用**大写折叠**比较(`to_uppercase`),不是 ASCII 不区分大小写:
/// macOS APFS 的文件名比较用的是 **Unicode casefold**,
/// `ſ`(U+017F,长 s)casefold 到 `s` ⇒ `migrate.ſql` 在磁盘上**就是** `migrate.sql`。
/// `to_uppercase` 把扩展名的 **12 种** casefold 等价拼法
/// (`s`∈{`s`,`S`,`ſ`} × `q`∈{`q`,`Q`} × `l`∈{`l`,`L`})**全部**映射到 `"SQL"`
/// ⇒ 一网打尽;`to_lowercase` 则会让 `ſ` 留在原地 ⇒ 漏。
const DDL_EXTENSION: &str = "SQL";
/// **内嵌**的 schema DDL(与仓库里的 `schema/migrate.sql` 逐字节相同)。
///
/// 🔴 用途:**内容级**兜底的比对基准(见 [`ddl_content_guard`])——
/// 「响应体与这份内容**逐字节相同** ⇒ 404 + JSON」。
/// 这条判据**不依赖文件名、不依赖大小写折叠、不依赖路径规范化**
/// ⇒ 拼法再怎么变都逃不掉。
const DDL_BYTES: &str = include_str!("../../schema/migrate.sql");
/// `/api/**` 未命中 ⇒ 404 + JSON(**不**返回 SPA 的 HTML)。
///
@@ -79,7 +110,7 @@ pub async fn api_not_found() -> Response {
/// 🔴 返回的是 `Router`(不是 `ServeDir`)——因为 **DDL 前置守卫 `ddl_guard` 必须跑在
/// `ServeDir` 之前**:`axum 0.8.9` 的 `Router::layer` 会同时包住 `fallback_router`
/// 与 `catch_all_fallback`(`axum-0.8.9/src/routing/mod.rs:303-317`)
/// ⇒ 守卫先于 `ServeDir` 执行 ⇒ 名为 `migrate.sql` 的路径不会由 `ServeDir` 吐出。
/// ⇒ 守卫先于 `ServeDir` 执行 ⇒ **扩展名命中 `.sql` 的路径不会由 `ServeDir` 吐出**。
///
/// ⚠️ 为什么不用 `tower::service_fn`:`tower` 只是 **dev-dependency**,
/// **lib 代码里不许用** `tower::service_fn` / `ServiceExt` ⇒ 用 axum 自己的 `any(handler)`。
@@ -96,21 +127,58 @@ pub fn spa_fallback(static_dir: impl Into<PathBuf>) -> Router {
.layer(axum::middleware::from_fn(ddl_guard))
}
/// 🔴 **DDL 前置守卫**:路径中**任意一段**(去尾部空白、忽略大小写)等于 DDL 文件名
/// ⇒ 404 + JSON。
/// 🔴 **DDL 前置守卫**:路径中**任意一段的扩展名**(去尾部空白与尾部 `.`、
/// **Unicode 大写折叠**后)等于 `SQL` ⇒ 404 + JSON。
///
/// 🔴 **跑在 `ServeDir` 之前**(见 `spa_fallback` 的说明)。
///
/// 判定用的是 **percent-decode 之后**的路径(与决策层同一口径)。
///
/// ⚠️ **边界**:判据只覆盖**这一个文件名** `migrate.sql`——
/// web root 里叫别的名字的 SQL 文件**不拦**。根因修复是「DDL 文件不在 web root」,
/// 本守卫只是文件名级的前置兜底。
/// ⚠️ **边界**:这是**类**规则(覆盖 `.sql` 这一类扩展名),但**只认扩展名**——
/// 「改了名、扩展名不再是 `.sql`」的副本**不拦** ⇒ 由 [`ddl_content_guard`] 兜。
pub async fn ddl_guard(request: Request, next: Next) -> Response {
if is_ddl_path(&decoded_path(request.uri().path())) {
return api_not_found().await;
}
next.run(request).await
ddl_content_guard(next.run(request).await).await
}
/// 🔴 **内容级兜底**:响应体与**内嵌 DDL 逐字节相同** ⇒ 404 + JSON。
///
/// 🔴 这条判据**只认内容**:文件名怎么拼、大小写怎么折叠、路径怎么规范化,**全都无关**
/// ⇒ 兜住「改了名字、但内容还是那份 DDL」的副本。
///
/// 🔴 **只在「长度正好是 DDL 长度」的响应上比对**,理由是**不能吞掉响应体**:
/// - `Content-Length` 缺失 ⇒ 长度未知 ⇒ **不比对**(否则要么无界缓冲、要么把体吃掉);
/// - `Content-Length` ≠ DDL 长度 ⇒ 内容不可能是 DDL ⇒ 直接放行
/// (**含 Range 片段**:片段的 `Content-Length` 小于整份 ⇒ 不比对)。
///
/// `ServeDir` 的文件响应**一定**带 `Content-Length`(`tower-http-0.6.11`
/// `src/services/fs/serve_dir/future.rs:317`;Range 分支在 `:284`),
/// ⇒ 真正的 DDL 文件**一定**落进「长度正好是 DDL 长度」这一支。
/// ⚠️ **整份 Range 请求**(`Range: bytes=0-`)的 `Content-Length` 也等于整份长度
/// ⇒ 同样会被逐字节比较并拦下(**不要**在这里按 `Content-Range` 放行:
/// 那样整份 Range 就成了绕过口)。
///
/// ⚠️ **边界**:只覆盖**与内嵌 DDL 逐字节相同**的内容(**改过一个字节**的副本不覆盖),
/// **片段响应**(`Content-Length` < DDL 长度,如部分 Range)不覆盖
/// ⇒ 根本控制仍然是「DDL 文件不在 web root」。
async fn ddl_content_guard(response: Response) -> Response {
let length = response
.headers()
.get(header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<usize>().ok());
if length != Some(DDL_BYTES.len()) {
return response;
}
let (parts, body) = response.into_parts();
match axum::body::to_bytes(body, DDL_BYTES.len()).await {
Ok(bytes) if bytes.as_ref() == DDL_BYTES.as_bytes() => api_not_found().await,
Ok(bytes) => Response::from_parts(parts, axum::body::Body::from(bytes)),
// `Content-Length` 说谎(实际比声明的长)⇒ fail-closed。
Err(_) => api_not_found().await,
}
}
/// 兜底决策:`/api` 命名空间 ⇒ 404 JSON;否则 ⇒ `index.html`。
@@ -143,7 +211,7 @@ fn is_api_path(decoded_path: &str) -> bool {
decoded_path == "/api" || decoded_path.starts_with("/api/")
}
/// 路径的**任意一段**(去尾部 ASCII 空白、忽略大小写)是否等于 DDL 文件名。
/// 路径的**任意一段**的**扩展名**是否命中 DDL 扩展名类(`SQL`)。
///
/// 🔴 判据是「**任意一段**」而不是「最后一段」——
/// `tower-http-0.6.11/src/services/fs/serve_dir/mod.rs:462-492` 用
@@ -151,16 +219,47 @@ fn is_api_path(decoded_path: &str) -> bool {
/// 于是 `/migrate.sql/.` 被 `ServeDir` 解析成「文件 `migrate.sql`」;
/// 只看末段会让 `.` / `%2e` 结尾的一族绕过守卫。
///
/// 🔴 **为什么是「扩展名 + Unicode 大写折叠」而不是「文件名 + ASCII 折叠」**:
/// macOS APFS 的文件名比较用的是 **Unicode casefold**,不是 ASCII 折叠——
/// `ſ`(U+017F,长 s)casefold 到 `s` ⇒ 磁盘上叫 `migrate.sql` 的文件,
/// 用 `migrate.ſql` 也能打开(**本机实测**:12 种扩展名拼法
/// `s∈{s,S,ſ} × q∈{q,Q} × l∈{l,L}` **全部**命中同一个文件)。
///
/// DDL 文件名 `migrate.sql` 的**逐字符 casefold 等价拼法**是**有限集**:
/// `migrate` 七个字母各 2 种(`m/M`…`e/E`)⇒ 2⁷;`.` 1 种;
/// `s` 3 种(`s`/`S`/`ſ`);`q` 2 种;`l` 2 种
/// ⇒ 2⁷×1×3×2×2 = **1536** 种。
/// **本机实测**:这 1536 种在磁盘上**全部**命中同一个文件,且**全部**被本判据覆盖。
/// 这 1536 种的**扩展名**就是那 12 种拼法,而 12 种经 **Unicode 大写折叠**
/// **全部**得到 `SQL`(`ſ` 大写为 `S`)⇒ 本判据**覆盖 1536 / 1536**。
/// ⚠️ 必须用 `to_uppercase`:`to_lowercase` 会让 `ſ` 留在原地
/// ⇒ 漏掉含 `ſ` 的 512 种。(旧的 `eq_ignore_ascii_case` 只覆盖 1024 / 1536。)
///
/// **充分性**:`ServeDir` 对**每个** `Component::Normal` 都 `push`
/// (Windows 上另有一道「保留设备名」检查,`migrate.sql` 不在其中),
/// 要吐出名为 `migrate.sql` 的文件,该文件名**必然**是其中一段
/// ⇒ 「任一段命中」⇒ 必拦。
/// ⇒ 要吐出名为 `migrate.sql`(或其 casefold 等价名)的文件,
/// 请求路径里对应的那一段**必然**是上述 1536 种拼法之一
/// ⇒ 该段扩展名大写折叠后**必然**是 `SQL` ⇒ 必拦。
///
/// ⚠️ **边界**:只看**扩展名** ⇒ 「改了名、扩展名不再是 `.sql`」的副本**不拦**
/// ⇒ 由 [`ddl_content_guard`] 按**内容**兜。
///
/// ⚠️ 入参**必须**是 [`decoded_path`] 之后的路径(守卫与决策层同一口径)。
fn is_ddl_path(decoded_path: &str) -> bool {
decoded_path
.split('/')
.any(|seg| seg.trim_end().eq_ignore_ascii_case(DDL_FILENAME))
decoded_path.split('/').any(is_ddl_segment)
}
/// 一段路径是否是「DDL 扩展名类」:去尾部空白与尾部 `.` 后,扩展名大写折叠后是 `SQL`。
///
/// ⚠️ **去尾部空白与 `.`** 是**保守**处理:APFS 上「尾部带点/带空格的名字」不是同一个文件
/// (本机实测:`migrate.sql.` / `migrate.sql ` 都打不开),但 HFS+ 会把尾部点
/// **从磁盘名里去掉** ⇒ 两种文件系统的行为不一致 ⇒ 一律按「命中」处理(多拦不错放)。
/// 判定用 `trim_end_matches(谓词)`,**空白与点混着排**也一并去掉(如 `migrate.sql . `)。
fn is_ddl_segment(segment: &str) -> bool {
let normalized = segment.trim_end_matches(|c: char| c.is_whitespace() || c == '.');
match normalized.rsplit_once('.') {
Some((_, extension)) => extension.to_uppercase() == DDL_EXTENSION,
None => false,
}
}
/// 判定用的**归一化路径**:percent-decode 之后的结果。
+178 -16
View File
@@ -25,11 +25,21 @@ async fn call(uri: &str) -> (StatusCode, String, String) {
/// 打一个请求到**指定** 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 req = Request::builder()
.uri(uri)
.body(Body::empty())
.expect("构造请求失败");
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
@@ -164,15 +174,13 @@ async fn static_assets_are_still_served() {
);
}
/// 在 `temp_dir` 下造一个「含 `migrate.sql` 的 web root」(并发安全的名字)。
///
/// 内容用**可识别的标记串**(不是真 DDL,避免报告里出现真 DDL 片段)。
/// 在 `temp_dir` 下造一个 web root,写入给定的 `(相对路径, 内容)` 文件对。
///
/// 🔴 名字 = **pid + 纳秒 + 进程内自增序号**:单靠纳秒仍有残余竞争
/// (同进程内两个并发用例可能拿到同一个纳秒 ⇒ 目录名撞车 ⇒
/// 先结束的那个把后者的目录删了 ⇒ 后者读到 `index.html missing`)。
/// 自增序号保证同进程内唯一。
fn tmp_web_root_with_ddl() -> PathBuf {
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!(
@@ -185,15 +193,29 @@ fn tmp_web_root_with_ddl() -> PathBuf {
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 失败");
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", "<title>tmp</title>"),
])
}
/// 🔴 **回归点(R2-1 / R3-1)**:DDL 文件**就在 web root 里**时,下列**每一条**变体都**必须**下不到。
///
/// 这条测试证明的是「前置守卫 `ddl_guard` 真的跑在 `ServeDir` **之前**」:
@@ -209,8 +231,9 @@ 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] = [
// 变体清单:复评实测漏网的 24 条 + R2 的 4 条 + 尾斜杠 / 编码斜杠 / 尾部空白等护栏
// + R4 的 Unicode casefold 一族(`ſ` 家族:旧守卫用 ASCII 折叠 ⇒ 这一族会漏网)。
const VARIANTS: [&str; 44] = [
// R2 的 4 条(原本就在)
"/migrate.sql",
"/MIGRATE.SQL",
@@ -253,6 +276,16 @@ async fn ddl_in_web_root_is_still_not_downloadable() {
"/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<String> = Vec::new();
@@ -311,3 +344,132 @@ async fn ddl_is_blocked_by_any_path_segment() {
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<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(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", "<title>tmp</title>"),
]);
let mut failures: Vec<String> = 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}"));
}
let _ = std::fs::remove_dir_all(&tmp);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}