Files
tdc-rs/tests/api_smoke.rs
T
adminandClaude Code 079dcff986 feat(console): 下线旧 API,托管上游完整前端构建产物
- 移除 /api/db/*、/api/ssw/tdc/node/identity*、/api/ssw/tdc/tds/* 及其旧 handler
- 静态托管改根挂载 + SPA fallback(深链回 index.html,vite base=/)
- /api/** 未命中回 404 + JSON(不吞成 SPA 的 HTML),/migrate.sql 同样 404
- 空体 405 改由响应改写中间件统一改写成业务信封,并保留 Allow 头
- 启动流程接入 registry::validate() fail-fast
- 交付 scripts/build-frontend.sh 作为可重放的前端构建入口

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

518 lines
19 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.
//! 全链路冒烟:路由装配 + 三道门 + 信封形状。
//!
//! ⚠️ 本测试二进制内共用一个 PGlite 实例(pglite-rs 每进程只允许一个)。
use std::sync::Arc;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::Router;
use http_body_util::BodyExt;
use pglite::PGlite;
use serde_json::Value;
use tdc_connector::auth::{auth_middleware, AuthState};
use tdc_connector::config::Config;
use tdc_connector::routes::build_router;
use tdc_connector::routes::mw::json_method_not_allowed;
use tdc_connector::session::SessionStore;
use tdc_connector::state::{AppState, BootstrapIdentity};
use tokio::sync::OnceCell;
use tower::ServiceExt;
static DB: OnceCell<Arc<PGlite>> = OnceCell::const_new();
async fn shared_db() -> Arc<PGlite> {
DB.get_or_init(|| async {
let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败"));
tdc_connector::db::ensure_schema(db.as_ref())
.await
.expect("建表失败");
db
})
.await
.clone()
}
/// 构造一个带鉴权中间件的 router,并返回当前生效的内部令牌与状态。
async fn build() -> (Router, String, AppState) {
let db = shared_db().await;
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
let sessions = Arc::new(SessionStore::new());
let token = config.internal_token.clone();
let state = AppState::new(
config.clone(),
db,
sessions.clone(),
BootstrapIdentity {
identity_id: "TEST-OP".to_string(),
identity_code: "TEST-CONNECTOR".to_string(),
issued_secret: None,
},
);
let auth_state = AuthState {
internal_token: config.internal_token.clone(),
sessions,
};
// 🔴 axum 0.8.9:`impl<B> Service<Request<B>> for Router<()>` —— **只有 `Router<()>` 实现
// `Service`**(`axum-0.8.9/src/routing/mod.rs:569`)。`build_router` 返回
// `Router<AppState>`(S = 还缺什么状态)⇒ 直接 `oneshot` **编译不过**。
// 必须再 `.with_state(state)` 一次把它落到 `Router<()>`。
// ✅ 本仓已有可用样板:`tests/auth_flow.rs` 的 `build_app()`。
let app: Router = build_router(state.clone())
// 🔴 与 `main.rs` 同一套 405 兜底:空体 405 ⇒ 业务信封(保留 `Allow` 头)。
.layer(axum::middleware::from_fn(json_method_not_allowed))
.layer(axum::middleware::from_fn_with_state(
auth_state,
auth_middleware,
))
.with_state(state.clone());
(app, token, state)
}
fn get(uri: &str, token: Option<&str>) -> Request<Body> {
let mut b = Request::builder().method("GET").uri(uri);
if let Some(t) = token {
b = b.header("X-Internal-Token", t);
}
b.body(Body::empty()).unwrap()
}
/// 构造一个带 JSON body 的请求。
fn json_req(method: &str, uri: &str, token: Option<&str>, body: &str) -> Request<Body> {
let mut b = Request::builder()
.method(method)
.uri(uri)
.header("Content-Type", "application/json");
if let Some(t) = token {
b = b.header("X-Internal-Token", t);
}
b.body(Body::from(body.to_string())).unwrap()
}
async fn call(app: &Router, r: Request<Body>) -> (StatusCode, Value) {
let resp = app.clone().oneshot(r).await.expect("请求失败");
let status = resp.status();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
(status, value)
}
/// 同 `call`,但**额外回响应头**(405 用例要断言 `Allow` 头存在)。
async fn call_with_headers(
app: &Router,
r: Request<Body>,
) -> (StatusCode, axum::http::HeaderMap, Value) {
let resp = app.clone().oneshot(r).await.expect("请求失败");
let status = resp.status();
let headers = resp.headers().clone();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
(status, headers, value)
}
#[tokio::test]
async fn crud_routes_are_guarded_and_use_the_business_envelope() {
let (app, token, _state) = build().await;
// ① 无凭证 ⇒ HTTP 401 + 裸三字段(无 data)
let (status, body) = call(&app, get("/api/ssw/tdc/Product", None)).await;
assert_eq!(status, 401);
assert_eq!(body["success"], false);
assert_eq!(body["code"], 401);
assert!(body.get("data").is_none(), "鉴权失败不得有 data 字段");
// ② 内部令牌 ⇒ HTTP 200 + 业务信封
let (status, body) = call(&app, get("/api/ssw/tdc/Product", Some(token.as_str()))).await;
assert_eq!(status, 200);
assert_eq!(body["code"], 200);
assert!(body["data"]["list"].is_array());
assert!(body["data"]["pagination"]["total"].is_number());
// ③ /All ⇒ 裸数组
let (status, body) = call(&app, get("/api/ssw/tdc/Product/All", Some(token.as_str()))).await;
assert_eq!(status, 200);
assert!(body["data"].is_array(), "/All 必须返回裸数组");
// ④ 18 个实体全部注册成功(随便挑几个含只读与审计的)
for api in [
"Dataset",
"DeliveryTask",
"AuditLog",
"Identity",
"PolicyTemplate",
] {
let (status, body) = call(
&app,
get(&format!("/api/ssw/tdc/{}", api), Some(token.as_str())),
)
.await;
assert_eq!(status, 200, "{} 列表应可用", api);
assert_eq!(body["code"], 200, "{} 列表应返回业务信封", api);
}
// ⑤ 资源侧只读聚合路由已注册(不是 404):无该 id ⇒ 业务失败 400
// 🔴 两条路由的「查无」文案**不同**(上游逐字对齐):
// Dataset ⇒ 「数据集不存在或资源已删除」(DatasetController:142)
// Resource ⇒ 「记录不存在或已删除」(ResourceController:210)
for (path, want_msg) in [
(
"/api/ssw/tdc/Resource/R-NOT-EXIST/Detail",
"记录不存在或已删除",
),
(
"/api/ssw/tdc/Dataset/R-NOT-EXIST/Detail",
"数据集不存在或资源已删除",
),
] {
let (status, body) = call(&app, get(path, Some(token.as_str()))).await;
assert_eq!(
status, 200,
"{} 必须已注册(404 说明路由没挂上):{:?}",
path, body
);
assert_eq!(body["code"], 400, "{} 查无应是业务失败:{}", path, body);
assert_eq!(body["msg"], want_msg, "{} 的查无文案与上游不符", path);
assert_eq!(
body.get("data"),
Some(&Value::Null),
"业务失败的 data 必须是 null(且**必须存在 data 键**)"
);
}
}
/// 🔴 **18 个实体逐一断言路由已挂上**:不能只抽查。
///
/// 路由缺失的表现是 HTTP 404 + 非业务信封 ⇒ 这里逐个断言
/// 「HTTP 200 + `code=200` + `data.list` 是数组」。
#[tokio::test]
async fn every_registry_entity_has_a_working_list_route() {
let (app, token, _state) = build().await;
let mut seen = 0usize;
for spec in tdc_connector::registry::REGISTRY {
seen += 1;
let (status, body) = call(&app, get(spec.path, Some(token.as_str()))).await;
assert_eq!(status, 200, "{} 列表路由未挂上:{:?}", spec.api_name, body);
assert_eq!(
body["code"], 200,
"{} 列表应返回业务信封:{:?}",
spec.api_name, body
);
assert!(
body["data"]["list"].is_array(),
"{} 列表 data.list 必须是数组:{:?}",
spec.api_name,
body
);
assert!(
body["data"]["pagination"]["total"].is_number(),
"{} 列表必须有 pagination.total:{:?}",
spec.api_name,
body
);
// /All 也要挂上(裸数组)
let (status, body) = call(
&app,
get(&format!("{}/All", spec.path), Some(token.as_str())),
)
.await;
assert_eq!(status, 200, "{}/All 路由未挂上:{:?}", spec.api_name, body);
assert!(
body["data"].is_array(),
"{}/All 必须返回裸数组",
spec.api_name
);
}
assert_eq!(seen, 18, "注册表必须是 18 个实体,实际 {}", seen);
}
#[tokio::test]
async fn incompatible_protocol_version_is_rejected_with_401() {
let (app, token, _state) = build().await;
let mut r = get("/api/ssw/tdc/Product", Some(token.as_str()));
r.headers_mut()
.insert("X-Protocol-Version", "2.0".parse().unwrap());
let (status, body) = call(&app, r).await;
assert_eq!(status, 401);
assert_eq!(body["msg"], "跨端协议版本不兼容,请升级对端");
assert!(body.get("data").is_none());
}
/// 🔴 **每实体 6 条路由里另外 4 族(GET {id} / POST / PUT / DELETE)必须走一遍 HTTP**。
///
/// 评审变异 M4(删 PUT 路由)、M5(删整个 `/{id}` 路由块)曾**存活** ⇒ 本用例是它们的解药。
#[tokio::test]
async fn write_routes_work_over_http() {
let (app, token, _state) = build().await;
let t = token.as_str();
// ① POST 新增 ⇒ 业务信封 + data 是新 id
let (status, body) = call(
&app,
json_req(
"POST",
"/api/ssw/tdc/PolicyTemplate",
Some(t),
r#"{"name":"冒烟策略模板"}"#,
),
)
.await;
assert_eq!(status, 200, "POST 应返回业务信封:{:?}", body);
assert_eq!(body["code"], 200, "POST 应成功:{:?}", body);
let id = body["data"]
.as_str()
.expect("新增成功后 data 必须是 id 字符串")
.to_string();
assert!(!id.is_empty(), "新增返回的 id 不得为空");
// ② GET {id} ⇒ 详情,且能看到刚建的 name
let (status, body) = call(
&app,
get(&format!("/api/ssw/tdc/PolicyTemplate/{}", id), Some(t)),
)
.await;
assert_eq!(status, 200, "GET {id} 应返回业务信封:{:?}", body);
assert_eq!(body["code"], 200, "GET {id} 应成功:{:?}", body);
assert_eq!(body["data"]["id"], id, "详情必须回显同一个 id");
assert_eq!(body["data"]["name"], "冒烟策略模板");
// ③ PUT {id} ⇒ 修改成功,且改完能读出来
let (status, body) = call(
&app,
json_req(
"PUT",
&format!("/api/ssw/tdc/PolicyTemplate/{}", id),
Some(t),
r#"{"name":"改名后的策略模板"}"#,
),
)
.await;
assert_eq!(status, 200, "PUT 应返回业务信封:{:?}", body);
assert_eq!(body["code"], 200, "PUT 应成功:{:?}", body);
let (status, body) = call(
&app,
get(&format!("/api/ssw/tdc/PolicyTemplate/{}", id), Some(t)),
)
.await;
assert_eq!(status, 200);
assert_eq!(
body["data"]["name"], "改名后的策略模板",
"PUT 的改动必须读得回来"
);
// ④ DELETE {id} ⇒ 成功;再 GET ⇒ 业务失败(逻辑删除生效)
let (status, body) = call(
&app,
json_req(
"DELETE",
&format!("/api/ssw/tdc/PolicyTemplate/{}", id),
Some(t),
"",
),
)
.await;
assert_eq!(status, 200, "DELETE 应返回业务信封:{:?}", body);
assert_eq!(body["code"], 200, "DELETE 应成功:{:?}", body);
let (status, body) = call(
&app,
get(&format!("/api/ssw/tdc/PolicyTemplate/{}", id), Some(t)),
)
.await;
assert_eq!(status, 200);
assert_eq!(
body["code"], 400,
"逻辑删除后再查必须是业务失败:{:?}",
body
);
}
/// 🔴 `/Detail` 必须是**聚合体**(带 `fieldRules` / `maskRules` 两张子表)。
///
/// 评审变异 M3(把 `detail_aggregate` 换成 `detail`)曾**存活** ⇒ 本用例是它的解药。
/// 上游前端 `ResourceDetailModal.vue` / `ProductDetailModal.vue` / `MountDataDrawer.vue`
/// 都依赖这两个字段。
#[tokio::test]
async fn resource_detail_returns_child_tables() {
let (app, token, state) = build().await;
// 写入资源 + 两条子表行(🔴 所有 DB 访问必须持 `state.db_lock`)
{
let _g = state.db_lock.lock().await;
state
.db
.exec(
"INSERT INTO tdc_resource (f_id, f_resource_code, f_name) \
VALUES ('R-AGG-1', 'RES-AGG-1', '聚合测试资源')",
)
.await
.expect("插入资源失败");
state
.db
.exec(
"INSERT INTO tdc_resource_field (f_id, f_resource_id, f_field_name, f_field_type) \
VALUES ('RF-AGG-1', 'R-AGG-1', 'id', 'varchar')",
)
.await
.expect("插入字段说明失败");
state
.db
.exec(
"INSERT INTO tdc_resource_mask_rule \
(f_id, f_resource_id, f_field_name, f_field_type, f_mask_type) \
VALUES ('RM-AGG-1', 'R-AGG-1', 'name', 'varchar', 'HASH')",
)
.await
.expect("插入脱敏规则失败");
}
let (status, body) = call(
&app,
get("/api/ssw/tdc/Resource/R-AGG-1/Detail", Some(token.as_str())),
)
.await;
assert_eq!(
status, 200,
"/Resource/{{id}}/Detail 应返回业务信封:{:?}",
body
);
assert_eq!(
body["code"], 200,
"/Resource/{{id}}/Detail 应成功:{:?}",
body
);
assert_eq!(body["data"]["id"], "R-AGG-1");
assert!(
body["data"]["fieldRules"].is_array(),
"/Detail 必须带 fieldRules 子表:{:?}",
body
);
assert!(
body["data"]["maskRules"].is_array(),
"/Detail 必须带 maskRules 子表:{:?}",
body
);
assert_eq!(body["data"]["fieldRules"].as_array().unwrap().len(), 1);
assert_eq!(body["data"]["maskRules"].as_array().unwrap().len(), 1);
// 同一资源走 Dataset 侧(同一张表)⇒ 同样能读到聚合体
let (status, body) = call(
&app,
get("/api/ssw/tdc/Dataset/R-AGG-1/Detail", Some(token.as_str())),
)
.await;
assert_eq!(status, 200);
assert_eq!(
body["code"], 200,
"/Dataset/{{id}}/Detail 应成功:{:?}",
body
);
assert!(body["data"]["fieldRules"].is_array());
assert!(body["data"]["maskRules"].is_array());
}
/// 🔴 畸形 JSON / 错误媒体类型 ⇒ **业务信封**(不是 axum 默认的 `text/plain` 400)。
///
/// 上游 `SswExceptionHandler#handleNotReadable` 把 `HttpMessageNotReadableException`
/// 映射成 `ActionResult.fail("请求体格式有误,请检查 JSON 结构与字段类型")`
/// ⇒ HTTP 200 + `code=400`(`ActionResult.fail(String)` 的 code 恒为 400)。
#[tokio::test]
async fn malformed_json_returns_the_business_envelope() {
let (app, token, _state) = build().await;
let t = token.as_str();
let (status, body) = call(
&app,
json_req("POST", "/api/ssw/tdc/PolicyTemplate", Some(t), "{bad"),
)
.await;
assert_eq!(
status, 200,
"畸形 JSON 也应是 HTTP 200 + 业务信封:{:?}",
body
);
assert_eq!(body["code"], 400, "畸形 JSON 应是业务失败:{:?}", body);
assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型");
assert_eq!(body.get("data"), Some(&Value::Null));
// 错误媒体类型:body 不是 JSON ⇒ 同一口径(上游 415 由 JNPF 全局兜底,形状未知)
let r = Request::builder()
.method("POST")
.uri("/api/ssw/tdc/PolicyTemplate")
.header("Content-Type", "text/plain")
.header("X-Internal-Token", t)
.body(Body::from("这不是 JSON"))
.unwrap();
let (status, body) = call(&app, r).await;
assert_eq!(status, 200, "错误媒体类型也应是业务信封:{:?}", body);
assert_eq!(body["code"], 400, "错误媒体类型应是业务失败:{:?}", body);
assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型");
}
/// 空 body 的写请求 ⇒ 业务失败(上游必填 `@RequestBody` ⇒ 空 body 被拒),**不**建出垃圾行。
#[tokio::test]
async fn empty_body_on_write_returns_the_business_envelope() {
let (app, token, _state) = build().await;
let t = token.as_str();
// 🔴 用**本用例专属**的实体(`Notification` ⇒ `tdc_notify`):
// 本测试二进制共用一个 PGlite,且 `cargo test` 并行跑用例 ⇒
// 若与 `write_routes_work_over_http` 共用 `PolicyTemplate`,
// 它的 POST 建行 / DELETE 之间的窗口会让「前后 total 对比」随机变红。
// `tdc_notify` 只有 `f_id` 是 NOT NULL 且无 DEFAULT ⇒ 空 body 原本能建出一行全 null 垃圾数据。
let (status, body) = call(&app, get("/api/ssw/tdc/Notification", Some(t))).await;
assert_eq!(status, 200);
let before = body["data"]["pagination"]["total"].as_i64().unwrap_or(0);
// POST + Content-Type: application/json + 空 body
let r = Request::builder()
.method("POST")
.uri("/api/ssw/tdc/Notification")
.header("Content-Type", "application/json")
.header("X-Internal-Token", t)
.body(Body::empty())
.unwrap();
let (status, body) = call(&app, r).await;
assert_eq!(
status, 200,
"空 body 也应是 HTTP 200 + 业务信封:{:?}",
body
);
assert_eq!(body["code"], 400, "空 body 应是业务失败:{:?}", body);
assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型");
assert_eq!(body.get("data"), Some(&Value::Null));
// 🔴 关键:不得建出一行垃圾数据
let (status, body) = call(&app, get("/api/ssw/tdc/Notification", Some(t))).await;
assert_eq!(status, 200);
let after = body["data"]["pagination"]["total"].as_i64().unwrap_or(0);
assert_eq!(after, before, "空 body 不得建出行:{:?}", body);
}
/// 方法不允许 ⇒ JSON(不是空体)**且保留 `Allow` 头**。
#[tokio::test]
async fn method_not_allowed_returns_json() {
let (app, token, _state) = build().await;
let r = Request::builder()
.method("PATCH")
.uri("/api/ssw/tdc/PolicyTemplate")
.header("X-Internal-Token", token.as_str())
.body(Body::empty())
.unwrap();
let (status, headers, body) = call_with_headers(&app, r).await;
assert_eq!(status, 405, "方法不允许应是 405:{:?}", body);
assert_eq!(body["code"], 405, "405 也要带 code:{:?}", body);
assert_eq!(body["msg"], "方法不被允许");
assert_eq!(body["data"], Value::Null, "405 信封的 data 必须是 null");
// 🔴 RFC 9110:405 响应 MUST 带 `Allow`。
// 旧的 `method_not_allowed_fallback` 换掉了整个响应 ⇒ `Allow` 丢失;
// 换成「响应改写中间件」后 headers 原样保留 ⇒ `Allow` 仍在。
let allow = headers
.get("allow")
.expect("405 响应必须带 Allow 头")
.to_str()
.expect("Allow 头必须是合法 ASCII");
assert!(!allow.is_empty(), "Allow 头不得为空:{:?}", allow);
}