账号层从本机 JSON 文件迁到 `base_user` 表,口令改用官方双 md5 公式, 并把从来没在管的「实体 → 权限键」那一层整条拆掉(D6 / D11)。 改动: - `src/tdc/service/account.rs`(重写):账号读写 `base_user` / `base_role` / `base_role_relation`;口令 `f_password = md5(lower(md5(明文)) + lower(f_secretkey))` (上游 `PasswordTokenGranter.java:186`),`f_secretkey` 每账号随机 UUID v4, 改密不换 secretkey;引导幂等;管理员位 = `f_is_administrator=1`,查询异常 ⇒ false。 - `src/tdc/controller/account.rs`(重写):登录改走官方公式比对;`require_admin` 改异步、 按 `f_is_administrator` fail-closed;出参形状不变、不回显口令与 secretkey。 - `src/tdc/entity/mod.rs`:删 `PERMISSION_KEYS` / `permission_key()`(18 条实体级权限键)。 - `src/tdc/service/identity.rs`:删 `capabilities()`;`/Auth/Me` 加 `roles` 键 (上游 `AuthController#me:207` 同款),角色码 SQL 逐字照抄上游。 - `src/tdc/service/crud.rs`:删 `require_write_permission()`,写路径改用 `require_menu_permission()`(与上游 `TdcCrudController.requireMenuPermission()` 同构)。 - `src/main.rs` / `src/tdc/state.rs` / `src/tdc/config.rs`:账号层改由 `bootstrap_account_layer()` 引导;`data/accounts.json` 保留但不再读取。 - `tests/permission_gate.rs` → `tests/permission_model.rs`(断言模型换成登录态闸门)。 影响: - 登录 / 用户管理 6 端点的数据源从 JSON 文件变成 `base_user` 表;出参形状不变。 - 实体级写权限**敞开**(任何登录用户可写全部 18 个实体)—— 与上游同构, 显式记账在 `docs/known-limitations.md` L4;部署退出门槛 = 账号只发给受信人。 - 存量 `data/accounts.json` 的账号**不导入**(D8)。 实测:cargo test 236 项全绿 0 failed · smoke.sh PASS=80 FAIL=0(基线 75 ⇒ +5)· check-boundary.sh exit 0 · check-entity.sh PASS=13 FAIL=0。 Co-Authored-By: Claude Code <[email protected]>
533 lines
21 KiB
Rust
533 lines
21 KiB
Rust
//! 账号层端到端:JNPF 兼容登录 + 用户管理。
|
||
//!
|
||
//! 🔴 **B4 之后,账号落在 `base_user` 表**(上游 j7 的载体)⇒ 本测试二进制内的
|
||
//! **所有用例共用同一个库里的同一批账号** ⇒
|
||
//! ① 引导(`bootstrap_account_layer`)**幂等**且**并发安全**(持 `db_lock`);
|
||
//! ② 每个用例的账号名**必须唯一**(否则撞「账号已存在」)。
|
||
//!
|
||
//! ⚠️ 本测试二进制内共用一个 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::platform::auth::{auth_middleware, AuthState};
|
||
use tdc_connector::platform::cipher::{encrypt_login_password, md5_hex};
|
||
use tdc_connector::platform::config::Config;
|
||
use tdc_connector::tdc::config::TdcConfig;
|
||
use tdc_connector::tdc::controller::build_router;
|
||
use tdc_connector::tdc::service::account;
|
||
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::OnceCell;
|
||
use tower::ServiceExt;
|
||
|
||
/// 测试用的内部令牌(走 `X-Internal-Token` 通道)。
|
||
const TEST_INTERNAL_TOKEN: &str = "test-internal-token";
|
||
|
||
/// 引导管理员的账号名 / 口令(**公开默认值**,仅本地调试用)。
|
||
const ADMIN: &str = "admin";
|
||
const ADMIN_PWD: &str = "admin";
|
||
|
||
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::platform::db::ensure_schema(db.as_ref())
|
||
.await
|
||
.expect("建表失败");
|
||
db
|
||
})
|
||
.await
|
||
.clone()
|
||
}
|
||
|
||
/// 造一个应用。
|
||
///
|
||
/// 🔴 `tag` 决定**测试身份行**的名字 ⇒ 并行用例互不干扰(`f_identity_code` 上有唯一约束)。
|
||
///
|
||
/// 🔴 **账号层共享**:本二进制里的账号都在同一个 `base_user` 表 ⇒ 引导**幂等**
|
||
/// (第一次建管理员,之后跳过)。
|
||
async fn build(tag: &str) -> Router {
|
||
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.internal_token = TEST_INTERNAL_TOKEN.to_string();
|
||
let sessions = Arc::new(SessionStore::new());
|
||
// 🔴 `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::platform::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 tdc_config = TdcConfig::default();
|
||
let state = TdcState::new(
|
||
AppState::new(config.clone(), db, sessions.clone()),
|
||
tdc_config.clone(),
|
||
BootstrapIdentity {
|
||
identity_id,
|
||
identity_code,
|
||
issued_secret: None,
|
||
},
|
||
);
|
||
// 🔴 账号层引导(种三个角色 + 建引导管理员):**幂等** ⇒ 并行用例都调也只建一次。
|
||
account::bootstrap_account_layer(&state, &tdc_config)
|
||
.await
|
||
.expect("账号层引导失败");
|
||
let auth_state = AuthState {
|
||
internal_token: config.internal_token.clone(),
|
||
sessions,
|
||
public_paths: Arc::new(public_paths::all_public_paths()),
|
||
};
|
||
// 🔴 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
|
||
}
|
||
|
||
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()
|
||
}
|
||
|
||
/// 用管理员令牌建一个账号(**初始口令 = `123456`**),返回账号 id。
|
||
async fn create_user(app: &Router, token: &str, account: &str, real_name: &str) -> String {
|
||
let req = Request::builder()
|
||
.method("POST")
|
||
.uri("/api/permission/Users")
|
||
.header("Content-Type", "application/json")
|
||
.header("Authorization", format!("bearer {}", token))
|
||
.body(Body::from(format!(
|
||
r#"{{"account":"{}","realName":"{}","gender":1}}"#,
|
||
account, real_name
|
||
)))
|
||
.unwrap();
|
||
let (status, body) = call(app, req).await;
|
||
assert_eq!(status, 200);
|
||
assert_eq!(body["code"], 200, "建号应成功:{}", body);
|
||
body["data"]["id"].as_str().expect("应返回 id").to_string()
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn oauth_login_returns_a_usable_token() {
|
||
let app = 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_PWD)),
|
||
)
|
||
.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 = 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_PWD).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(), "列表不得回显口令");
|
||
// 🔴 官方公式的两个密钥列**同样不得外泄**
|
||
assert!(first.get("f_password").is_none(), "列表不得回显口令散列");
|
||
assert!(first.get("f_secretkey").is_none(), "列表不得回显秘钥");
|
||
assert!(first.get("secretkey").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(明文)`
|
||
/// → 官方双 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 = build("upstreamcipher").await;
|
||
let admin_token = login_token(&app, ADMIN, ADMIN_PWD).await;
|
||
// 新建账号的初始口令 = `DEFAULT_NEW_USER_PASSWORD` = "123456"
|
||
create_user(&app, &admin_token, "dave-upstream", "戴夫").await;
|
||
|
||
// ① 上游字面密文 ⇒ 登录成功
|
||
let form = format!(
|
||
"account=dave-upstream&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-upstream&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 = 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 = build("nonadmin").await;
|
||
let admin_token = login_token(&app, ADMIN, ADMIN_PWD).await;
|
||
// 建一个**非管理员**(初始口令 = `DEFAULT_NEW_USER_PASSWORD` = "123456")
|
||
create_user(&app, &admin_token, "bob-nonadmin", "鲍勃").await;
|
||
|
||
let token = login_token(&app, "bob-nonadmin", "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 = build("maxkey").await;
|
||
|
||
let form = format!(
|
||
"account={ADMIN}&password={}&grant_type=maxkey&code=abc&state=xyz",
|
||
encrypt_login_password(ADMIN_PWD)
|
||
);
|
||
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 = build("plain").await;
|
||
|
||
let (status, body) = call(
|
||
&app,
|
||
post_form(
|
||
"/api/oauth/Login",
|
||
format!("account={ADMIN}&password={ADMIN_PWD}&grant_type=password"),
|
||
),
|
||
)
|
||
.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 = build("manage").await;
|
||
let token = login_token(&app, ADMIN, ADMIN_PWD).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-manage","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-manage");
|
||
assert_eq!(body["data"]["gender"], 2);
|
||
assert_eq!(body["data"]["mobilePhone"], "13900000000");
|
||
assert!(
|
||
body["data"].get("passwordMd5").is_none(),
|
||
"建号回执不得回显口令:{}",
|
||
body
|
||
);
|
||
|
||
// ② 改密(`md5(明文)`,上游前端用 `md5Hex(pwd)` 传)
|
||
let new_plain = "newpass-2026";
|
||
let new_md5 = md5_hex(new_plain);
|
||
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(format!(
|
||
r#"{{"userPassword":"{}","validatePassword":"{}"}}"#,
|
||
new_md5, new_md5
|
||
)))
|
||
.unwrap();
|
||
let (status, body) = call(&app, req).await;
|
||
assert_eq!(status, 200);
|
||
assert_eq!(body["code"], 200, "改密应成功:{}", body);
|
||
|
||
// ③ 初始口令此时应已失效
|
||
let (status, body) = call(
|
||
&app,
|
||
post_form("/api/oauth/Login", login_form("carol-manage", "123456")),
|
||
)
|
||
.await;
|
||
assert_eq!(status, 200);
|
||
assert_ne!(body["code"], 200, "改密后旧口令必须失效:{}", body);
|
||
|
||
// ④ 新口令可登录
|
||
let (status, body) = call(
|
||
&app,
|
||
post_form("/api/oauth/Login", login_form("carol-manage", new_plain)),
|
||
)
|
||
.await;
|
||
assert_eq!(status, 200);
|
||
assert_eq!(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-manage", new_plain)),
|
||
)
|
||
.await;
|
||
assert_eq!(status, 200);
|
||
assert_eq!(body["code"], 400);
|
||
assert_eq!(body["msg"], "账号已被禁用");
|
||
}
|
||
|
||
/// 🔴 **管理员账号不可删**(对齐上游 JNPF 的「内置管理员保护」)。
|
||
#[tokio::test]
|
||
async fn the_administrator_account_cannot_be_removed() {
|
||
let app = build("adminremove").await;
|
||
let token = login_token(&app, ADMIN, ADMIN_PWD).await;
|
||
|
||
// 找到 admin 的 id
|
||
let (_, body) = call(
|
||
&app,
|
||
get_json("/api/permission/Users?currentPage=1&pageSize=200", Some(&token)),
|
||
)
|
||
.await;
|
||
let list = body["data"]["list"].as_array().unwrap().clone();
|
||
let admin = list
|
||
.iter()
|
||
.find(|a| a["account"] == ADMIN)
|
||
.expect("列表应含 admin");
|
||
let admin_id = admin["id"].as_str().unwrap().to_string();
|
||
|
||
let req = Request::builder()
|
||
.method("DELETE")
|
||
.uri(format!("/api/permission/Users/{}", admin_id))
|
||
.header("Authorization", format!("bearer {}", token))
|
||
.body(Body::empty())
|
||
.unwrap();
|
||
let (status, body) = call(&app, req).await;
|
||
assert_eq!(status, 200, "业务失败也是 HTTP 200:{}", body);
|
||
assert_ne!(body["code"], 200, "管理员账号不得被删:{}", body);
|
||
assert_eq!(body["msg"], "管理员账号不可删除");
|
||
}
|
||
|
||
/// 🔴 **角色码三件套**:管理员在 `/Auth/Me` 里带 `roles` 键(上游 `AuthController#me` 同款)。
|
||
///
|
||
/// ⚠️ 上游的角色判据是 `f_en_code IN ('tdcProvider','tdcConsumer','tdsReadOnly')`,
|
||
/// 而引导管理员绑的是 `user` 角色(上游 `connector_seed` 的第三个角色)
|
||
/// ⇒ **引导管理员的角色码数组为空**(上游同口径,不是本仓的 bug)。
|
||
#[tokio::test]
|
||
async fn the_me_endpoint_carries_the_roles_key() {
|
||
let app = build("roles").await;
|
||
let token = login_token(&app, ADMIN, ADMIN_PWD).await;
|
||
let (status, body) = call(&app, get_json("/api/ssw/tdc/Auth/Me", Some(&token))).await;
|
||
assert_eq!(status, 200);
|
||
assert!(
|
||
body["data"].get("roles").is_some(),
|
||
"/Auth/Me 必须带 roles 键(上游同款):{}",
|
||
body
|
||
);
|
||
assert!(body["data"]["roles"].is_array(), "roles 必须是数组");
|
||
}
|