Files
tdc-rs/src/routes/fallback.rs
T
adminandClaude Code 0828bcfbc1 fix(fallback): 内容级兜底连 Range 分段一起拦,别让 DDL 被分块拼回来
影响:改名(或任意换名)的 DDL 副本之前只能用「整份响应」判据拦住;
`Range: bytes=0-1000` 这类分块请求的响应体只有 1001 字节 ⇒ 逃过整份比对 ⇒
逐段请求能把整份 DDL **拼回来**(实测 206 吐出 DDL 开头 1001 字节)⇒ 等于完整泄露。

改动:
- `src/routes/fallback.rs`:内容级兜底改为「拿响应体的哪一段去比」——
  无 `Content-Range` 时比整份(`Content-Length` 正好等于 DDL 长度才比),
  有 `Content-Range` 时比**同偏移**的 DDL 片段(`DDL[start..=end]`)⇒ 分块下载同样被拦。
- 新增 `parse_content_range`(只认 `bytes` 单位 + 闭区间,忽略 `total`)。
- `tests/spa_fallback.rs`:补 ④ 片段 Range ④⑤ 中段 Range ⇒ 404 JSON 且不含 DDL,
  ⑥ 片段 Range 打在等长不同内容的文件上 ⇒ 仍 206(证明比的是内容不是长度)。
- `src/main.rs` / `README.md`:兜底描述同步为「整份或 Range 分段」。

设计:`total` 段被忽略 ⇒ 「DDL + 一段尾巴」这类副本的前 N 字节同样被拦。

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

