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
+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)]
|
||||
|
||||
Reference in new issue
Block a user