fix(auth): 引导失败不得回传密钥 + 键集合测试对着生产函数断言 + 锁改为进程级

- bootstrap INSERT 失败时不再回传/打印密钥(否则会打印一个永远登不上的死凭证),
  且 main.rs 因「没有身份」直接退出进程
- me_payload_key_set_is_stable 改为走生产函数 me_payload 比对精确键集合(原先是字面量自证)
- db_lock 改为进程级单例(pglite-rs 每进程只允许一个 PGlite ⇒ 一个进程只需要一把锁),
  main.rs 只造一个 AppState
- 启动时每次回显生效的身份 id/identityCode;配置码与库中已有身份码不一致时明确告警
- 随机密钥挪到「确定要建身份」之后生成(签发即落库变成结构上的不变量)

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
adminandClaude Code committed 2026-10-24 19:42:35 +08:00
1 parent c95b9d6e10
commit 17cfc505e9
5 files changed
+204 -19

No files matched your search

+60 -11
View File
@@ -83,11 +83,6 @@ pub fn space_view(id: &str, name: &str, space_code: &str) -> Value {
pub async fn bootstrap_identity(state: &AppState) -> BootstrapIdentity {
let identity_code = state.config.identity_code.clone();
let identity_name = state.config.identity_name.clone();
let secret = state
.config
.identity_secret
.clone()
.unwrap_or_else(|| hex::encode(random_bytes()));
// 🔴 「查不到 ⇒ 插入」必须**在同一把锁里**完成,否则并发启动会建出两条身份。
let _g = state.db_lock.lock().await;
@@ -117,6 +112,13 @@ pub async fn bootstrap_identity(state: &AppState) -> BootstrapIdentity {
.unwrap_or("")
.to_string();
if !id.is_empty() {
if code != identity_code {
eprintln!(
"[tdc-connector] ⚠️ 配置的 identityCode = {} 与库中已有身份的 identityCode = {} 不一致,\
本次沿用库中已有身份(用库里的码登录)",
identity_code, code
);
}
return BootstrapIdentity {
identity_id: id,
identity_code: code,
@@ -127,6 +129,14 @@ pub async fn bootstrap_identity(state: &AppState) -> BootstrapIdentity {
// ② 建一条新身份
let identity_id = next_id();
// 🔴 密钥**只在真的要建身份时**才生成 ⇒ 「签发即落库」是结构上的不变量,
// 幂等启动不再白烧一次 RNG 抽样。
// (运维显式配置的 `TDC_IDENTITY_SECRET` 仍然优先。)
let secret = state
.config
.identity_secret
.clone()
.unwrap_or_else(|| hex::encode(random_bytes()));
// 🔴 全部走**绑定参数**(不拼字符串字面量)—— 环境变量里的引号/分号不会破坏语句。
let insert = "INSERT INTO tdc_identity \
(f_id, f_identity_code, f_name, f_subject_name, f_secret_key, f_status, \
@@ -155,6 +165,13 @@ pub async fn bootstrap_identity(state: &AppState) -> BootstrapIdentity {
.await
{
eprintln!("[tdc-connector] 引导本地身份失败: {}", e);
// 🔴 插入失败 ⇒ **库里没有身份行** ⇒ 不得回传密钥(否则会打印一个永不生效的凭证),
// 也不得回传一个根本没落库的 id。
return BootstrapIdentity {
identity_id: String::new(),
identity_code,
issued_secret: None,
};
}
BootstrapIdentity {
@@ -462,10 +479,28 @@ mod tests {
}
/// 🔴 `me` 的 `data` 形状是前端逐字读的 ⇒ 键名集合不得漂移。
///
/// ⚠️ **必须走生产函数 `me_payload`** —— 拿字面量数组自证等于没断言
/// (把 `"tdsEndpoint"` 改成 `"tds_endpoint"` 时,字面量版照样全绿)。
#[test]
fn me_payload_key_set_is_stable() {
// 与 `me_payload` 里 json! 的键一一对应(这里只锁「键名集合」)。
let keys = [
let row = json!({
"f_id": "id-1",
"f_identity_code": "LOCAL-CONNECTOR",
"f_name": "本地连接器",
"f_subject_id": Value::Null,
"f_subject_name": Value::Null,
"f_capability": Value::Null,
"f_status": "ONLINE",
"f_register_status": "REGISTERED",
"f_tds_space_id": Value::Null,
"f_tds_space_name": Value::Null,
"f_endpoint": Value::Null,
"f_tds_endpoint": Value::Null,
});
let payload = me_payload(&row, true, "LOCAL-CONNECTOR");
let mut expected: Vec<String> = [
"accessAllowed",
"reason",
"account",
@@ -481,10 +516,24 @@ mod tests {
"tdsSpaceName",
"endpoint",
"tdsEndpoint",
];
assert_eq!(keys.len(), 15, "me 的字段数(13 + endpoint/tdsEndpoint)");
assert!(!keys.contains(&"secretKey"), "不得回显密钥");
assert!(!keys.contains(&"f_secret_key"), "不得回显密钥列");
]
.iter()
.map(|s| s.to_string())
.collect();
expected.sort();
let mut got: Vec<String> = payload
.as_object()
.expect("payload 必须是 JSON 对象")
.keys()
.cloned()
.collect();
got.sort();
// 🔴 精确集合断言:多一个、少一个、改一个名字,全都会红
assert_eq!(got, expected, "me 的键集合必须与前端契约逐字一致");
// 不得回显密钥
assert!(!got.iter().any(|k| k == "secretKey" || k == "f_secret_key"));
}
/// 🔴 `endpoint` / `tdsEndpoint` 在库里为 NULL 时,键**仍然存在**、值是 `null`
+17 -5
View File
@@ -633,15 +633,27 @@ async fn main() {
let sessions = Arc::new(SessionStore::new());
// ⚠️ pglite-rs **每进程只允许一个 PGlite 实例**(crate 内部 `static OPEN`),
// ⇒ 引导身份必须复用上面这个 db(不能另开 `open_temp`),
// 所以先用同一个 db 造一个临时 AppState 做引导,再造最终的 AppState。
let bootstrap_state = AppState::new(
// ⇒ 引导身份必须复用上面这个 db(不能另开 `open_temp`)。
// ⚠️ 全进程只造**一个** `AppState`(两个 `AppState` 意味着两把 db_lock ⇒ 序列化前提被破坏);
// 引导完用 `with_bootstrap` 把结果换回去。
let state = AppState::new(
config.clone(),
db.clone(),
sessions.clone(),
BootstrapIdentity::default(),
);
let bootstrap = tdc_connector::domain::identity::bootstrap_identity(&bootstrap_state).await;
let bootstrap = tdc_connector::domain::identity::bootstrap_identity(&state).await;
// 🔴 没有身份(引导 INSERT 失败)⇒ 直接退出:一个连登录都做不了的连接器,
// 「启动失败一眼看得出」远好于「服务起着但一登录就报错」。
if bootstrap.identity_id.is_empty() {
eprintln!("[tdc-connector] 引导本地连接器身份失败:无法创建身份行,进程退出");
std::process::exit(1);
}
// 每次启动都回显当前生效的身份(不只首次)⇒ 运维随时能确认「现在用的是哪个身份」。
println!(
"[tdc-connector] 本地连接器身份: id = {}, identityCode = {}",
bootstrap.identity_id, bootstrap.identity_code
);
if let Some(secret) = bootstrap.issued_secret.as_ref() {
println!("[tdc-connector] 首次启动:已创建本地连接器身份");
println!("[tdc-connector] identityCode = {}", bootstrap.identity_code);
@@ -649,7 +661,7 @@ async fn main() {
println!("[tdc-connector] ⚠️ 密钥只打印这一次,请立刻保存");
}
let state = AppState::new(config.clone(), db.clone(), sessions.clone(), bootstrap);
let state = state.with_bootstrap(bootstrap);
let auth_state = AuthState {
internal_token: config.internal_token.clone(),
+43 -3
View File
@@ -1,6 +1,6 @@
//! 全局应用状态:PGlite 句柄 + DB 锁 + 会话存储 + 配置。
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use pglite::PGlite;
use tokio::sync::Mutex;
@@ -8,11 +8,26 @@ use tokio::sync::Mutex;
use crate::config::Config;
use crate::session::SessionStore;
/// 进程级唯一的 DB 锁。
///
/// 🔴 pglite-rs **每进程只允许一个 PGlite 实例** ⇒ 一个进程里只可能有**一个**数据库
/// ⇒ 所有 `AppState` 必须共享**同一把**锁。
/// (早期实现是「每个 `AppState` 各造一把」⇒ 同一库上出现两把锁 ⇒ 序列化前提被破坏。)
static DB_LOCK: OnceLock<Arc<Mutex<()>>> = OnceLock::new();
/// 取进程级那把 DB 锁。
pub fn process_db_lock() -> Arc<Mutex<()>> {
DB_LOCK.get_or_init(|| Arc::new(Mutex::new(()))).clone()
}
#[derive(Clone)]
pub struct AppState {
pub config: Arc<Config>,
pub db: Arc<PGlite>,
/// PGlite 是单 in-process backend,所有 DB 访问必须持这把锁。
///
/// 🔴 这是**进程级唯一**的那把(见 [`process_db_lock`])⇒ 同一进程里的所有
/// `AppState`(哪怕指向同一个 `PGlite`)都共享它。
pub db_lock: Arc<Mutex<()>>,
pub sessions: Arc<SessionStore>,
/// 首次启动引导出来的本地身份。
@@ -37,12 +52,23 @@ impl AppState {
Self {
config: Arc::new(config),
db,
db_lock: Arc::new(Mutex::new(())),
db_lock: process_db_lock(),
sessions,
bootstrap: Arc::new(bootstrap),
}
}
/// 换掉引导身份(**其余字段原样保留**,特别是 `db_lock`)。
///
/// 用途:启动时先用 `BootstrapIdentity::default()` 造状态、跑引导,再把结果换回来 ——
/// 这样全程只有**一个** `AppState`(也就只有一把 `db_lock`)。
pub fn with_bootstrap(self, bootstrap: BootstrapIdentity) -> Self {
Self {
bootstrap: Arc::new(bootstrap),
..self
}
}
/// 运行期配置(便捷访问:`state.cfg()`)。
pub fn cfg(&self) -> &Config {
&self.config
@@ -70,6 +96,20 @@ mod tests {
let config = Config::from_env(std::env::current_dir().unwrap_or_default());
let sessions = Arc::new(SessionStore::new());
assert!(Arc::strong_count(&sessions) >= 1);
assert_eq!(config.port, crate::config::DEFAULT_PORT);
// ⚠️ 不断言 `config.port == DEFAULT_PORT` —— `Config::from_env` 会读环境变量 `PORT`
// (CI / 开发机常常设了)⇒ 那条断言是环境相关的、必然偶发红。
assert!(config.port > 0, "端口必须是有效端口,不能是 0");
}
/// 🔴 进程级单锁:所有 `AppState` 必须共享**同一把** `db_lock`
/// (pglite-rs 每进程只允许一个 PGlite ⇒ 一个进程只需要一把锁)。
#[test]
fn process_db_lock_is_shared_by_every_app_state() {
let a = process_db_lock();
let b = process_db_lock();
assert!(
Arc::ptr_eq(&a, &b),
"同一进程内的 db_lock 必须是同一把(否则同一库上出现两把锁 ⇒ 序列化前提被破坏)"
);
}
}
+41
View File
@@ -48,6 +48,47 @@ async fn test_state_with(sessions: Arc<SessionStore>) -> AppState {
AppState::new(config, db, sessions, BootstrapIdentity::default())
}
/// 🔴 同一个 PGlite 上的所有 `AppState` 必须共享**同一把** `db_lock`。
///
/// pglite-rs 每进程只允许一个 PGlite ⇒ 一个进程只需要一把锁 ⇒ 锁的粒度是**进程**。
/// (早期实现是「每个 `AppState` 各造一把」⇒ 同一库上两把锁 ⇒ 序列化前提被破坏。)
#[tokio::test]
async fn two_app_states_on_the_same_db_share_one_db_lock() {
let _guard = SERIAL.lock().await;
let db = shared_db().await;
let sessions = Arc::new(SessionStore::new());
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
let s1 = AppState::new(
config.clone(),
db.clone(),
sessions.clone(),
BootstrapIdentity::default(),
);
let s2 = AppState::new(
config.clone(),
db.clone(),
sessions.clone(),
BootstrapIdentity::default(),
);
assert!(
Arc::ptr_eq(&s1.db_lock, &s2.db_lock),
"同一个 PGlite 上的所有 AppState 必须共享同一把 db_lock"
);
// `with_bootstrap` 换引导身份时**不得**换掉锁
let s3 = s1.with_bootstrap(BootstrapIdentity {
identity_id: "id-x".to_string(),
identity_code: "TEST-CONNECTOR".to_string(),
issued_secret: None,
});
assert!(
Arc::ptr_eq(&s3.db_lock, &s2.db_lock),
"with_bootstrap 只换 bootstrap 字段,db_lock 必须原样保留"
);
assert_eq!(s3.bootstrap.identity_id, "id-x");
}
/// 清空身份表(让「首次引导」用例可确定地拿到「新建」语义)。
async fn clear_identities(state: &AppState) {
let _g = state.db_lock.lock().await;
+43
View File
@@ -0,0 +1,43 @@
//! 引导失败的端到端用例:INSERT 失败 ⇒ **不得**回传密钥。
//!
//! ⚠️ 本文件是**独立测试二进制** ⇒ 独立进程 ⇒ 独立 PGlite
//! (pglite-rs 每进程只允许一个实例)。
use std::sync::Arc;
use pglite::PGlite;
use tdc_connector::config::Config;
use tdc_connector::domain::identity::bootstrap_identity;
use tdc_connector::session::SessionStore;
use tdc_connector::state::{AppState, BootstrapIdentity};
#[tokio::test]
async fn bootstrap_insert_failure_yields_no_secret() {
let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败"));
tdc_connector::db::ensure_schema(db.as_ref()).await.expect("建表失败");
// 让 INSERT 必然失败:把目标表删掉
// (`PGlite::exec(&self, sql: &str)` 是无参版本;带参的是 `query(sql, &[&(dyn ToSql + Sync)])`)
db.exec("DROP TABLE tdc_identity").await.expect("删表失败");
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
let state = AppState::new(
config,
db,
Arc::new(SessionStore::new()),
BootstrapIdentity::default(),
);
let bootstrap = bootstrap_identity(&state).await;
// 🔴 失败 ⇒ 不得有密钥、不得有 id
assert!(
bootstrap.issued_secret.is_none(),
"引导失败时不得回传密钥,实际 {:?}",
bootstrap.issued_secret
);
assert!(
bootstrap.identity_id.is_empty(),
"引导失败时不得回传没落库的 id,实际 {:?}",
bootstrap.identity_id
);
}