331 lines
18 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 兜底。
//!
//! 本模块把「未命中路径」的处理从二进制 crate(`src/main.rs`)搬进 lib,
//! 于是集成测试(`tests/spa_fallback.rs`)能**直接**对它 `oneshot` 断言行为。
//!
//! ## 语义
//!
//! 下表是**充分条件**(命中即如此),**不是**穷举:
//!
//! | 请求路径 / 响应 | 结果 |
//! |---|---|
//! | `/api`、`/api/`、`/api/**` | **404 + JSON**(`api_not_found()`) |
//! | 路径中**任意一段**的**扩展名**(去尾部空白与尾部 `.`、**Unicode 大写折叠**后)等于 `SQL` | **404 + JSON**(**前置守卫** `ddl_guard`) |
//! | 响应体与**内嵌 DDL 逐字节相同**(**不论文件名**) | **404 + JSON**(**内容级兜底** `ddl_content_guard`) |
//! | 响应体是**内嵌 DDL 的某一片段**(`Range` 分块下载) | **404 + JSON**(**内容级兜底** `ddl_content_guard`) |
//! | 命中 `static/` 里的真实文件、且响应体**不**与内嵌 DDL 逐字节相同 | 由 `ServeDir` 直接出 |
//! | 其余未命中路径(`/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` 根本读不到它。
//! ⚠️ 这才是**根本控制**;下面两道都是**兜底**。
//!
//! 🔴 **兜底 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」的副本。
//! ⚠️ **必须连 `Range` 分段一起兜**:`Range: bytes=0-1000` 的响应体只有 1001 字节,
//! 逐段请求能把整份 DDL **拼回来** ⇒ 那等于**完整泄露**。
//!
//! ⚠️ **边界**:兜底 1 覆盖 `.sql` 这一**类**扩展名;兜底 2 只覆盖**与内嵌 DDL 逐字节相同**的内容
//! (**改过一个字节**的副本:整份响应不拦)⇒ 真正的控制仍然是「DDL 文件不在 web root」。
//!
//! ## 为什么 `/api` 用「精确前缀」而不是裸 `starts_with`
//!
//! `/apifoo` 这类**非** `/api` 命名空间的 SPA 深链仍应回 `index.html`(前端路由接管),
//! 不能被误吞成 404 JSON。
//!
//! ## 路径判定口径(守卫与决策层**必须一致**)
//!
//! 两处都先 **percent-decode** 再判定:
//! - `/api%2Ffoo` 解码后是 `/api/foo` ⇒ 落在 `/api` 命名空间 ⇒ **404 JSON**;
//! - `/apifoo` 解码后仍是 `/apifoo` ⇒ **不被误吞**(回 SPA HTML)。
//!
//! ⚠️ **只 decode 一层是刻意选择**(契约,不是遗漏):decode 两层会让 `%252F` 变成 `/`,
//! 与 `ServeDir` / 浏览器对同一 URL 的解释**不一致**;decode 零层又认不出 `%2F`。
//! 一层 decode 恰好与 `ServeDir`(`tower-http` 也只 decode 一层)对齐。
use std::path::{Path, PathBuf};
use axum::extract::Request;
use axum::http::{header, StatusCode, Uri};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::routing::any;
use axum::Router;
use serde_json::json;
use tower_http::services::ServeDir;
/// 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)。
///
/// 🔴 形状与 `auth::reject` 同族(裸三字段、**无 `data` 键**):
/// 前端 axios 错误分支 `Promise.reject(new Error(body.msg || …))` ⇒ 「接口不存在」如实显示。
/// 若这里回 HTML(200 + `text/html`)⇒ 前端拦截器判 `body.code === undefined`
/// ⇒ **不 reject** ⇒ 视图静默渲染成「空表且不报错」⇒ 把「接口没了」误读成「没有数据」。
pub async fn api_not_found() -> Response {
(
StatusCode::NOT_FOUND,
axum::Json(json!({
"success": false,
"code": 404,
"msg": "接口不存在"
})),
)
.into_response()
}
/// 兜底服务:`ServeDir`(出 `static/` 里的真实文件)+ **找不到文件时**的决策层。
///
/// 决策层是一个内层 `Router<()>`(`Router` 本身就是 `Service`,可直接当 `ServeDir` 的 fallback):
/// `/api` 命名空间 ⇒ 404 JSON;其余 ⇒ `static/index.html`(200 `text/html`)。
///
/// 🔴 返回的是 `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` 执行 ⇒ **扩展名命中 `.sql` 的路径不会由 `ServeDir` 吐出**。
///
/// ⚠️ 为什么不用 `tower::service_fn`:`tower` 只是 **dev-dependency**,
/// **lib 代码里不许用** `tower::service_fn` / `ServiceExt` ⇒ 用 axum 自己的 `any(handler)`。
pub fn spa_fallback(static_dir: impl Into<PathBuf>) -> Router {
let static_dir = static_dir.into();
let index_file = static_dir.join("index.html");
// 内层 Router:把「找不到文件」的决策交给 handler(`Router<()>` ⇒ 状态类型被钉死为 `()`)。
let decision: Router = Router::new().fallback(any(move |uri: Uri| {
let index_file = index_file.clone();
async move { fallback_response(&index_file, &uri).await }
}));
Router::new()
.fallback_service(ServeDir::new(&static_dir).fallback(decision))
.layer(axum::middleware::from_fn(ddl_guard))
}
/// 🔴 **DDL 前置守卫**:路径中**任意一段的扩展名**(去尾部空白与尾部 `.`、
/// **Unicode 大写折叠**后)等于 `SQL` ⇒ 404 + JSON。
///
/// 🔴 **跑在 `ServeDir` 之前**(见 `spa_fallback` 的说明)。
///
/// 判定用的是 **percent-decode 之后**的路径(与决策层同一口径)。
///
/// ⚠️ **边界**:这是**类**规则(覆盖 `.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;
}
ddl_content_guard(next.run(request).await).await
}
/// 🔴 **内容级兜底**:响应体是**内嵌 DDL**(或它的**某一片段**)⇒ 404 + JSON。
///
/// 🔴 这条判据**只认内容**:文件名怎么拼、大小写怎么折叠、路径怎么规范化,**全都无关**
/// ⇒ 兜住「改了名字、但内容还是那份 DDL」的副本。
///
/// 🔴 **比对哪一段**,由响应头决定(**不能吞掉响应体**,所以只在「有把握的那一段」上比对):
/// - **无 `Content-Range`** ⇒ 比**整份**:`Content-Length` **正好等于** DDL 长度才比
/// (缺失 ⇒ 长度未知 ⇒ **不比对**;不等 ⇒ 内容不可能是 DDL ⇒ 放行);
/// - **有 `Content-Range`** ⇒ 比**该偏移处的片段**:把响应体与
/// `DDL[start..=end]` 逐字节比。
///
/// 🔴 **为什么必须连分段一起兜**:`Range: bytes=0-1000` 这类**分块下载**的响应体
/// 只有 1001 字节(`Content-Length` ≠ DDL 长度)⇒ 只按「整份长度」比对会**放行**
/// ⇒ 而逐段请求可以把整份 DDL **拼回来** ⇒ 那就是**完整泄露**,不是「片段泄露」。
/// ⇒ 分段请求必须拿「同偏移的 DDL 片段」来比。
///
/// `ServeDir` 的文件响应**一定**带 `Content-Length`(`tower-http-0.6.11`
/// `src/services/fs/serve_dir/future.rs:317`;Range 分支在 `:284`),
/// Range 响应另外带 `Content-Range`(`:290` 附近)⇒ 两条判据都拿得到。
///
/// ⚠️ **边界**:只覆盖**与内嵌 DDL 逐字节相同**的内容
/// (**改过一个字节**的副本:整份响应不拦;但该副本的 Range 片段里,
/// **不含**那个改动字节的片段仍与 DDL 对应片段逐字节相同 ⇒ 仍会被拦)
/// ⇒ 根本控制仍然是「DDL 文件不在 web root」。
async fn ddl_content_guard(response: Response) -> Response {
let content_length = response
.headers()
.get(header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<usize>().ok());
let content_range = response
.headers()
.get(header::CONTENT_RANGE)
.and_then(|v| v.to_str().ok())
.and_then(parse_content_range);
// 要拿响应体的**哪一段**去和 DDL 比(`None` ⇒ 不比对,放行)。
let slice: Option<(usize, usize)> = match content_range {
// ① 分段响应 ⇒ 比**同偏移**的 DDL 片段。
Some((start, end)) if start <= end && end < DDL_BYTES.len() => Some((start, end)),
Some(_) => None,
// ② 整份响应 ⇒ 只在长度**正好**是 DDL 长度时才比。
None if content_length == Some(DDL_BYTES.len()) => Some((0, DDL_BYTES.len() - 1)),
None => None,
};
let Some((start, end)) = slice else {
return response;
};
let expected = &DDL_BYTES.as_bytes()[start..=end];
let (parts, body) = response.into_parts();
match axum::body::to_bytes(body, expected.len()).await {
Ok(bytes) if bytes.as_ref() == expected => api_not_found().await,
Ok(bytes) => Response::from_parts(parts, axum::body::Body::from(bytes)),
// 长度说谎(实际比声明的长)⇒ fail-closed。
Err(_) => api_not_found().await,
}
}
/// 解析 `Content-Range: bytes <start>-<end>/<total>` ⇒ `(start, end)`。
///
/// 🔴 **只认 `bytes` 单位 + 闭区间 `start-end`**;`total` 段**一律忽略**。
///
/// 🔴 **为什么忽略 `total`**:我们要判的是「**这一段**是不是内嵌 DDL 的对应片段」
/// ⇒ 只需要 `start`/`end`;忽略 `total` 还顺带兜住「DDL + 一段尾巴」这类副本
/// (`total` 比 DDL 长,但它的前 N 字节**就是** DDL 的前 N 字节 ⇒ 片段仍会被拦)。
fn parse_content_range(value: &str) -> Option<(usize, usize)> {
let rest = value.trim().strip_prefix("bytes ")?;
let (range, _total) = rest.split_once('/')?;
let (start, end) = range.trim().split_once('-')?;
Some((start.trim().parse().ok()?, end.trim().parse().ok()?))
}
/// 兜底决策:`/api` 命名空间 ⇒ 404 JSON;否则 ⇒ `index.html`。
///
/// ⚠️ DDL 判定**不在这里**(已由前置守卫 `ddl_guard` 拦在 `ServeDir` 之前 ⇒ 此处再判是死代码)。
async fn fallback_response(index_file: &Path, uri: &Uri) -> Response {
if is_api_path(&decoded_path(uri.path())) {
return api_not_found().await;
}
// SPA 深链 ⇒ 回 index.html(前端路由接管)。
match tokio::fs::read(index_file).await {
Ok(bytes) => ([(header::CONTENT_TYPE, "text/html")], bytes).into_response(),
Err(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
"index.html missing",
)
.into_response(),
}
}
/// 是否落在 `/api` 命名空间(`/api`、`/api/`、`/api/**`)。
///
/// 🔴 用 `== "/api" || starts_with("/api/")` 而不是裸 `starts_with("/api")`:
/// 后者会把 `/apifoo` 这类**非** API 的 SPA 深链也吞成 404 JSON。
///
/// ⚠️ 入参**必须**是 [`decoded_path`] 之后的路径(守卫与决策层同一口径):
/// `/api%2Ffoo` 解码后是 `/api/foo` ⇒ 属于 `/api` 命名空间 ⇒ 404 JSON。
fn is_api_path(decoded_path: &str) -> bool {
decoded_path == "/api" || decoded_path.starts_with("/api/")
}
/// 路径的**任意一段**的**扩展名**是否命中 DDL 扩展名类(`SQL`)。
///
/// 🔴 判据是「**任意一段**」而不是「最后一段」——
/// `tower-http-0.6.11/src/services/fs/serve_dir/mod.rs:462-492` 用
/// `Path::components()` 归一化并**丢弃 `Component::CurDir`(`.`)**,
/// 于是 `/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`
/// ⇒ 要吐出名为 `migrate.sql`(或其 casefold 等价名)的文件,
/// 请求路径里对应的那一段**必然**是上述 1536 种拼法之一
/// ⇒ 该段扩展名大写折叠后**必然**是 `SQL` ⇒ 必拦。
///
/// ⚠️ **边界**:只看**扩展名** ⇒ 「改了名、扩展名不再是 `.sql`」的副本**不拦**
/// ⇒ 由 [`ddl_content_guard`] 按**内容**兜。
///
/// ⚠️ 入参**必须**是 [`decoded_path`] 之后的路径(守卫与决策层同一口径)。
fn is_ddl_path(decoded_path: &str) -> bool {
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 之后的结果。
///
/// 🔴 守卫(`ddl_guard`)与决策层(`fallback_response`)**必须**用同一个口径,
/// 否则会出现「一边认为在 `/api` 下、另一边不认为」的不一致。
fn decoded_path(raw_path: &str) -> String {
percent_decode(raw_path)
}
/// 最小实现的 percent-decode(只处理 `%XX`;非法的 `%` 原样保留)。
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hi = (bytes[i + 1] as char).to_digit(16);
let lo = (bytes[i + 2] as char).to_digit(16);
if let (Some(hi), Some(lo)) = (hi, lo) {
out.push((hi * 16 + lo) as u8);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}