- 每个实体 6 条路由(列表/All/详情/新增/修改/删除),路径参数用 axum 0.8 的 {id}
- 冒烟覆盖:无凭证 401 裸三字段、内部令牌业务信封、/All 裸数组、协议版本不兼容 401
- 补资源侧只读聚合路由 /Resource/{id}/Detail 与 /Dataset/{id}/Detail(上游前端在用)
Co-Authored-By: Claude Code <[email protected]>
172 lines
6.8 KiB
Rust
172 lines
6.8 KiB
Rust
//! 全链路冒烟:路由装配 + 三道门 + 信封形状。
|
||
//!
|
||
//! ⚠️ 本测试二进制内共用一个 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::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) {
|
||
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())
|
||
.layer(axum::middleware::from_fn_with_state(auth_state, auth_middleware))
|
||
.with_state(state);
|
||
(app, token)
|
||
}
|
||
|
||
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()
|
||
}
|
||
|
||
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)
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn crud_routes_are_guarded_and_use_the_business_envelope() {
|
||
let (app, token) = 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
|
||
for path 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"], "记录不存在或已删除");
|
||
assert!(body["data"].is_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) = 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) = 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());
|
||
}
|