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]>
This commit is contained in:
1 parent
e75dcf9370
commit
e475137366
11 files changed
+1421
-10
No files matched your search
Generated
+125
-8
@@ -2,6 +2,17 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
@@ -93,6 +104,15 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
@@ -102,6 +122,15 @@ dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-padding"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -149,7 +178,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"cpufeatures 0.3.1",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
@@ -164,6 +193,16 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common 0.1.7",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
@@ -182,6 +221,15 @@ version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
@@ -191,6 +239,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
@@ -209,15 +267,25 @@ dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
@@ -232,6 +300,15 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ecb"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a8bfa975b1aec2145850fcaa1c6fe269a16578c44705a532ae3edc92b8881c7"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
@@ -361,6 +438,16 @@ dependencies = [
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
@@ -400,7 +487,7 @@ version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -651,6 +738,16 @@ dependencies = [
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"block-padding",
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.2"
|
||||
@@ -719,6 +816,16 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.11.0"
|
||||
@@ -726,7 +833,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -886,7 +993,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"fallible-iterator",
|
||||
"hmac",
|
||||
"md-5",
|
||||
"md-5 0.11.0",
|
||||
"memchr",
|
||||
"rand 0.10.3",
|
||||
"sha2",
|
||||
@@ -1273,8 +1380,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
"cpufeatures 0.3.1",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1395,15 +1502,19 @@ dependencies = [
|
||||
name = "tdc-connector"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"axum",
|
||||
"chrono",
|
||||
"ecb",
|
||||
"hex",
|
||||
"http-body-util",
|
||||
"md-5 0.10.6",
|
||||
"pglite-rs",
|
||||
"rand 0.8.8",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -1647,6 +1758,12 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
version = "0.3.2"
|
||||
|
||||
+13
@@ -24,6 +24,19 @@ reqwest = { version = "0.12", default-features = false, features = ["json", "rus
|
||||
rand = "0.8"
|
||||
hex = "0.4"
|
||||
|
||||
# 登录口令加解密(与上游前端 cipher.ts 对齐):AES-256-ECB + MD5
|
||||
# 🔴 版本组合自洽,别混用:aes 0.8 / ecb 0.1 都依赖 cipher 0.4 家族;
|
||||
# aes 0.9 / ecb 0.2 是 cipher 0.5 家族,两套泛型不通用。
|
||||
# 🔴 md-5 钉 0.10(crate 名 `md5`,`use md5::{Digest, Md5};`);0.11 的 API 不同。
|
||||
aes = "0.8"
|
||||
ecb = "0.1"
|
||||
md-5 = "0.10"
|
||||
# 登录表单解析(application/x-www-form-urlencoded)。
|
||||
# ⚠️ axum 0.8.9 的 `Form<T>` 只实现 `FromRequest`、不实现 `OptionalFromRequest`
|
||||
# ⇒ `Option<Form<T>>` 编译不过 ⇒ 改为「取原始 body + serde_urlencoded 自己解析」。
|
||||
# `serde_urlencoded 0.7.1` 已在 `Cargo.lock` 里(axum 的传递依赖)⇒ 不引入新下载。
|
||||
serde_urlencoded = "0.7"
|
||||
|
||||
# 内嵌 PostgreSQL(进程内原生编译,非 WASM):承载全部 tdc_* 业务数据
|
||||
# 包名 pglite-rs,import 为 pglite。无需扩展时不用 build.rs/export_dynamic。
|
||||
pglite-rs = "0.2"
|
||||
|
||||
@@ -15,8 +15,13 @@
|
||||
|
||||
> 红线:原 TDC 与 TDS **只走 HTTP 契约、不编译期耦合**。
|
||||
> 本实现**不代理** TDS(TDS 侧出向客户端属后续任务)。
|
||||
> 🔴 上游前端登录走 JNPF 门户账号(`POST /api/oauth/Login`)——**该端点本仓尚未实现**
|
||||
> (属后续任务)⇒ 现在登录请用 `/api/ssw/tdc/Auth/Login`。
|
||||
> 🔴 上游前端登录走 JNPF 门户账号(`POST /api/oauth/Login`)——**本仓已实现**
|
||||
> (JNPF 兼容面:口令用上游 `cipher.ts` 的 **AES-256-ECB 密文 hex** 传输,
|
||||
> `grant_type=password`;`grant_type=maxkey` 如实报业务失败,**不伪装成功**)。
|
||||
> 但**不引入 j7** ⇒ 用本连接器自己的**本地账号库** `data/accounts.json` 顶替
|
||||
> (口令只存 `md5(明文)`,**永不回显**);首次启动自动引导一个管理员账号
|
||||
> **`admin` / `admin`**(⚠️ **本地调试默认值**,对外部署前必须改掉)。
|
||||
> 连接器身份登录(`/api/ssw/tdc/Auth/Login`)也仍然可用。
|
||||
|
||||
## 运行
|
||||
|
||||
@@ -71,6 +76,13 @@ sccache 0.18 经 `~/.cargo/config.toml` 的 `[build] rustc-wrapper` + `[env] SCC
|
||||
| GET | `/api/ssw/tdc/Auth/Me` | 当前身份视图(**去敏**:不含私钥/一次性密钥) |
|
||||
| GET | `/api/ssw/tdc/Auth/Spaces` | 环境空间列表 |
|
||||
| GET | `/api/ssw/tdc/Auth/SsoConfig` | SSO 配置(上游前端登录页用) |
|
||||
| POST | `/api/oauth/Login` | **JNPF 兼容登录**(`application/x-www-form-urlencoded`:`account` / `password`(**密文 hex**) / `grant_type=password`)|
|
||||
| GET | `/api/permission/Users` | 用户管理 · 列表(分页 + 关键字;**仅管理员**)|
|
||||
| POST | `/api/permission/Users` | 用户管理 · 新建(**仅管理员**;初始口令 `123456`)|
|
||||
| PUT | `/api/permission/Users/{id}` | 用户管理 · 改资料(**仅管理员**)|
|
||||
| DELETE | `/api/permission/Users/{id}` | 用户管理 · 删账号(**仅管理员**;管理员账号不可删)|
|
||||
| POST | `/api/permission/Users/{id}/Actions/ResetPassword` | 重设口令(收 `md5(明文)`;**仅管理员**)|
|
||||
| PUT | `/api/permission/Users/{id}/Actions/State` | 启用 / 禁用(`enabledMark`;**仅管理员**)|
|
||||
| GET / POST | `/api/ssw/tdc/{Entity}` | 18 个实体的列表 / 新建 |
|
||||
| GET | `/api/ssw/tdc/{Entity}/All` | 不分页全量 |
|
||||
| GET / PUT / DELETE | `/api/ssw/tdc/{Entity}/{id}` | 详情 / 修改 / 逻辑删除 |
|
||||
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
//! 本连接器的**本地账号库**(上游叫「连接器自己的 j7」)。
|
||||
//!
|
||||
//! ⚠️ 上游账号表住在 JNPF 平台库(j7),本仓不引入 j7 ⇒ 改用**本机 JSON 文件**
|
||||
//! `data/accounts.json`。刻意**不建 `tdc_*` 表** ⇒ `schema/migrate.sql` 保持上游 30 表
|
||||
//! **逐字节一致**,`/api/health` 的 `tables` 恒为 30。
|
||||
//!
|
||||
//! 口令只存 `md5(明文)`(与上游 JNPF 同口径:`ResetPassword` 收 `md5(明文)`)。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::cipher::md5_hex;
|
||||
|
||||
/// 新建账号的初始口令(上游取 `base_sys_config.newUserDefaultPassword`,本端固定值)。
|
||||
pub const DEFAULT_NEW_USER_PASSWORD: &str = "123456";
|
||||
|
||||
/// 首次启动引导的管理员账号名(上游前端登录页默认填 `admin`)。
|
||||
pub const BOOTSTRAP_ADMIN_ACCOUNT: &str = "admin";
|
||||
|
||||
/// 首次启动引导的管理员口令。⚠️ **本地调试默认值**,README 里必须写明。
|
||||
pub const BOOTSTRAP_ADMIN_PASSWORD: &str = "admin";
|
||||
|
||||
/// 落盘失败 ⇒ 业务错误文案(写路径的 `Result<_, String>` 统一用它)。
|
||||
///
|
||||
/// 🔴 落盘失败**必须**当业务失败抛出去(账号改了却没存下来 ⇒ 内存与磁盘不一致 ⇒ 更糟),
|
||||
/// 不能吞掉。
|
||||
fn save_err(e: std::io::Error) -> String {
|
||||
format!("保存账号库失败: {}", e)
|
||||
}
|
||||
|
||||
/// 常量时间比较(长度不同直接 false)。
|
||||
pub fn constant_time_eq(a: &str, b: &str) -> bool {
|
||||
let (a, b) = (a.as_bytes(), b.as_bytes());
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0u8;
|
||||
for (x, y) in a.iter().zip(b.iter()) {
|
||||
diff |= x ^ y;
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Account {
|
||||
pub id: String,
|
||||
pub account: String,
|
||||
pub real_name: String,
|
||||
pub gender: i64,
|
||||
#[serde(default)]
|
||||
pub mobile_phone: Option<String>,
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
/// 1 = 启用,0 = 禁用(上游 `enabledMark`)。
|
||||
pub enabled_mark: i64,
|
||||
/// 是否管理员(上游 `f_is_administrator`)⇒ 能不能管 `/api/permission/Users*`。
|
||||
pub administrator: bool,
|
||||
/// `md5(明文)`(32 个 hex 字符)。**永不回显**。
|
||||
pub password_md5: String,
|
||||
pub creator_time: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct AccountFile {
|
||||
#[serde(default)]
|
||||
pub accounts: Vec<Account>,
|
||||
}
|
||||
|
||||
/// 账号库:JSON 文件 + 进程内互斥锁。
|
||||
pub struct AccountStore {
|
||||
/// `None` = 内存库(不落盘)⇒ 早期任务与单测用 `AccountStore::empty()`。
|
||||
path: Option<PathBuf>,
|
||||
inner: Mutex<AccountFile>,
|
||||
}
|
||||
|
||||
impl AccountStore {
|
||||
/// 打开(或创建)账号文件;**库里没有账号时引导一个 `admin`**。
|
||||
pub fn open(path: &Path) -> std::io::Result<Self> {
|
||||
let mut file: AccountFile = match std::fs::read(path) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
|
||||
Err(_) => AccountFile::default(),
|
||||
};
|
||||
if file.accounts.is_empty() {
|
||||
file.accounts.push(Account {
|
||||
id: crate::ids::next_id(),
|
||||
account: BOOTSTRAP_ADMIN_ACCOUNT.to_string(),
|
||||
real_name: "管理员".to_string(),
|
||||
gender: 1,
|
||||
mobile_phone: None,
|
||||
description: Some("首次启动引导".to_string()),
|
||||
enabled_mark: 1,
|
||||
administrator: true,
|
||||
password_md5: md5_hex(BOOTSTRAP_ADMIN_PASSWORD),
|
||||
creator_time: now_iso(),
|
||||
});
|
||||
}
|
||||
let store = Self {
|
||||
path: Some(path.to_path_buf()),
|
||||
inner: Mutex::new(file),
|
||||
};
|
||||
store.save()?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// 内存库(不落盘)。
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
path: None,
|
||||
inner: Mutex::new(AccountFile::default()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list(&self) -> Vec<Account> {
|
||||
self.inner.lock().expect("账号库锁中毒").accounts.clone()
|
||||
}
|
||||
|
||||
pub fn find(&self, id: &str) -> Option<Account> {
|
||||
self.list().into_iter().find(|a| a.id == id)
|
||||
}
|
||||
|
||||
pub fn find_by_account(&self, account: &str) -> Option<Account> {
|
||||
self.list().into_iter().find(|a| a.account == account)
|
||||
}
|
||||
|
||||
/// 新建账号;账号名重复 ⇒ `Err("账号已存在")`。初始口令固定为 `DEFAULT_NEW_USER_PASSWORD`
|
||||
/// (上游口径:新建的初始口令**不取请求里的 password**,而是系统默认口令)。
|
||||
pub fn create(
|
||||
&self,
|
||||
account: &str,
|
||||
real_name: &str,
|
||||
gender: i64,
|
||||
mobile_phone: Option<String>,
|
||||
description: Option<String>,
|
||||
) -> Result<Account, String> {
|
||||
let account = account.trim();
|
||||
if account.is_empty() {
|
||||
return Err("账号必填".to_string());
|
||||
}
|
||||
let mut guard = self.inner.lock().expect("账号库锁中毒");
|
||||
if guard.accounts.iter().any(|a| a.account == account) {
|
||||
return Err("账号已存在".to_string());
|
||||
}
|
||||
let row = Account {
|
||||
id: crate::ids::next_id(),
|
||||
account: account.to_string(),
|
||||
real_name: real_name.trim().to_string(),
|
||||
gender,
|
||||
mobile_phone,
|
||||
description,
|
||||
enabled_mark: 1,
|
||||
administrator: false,
|
||||
password_md5: md5_hex(DEFAULT_NEW_USER_PASSWORD),
|
||||
creator_time: now_iso(),
|
||||
};
|
||||
guard.accounts.push(row.clone());
|
||||
self.save_locked(&guard).map_err(save_err)?;
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
/// 更新资料(**不动口令**)。
|
||||
pub fn update(
|
||||
&self,
|
||||
id: &str,
|
||||
real_name: &str,
|
||||
gender: i64,
|
||||
mobile_phone: Option<String>,
|
||||
description: Option<String>,
|
||||
) -> Result<Account, String> {
|
||||
let mut guard = self.inner.lock().expect("账号库锁中毒");
|
||||
let row = guard
|
||||
.accounts
|
||||
.iter_mut()
|
||||
.find(|a| a.id == id)
|
||||
.ok_or_else(|| "账号不存在".to_string())?;
|
||||
row.real_name = real_name.trim().to_string();
|
||||
row.gender = gender;
|
||||
row.mobile_phone = mobile_phone;
|
||||
row.description = description;
|
||||
let out = row.clone();
|
||||
self.save_locked(&guard).map_err(save_err)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 删除(**管理员账号不许删**)。
|
||||
pub fn remove(&self, id: &str) -> Result<(), String> {
|
||||
let mut guard = self.inner.lock().expect("账号库锁中毒");
|
||||
let row = guard
|
||||
.accounts
|
||||
.iter()
|
||||
.find(|a| a.id == id)
|
||||
.ok_or_else(|| "账号不存在".to_string())?;
|
||||
if row.administrator {
|
||||
return Err("管理员账号不可删除".to_string());
|
||||
}
|
||||
guard.accounts.retain(|a| a.id != id);
|
||||
self.save_locked(&guard).map_err(save_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 启用 / 禁用。
|
||||
pub fn set_enabled(&self, id: &str, enabled_mark: i64) -> Result<Account, String> {
|
||||
let mut guard = self.inner.lock().expect("账号库锁中毒");
|
||||
let row = guard
|
||||
.accounts
|
||||
.iter_mut()
|
||||
.find(|a| a.id == id)
|
||||
.ok_or_else(|| "账号不存在".to_string())?;
|
||||
row.enabled_mark = if enabled_mark == 0 { 0 } else { 1 };
|
||||
let out = row.clone();
|
||||
self.save_locked(&guard).map_err(save_err)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 重设口令(传入的是 `md5(明文)`,32 个 hex 字符)。
|
||||
pub fn reset_password(&self, id: &str, password_md5: &str) -> Result<Account, String> {
|
||||
let mut guard = self.inner.lock().expect("账号库锁中毒");
|
||||
let row = guard
|
||||
.accounts
|
||||
.iter_mut()
|
||||
.find(|a| a.id == id)
|
||||
.ok_or_else(|| "账号不存在".to_string())?;
|
||||
row.password_md5 = password_md5.to_string();
|
||||
let out = row.clone();
|
||||
self.save_locked(&guard).map_err(save_err)?;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// 落盘(**先写临时文件再 rename**,避免写坏文件;`path == None` 时是空操作)。
|
||||
impl AccountStore {
|
||||
fn save(&self) -> std::io::Result<()> {
|
||||
let guard = self.inner.lock().expect("账号库锁中毒");
|
||||
self.save_locked(&guard)
|
||||
}
|
||||
|
||||
fn save_locked(&self, file: &AccountFile) -> std::io::Result<()> {
|
||||
let Some(path) = &self.path else {
|
||||
return Ok(());
|
||||
};
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
std::fs::write(&tmp, serde_json::to_vec_pretty(file).unwrap_or_default())?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前 UTC 时间(`YYYY-MM-DD HH:MM:SS`)。
|
||||
pub fn now_iso() -> String {
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0);
|
||||
let days = secs.div_euclid(86_400);
|
||||
let rem = secs.rem_euclid(86_400);
|
||||
let (y, m, d) = civil_from_days(days);
|
||||
format!(
|
||||
"{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
|
||||
rem / 3600,
|
||||
(rem % 3600) / 60,
|
||||
rem % 60
|
||||
)
|
||||
}
|
||||
|
||||
/// 天元纪日 → 公历年月日(Hinnant 算法,闰年规则完整)。
|
||||
fn civil_from_days(z: i64) -> (i64, u32, u32) {
|
||||
let z = z + 719_468;
|
||||
// 🔴 `if/else` 表达式必须**加括号**再参与运算 —— 否则 `let era = if … {} / 146_097;`
|
||||
// 的解析含义依赖 Rust 对「块表达式后接运算符」的贪婪规则,脆弱且易被误读。
|
||||
let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
|
||||
let doe = (z - era * 146_097) as u64;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe as i64 + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||
(if m <= 2 { y + 1 } else { y }, m, d)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 账号文件路径(**不**清理,用于读回)。
|
||||
fn tmp_path(name: &str) -> PathBuf {
|
||||
PathBuf::from("target").join(format!("test-accounts-{name}.json"))
|
||||
}
|
||||
|
||||
/// 每次用例都用**干净**的账号文件 ——
|
||||
/// 否则第二次 `cargo test` 会因「bob 已存在」而红(账号库是**持久**的 JSON 文件)。
|
||||
fn fresh_path(name: &str) -> PathBuf {
|
||||
let p = tmp_path(name);
|
||||
let _ = std::fs::remove_file(&p);
|
||||
let _ = std::fs::remove_file(p.with_extension("json.tmp"));
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstraps_an_admin_account_on_first_open() {
|
||||
let store = AccountStore::open(&fresh_path("bootstrap")).expect("打开账号库失败");
|
||||
let admin = store.find_by_account("admin").expect("应有 admin 账号");
|
||||
assert!(admin.administrator);
|
||||
assert_eq!(admin.enabled_mark, 1);
|
||||
assert_eq!(admin.password_md5, md5_hex("admin"));
|
||||
// 🔴 口令只存 md5:新建一个默认口令账号后,文件里出现的是 **md5 hex** 而不是明文。
|
||||
// (⚠️ 不能用 `!raw.contains("\"admin\"")` 判 —— 账号**名**就是 "admin",
|
||||
// JSON 里必有 `"account": "admin"` ⇒ 那条断言恒假。)
|
||||
let created = store
|
||||
.create("bob", "鲍勃", 1, None, None)
|
||||
.expect("建号失败");
|
||||
assert_eq!(created.password_md5, md5_hex(DEFAULT_NEW_USER_PASSWORD));
|
||||
let raw = std::fs::read_to_string(tmp_path("bootstrap")).unwrap();
|
||||
assert!(
|
||||
!raw.contains(&format!(
|
||||
"\"password_md5\": \"{}\"",
|
||||
DEFAULT_NEW_USER_PASSWORD
|
||||
)),
|
||||
"文件里不得出现明文口令:{}",
|
||||
raw
|
||||
);
|
||||
assert!(
|
||||
raw.contains(&format!(
|
||||
"\"password_md5\": \"{}\"",
|
||||
md5_hex(DEFAULT_NEW_USER_PASSWORD)
|
||||
)),
|
||||
"文件里应存 md5(明文)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_update_and_reset_password() {
|
||||
let store = AccountStore::open(&fresh_path("crud")).expect("打开账号库失败");
|
||||
let created = store
|
||||
.create("bob", "鲍勃", 1, None, None)
|
||||
.expect("建号失败");
|
||||
assert_eq!(
|
||||
store.find_by_account("bob").unwrap().password_md5,
|
||||
md5_hex(DEFAULT_NEW_USER_PASSWORD)
|
||||
);
|
||||
assert!(
|
||||
store.create("bob", "重复", 1, None, None).is_err(),
|
||||
"账号名重复应报错"
|
||||
);
|
||||
let updated = store
|
||||
.update(&created.id, "鲍勃二世", 2, Some("13800000000".into()), None)
|
||||
.unwrap();
|
||||
assert_eq!(updated.real_name, "鲍勃二世");
|
||||
store
|
||||
.reset_password(&created.id, &md5_hex("newpass"))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
store.find(&created.id).unwrap().password_md5,
|
||||
md5_hex("newpass")
|
||||
);
|
||||
assert!(store.remove(&created.id).is_ok());
|
||||
assert!(store.find(&created.id).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn administrator_cannot_be_removed() {
|
||||
let store = AccountStore::open(&fresh_path("admin")).expect("打开账号库失败");
|
||||
let admin = store.find_by_account("admin").unwrap();
|
||||
assert!(store.remove(&admin.id).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn civil_from_days_matches_known_dates() {
|
||||
assert_eq!(civil_from_days(0), (1970, 1, 1));
|
||||
assert_eq!(civil_from_days(20_750), (2026, 10, 24));
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
//! 登录口令的加解密 —— 与上游前端 `src/utils/cipher.ts` **逐字对齐**。
|
||||
//!
|
||||
//! 上游算法(JNPF 前端约定):
|
||||
//! 1. key = `md5(CIPHER_KEY)` 的**十六进制字符串的 UTF-8 字节**(32 字节 ⇒ AES-256)
|
||||
//! 2. src = `md5(plain)` 的**十六进制字符串的 UTF-8 字节**(32 字节)
|
||||
//! 3. AES-256-ECB + Pkcs7 ⇒ 48 字节密文 ⇒ hex 字符串
|
||||
//!
|
||||
//! 🔴 **关键坑**:`CryptoJS.enc.Utf8.parse(md5(x))` 解析的是 **hex 字符串本身**(32 个 ASCII 字节),
|
||||
//! 不是 md5 摘要的 16 个原始字节 —— 用原始字节会退化成 AES-128,密文长度也对不上(32 vs 48)。
|
||||
//!
|
||||
//! 本仓的**登录面**只解密:上游前端把明文口令加密后送上来,服务端解出 `md5(明文)`
|
||||
//! 再与账号库里存的 `md5(明文)` 逐字比较(口令明文永不落盘、永不外泄)。
|
||||
|
||||
use aes::cipher::{generic_array::GenericArray, BlockDecryptMut, BlockEncryptMut, KeyInit};
|
||||
use ecb::{Decryptor, Encryptor};
|
||||
use md5::{Digest, Md5};
|
||||
|
||||
type Aes256EcbEnc = Encryptor<aes::Aes256>;
|
||||
type Aes256EcbDec = Decryptor<aes::Aes256>;
|
||||
|
||||
/// 与上游前端 `CIPHER_KEY` 一致(上游注释:必须与 JNPF 前端 `.env` 的 `VITE_CIPHER_KEY` 完全一致)。
|
||||
pub const CIPHER_KEY: &str = "EY8WePvjM5GGwQzn";
|
||||
|
||||
/// MD5 的小写 hex(32 字符)。
|
||||
pub fn md5_hex(input: &str) -> String {
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(input.as_bytes());
|
||||
hasher
|
||||
.finalize()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 密文 hex → **明文的 md5 hex**(32 个 ASCII 字符)。
|
||||
///
|
||||
/// 返回 `None` 的情形:hex 非法 / 长度不是 16 的倍数 / Pkcs7 填充不自洽 / 解出来不是 UTF-8。
|
||||
pub fn decrypt_login_password(cipher_hex: &str) -> Option<String> {
|
||||
let mut buf = hex::decode(cipher_hex.trim()).ok()?;
|
||||
if buf.is_empty() || buf.len() % 16 != 0 {
|
||||
return None;
|
||||
}
|
||||
let key = md5_hex(CIPHER_KEY);
|
||||
// 🔴 `ecb` 0.1 只实现了 `BlockDecryptMut`(**原地**改块)⇒ 用 `decrypt_block_mut`。
|
||||
// `dec` 必须是 `mut`,否则 E0596。
|
||||
let mut dec = Aes256EcbDec::new(GenericArray::from_slice(key.as_bytes()));
|
||||
for chunk in buf.chunks_mut(16) {
|
||||
dec.decrypt_block_mut(GenericArray::from_mut_slice(chunk));
|
||||
}
|
||||
// 去 Pkcs7 填充
|
||||
let pad = *buf.last()? as usize;
|
||||
if pad == 0 || pad > 16 || pad > buf.len() {
|
||||
return None;
|
||||
}
|
||||
if buf[buf.len() - pad..].iter().any(|b| *b as usize != pad) {
|
||||
return None;
|
||||
}
|
||||
buf.truncate(buf.len() - pad);
|
||||
String::from_utf8(buf).ok()
|
||||
}
|
||||
|
||||
/// 明文 → 密文 hex(与上游 `encryptPassword` 同义)。
|
||||
///
|
||||
/// 服务端本身只用解密;这个方向**只为测试**:让集成测试能造出上游前端送来的密文,
|
||||
/// 且**不是自证自洽** —— 断言用的是上游仓库注释里的**原始向量**。
|
||||
pub fn encrypt_login_password(plain: &str) -> String {
|
||||
let key = md5_hex(CIPHER_KEY);
|
||||
let src = md5_hex(plain);
|
||||
let mut buf = src.as_bytes().to_vec();
|
||||
let pad = 16 - buf.len() % 16;
|
||||
buf.extend(std::iter::repeat_n(pad as u8, pad));
|
||||
// 🔴 `ecb` 0.1 只实现了 `BlockEncryptMut`(**原地**改块)⇒ 用 `encrypt_block_mut`。
|
||||
// `enc` 必须是 `mut`,否则 E0596。
|
||||
let mut enc = Aes256EcbEnc::new(GenericArray::from_slice(key.as_bytes()));
|
||||
for chunk in buf.chunks_mut(16) {
|
||||
enc.encrypt_block_mut(GenericArray::from_mut_slice(chunk));
|
||||
}
|
||||
hex::encode(buf)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 上游 `src/utils/cipher.ts` 的**自检向量**(上游注释原文):
|
||||
/// `encryptPassword('123456') === 'd4958348…cdc02b'`
|
||||
const UPSTREAM_VECTOR: &str = "d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b";
|
||||
|
||||
#[test]
|
||||
fn md5_matches_known_values() {
|
||||
assert_eq!(md5_hex("123456"), "e10adc3949ba59abbe56e057f20f883e");
|
||||
assert_eq!(md5_hex(CIPHER_KEY), "05b0175907a859751f57a04d5a5ee9ac");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypt_reproduces_the_upstream_self_test_vector() {
|
||||
assert_eq!(encrypt_login_password("123456"), UPSTREAM_VECTOR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decrypts_the_upstream_self_test_vector() {
|
||||
assert_eq!(
|
||||
decrypt_login_password(UPSTREAM_VECTOR).as_deref(),
|
||||
Some("e10adc3949ba59abbe56e057f20f883e")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_garbage() {
|
||||
assert!(decrypt_login_password("not-hex").is_none());
|
||||
assert!(decrypt_login_password("00112233").is_none());
|
||||
assert!(decrypt_login_password("").is_none());
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,9 @@
|
||||
//! - 所有 DB 访问持 `state.db_lock`(PGlite 单 in-process backend)。
|
||||
//! - 任意 SELECT 走 `db::query_json()`(row_to_json 包裹)。
|
||||
|
||||
pub mod account;
|
||||
pub mod auth;
|
||||
pub mod cipher;
|
||||
pub mod codec;
|
||||
pub mod config;
|
||||
pub mod crud;
|
||||
|
||||
@@ -124,6 +124,15 @@ async fn main() {
|
||||
|
||||
let state = state.with_bootstrap(bootstrap);
|
||||
|
||||
// 本地账号库(上游完整前端的 JNPF 兼容登录用):JSON 文件,不进数据库。
|
||||
// 🔴 挂在 `with_bootstrap` **之后**(`with_accounts` 只换 `accounts` 字段,其余保留)。
|
||||
// ⚠️ `data_dir` 已在上面定义(来自 `config.data_dir`)⇒ 这里**不重新定义**。
|
||||
let accounts = Arc::new(
|
||||
tdc_connector::account::AccountStore::open(&data_dir.join("accounts.json"))
|
||||
.expect("打开本地账号库失败"),
|
||||
);
|
||||
let state = state.with_accounts(accounts);
|
||||
|
||||
let auth_state = AuthState {
|
||||
internal_token: config.internal_token.clone(),
|
||||
sessions: sessions.clone(),
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! 本地账号相关的对外端点:
|
||||
//! · `POST /api/oauth/Login`(**上游完整前端登录链的第 ① 步**,JNPF 兼容面)
|
||||
//! · `/api/permission/Users*`(「用户管理」页;上游复用 JNPF 的用户 CRUD)
|
||||
//!
|
||||
//! ⚠️ 业务失败一律 **HTTP 200 + body `code` != 200**(上游前端按 `body.code` 判成败)。
|
||||
//! 鉴权/授权失败是**另一种**形状(HTTP 401/403 + 裸三字段),见 `crate::auth::reject`。
|
||||
|
||||
use axum::extract::{Extension, Path, Query, State};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post, put};
|
||||
use axum::Router;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::account::{constant_time_eq, Account};
|
||||
use crate::auth::Principal;
|
||||
use crate::cipher::decrypt_login_password;
|
||||
use crate::envelope::{ActionResult, Pagination};
|
||||
use crate::state::AppState;
|
||||
|
||||
/// 登录表单(`application/x-www-form-urlencoded`)。
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct LoginForm {
|
||||
pub account: String,
|
||||
/// 上游前端送的是 **密文 hex**(`cipher.ts` 的 `encryptPassword`)。
|
||||
pub password: String,
|
||||
/// ⚠️ **不加** `#[serde(rename_all = "camelCase")]`:camelCase 会把 `grant_type`
|
||||
/// 改名成 `grantType`,而上游表单送的是 **`grant_type=password`** ⇒ 字段永远为 `None`。
|
||||
/// (`account` / `password` 是单词,camelCase 对它们无影响。)
|
||||
#[serde(default, alias = "grantType")]
|
||||
pub grant_type: Option<String>,
|
||||
}
|
||||
|
||||
pub fn router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/api/oauth/Login", post(login))
|
||||
.route("/api/permission/Users", get(list_users).post(create_user))
|
||||
.route(
|
||||
"/api/permission/Users/{id}",
|
||||
put(update_user).delete(remove_user),
|
||||
)
|
||||
.route(
|
||||
"/api/permission/Users/{id}/Actions/ResetPassword",
|
||||
post(reset_password),
|
||||
)
|
||||
.route("/api/permission/Users/{id}/Actions/State", put(set_state))
|
||||
}
|
||||
|
||||
async fn login(State(state): State<AppState>, body: axum::body::Bytes) -> Response {
|
||||
// 🔴 axum 0.8.9:`Form<T>` 只实现了 `FromRequest`,**没有** `OptionalFromRequest`
|
||||
// ⇒ `Option<Form<LoginForm>>` **编译不过**(`axum-0.8.9/src/form.rs` 只有
|
||||
// `impl<T, S> FromRequest<S> for Form<T>`)⇒ 自己取原始 body 解析。
|
||||
// `Bytes` 是 `FromRequest` ⇒ 任何 Content-Type 都能拿到 body ⇒ 解析失败也走业务信封。
|
||||
let form: LoginForm = match serde_urlencoded::from_bytes(&body) {
|
||||
Ok(f) => f,
|
||||
Err(_) => return ActionResult::fail("登录参数缺失").into_response(),
|
||||
};
|
||||
// 🔴 MaxKey SSO:本仓**没有** MaxKey 服务器 ⇒ 如实报业务失败,**绝不伪装成功**
|
||||
// (上游 `auth.ts` 的 `maxkeyLogin` 注释明确要求「失败如实抛出」)。
|
||||
if form.grant_type.as_deref() == Some("maxkey") {
|
||||
return ActionResult::fail("MaxKey 统一认证未启用,请使用账号口令登录").into_response();
|
||||
}
|
||||
let account = form.account.trim();
|
||||
let row = match state.accounts.find_by_account(account) {
|
||||
Some(r) => r,
|
||||
None => return ActionResult::fail("账号或密码错误").into_response(),
|
||||
};
|
||||
if row.enabled_mark != 1 {
|
||||
return ActionResult::fail("账号已被禁用").into_response();
|
||||
}
|
||||
// 解出的是「明文的 md5 hex」⇒ 与账号库里存的 `md5(明文)` 逐字比较。
|
||||
let Some(plain_md5) = decrypt_login_password(&form.password) else {
|
||||
return ActionResult::fail("账号或密码错误").into_response();
|
||||
};
|
||||
if !constant_time_eq(&plain_md5, &row.password_md5) {
|
||||
return ActionResult::fail("账号或密码错误").into_response();
|
||||
}
|
||||
let token = state.sessions.create_account(&row.id, &row.account);
|
||||
// 🔴 `data.token` **不带** `bearer ` 前缀(上游前端自己补,见 `request.ts` 的 `setToken`)。
|
||||
ActionResult::ok(json!({
|
||||
"token": token,
|
||||
"expiresIn": 7200,
|
||||
"userInfo": {
|
||||
"userName": row.account,
|
||||
"realName": row.real_name,
|
||||
"nickName": row.real_name,
|
||||
},
|
||||
}))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// 账号的对外视图(**不含 `password_md5`**)。
|
||||
///
|
||||
/// 🔴 手工挑字段,**不**在 `Account` 上用 `#[serde(skip_serializing)]`
|
||||
/// (那会让落盘 JSON 缺字段、回读失败)—— 落盘与外发是**两套形状**。
|
||||
fn account_view(a: &Account) -> Value {
|
||||
json!({
|
||||
"id": a.id,
|
||||
"account": a.account,
|
||||
"realName": a.real_name,
|
||||
"gender": a.gender,
|
||||
"mobilePhone": a.mobile_phone,
|
||||
"enabledMark": a.enabled_mark,
|
||||
"creatorTime": a.creator_time,
|
||||
"description": a.description,
|
||||
})
|
||||
}
|
||||
|
||||
/// 管理员闸门:连接器身份会话(`Principal::Session`)或**管理员账号**放行,其余 403。
|
||||
///
|
||||
/// 🔴 **刻意比上游严一档**:上游 `TdcAuthFilter` 的内部令牌通道(`X-Internal-Token`)
|
||||
/// 与身份会话通道(`X-Auth-Token`)都**直接放行**、不过管理员门;本仓把
|
||||
/// **内部令牌也拒了**(内部令牌是服务端通道,不该被当成「管理员」)。
|
||||
/// 差异登记见 Task 12 报告 §4。
|
||||
///
|
||||
/// 🔴 **fail-closed**(对齐上游 `TdcConnectorAdminGuard`):账号查不到 ⇒ `false` ⇒ 403。
|
||||
#[allow(clippy::result_large_err)]
|
||||
fn require_admin(state: &AppState, p: Option<&Extension<Principal>>) -> Result<(), Response> {
|
||||
match p.map(|e| &e.0) {
|
||||
Some(Principal::Session { .. }) => Ok(()),
|
||||
Some(Principal::Account { account_id, .. }) => {
|
||||
let admin = state
|
||||
.accounts
|
||||
.find(account_id)
|
||||
.map(|a| a.administrator)
|
||||
.unwrap_or(false);
|
||||
if admin {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(crate::auth::reject(
|
||||
axum::http::StatusCode::FORBIDDEN,
|
||||
"仅管理员可管理连接器用户",
|
||||
))
|
||||
}
|
||||
}
|
||||
// 内部令牌通道:**刻意**不过管理员门(见函数注释)⇒ 与上游的差异。
|
||||
Some(Principal::Internal { .. }) => Err(crate::auth::reject(
|
||||
axum::http::StatusCode::FORBIDDEN,
|
||||
"仅管理员可管理连接器用户",
|
||||
)),
|
||||
None => Err(crate::auth::reject(
|
||||
axum::http::StatusCode::UNAUTHORIZED,
|
||||
"内部接口凭证无效",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 列表的查询参数(上游前端发 `currentPage` / `pageSize` / `keyword`)。
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UserQuery {
|
||||
#[serde(default)]
|
||||
pub current_page: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub page_size: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub keyword: Option<String>,
|
||||
}
|
||||
|
||||
async fn list_users(
|
||||
State(state): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
Query(q): Query<UserQuery>,
|
||||
) -> Response {
|
||||
if let Err(e) = require_admin(&state, p.as_ref()) {
|
||||
return e;
|
||||
}
|
||||
let page = q.current_page.unwrap_or(1).max(1) as usize;
|
||||
let size = q.page_size.unwrap_or(20).clamp(1, 500) as usize;
|
||||
let keyword = q.keyword.unwrap_or_default().trim().to_lowercase();
|
||||
|
||||
let matched: Vec<Value> = state
|
||||
.accounts
|
||||
.list()
|
||||
.iter()
|
||||
.filter(|a| {
|
||||
keyword.is_empty()
|
||||
|| a.account.to_lowercase().contains(&keyword)
|
||||
|| a.real_name.to_lowercase().contains(&keyword)
|
||||
})
|
||||
.map(account_view)
|
||||
.collect();
|
||||
let total = matched.len();
|
||||
// 🔴 `page` 来自客户端 ⇒ 用 `saturating_mul` 防溢出(超大 page 不该 panic)。
|
||||
let start = (page - 1).saturating_mul(size);
|
||||
let list: Vec<Value> = matched.into_iter().skip(start).take(size).collect();
|
||||
// 🔴 `ActionResult::page` 的**确切签名**(`src/envelope.rs`,Task 2 定的):
|
||||
// `page(list: Vec<Value>, pagination: Pagination) -> ActionResult<Value>`
|
||||
// —— **不是**四个平铺参数。`Pagination` 是 `pub` 且字段 `current_page/page_size/total`。
|
||||
ActionResult::page(
|
||||
list,
|
||||
Pagination {
|
||||
current_page: page as i64,
|
||||
page_size: size as i64,
|
||||
total: total as i64,
|
||||
},
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CreateUserBody {
|
||||
/// 🔴 必填但**不**在反序列化阶段强制 ⇒ 缺失时走**业务信封**(HTTP 200 + code 400),
|
||||
/// 而不是 axum 的 422 反序列化错误(那是另一种形状)。
|
||||
#[serde(default)]
|
||||
pub account: String,
|
||||
#[serde(default)]
|
||||
pub real_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub gender: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub mobile_phone: Option<String>,
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
async fn create_user(
|
||||
State(state): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
body: Option<axum::extract::Json<CreateUserBody>>,
|
||||
) -> Response {
|
||||
if let Err(e) = require_admin(&state, p.as_ref()) {
|
||||
return e;
|
||||
}
|
||||
let Some(body) = body else {
|
||||
return ActionResult::fail("请求体缺失").into_response();
|
||||
};
|
||||
if body.account.trim().is_empty() {
|
||||
return ActionResult::fail("账号必填").into_response();
|
||||
}
|
||||
match state.accounts.create(
|
||||
&body.account,
|
||||
body.real_name.as_deref().unwrap_or(&body.account),
|
||||
body.gender.unwrap_or(1),
|
||||
body.mobile_phone.clone(),
|
||||
body.description.clone(),
|
||||
) {
|
||||
Ok(row) => ActionResult::ok(account_view(&row)).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateUserBody {
|
||||
#[serde(default)]
|
||||
pub real_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub gender: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub mobile_phone: Option<String>,
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
async fn update_user(
|
||||
State(state): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
Path(id): Path<String>,
|
||||
body: Option<axum::extract::Json<UpdateUserBody>>,
|
||||
) -> Response {
|
||||
if let Err(e) = require_admin(&state, p.as_ref()) {
|
||||
return e;
|
||||
}
|
||||
let Some(body) = body else {
|
||||
return ActionResult::fail("请求体缺失").into_response();
|
||||
};
|
||||
let current = match state.accounts.find(&id) {
|
||||
Some(r) => r,
|
||||
None => return ActionResult::fail("账号不存在").into_response(),
|
||||
};
|
||||
match state.accounts.update(
|
||||
&id,
|
||||
body.real_name.as_deref().unwrap_or(¤t.real_name),
|
||||
body.gender.unwrap_or(current.gender),
|
||||
body.mobile_phone.clone().or(current.mobile_phone.clone()),
|
||||
body.description.clone().or(current.description.clone()),
|
||||
) {
|
||||
Ok(row) => ActionResult::ok(account_view(&row)).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove_user(
|
||||
State(state): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
if let Err(e) = require_admin(&state, p.as_ref()) {
|
||||
return e;
|
||||
}
|
||||
match state.accounts.remove(&id) {
|
||||
Ok(()) => ActionResult::ok(json!({ "id": id })).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ResetPasswordBody {
|
||||
/// `md5(明文)`(32 个 hex 字符)—— 上游前端用 `md5Hex(pwd)` 传。
|
||||
#[serde(default)]
|
||||
pub user_password: String,
|
||||
#[serde(default)]
|
||||
pub validate_password: Option<String>,
|
||||
}
|
||||
|
||||
async fn reset_password(
|
||||
State(state): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
Path(id): Path<String>,
|
||||
body: Option<axum::extract::Json<ResetPasswordBody>>,
|
||||
) -> Response {
|
||||
if let Err(e) = require_admin(&state, p.as_ref()) {
|
||||
return e;
|
||||
}
|
||||
let Some(body) = body else {
|
||||
return ActionResult::fail("请求体缺失").into_response();
|
||||
};
|
||||
if body.user_password.len() != 32 || !body.user_password.chars().all(|c| c.is_ascii_hexdigit())
|
||||
{
|
||||
return ActionResult::fail("口令格式不正确").into_response();
|
||||
}
|
||||
if let Some(v) = &body.validate_password {
|
||||
if v != &body.user_password {
|
||||
return ActionResult::fail("两次输入的口令不一致").into_response();
|
||||
}
|
||||
}
|
||||
match state
|
||||
.accounts
|
||||
.reset_password(&id, &body.user_password.to_lowercase())
|
||||
{
|
||||
Ok(row) => ActionResult::ok(account_view(&row)).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StateBody {
|
||||
#[serde(default)]
|
||||
pub enabled_mark: Option<i64>,
|
||||
}
|
||||
|
||||
async fn set_state(
|
||||
State(state): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
Path(id): Path<String>,
|
||||
body: Option<axum::extract::Json<StateBody>>,
|
||||
) -> Response {
|
||||
if let Err(e) = require_admin(&state, p.as_ref()) {
|
||||
return e;
|
||||
}
|
||||
let Some(body) = body else {
|
||||
return ActionResult::fail("请求体缺失").into_response();
|
||||
};
|
||||
let Some(enabled_mark) = body.enabled_mark else {
|
||||
return ActionResult::fail("启用状态必填").into_response();
|
||||
};
|
||||
match state.accounts.set_enabled(&id, enabled_mark) {
|
||||
Ok(row) => ActionResult::ok(account_view(&row)).into_response(),
|
||||
Err(msg) => ActionResult::fail(msg).into_response(),
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 按域装配的 axum Router。
|
||||
|
||||
pub mod account;
|
||||
pub mod auth;
|
||||
pub mod body;
|
||||
pub mod crud;
|
||||
@@ -26,6 +27,7 @@ pub fn build_router(state: AppState) -> Router<AppState> {
|
||||
Router::new()
|
||||
.merge(health::router())
|
||||
.merge(auth::router())
|
||||
.merge(account::router())
|
||||
.merge(crud::router())
|
||||
.with_state(state)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
|
||||
use pglite::PGlite;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::account::AccountStore;
|
||||
use crate::config::Config;
|
||||
use crate::session::SessionStore;
|
||||
|
||||
@@ -32,6 +33,8 @@ pub struct AppState {
|
||||
pub sessions: Arc<SessionStore>,
|
||||
/// 首次启动引导出来的本地身份。
|
||||
pub bootstrap: Arc<BootstrapIdentity>,
|
||||
/// 本连接器的本地账号库(默认是**内存空库** ⇒ 早期任务与单测不必改)。
|
||||
pub accounts: Arc<AccountStore>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -55,6 +58,7 @@ impl AppState {
|
||||
db_lock: process_db_lock(),
|
||||
sessions,
|
||||
bootstrap: Arc::new(bootstrap),
|
||||
accounts: Arc::new(AccountStore::empty()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +77,14 @@ impl AppState {
|
||||
pub fn cfg(&self) -> &Config {
|
||||
&self.config
|
||||
}
|
||||
|
||||
/// 挂上本地账号库(**其余字段原样保留**,特别是 `db_lock`)。
|
||||
///
|
||||
/// 用途:启动时先造状态、跑身份引导,再把账号库换上去 ——
|
||||
/// 这样全程只有**一个** `AppState`(也就只有一把 `db_lock`)。
|
||||
pub fn with_accounts(self, accounts: Arc<AccountStore>) -> Self {
|
||||
Self { accounts, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
//! 账号层端到端: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"], "账号已被禁用");
|
||||
}
|
||||
Reference in new issue
Block a user