Files
tdc-rs/tests/auth_flow.rs
T
admin df7ce37ba9 refactor(b1b-c5): 白名单清单归业务层 —— 平台层零端点字面量
- 删掉 platform::auth 的 WHITE_URL / EXTRA_WHITE_URL 两个 const
- AuthState 增字段 public_paths: Arc<Vec<&'static str>>(清单由业务层注入)
- 清单真源移到 tdc::support::public_paths:4 条活路径(3 业务 + /api/health),
  并剪掉上游 gateway.white-url 里本仓**无对应路由**的 9 条死路径
  (Gateway×2 / P2P×5 / Portal / Topology)⇒ 记 D17(spec 写「7 条」与实际「9 条」有出入)
- platform::auth 的 is_white_url 改成「清单由调用方给」,机制不变(Ant 匹配)
- 单测:平台层 white_url_matching_is_manifest_driven(机制)+
  业务层 the_manifest_holds_exactly_the_live_endpoints / dead_upstream_paths_are_not_in_the_manifest
- 边界账本清空 B1b 责任条目(CP1/CP4 全部归零)⇒ 账本只剩 2 条永久豁免
2026-10-26 20:36:17 +08:00

352 lines
13 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.
//! 身份域端到端:引导 → 登录 → 会话令牌 → 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::controller::build_router;
use tdc_connector::tdc::support::public_paths;
use tdc_connector::platform::session::SessionStore;
use tdc_connector::platform::state::{AppState, BootstrapIdentity};
use tokio::sync::{Mutex, OnceCell};
static DB: OnceCell<Arc<PGlite>> = OnceCell::const_new();
/// 串行闸门:所有碰库的用例排队跑。
static SERIAL: Mutex<()> = Mutex::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::platform::db::ensure_schema(db.as_ref())
.await
.expect("建表失败");
db
})
.await
.clone()
}
async fn test_state() -> AppState {
test_state_with(Arc::new(SessionStore::new())).await
}
/// 与 `main.rs` 一致:**登录签发的会话与鉴权中间件必须共用同一个 store**。
async fn test_state_with(sessions: Arc<SessionStore>) -> AppState {
let db = shared_db().await;
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
config.identity_name = "测试连接器".to_string();
config.identity_secret = Some("test-secret-key".to_string());
AppState::new(config, db, sessions, BootstrapIdentity::default())
}
/// 🔴 同一个 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 mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
let s1 = AppState::new(
config.clone(),
db.clone(),
sessions.clone(),
BootstrapIdentity::default(),
);
let s2 = AppState::new(
config.clone(),
db.clone(),
sessions.clone(),
BootstrapIdentity::default(),
);
assert!(
Arc::ptr_eq(&s1.db_lock, &s2.db_lock),
"同一个 PGlite 上的所有 AppState 必须共享同一把 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).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).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).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).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).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).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).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;
});
// 本机 curl/reqwest 走系统代理会劫持 loopback ⇒ 显式关掉代理。
let client = reqwest::Client::builder()
.no_proxy()
.build()
.expect("构造 http client");
let base = format!("http://{}", addr);
// ① 鉴权失败:无凭证访问 `Auth/Me` ⇒ HTTP 401 + 裸三字段(无 data)。
let resp = client
.get(format!("{}/api/ssw/tdc/Auth/Me", base))
.send()
.await
.expect("请求失败");
assert_eq!(resp.status().as_u16(), 401, "鉴权失败必须是 HTTP 401");
let body: Value = resp.json().await.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 = client
.post(format!("{}/api/ssw/tdc/Auth/Login", base))
.json(&json!({"identityCode": "TEST-CONNECTOR", "secretKey": "wrong"}))
.send()
.await
.expect("请求失败");
assert_eq!(resp.status().as_u16(), 200, "业务失败必须是 HTTP 200");
let body: Value = resp.json().await.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 = client
.post(format!("{}/api/ssw/tdc/Auth/Login", base))
.json(&json!({"identityCode": "TEST-CONNECTOR", "secretKey": "test-secret-key"}))
.send()
.await
.expect("请求失败");
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.expect("响应体不是 JSON");
assert_eq!(body["code"], json!(200));
let token = body["data"]["token"]
.as_str()
.expect("应返回 token")
.to_string();
let resp = client
.get(format!("{}/api/ssw/tdc/Auth/Spaces", base))
.header("X-Auth-Token", token)
.send()
.await
.expect("请求失败");
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.expect("响应体不是 JSON");
assert_eq!(body["code"], json!(200));
assert!(body["data"].is_array(), "Auth/Spaces 的 data 必须是裸数组");
server.abort();
}