Files
admin 400d883e1a feat(p6): 平台改为预编译 rlib 接入,依赖全部来自包内闭包
- 新增 scripts/fetch-platform.sh:读 .sspf-version 解包 vendor/ + 生成 .cargo/config.toml(rustflags + rustdocflags),只校工具链 channel
- Cargo.toml 的 [dependencies]/[dev-dependencies] 清空:17 个 crate 全部 --extern 自平台闭包
- release profile lto 由 thin 改 false(平台 rlib bitcode-free,开 LTO 找不到 __bitcode)
- tower-http 不在闭包 ⇒ 自研 platform::static_files(ServeDir 等价,含 Range 206)与 platform::cors(permissive 等价)
- reqwest 与 extern tokio 双 runtime 必 panic(no reactor running)⇒ 自研 platform::http(HTTP/1.1 明文)
- tests/auth_flow 的 reqwest 调用改用 lib 客户端;tds_biz 的头白名单补 connection
- 新增尺子 check-platform-package.sh:依赖单一来源 + 真编一次证明平台闭包零重编
- 验收:cargo test 306 passed / 七把尺子 + 新尺子全绿;dev 构建 2.5s 只编本仓
2026-11-05 13:01:27 +08:00

395 lines
15 KiB
Rust
Raw Permalink 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.
//! 身份域端到端:引导 → 登录 → 会话令牌 → Me → Spaces。
//!
//! ⚠️ 整个测试二进制共用一个 PGlite 实例(pglite-rs 每进程只允许一个)。
//! ⚠️ 用例之间用 `SERIAL` 串行化:它们共用同一张 `tdc_identity` 表,
//! 并发跑会让「谁先建了身份」不确定(引导幂等性断言会随机翻车)。
use std::sync::Arc;
use axum::extract::State;
use axum::Router;
use pglite::PGlite;
use serde_json::{json, Value};
use tdc_connector::platform::auth::{auth_middleware, AuthState};
use tdc_connector::platform::config::Config;
use tdc_connector::tdc::service::identity;
use tdc_connector::tdc::config::TdcConfig;
use tdc_connector::tdc::controller::build_router;
use tdc_connector::tdc::support::public_paths;
use tdc_connector::platform::session::SessionStore;
use tdc_connector::platform::state::AppState;
use tdc_connector::tdc::state::{BootstrapIdentity, TdcState};
use tokio::sync::{Mutex, OnceCell};
static DB: OnceCell<Arc<PGlite>> = OnceCell::const_new();
/// 串行闸门:所有碰库的用例排队跑。
static SERIAL: Mutex<()> = Mutex::const_new(());
/// 测试用 HTTP 调用 ⇒ `(状态码, 响应体文本)`。
///
/// 🔴 用本仓 `platform::http::HttpClient`,**不用 `reqwest`**:平台改为预编译 rlib 发布后
/// 依赖全来自平台闭包,`reqwest` 不在里面;一旦在本仓声明,cargo 会给它**再编一份
/// tokio** ⇒ 与 `#[tokio::main]` 用的那份不是同一个 runtime ⇒ 实测 panic
/// `there is no reactor running`。详见 `src/platform/http.rs` 的模块文档。
async fn http_call(
method: &str,
url: &str,
headers: &[(&str, &str)],
body: Option<Value>,
) -> (u16, String) {
use axum::http::{header, HeaderMap, HeaderName, HeaderValue};
let mut hm = HeaderMap::new();
for (k, v) in headers {
hm.insert(
HeaderName::from_bytes(k.as_bytes()).expect("头名非法"),
HeaderValue::from_str(v).expect("头值非法"),
);
}
let payload = body.map(|b| serde_json::to_vec(&b).expect("请求体序列化失败"));
if payload.is_some() {
hm.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
}
let client = tdc_connector::platform::http::HttpClient::new(
std::time::Duration::from_secs(5),
std::time::Duration::from_secs(5),
);
let resp = client
.send(method, url, &hm, payload.as_deref())
.await
.expect("请求失败");
(resp.status, resp.body)
}
async fn shared_db() -> Arc<PGlite> {
DB.get_or_init(|| async {
let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败"));
tdc_connector::platform::db::ensure_schema(db.as_ref())
.await
.expect("建表失败");
db
})
.await
.clone()
}
async fn test_state() -> TdcState {
test_state_with(Arc::new(SessionStore::new())).await
}
/// 与 `main.rs` 一致:**登录签发的会话与鉴权中间件必须共用同一个 store**。
async fn test_state_with(sessions: Arc<SessionStore>) -> TdcState {
let db = shared_db().await;
let config = Config::from_env(std::env::current_dir().unwrap());
TdcState::new(
AppState::new(config, db, sessions),
TdcConfig::default(),
BootstrapIdentity::default(),
)
}
/// 🔴 业务配置(身份与引导)**不在平台 Config 里**(v3 spec §2.3.1 C8)⇒ 单独造一份。
fn test_tdc_config() -> TdcConfig {
TdcConfig {
identity_code: "TEST-CONNECTOR".to_string(),
identity_name: "测试连接器".to_string(),
identity_secret: Some("test-secret-key".to_string()),
bootstrap_admin_account: "admin".to_string(),
bootstrap_admin_password: None,
}
}
/// 🔴 同一个 PGlite 上的所有 `AppState` 必须共享**同一把** `db_lock`。
///
/// pglite-rs 每进程只允许一个 PGlite ⇒ 一个进程只需要一把锁 ⇒ 锁的粒度是**进程**。
/// (早期实现是「每个 `AppState` 各造一把」⇒ 同一库上两把锁 ⇒ 序列化前提被破坏。)
#[tokio::test]
async fn two_app_states_on_the_same_db_share_one_db_lock() {
let _guard = SERIAL.lock().await;
let db = shared_db().await;
let sessions = Arc::new(SessionStore::new());
let config = Config::from_env(std::env::current_dir().unwrap());
let s1 = TdcState::new(
AppState::new(config.clone(), db.clone(), sessions.clone()),
TdcConfig::default(),
BootstrapIdentity::default(),
);
let s2 = TdcState::new(
AppState::new(config.clone(), db.clone(), sessions.clone()),
TdcConfig::default(),
BootstrapIdentity::default(),
);
assert!(
Arc::ptr_eq(&s1.db_lock, &s2.db_lock),
"同一个 PGlite 上的所有状态必须共享同一把 db_lock"
);
// `with_bootstrap` 换引导身份时**不得**换掉锁
let s3 = s1.with_bootstrap(BootstrapIdentity {
identity_id: "id-x".to_string(),
identity_code: "TEST-CONNECTOR".to_string(),
issued_secret: None,
});
assert!(
Arc::ptr_eq(&s3.db_lock, &s2.db_lock),
"with_bootstrap 只换 bootstrap 字段,db_lock 必须原样保留"
);
assert_eq!(s3.bootstrap.identity_id, "id-x");
}
/// 清空身份表(让「首次引导」用例可确定地拿到「新建」语义)。
async fn clear_identities(state: &AppState) {
let _g = state.db_lock.lock().await;
state
.db
.exec("DELETE FROM tdc_identity")
.await
.expect("清空 tdc_identity 失败");
}
async fn body_of(resp: axum::response::Response) -> Value {
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.expect("读取响应体失败");
serde_json::from_slice(&bytes).expect("响应体不是 JSON")
}
#[tokio::test]
async fn bootstrap_creates_one_identity_and_is_idempotent() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
// 先清空 ⇒ 本用例一定走「首次引导」分支(否则并发下可能被别人抢先建过)。
clear_identities(&state).await;
let first = identity::bootstrap_identity(&state, &test_tdc_config()).await;
assert!(!first.identity_id.is_empty(), "应创建出身份");
assert_eq!(first.identity_code, "TEST-CONNECTOR");
assert!(first.issued_secret.is_some(), "首次引导应签发一次密钥");
let second = identity::bootstrap_identity(&state, &test_tdc_config()).await;
assert_eq!(second.identity_id, first.identity_id, "引导必须幂等");
assert!(second.issued_secret.is_none(), "已有身份时不得再签发密钥");
}
#[tokio::test]
async fn login_rejects_unknown_identity_and_wrong_secret() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let resp = identity::login(
State(state.clone()),
Some(axum::Json(
json!({"identityCode": "NOPE", "secretKey": "x"}),
)),
)
.await;
let body = body_of(resp).await;
assert_eq!(body["code"], 400);
assert_eq!(body["msg"], "连接器身份不存在");
let resp = identity::login(
State(state.clone()),
Some(axum::Json(
json!({"identityCode": "TEST-CONNECTOR", "secretKey": "wrong"}),
)),
)
.await;
let body = body_of(resp).await;
assert_eq!(body["code"], 400);
assert_eq!(body["msg"], "连接器身份密钥校验失败");
let resp = identity::login(
State(state.clone()),
Some(axum::Json(json!({"secretKey": "x"}))),
)
.await;
let body = body_of(resp).await;
assert_eq!(body["msg"], "identityCode 必填");
}
#[tokio::test]
async fn login_succeeds_and_me_returns_identity_without_secret() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let resp = identity::login(
State(state.clone()),
Some(axum::Json(
json!({"identityCode": "TEST-CONNECTOR", "secretKey": "test-secret-key"}),
)),
)
.await;
let body = body_of(resp).await;
assert_eq!(body["code"], 200);
let token = body["data"]["token"]
.as_str()
.expect("应返回 token")
.to_string();
assert_eq!(body["data"]["identityCode"], "TEST-CONNECTOR");
// 会话可查
let session = state.sessions.lookup(&token).expect("会话应存在");
assert_eq!(session.identity_code, "TEST-CONNECTOR");
// Me 不泄露密钥
// ⚠️ `me` 有两个参数:`(State, Option<Extension<Principal>>)` ⇒ 第二个参数不能省。
let resp = identity::me(State(state.clone()), None).await;
let body = body_of(resp).await;
assert_eq!(body["code"], 200);
assert_eq!(body["data"]["identityCode"], "TEST-CONNECTOR");
assert!(body["data"].get("secretKey").is_none(), "不得回显密钥");
assert!(body["data"].get("f_secret_key").is_none(), "不得回显密钥列");
}
#[tokio::test]
async fn me_carries_every_field_the_upstream_frontend_reads() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let resp = identity::me(State(state.clone()), None).await;
let body = body_of(resp).await;
let data = &body["data"];
// 上游前端 `Login.vue` / `IdentityManage.vue` / `ProductManage.vue` 真实读取的字段
for k in [
"accessAllowed",
"reason",
"account",
"subjectId",
"subjectName",
"tdsSpaceId",
"tdsSpaceName",
] {
assert!(data.get(k).is_some(), "Auth/Me 必须带字段 {}", k);
}
// 未登录 ⇒ accessAllowed 必须是 false(前端据此 logout)
assert_eq!(data["accessAllowed"], json!(false));
// 单体部署 ⇒ 永不拒 ⇒ reason 恒 null
assert_eq!(data["reason"], Value::Null);
}
#[tokio::test]
async fn spaces_returns_a_bare_array_of_space_views() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let resp = identity::spaces(State(state.clone())).await;
let body = body_of(resp).await;
assert_eq!(body["code"], 200);
// 裸数组(前端 `arr = Array.isArray(list) ? list : (list?.list || [])`)
assert!(body["data"].is_array(), "Auth/Spaces 的 data 必须是裸数组");
// 本地没有平台空间 ⇒ 绑定空间未配时返回空数组(前端 `.catch(() => [])` 容忍)
let list = body["data"].as_array().unwrap();
for s in list {
assert!(s.get("id").is_some(), "空间必须有 id");
assert!(s.get("name").is_some(), "空间必须有 name");
assert!(s.get("spaceCode").is_some(), "空间必须有 spaceCode");
assert_eq!(s.as_object().unwrap().len(), 3, "空间元素恰好三个键");
}
}
/// 🔴 两套响应形状必须分开:
/// - 业务失败 = **HTTP 200** + `{code,msg,data}`;
/// - 鉴权失败 = **HTTP 401** + `{success:false,code,msg}`(**无 `data`**)。
#[tokio::test]
async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
let _guard = SERIAL.lock().await;
// 装配带鉴权中间件的真实路由(与 `main.rs` 同一套:会话 store 必须共用)。
let sessions = Arc::new(SessionStore::new());
let state = test_state_with(sessions.clone()).await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let auth_state = AuthState {
internal_token: "test-internal-token".to_string(),
sessions: sessions.clone(),
public_paths: Arc::new(public_paths::all_public_paths()),
};
let app: Router = build_router(state.clone())
.layer(axum::middleware::from_fn_with_state(
auth_state,
auth_middleware,
))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("绑定端口");
let addr = listener.local_addr().expect("读本地地址");
let server = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
// ⚠️ P6:平台闭包里没有 `reqwest`(它会自带一份 tokio ⇒ 与 extern 的 tokio 不是同一个
// runtime,实测 panic `no reactor running`)⇒ 用本仓 lib 里的极简客户端。
let base = format!("http://{}", addr);
// ① 鉴权失败:无凭证访问 `Auth/Me` ⇒ HTTP 401 + 裸三字段(无 data)。
let resp = http_call("GET", &format!("{}/api/ssw/tdc/Auth/Me", base), &[], None).await;
assert_eq!(resp.0, 401, "鉴权失败必须是 HTTP 401");
let body: Value = serde_json::from_str(&resp.1).expect("响应体不是 JSON");
assert_eq!(body["success"], json!(false));
assert_eq!(body["code"], json!(401));
assert!(
body.get("data").is_none(),
"鉴权失败 body 不得含 data:{}",
body
);
assert_eq!(
body.as_object().unwrap().len(),
3,
"鉴权失败 body 恰好三个键"
);
// ② 业务失败:密钥不对 ⇒ HTTP 200 + `{code:400,msg,data}`。
let resp = http_call(
"POST",
&format!("{}/api/ssw/tdc/Auth/Login", base),
&[],
Some(json!({"identityCode": "TEST-CONNECTOR", "secretKey": "wrong"})),
)
.await;
assert_eq!(resp.0, 200, "业务失败必须是 HTTP 200");
let body: Value = serde_json::from_str(&resp.1).expect("响应体不是 JSON");
assert_eq!(body["code"], json!(400));
assert_eq!(body["msg"], json!("连接器身份密钥校验失败"));
assert!(body.get("success").is_none(), "业务信封不得含 success 字段");
assert!(
body.get("data").is_some(),
"业务信封带 data 键(此处为 null)"
);
// ③ 登录成功 ⇒ 拿到令牌;带令牌再取 `Auth/Spaces` ⇒ 裸数组。
let resp = http_call(
"POST",
&format!("{}/api/ssw/tdc/Auth/Login", base),
&[],
Some(json!({"identityCode": "TEST-CONNECTOR", "secretKey": "test-secret-key"})),
)
.await;
assert_eq!(resp.0, 200);
let body: Value = serde_json::from_str(&resp.1).expect("响应体不是 JSON");
assert_eq!(body["code"], json!(200));
let token = body["data"]["token"]
.as_str()
.expect("应返回 token")
.to_string();
let resp = http_call(
"GET",
&format!("{}/api/ssw/tdc/Auth/Spaces", base),
&[("X-Auth-Token", token.as_str())],
None,
)
.await;
assert_eq!(resp.0, 200);
let body: Value = serde_json::from_str(&resp.1).expect("响应体不是 JSON");
assert_eq!(body["code"], json!(200));
assert!(body["data"].is_array(), "Auth/Spaces 的 data 必须是裸数组");
server.abort();
}