- src/routes/fallback.rs: spa_fallback 返回 Router 并挂 from_fn(ddl_guard) 前置守卫(axum 0.8.9 的 Router::layer 同时包住 fallback_router 与 catch_all_fallback ⇒ 守卫必然先于 ServeDir);决策层的 DDL 判定移除(死代码), is_api_path/is_ddl_path 统一改用 percent-decode 之后的路径 - src/main.rs: 注释改成事实——真正的守卫是 ddl_guard,不是那条字面路由 - tests/spa_fallback.rs: 新增 ddl_in_web_root_is_still_not_downloadable (临时 web root 里放 migrate.sql ⇒ 仍须 404 + JSON 且不含 CREATE TABLE), 并在既有用例里追加 /api%2Ffoo ⇒ 404 JSON、/apifoo ⇒ 不被误吞 - README.md: 删虚构的「契约网关」与「6 条脱敏规则 + 默认环境空间」, 换成真实的 30 张表,并把已删除的旧控制台生命周期能力改成现状说明 (动作端点属后续分期、尚未实现 ⇒ 前端点这些按钮会 404) Co-Authored-By: Claude Code <[email protected]>
208 lines
8.0 KiB
Rust
208 lines
8.0 KiB
Rust
//! 兜底服务(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` 直接出,不走兜底)。
|
||
#[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)]
|
||
);
|
||
}
|
||
|
||
/// 🔴 **回归点(R2-1)**:DDL 文件**就在 web root 里**时,也**必须**下不到。
|
||
///
|
||
/// 这条测试证明的是「前置守卫 `ddl_guard` 真的跑在 `ServeDir` **之前**」:
|
||
/// - 若守卫只在 `ServeDir` 的 decision 层(文件没找到时)判定 ⇒ 这里会 **200 + 完整 DDL**;
|
||
/// - 若守卫是前置中间件 ⇒ 无论文件在不在 web root,都是 **404 + JSON**。
|
||
#[tokio::test]
|
||
async fn ddl_in_web_root_is_still_not_downloadable() {
|
||
// 在临时目录里造一个「含 migrate.sql 的 web root」。
|
||
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)
|
||
));
|
||
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 失败");
|
||
|
||
let mut failures: Vec<String> = Vec::new();
|
||
for uri in [
|
||
"/migrate.sql",
|
||
"/MIGRATE.SQL",
|
||
"/migrate%2Esql",
|
||
"//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(DDL 在 web root 里也下不到),实际 {status},body={head}"
|
||
));
|
||
}
|
||
if ct != "application/json" {
|
||
failures.push(format!("uri={uri} 必须是 JSON,实际 {ct},body={head}"));
|
||
}
|
||
if body.contains("CREATE TABLE") {
|
||
failures.push(format!("uri={uri} 响应体不得含 DDL:{head}"));
|
||
}
|
||
}
|
||
|
||
// 只删**自己**在 temp_dir 下建的那个目录(不碰仓库里任何东西)。
|
||
let _ = std::fs::remove_dir_all(&tmp);
|
||
|
||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||
}
|