From 0f84fbdb831edd598680cb96e8525e9583ba443c Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 25 Oct 2026 00:06:23 +0800 Subject: [PATCH] =?UTF-8?q?feat(routes):=2018=20=E5=AE=9E=E4=BD=93=20CRUD?= =?UTF-8?q?=20=E8=B7=AF=E7=94=B1=E8=A3=85=E9=85=8D=20+=20=E5=85=A8?= =?UTF-8?q?=E9=93=BE=E8=B7=AF=E5=86=92=E7=83=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 每个实体 6 条路由(列表/All/详情/新增/修改/删除),路径参数用 axum 0.8 的 {id} - 冒烟覆盖:无凭证 401 裸三字段、内部令牌业务信封、/All 裸数组、协议版本不兼容 401 - 补资源侧只读聚合路由 /Resource/{id}/Detail 与 /Dataset/{id}/Detail(上游前端在用) Co-Authored-By: Claude Code --- src/routes/crud.rs | 112 ++++++++++++++++++++++++++++- tests/api_smoke.rs | 171 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 281 insertions(+), 2 deletions(-) create mode 100644 tests/api_smoke.rs diff --git a/src/routes/crud.rs b/src/routes/crud.rs index 10705df..0112845 100644 --- a/src/routes/crud.rs +++ b/src/routes/crud.rs @@ -1,9 +1,117 @@ -//! 18 实体的通用 CRUD 路由(Task 9 实现)。 +//! 18 实体的通用 CRUD 路由装配。 +//! +//! 每个实体注册 6 条路由: +//! GET {path} 分页列表 +//! GET {path}/All 全量列表(≤1000;**仍是业务信封** `{code,msg,data:[…]}`) +//! GET {path}/{id} 详情 +//! POST {path} 新增 +//! PUT {path}/{id} 修改 +//! DELETE {path}/{id} 逻辑删除 +//! +//! 🔴 axum 规定**主体抽取器必须是最后一个参数** ⇒ `Option>` 永远排最后, +//! `Option>` 排它前面。 +//! +//! 🔴 路由路径**一律取 `TableSpec::path`**(注册表是唯一真源)⇒ 不另写字符串。 +use axum::extract::{Extension, Path, RawQuery, State}; +use axum::routing::get; use axum::Router; +use serde_json::Value; +use crate::auth::Principal; +use crate::crud; +use crate::registry::{self, TableSpec}; use crate::state::AppState; pub fn router() -> Router { - Router::new() + let mut r = Router::new(); + for spec in registry::REGISTRY { + let s: &'static TableSpec = spec; + r = r + .route( + s.path, + get(move |State(st): State, q: RawQuery, p: Option>| { + let params = crud::parse_query(q.0.as_deref()); + let principal = p.map(|e| e.0); + async move { crud::list(&st, s, ¶ms, principal.as_ref()).await } + }) + .post( + move |State(st): State, + p: Option>, + b: Option>| { + let principal = p.map(|e| e.0); + let body = b.map(|axum::Json(v)| v).unwrap_or(Value::Null); + async move { crud::create(&st, s, &body, principal.as_ref()).await } + }, + ), + ) + .route( + &format!("{}/All", s.path), + get(move |State(st): State, q: RawQuery, p: Option>| { + let params = crud::parse_query(q.0.as_deref()); + let principal = p.map(|e| e.0); + async move { crud::all(&st, s, ¶ms, principal.as_ref()).await } + }), + ) + .route( + &format!("{}/{{id}}", s.path), + get(move |Path(id): Path, + State(st): State, + p: Option>| { + let principal = p.map(|e| e.0); + async move { crud::detail(&st, s, &id, principal.as_ref()).await } + }) + .put( + move |Path(id): Path, + State(st): State, + p: Option>, + b: Option>| { + let principal = p.map(|e| e.0); + let body = b.map(|axum::Json(v)| v).unwrap_or(Value::Null); + async move { crud::update(&st, s, &id, &body, principal.as_ref()).await } + }, + ) + .delete( + move |Path(id): Path, + State(st): State, + p: Option>| { + let principal = p.map(|e| e.0); + async move { crud::delete(&st, s, &id, principal.as_ref()).await } + }, + ), + ); + } + + // ------------------------------------------------------------------ + // 资源侧只读聚合体(上游 `ResourceController#detailOf` / `DatasetController#detailOf`) + // + // 🔴 路径里的 `{id}` 与上面的 `/{Entity}/{id}` **同层并存** —— + // matchit 允许「参数段 + 更深的静态段」,静态段优先匹配,无冲突。 + // 🔴 `Dataset` 在注册表里 `table = "tdc_resource"`(只读视图)⇒ 聚合体与 Resource 同源。 + { + let res_spec: &'static TableSpec = + registry::find("Resource").expect("Resource 必须在注册表里"); + let ds_spec: &'static TableSpec = + registry::find("Dataset").expect("Dataset 必须在注册表里"); + r = r + .route( + "/api/ssw/tdc/Resource/{id}/Detail", + get(move |Path(id): Path, + State(st): State, + p: Option>| { + let principal = p.map(|e| e.0); + async move { crud::detail_aggregate(&st, res_spec, &id, principal.as_ref()).await } + }), + ) + .route( + "/api/ssw/tdc/Dataset/{id}/Detail", + get(move |Path(id): Path, + State(st): State, + p: Option>| { + let principal = p.map(|e| e.0); + async move { crud::detail_aggregate(&st, ds_spec, &id, principal.as_ref()).await } + }), + ); + } + r } diff --git a/tests/api_smoke.rs b/tests/api_smoke.rs new file mode 100644 index 0000000..80a84f3 --- /dev/null +++ b/tests/api_smoke.rs @@ -0,0 +1,171 @@ +//! 全链路冒烟:路由装配 + 三道门 + 信封形状。 +//! +//! ⚠️ 本测试二进制内共用一个 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> = OnceCell::const_new(); + +async fn shared_db() -> Arc { + 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 Service> for Router<()>` —— **只有 `Router<()>` 实现 + // `Service`**(`axum-0.8.9/src/routing/mod.rs:569`)。`build_router` 返回 + // `Router`(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 { + 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) -> (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()); +}