Files
tdc-rs/tests/account_api.rs
T
adminandClaude Code 3586333a7a fix(review): 整分支终审修 3 处 —— 密文契约外部锚点 / 相对数据目录分家 / 首启默认口令可覆盖
终审(就地执行)发现的 3 个问题:

1. 密文契约只在单元层被钉住(R1 未闭环):集成测试用本仓自己的
   encrypt_login_password 造密文 ⇒ 自证自洽 ⇒ CIPHER_KEY 改错时全绿。
   新增 login_accepts_the_upstream_literal_ciphertext:用上游仓库注释里的
   字面密文登录成功,篡一个字节必须失败。
   变异自证:换掉 CIPHER_KEY ⇒ 旧 7 例仍全绿、只有新用例红。

2. 相对 TDC_DATA_DIR 会让数据目录分家:pglite-rs 打开数据目录后会 chdir
   进去 ⇒ 之后 accounts.json 落到 data/tdc.pg/<相对路径>/ 下。
   Config::from_env 在 chdir 之前把数据目录钉成绝对路径(新增纯函数
   data_dir_from + 单测)。

3. 首启管理员口令是公开默认值 admin 且无覆盖机制(R2 未闭环):
   新增 TDC_BOOTSTRAP_ADMIN_ACCOUNT / TDC_BOOTSTRAP_ADMIN_PASSWORD;
   TDC_STRICT_SECRETS=1 时还有管理员在用默认口令 ⇒ 启动即失败。

验收:207 passed / 0 failed / 1 ignored;clippy --all-targets 干净。

Co-Authored-By: Claude Code <[email protected]>
2026-10-25 11:44:37 +08:00

