Files
tdc-rs/tests/account_api.rs
T
adminandClaude Code e475137366 feat(auth): 本地账号层 + JNPF 兼容登录,上游完整控制台可登录
- cipher.rs:MD5 + AES-256-ECB,与上游前端 cipher.ts 逐字对齐(含上游自检向量)
- account.rs:本地账号库存 data/accounts.json(不建 tdc_* 表,30 表口径不变),首启引导 admin
- 新增 POST /api/oauth/Login(grant_type=password)与 /api/permission/Users*(仅管理员)
- AppState 增 accounts 字段与 with_accounts 构造器
- 账号登录走 SessionKind::Account,Auth/Me 返 accessAllowed + account
- README:订正「/api/oauth/Login 尚未实现」并补新端点表

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

389 lines
14 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
);
}
/// 🔴 **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"], "账号已被禁用");
}