Files
tdc-rs/tests/spa_fallback.rs
T
adminandClaude Sonnet 5.5 e72345a958 fix(console): schema DDL 移出 web root,兜底行为抽进 lib 并锁进 CI
- static/migrate.sql ⇒ schema/migrate.sql(编译期内嵌不变,运行期不在 web root)
  ⇒ 大小写 / %2E / 尾斜杠 / 双斜杠等路径变体全部拿不到 DDL
- 404 与 SPA 兜底从二进制 crate 抽进 lib(src/routes/fallback.rs)
  ⇒ /api 与 /api/ 统一回 404 JSON,SPA 深链回 index.html
- 新增 tests/spa_fallback.rs:6 条断言锁住兜底行为
- README 整段重写为现行 18 实体 CRUD + 鉴权面 + 上游 SPA 托管
- build-frontend.sh 可执行;产物目录缺失时回落 npm 构建路径
- registry::validate() 挪到 PGlite::open 之前,注册表写坏即秒退
- mw.rs 注释点明两套 4xx 形状并存是刻意分歧

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 05:58:20 +08:00

134 lines
4.7 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::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) {
let svc = spa_fallback(static_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` 键**)。
#[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
);
}
/// `/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)]
);
}