438 lines
17 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.
//! 账号层端到端:JNPF 兼容登录 + 用户管理。
//!
//! ⚠️ 本测试二进制内共用一个 PGlite 实例(pglite-rs 每进程只允许一个)。
//! ⚠️ 账号库是**持久**的 JSON 文件 ⇒ **每个用例用各自的文件**(`build(tag)`),
//! 否则并行跑的用例会互相覆盖账号。
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::account::AccountStore;
use tdc_connector::auth::{auth_middleware, AuthState};
use tdc_connector::cipher::encrypt_login_password;
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;
/// 测试用的内部令牌(走 `X-Internal-Token` 通道)。
const TEST_INTERNAL_TOKEN: &str = "test-internal-token";
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()
}
/// 造一个应用 + 它的账号库。
///
/// 🔴 `tag` 决定**账号文件**与**测试身份行**的名字 ⇒ 并行用例互不干扰。
async fn build(tag: &str) -> (Router, Arc<AccountStore>) {
let db = shared_db().await;
let mut config = Config::from_env(std::env::current_dir().unwrap());
// 🔴 `tdc_identity.f_identity_code` 上有唯一约束 `uk_tdc_identity_code`
// ⇒ 每个用例的身份码必须**唯一**(否则并行插入互相撞车)。
let identity_code = format!("TEST-CONNECTOR-{}", tag);
config.identity_code = identity_code.clone();
config.internal_token = TEST_INTERNAL_TOKEN.to_string();
let sessions = Arc::new(SessionStore::new());
// 账号库是**持久**的 JSON 文件 ⇒ 先清干净(否则上一轮残留账号影响断言)。
let acc_path = std::path::PathBuf::from(format!("target/test-accounts-api-{}.json", tag));
let _ = std::fs::remove_file(&acc_path);
let _ = std::fs::remove_file(acc_path.with_extension("json.tmp"));
let accounts = Arc::new(AccountStore::open(&acc_path).expect("打开账号库失败"));
// 🔴 `GET /api/ssw/tdc/Auth/Me` 会按 `state.bootstrap.identity_id` 去 `tdc_identity` 查身份 ——
// 测试库里**没有**身份行 ⇒ `me` 回「连接器身份不存在」⇒ 断言拿不到 `accessAllowed`。
// ⇒ 这里补一条与 `BootstrapIdentity.identity_id` 对齐的身份行(**每个用例一行**,
// 避免并行用例互相删/插同一行)。
let identity_id = format!("TEST-OP-{}", tag);
{
// 🔴 锁的持有者必须活过 `await` ⇒ 先把 `Arc` 绑到变量上(否则临时值当场析构)。
let db_lock = tdc_connector::state::process_db_lock();
let _g = db_lock.lock().await;
db.exec(&format!(
"INSERT INTO tdc_identity (f_id, f_identity_code, f_name) \
VALUES ('{}', '{}', '测试身份')",
identity_id, identity_code
))
.await
.expect("插入测试身份失败");
}
let state = AppState::new(
config.clone(),
db,
sessions.clone(),
BootstrapIdentity {
identity_id,
identity_code,
issued_secret: None,
},
)
.with_accounts(accounts.clone());
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<()>`。
let app = build_router(state.clone())
.layer(axum::middleware::from_fn_with_state(
auth_state,
auth_middleware,
))
.with_state(state);
(app, accounts)
}
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)
}
fn login_form(account: &str, plain: &str) -> String {
format!(
"account={account}&password={}&grant_type=password",
encrypt_login_password(plain)
)
}
fn post_form(uri: &str, body: String) -> Request<Body> {
Request::builder()
.method("POST")
.uri(uri)
.header("Content-Type", "application/x-www-form-urlencoded")
.body(Body::from(body))
.unwrap()
}
fn get_json(uri: &str, token: Option<&str>) -> Request<Body> {
let mut b = Request::builder().method("GET").uri(uri);
if let Some(t) = token {
b = b.header("Authorization", format!("bearer {}", t));
}
b.body(Body::empty()).unwrap()
}
/// 登录并取回 token(失败时 panic,附带 body 便于定位)。
async fn login_token(app: &Router, account: &str, plain: &str) -> String {
let (status, body) = call(
app,
post_form("/api/oauth/Login", login_form(account, plain)),
)
.await;
assert_eq!(status, 200, "登录应回 HTTP 200(业务失败也是 200)");
assert_eq!(body["code"], 200, "登录应成功,实际 body: {}", body);
body["data"]["token"]
.as_str()
.expect("应返回 token")
.to_string()
}
#[tokio::test]
async fn oauth_login_returns_a_usable_token() {
let (app, _accounts) = build("login").await;
// ① 口令错 ⇒ HTTP 200 + code != 200(前端据此提示,**不**跳登录页)
let (status, body) = call(
&app,
post_form("/api/oauth/Login", login_form("admin", "wrong")),
)
.await;
assert_eq!(status, 200);
assert_ne!(body["code"], 200);
assert_eq!(body["msg"], "账号或密码错误");
assert!(body["data"].is_null(), "失败时不得带 data:{}", body);
// ② 口令对 ⇒ 返回 token + userInfo
let (status, body) = call(
&app,
post_form("/api/oauth/Login", login_form("admin", "admin")),
)
.await;
assert_eq!(status, 200);
assert_eq!(body["code"], 200);
let token = body["data"]["token"]
.as_str()
.expect("应返回 token")
.to_string();
assert!(!token.is_empty());
// 🔴 前端自己补 `bearer ` 前缀(`request.ts` 的 `setToken`)⇒ 后端返的**不能**带。
assert!(
!token.to_lowercase().starts_with("bearer "),
"token 不应带 bearer 前缀:{}",
token
);
assert_eq!(body["data"]["userInfo"]["userName"], "admin");
assert_eq!(body["data"]["userInfo"]["realName"], "管理员");
assert_eq!(body["data"]["userInfo"]["nickName"], "管理员");
assert_eq!(body["data"]["expiresIn"], 7200);
// ③ 拿令牌访问 Auth/Me ⇒ accessAllowed === true
let (status, body) = call(&app, get_json("/api/ssw/tdc/Auth/Me", Some(&token))).await;
assert_eq!(status, 200);
assert_eq!(body["data"]["accessAllowed"], true);
assert_eq!(body["data"]["account"], "admin");
}
#[tokio::test]
async fn user_management_requires_an_administrator() {
let (app, _accounts) = build("users").await;
// ① 无凭证 ⇒ 401(鉴权中间件拦下)
let (status, body) = call(&app, get_json("/api/permission/Users", None)).await;
assert_eq!(status, 401);
assert_eq!(body["code"], 401);
assert!(body.get("data").is_none(), "鉴权失败不得有 data 键");
// ② 管理员账号 ⇒ 200 + 列表里能看到 admin,且**不含口令字段**
let token = login_token(&app, "admin", "admin").await;
let (status, body) = call(
&app,
get_json(
"/api/permission/Users?currentPage=1&pageSize=20",
Some(&token),
),
)
.await;
assert_eq!(status, 200);
assert!(body["data"]["list"].is_array());
assert!(body["data"]["pagination"]["total"].as_u64().unwrap() >= 1);
let first = &body["data"]["list"][0];
assert!(first.get("passwordMd5").is_none(), "列表不得回显口令");
assert!(first.get("password_md5").is_none(), "列表不得回显口令");
// 列表里能按账号名找到 admin
let list = body["data"]["list"].as_array().unwrap();
assert!(
list.iter().any(|a| a["account"] == "admin"),
"列表应含 admin 账号:{:?}",
list
);
}
/// 🔴 **R1 · 密文契约的「仓外」锚点**:用**上游仓库注释里的字面密文**登录。
///
/// 🔴 为什么必须有一条**不依赖本仓加解密实现**的用例:
/// 其余用例都用 `encrypt_login_password()` 造密文 ⇒ **自证自洽** ⇒
/// `CIPHER_KEY` 被改错时它们**全绿**(实测过:换 key 后 7 个用例仍全过)。
/// 上游契约只被 `src/cipher.rs` 的单元测试(字面向量)钉住 —— 那是**单元**层。
/// 本用例是**端到端**层:字面密文 ⇒ 登录成功 ⇒ **整条链**(解密 → md5 比对
/// → 会话签发)都对齐上游。
///
/// 上游 `src/utils/cipher.ts` 自检向量:`encryptPassword('123456')` 的字面密文。
const UPSTREAM_CIPHER_OF_123456: &str = "d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b";
#[tokio::test]
async fn login_accepts_the_upstream_literal_ciphertext() {
let (app, accounts) = build("upstreamcipher").await;
// 新建账号的初始口令 = `DEFAULT_NEW_USER_PASSWORD` = "123456"
// ⇒ 账号库里存的是 `md5("123456")` = e10adc3949ba59abbe56e057f20f883e
let dave = accounts
.create("dave", "戴夫", 1, None, None)
.expect("建号失败");
assert_eq!(dave.password_md5, "e10adc3949ba59abbe56e057f20f883e");
// ① 上游字面密文 ⇒ 登录成功
let form = format!(
"account=dave&password={}&grant_type=password",
UPSTREAM_CIPHER_OF_123456
);
let (status, body) = call(&app, post_form("/api/oauth/Login", form)).await;
assert_eq!(status, 200);
assert_eq!(
body["code"], 200,
"上游字面密文应能登录(密文契约被改坏了?): {}",
body
);
assert!(!body["data"]["token"].as_str().unwrap_or_default().is_empty());
// ② 同一密文**篡一个字节** ⇒ 必然解出垃圾 ⇒ 业务失败(不许静默放行)
let mut tampered = UPSTREAM_CIPHER_OF_123456.to_string();
tampered.replace_range(0..1, if tampered.starts_with('d') { "e" } else { "d" });
let form = format!(
"account=dave&password={}&grant_type=password",
tampered
);
let (status, body) = call(&app, post_form("/api/oauth/Login", form)).await;
assert_eq!(status, 200);
assert_ne!(body["code"], 200, "篡改的密文必须登录失败:{}", body);
assert_eq!(body["msg"], "账号或密码错误");
}
/// 🔴 **E2 刻意分歧**:内部令牌通道访问用户管理 ⇒ **403**(上游更宽松,直接放行)。
#[tokio::test]
async fn internal_token_channel_is_rejected_by_the_admin_gate() {
let (app, _accounts) = build("internal").await;
let req = Request::builder()
.method("GET")
.uri("/api/permission/Users")
.header("X-Internal-Token", TEST_INTERNAL_TOKEN)
.header("X-Protocol-Version", "1.0")
.body(Body::empty())
.unwrap();
let (status, body) = call(&app, req).await;
assert_eq!(
status, 403,
"内部令牌不得被当成管理员(刻意比上游严): {}",
body
);
assert_eq!(body["code"], 403);
assert_eq!(body["msg"], "仅管理员可管理连接器用户");
assert!(body.get("data").is_none(), "鉴权失败不得有 data 键");
}
/// 🔴 **E3 fail-closed**:非管理员账号 ⇒ 403;查不到账号 ⇒ 同样 403。
#[tokio::test]
async fn non_admin_account_cannot_manage_users() {
let (app, accounts) = build("nonadmin").await;
// 直接在账号库里建一个**非管理员**(初始口令 = `DEFAULT_NEW_USER_PASSWORD` = "123456")
let bob = accounts
.create("bob", "鲍勃", 1, None, None)
.expect("建号失败");
assert!(!bob.administrator);
let token = login_token(&app, "bob", "123456").await;
let (status, body) = call(&app, get_json("/api/permission/Users", Some(&token))).await;
assert_eq!(status, 403, "非管理员不得管用户:{}", body);
assert_eq!(body["msg"], "仅管理员可管理连接器用户");
}
/// 🔴 **MaxKey SSO 不实现 ⇒ 如实报业务失败,绝不伪装成功**。
#[tokio::test]
async fn maxkey_grant_is_reported_as_a_business_failure() {
let (app, _accounts) = build("maxkey").await;
let form = format!(
"account=admin&password={}&grant_type=maxkey&code=abc&state=xyz",
encrypt_login_password("admin")
);
let (status, body) = call(&app, post_form("/api/oauth/Login", form)).await;
assert_eq!(status, 200, "业务失败也是 HTTP 200");
assert_eq!(body["code"], 400, "MaxKey 必须报业务失败:{}", body);
assert!(
body["msg"].as_str().unwrap().contains("MaxKey"),
"msg 应说明 MaxKey 未启用:{}",
body
);
assert!(
body["data"].is_null(),
"MaxKey 失败不得返回 token:{}",
body
);
}
/// 明文口令(未加密)⇒ 业务失败。
#[tokio::test]
async fn plain_text_password_is_rejected() {
let (app, _accounts) = build("plain").await;
let (status, body) = call(
&app,
post_form(
"/api/oauth/Login",
"account=admin&password=admin&grant_type=password".to_string(),
),
)
.await;
assert_eq!(status, 200);
assert_eq!(body["code"], 400);
assert_eq!(body["msg"], "账号或密码错误");
}
/// 用户管理闭环:建号 → 列表可见 → 改密 → 用新口令登录 → 禁用 → 禁用的账号登不进来。
#[tokio::test]
async fn admin_can_manage_accounts_end_to_end() {
let (app, _accounts) = build("manage").await;
let token = login_token(&app, "admin", "admin").await;
// ① 建号
let req = Request::builder()
.method("POST")
.uri("/api/permission/Users")
.header("Content-Type", "application/json")
.header("Authorization", format!("bearer {}", token))
.body(Body::from(
r#"{"account":"carol","realName":"卡罗尔","gender":2,"mobilePhone":"13900000000"}"#,
))
.unwrap();
let (status, body) = call(&app, req).await;
assert_eq!(status, 200);
assert_eq!(body["code"], 200, "建号应成功:{}", body);
let carol_id = body["data"]["id"].as_str().expect("应返回 id").to_string();
assert_eq!(body["data"]["account"], "carol");
assert!(
body["data"].get("passwordMd5").is_none(),
"建号回执不得回显口令:{}",
body
);
// ② 改密(`md5(明文)`,上游前端用 `md5Hex(pwd)` 传)
let req = Request::builder()
.method("POST")
.uri(format!(
"/api/permission/Users/{}/Actions/ResetPassword",
carol_id
))
.header("Content-Type", "application/json")
.header("Authorization", format!("bearer {}", token))
.body(Body::from(
r#"{"userPassword":"2fe08b6d3a2d1c8a3d0f0e6b7a9c1d2e","validatePassword":"2fe08b6d3a2d1c8a3d0f0e6b7a9c1d2e"}"#,
))
.unwrap();
let (status, body) = call(&app, req).await;
assert_eq!(status, 200);
assert_eq!(body["code"], 200, "改密应成功:{}", body);
// ③ 用新口令登录 ⇒ 成功(初始口令 123456 此时应已失效)
let (status, body) = call(
&app,
post_form("/api/oauth/Login", login_form("carol", "123456")),
)
.await;
assert_eq!(status, 200);
assert_ne!(body["code"], 200, "改密后旧口令必须失效:{}", body);
// ④ 禁用
let req = Request::builder()
.method("PUT")
.uri(format!("/api/permission/Users/{}/Actions/State", carol_id))
.header("Content-Type", "application/json")
.header("Authorization", format!("bearer {}", token))
.body(Body::from(r#"{"enabledMark":0}"#))
.unwrap();
let (status, body) = call(&app, req).await;
assert_eq!(status, 200);
assert_eq!(body["code"], 200, "禁用应成功:{}", body);
assert_eq!(body["data"]["enabledMark"], 0);
// ⑤ 被禁用的账号登不进来
let (status, body) = call(
&app,
post_form("/api/oauth/Login", login_form("carol", "123456")),
)
.await;
assert_eq!(status, 200);
assert_eq!(body["code"], 400);
assert_eq!(body["msg"], "账号已被禁用");
}