refactor(b1b-c8): 配置分家 —— 平台 Config 零业务字段

**影响**
- `platform::config::Config` 不再持有 `identity_code` / `identity_name` /
  `identity_secret` / `bootstrap_admin_account` / `bootstrap_admin_password`;
  平台层**不认识**「本连接器是谁」。
- 新增业务层 `tdc::config::TdcConfig`(同五项)与 `tdc::constant`(默认值 + 业务 env 名清单)。
- 对外契约**零变化**(env 名、默认值、取值口径逐字不变)。

**改动**
- 新增 `src/tdc/config.rs`:`TdcConfig::from_env` / `from_raw`(纯函数,可单测)/
  `Default`;`src/tdc/constant.rs`:默认值 + 5 个业务 env 名(+ 撞名自检)。
- `src/platform/config.rs`:删 3 个业务常量与 5 个字段;`env_or_default` 转 `pub`
  (平台提供**机制**,业务提供**清单**)。
- `identity::bootstrap_identity(state, &tdc_config)`:业务配置改为**显式入参**
  (平台层不再持有它 ⇒ 装配层递进去)。
- `main.rs` 造 `TdcConfig::from_env()` 并递给引导与账号库;
  8 个测试文件同步改用 `TdcConfig`。
- `CLAUDE.md` + `.workbuddy/memory/2026-10-26.md` 同步。

**设计**
- `TdcConfig::from_raw(..)` 做成纯函数(不读进程全局 env)⇒ 与平台层同口径,
  测试不引入串行/并行竞态。

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
adminandClaude committed 2026-10-26 20:57:38 +08:00
1 parent f8764b248c
commit 1797aa0d64
16 files changed
+354 -102

No files matched your search

+34 -3
View File
@@ -108,10 +108,41 @@ cargo test → exit 0(全绿)
---
## B1b · 包结构重组 + C1–C12 收敛(进行中,**每条 C 项一个 commit**)
搬家与收敛同步进行;**行为零变化** ⇒ 每步都跑四把尺子(`cargo test` / `smoke.sh` / `check-boundary.sh` / `check-entity.sh`)。
| C 项 | 一句话 | commit |
|---|---|---|
| C1 | 子表清单归业务 spec(`TableSpec::child_tables`)⇒ 引擎零 `match api_name` | `a3f6de5` |
| C2 | 「查无此条」文案归业务 spec(`TableSpec::not_found_msg`) | `c4840a3` |
| C3 | 聚合详情路由由 spec 声明(`TableSpec::aggregate_detail`)⇒ 控制器零硬编码实体名 | `8b47216` |
| C4 | schema 探针通用化(数 `pg_tables` 总数,不再点名业务表) | `42cb97c` |
| C5 | 免鉴权端点清单归业务层(`tdc::support::public_paths`)⇒ 平台层零端点字面量 | `df7ce37` |
| C6 | 「假权限层」拆除清单**先记账**(零代码改动) | `8618465` |
| C7 | `/api/health` 补 `baseTables`(W5 契约的账号层表数) | `f8764b2` |
| C8 | 配置分家:平台 `Config` 削掉 5 个业务字段,业务配置进 `tdc::config::TdcConfig` | 本次提交 |
**关键决定**
- **C5 剪了 9 条死路径不是 7 条**:上游 `gateway.white-url` 里 P2P 是 **5** 条(不是 4)⇒ 实际死路径 9 条
⇒ 记 **D17**(`src/tdc/support/public_paths.rs` 的表 + `docs/decisions.md`)。
- **账本是 ratchet**:越界条目在**修掉它的那个 commit 里删行**(失效条目会让尺子红)⇒ 只剩 2 条永久假阳性豁免。
- **C8 的业务配置走显式入参**:`bootstrap_identity(state, &tdc_config)`;`TdcConfig::from_raw(..)` 是纯函数(不读全局 env)⇒ 可单测。
C9 会把 `TdcConfig` 收进业务层 `TdcState` ⇒ 那时再改成单参。
**C8 之后的实测**:`cargo test` **235 passed / 0 failed / 1 ignored**(新增 6 条:TdcConfig 4 + 业务常量 2)·
`smoke.sh` **PASS=75 FAIL=0**(断言数不变)· `check-boundary.sh` **exit 0**(未记账越界 0 · 失效条目 0)· `check-entity.sh` **PASS=15 FAIL=0**。
---
## 当前状态
- 分支 `feat/mvc-align-v3`;**回退点 = `06f5a79`**(v3 spec 落点)。
- 下一批 = **B1b**(包结构重组 + C1–C12 收敛,**每条 C 项单独提交**)。
- B1b 验收:`cargo test` 223 条全绿 + `smoke.sh` 断言数 **== 75** + `check-boundary.sh` 全绿
(**7 条 B1b 账本条目清空**)+ `check-entity.sh` 全绿 + 浏览器验收重跑。
- B1b 已完成 **C1–C8**;下一条 = **C9**(`AppState` 拆两半:平台 `AppState` + 业务 `TdcState`)。
C9 之后还剩 **C10**(`tdc_identity` 领域 SQL 收口到 `tdc/service/identity.rs` + 只 SELECT 明确列)/
**C11**(`constant_time_eq` 上收到平台)/ **C12**(`civil_from_days`/`now_iso` 换 `chrono`,口径 **UTC**)。
- B1b 验收:`cargo test` 全绿 + `smoke.sh` 断言数 **== 75** + `check-boundary.sh` 全绿
(**7 条 B1b 账本条目已清空**)+ `check-entity.sh` 全绿 + 浏览器验收重跑(**未重跑** ⇒ B5 前补)。
- ⚠️ **B2 前必须先停掉占着 `data/tdc.pg` 的旧开发服**(pglite 每数据目录只允许一个进程)。
+11 -1
View File
@@ -35,7 +35,7 @@ tdc-rs/
│ ├── lib.rs # 模块声明(只暴露 `platform` 与 `tdc` 两层,bin 只做装配)
│ ├── platform/ # 【平台层】与业务**零**知识(边界由 check-boundary.sh 静态钉住)
│ │ ├── state.rs # AppState(config + db + db_lock + sessions + accounts + bootstrap + tds)
│ │ ├── config.rs # 环境变量配置 + 密钥守卫
│ │ ├── config.rs # **平台**环境变量配置(端口/数据目录/令牌/出向地址)+ 密钥守卫(**零业务字段**)
│ │ ├── db.rs # PGlite 封装(query_json / ensure_schema / f_↔camelCase 映射)
│ │ ├── session.rs # 会话存储(两种 kind:Identity / Account)
│ │ ├── envelope.rs # 业务信封 ActionResult(HTTP 200 + {code,msg,data})
@@ -53,6 +53,8 @@ tdc-rs/
│ ├── controller/ # HTTP 端点:crud / health / auth / account / tds_biz
│ ├── client/tds.rs # TDS 出向客户端(照抄上游 TdsReportClient 的 internal 通道,9 个方法)
│ ├── util/code.rs # 业务编码生成器(原 src/codec.rs:PRO/RES/API/DS 前缀 + 两套上游生成器)
│ ├── config.rs # **业务**配置 TdcConfig(身份码/身份名/身份密钥/引导管理员账号口令)
│ ├── constant.rs # **业务**常量(身份码/身份名默认值 + 业务 env 名清单)
│ ├── support/ # 业务侧公共清单(public_paths:免鉴权端点)
│ └── policy/ engine/ schedule/ notify/ heartbeat/ sso/ # 上游同名包占位(后续批)
├── static/ # 上游 SPA 构建产物(index.html + logo.png + assets/,8 个产物文件)
@@ -78,6 +80,11 @@ tdc-rs/
这条**可被静态检查** ⇒ `scripts/check-boundary.sh` 的 4 个接触点(CP1–CP4)。
🔴 **通用 CRUD 引擎住在业务层**(`tdc/mapper.rs` + `tdc/service/crud.rs` + `tdc/controller/crud.rs`,
对位上游 `TdcCrudController`)但**逻辑必须实体无关(零 `match api_name`)** ⇒ 分支只能读 `TableSpec` 字段。
- 🔴 **平台配置与业务配置分家**(v3 spec §2.3.1 C8):平台 `platform::config::Config` 只留
**端口 / 数据目录 / 入向令牌 / 出向令牌与地址 / 单机模式 / 密钥守卫**;
**身份码 / 身份名 / 身份密钥 / 引导管理员账号与口令** 归业务层 `tdc::config::TdcConfig`
(默认值与 env 名清单在 `tdc::constant`)⇒ 平台层**不认识**「本连接器是谁」。
平台层只提供**机制**(`platform::config::env_or_default`:空白 ⇒ 回落默认值),业务层提供**清单**。
- 🔴 **前端不直接持有数据库。** 所有数据访问经 `/api/ssw/tdc/*` REST;不得把 PGlite 重新塞回浏览器。
- 🔴 **不自研前端。** 控制台 = **上游完整前端的构建产物**(`static/`)。改 UI 改上游,**不在本仓写前端**。
- 🔴 **业务错误必须读 body 的 `code`。** 上游 TDS 用 HTTP 200 承载业务错误码(如 `code:600` 登录过期),
@@ -247,6 +254,9 @@ bash scripts/check-entity.sh # ③ 实体静态(加实体的接触点完
🔴 `hidden_fields` 的键名是 **camelCase JSON 键**(不是列名);
`update` 的 frozen 列自检必须**跳过 hidden 列**(上游 `devUrl`/`devToken` 既是
`@JsonIgnore` 又是 frozen ⇒ Jackson 绑不上 ⇒ 上游既不拒也不写 ⇒ 本仓不能 400)。
16. **引导身份要显式递业务配置**(C8):`identity::bootstrap_identity(state, &tdc_config)`
——身份码/身份名/身份密钥**不在** `state.config` 里 ⇒ 由装配层(`main.rs`)造
`TdcConfig::from_env()` 递进去。`TdcConfig::from_raw(..)` 是**纯函数**(不读全局 env)⇒ 可单测。
## 数据模型
+7 -3
View File
@@ -26,6 +26,7 @@ use tower_http::cors::CorsLayer;
use tdc_connector::platform::auth::{auth_middleware, AuthState};
use tdc_connector::platform::config::Config;
use tdc_connector::platform::db::ensure_schema;
use tdc_connector::tdc::config::TdcConfig;
use tdc_connector::tdc::controller::build_router;
use tdc_connector::tdc::support::public_paths;
use tdc_connector::platform::fallback::{api_not_found, spa_fallback};
@@ -68,6 +69,8 @@ async fn main() {
let project_dir = resolve_project_dir();
let config = Config::from_env(project_dir.clone());
// 🔴 业务配置(身份与引导)**不在平台 Config 里**(v3 spec §2.3.1 C8)⇒ 单独装配。
let tdc_config = TdcConfig::from_env();
if let Err(msg) = config.check_secret_guard() {
eprintln!("[tdc-connector] {}", msg);
std::process::exit(1);
@@ -114,7 +117,8 @@ async fn main() {
sessions.clone(),
BootstrapIdentity::default(),
);
let bootstrap = tdc_connector::tdc::service::identity::bootstrap_identity(&state).await;
let bootstrap =
tdc_connector::tdc::service::identity::bootstrap_identity(&state, &tdc_config).await;
// 🔴 没有身份(引导 INSERT 失败)⇒ 直接退出:一个连登录都做不了的连接器,
// 「启动失败一眼看得出」远好于「服务起着但一登录就报错」。
if bootstrap.identity_id.is_empty() {
@@ -145,8 +149,8 @@ async fn main() {
let accounts = Arc::new(
tdc_connector::tdc::service::account::AccountStore::open_with_admin(
&data_dir.join("accounts.json"),
&config.bootstrap_admin_account,
config
&tdc_config.bootstrap_admin_account,
tdc_config
.bootstrap_admin_password
.as_deref()
.unwrap_or(tdc_connector::tdc::service::account::BOOTSTRAP_ADMIN_PASSWORD),
+9 -63
View File
@@ -13,10 +13,11 @@ pub const DEFAULT_INTERNAL_TOKEN: &str = "ssw-internal-token-e2e";
/// 方向相反,混用会把两套密钥耦在一起 ⇒ 出向单独用 `SSW_TDS_INTERNAL_TOKEN`。
pub const DEFAULT_TDS_INTERNAL_TOKEN: &str = "ssw-internal-token-e2e";
pub const DEFAULT_PORT: u16 = 30000;
pub const DEFAULT_IDENTITY_CODE: &str = "LOCAL-CONNECTOR";
pub const DEFAULT_IDENTITY_NAME: &str = "本地连接器";
/// 首次启动引导的本地管理员**账号名**默认值。
pub const DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT: &str = "admin";
// 🔴 **业务配置不在本模块**(v3 spec §2.3.1 C8):身份码 / 身份名 / 身份密钥 /
// 引导管理员账号口令这五项是**业务口径** ⇒ 归 `crate::tdc::config::TdcConfig`
// (常量在 `crate::tdc::constant`)。平台配置只认「端口 / 数据目录 / 令牌 /
// 出向地址 / 单机模式 / 密钥守卫」这类**与业务无关**的运行参数。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StandaloneMode {
@@ -39,7 +40,10 @@ impl StandaloneMode {
/// 取环境变量值;未设置或**空白**时回落默认值。
///
/// 纯函数,不读进程全局 env —— 便于单测(测试里改全局 env 会引入串行/并行竞态)。
fn env_or_default(raw: Option<String>, default: &str) -> String {
///
/// 🔴 **公开**(v3 spec §2.3.1 C8):业务层的 `tdc::config::TdcConfig` 复用同一口径
/// (空白 ⇒ 回落默认值)⇒ 平台层提供**机制**,业务层提供**清单**。
pub fn env_or_default(raw: Option<String>, default: &str) -> String {
match raw {
Some(v) if !v.trim().is_empty() => v,
_ => default.to_string(),
@@ -119,16 +123,6 @@ pub struct Config {
pub tds_base_url: Option<String>,
pub standalone: StandaloneMode,
pub strict_secrets: bool,
pub identity_code: String,
pub identity_name: String,
pub identity_secret: Option<String>,
/// 首次启动引导的**本地管理员账号名**(`TDC_BOOTSTRAP_ADMIN_ACCOUNT`)。
pub bootstrap_admin_account: String,
/// 首次启动引导的**本地管理员口令**(`TDC_BOOTSTRAP_ADMIN_PASSWORD`)。
///
/// 🔴 `None` = 未设置 ⇒ 落回公开默认值 `admin`(本地调试用)
/// ⇒ 生产档必须设(`TDC_STRICT_SECRETS=1` 会因此拒绝启动)。
pub bootstrap_admin_password: Option<String>,
}
impl Config {
@@ -168,44 +162,6 @@ impl Config {
.as_str(),
"1" | "true" | "yes"
);
let identity_code = env_or_default(
std::env::var("TDC_IDENTITY_CODE").ok(),
DEFAULT_IDENTITY_CODE,
)
.trim()
.to_string();
let identity_name = env_or_default(
std::env::var("TDC_IDENTITY_NAME").ok(),
DEFAULT_IDENTITY_NAME,
)
.trim()
.to_string();
let identity_secret = {
let raw = env_or_default(std::env::var("TDC_IDENTITY_SECRET").ok(), "");
let v = raw.trim().to_string();
if v.is_empty() {
None
} else {
Some(v)
}
};
// 🔴 本地管理员的引导账号/口令:口令**不设** ⇒ 落回公开默认值 `admin`
// (本地调试用);生产档(`TDC_STRICT_SECRETS=1`)必须显式设置。
let bootstrap_admin_account = env_or_default(
std::env::var("TDC_BOOTSTRAP_ADMIN_ACCOUNT").ok(),
DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT,
)
.trim()
.to_string();
let bootstrap_admin_password = {
let raw = env_or_default(std::env::var("TDC_BOOTSTRAP_ADMIN_PASSWORD").ok(), "");
let v = raw.trim().to_string();
if v.is_empty() {
None
} else {
Some(v)
}
};
Self {
port,
project_dir,
@@ -215,11 +171,6 @@ impl Config {
tds_base_url,
standalone,
strict_secrets,
identity_code,
identity_name,
identity_secret,
bootstrap_admin_account,
bootstrap_admin_password,
}
}
@@ -269,11 +220,6 @@ mod tests {
tds_base_url: None,
standalone: StandaloneMode::Auto,
strict_secrets: false,
identity_code: DEFAULT_IDENTITY_CODE.to_string(),
identity_name: DEFAULT_IDENTITY_NAME.to_string(),
identity_secret: None,
bootstrap_admin_account: DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT.to_string(),
bootstrap_admin_password: None,
}
}
+180
View File
@@ -0,0 +1,180 @@
//! 业务配置(**业务层** —— v3 spec §2.3.1 C8)。
//!
//! ## 为什么要拆
//!
//! C8 之前,`platform::config::Config` 一个 struct 混着两类字段:
//!
//! | 类别 | 字段 | 归属 |
//! |---|---|---|
//! | **平台运行参数** | `port` / `project_dir` / `data_dir` / `internal_token` / `tds_internal_token` / `tds_base_url` / `standalone` / `strict_secrets` | `platform::config::Config` |
//! | **业务口径** | `identity_code` / `identity_name` / `identity_secret` / `bootstrap_admin_account` / `bootstrap_admin_password` | **本模块** `TdcConfig` |
//!
//! 🔴 平台层**不许**知道「本连接器的身份码是什么」「引导哪个管理员」——那是业务知识。
//! 平台层只提供**机制**(`platform::config::env_or_default`:空白 ⇒ 回落默认值),
//! 业务层提供**清单**(env 名与默认值在 `tdc::constant`)。
//!
//! ## 取值口径(与拆分前**逐字一致** ⇒ 行为零变化)
//!
//! - 身份码 / 身份名 / 引导账号名:未设或纯空白 ⇒ 回落默认值,再 `trim`。
//! - 身份密钥 / 引导口令:未设或纯空白 ⇒ `None`(口令另由 `AccountStore` 落回公开默认值 `admin`,
//! 生产档由 `TDC_STRICT_SECRETS=1` 拒绝启动)。
use crate::platform::config::env_or_default;
use crate::tdc::constant::{
DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT, DEFAULT_IDENTITY_CODE, DEFAULT_IDENTITY_NAME,
ENV_BOOTSTRAP_ADMIN_ACCOUNT, ENV_BOOTSTRAP_ADMIN_PASSWORD, ENV_IDENTITY_CODE,
ENV_IDENTITY_NAME, ENV_IDENTITY_SECRET,
};
/// 业务配置(身份与引导)。
#[derive(Debug, Clone)]
pub struct TdcConfig {
/// 本连接器的身份码(`TDC_IDENTITY_CODE`)。
pub identity_code: String,
/// 本连接器的身份名(`TDC_IDENTITY_NAME`)。
pub identity_name: String,
/// 本连接器的身份密钥(`TDC_IDENTITY_SECRET`)。
///
/// 🔴 `None` = 未设 ⇒ 引导时**随机签发一次**并只打印一次。
pub identity_secret: Option<String>,
/// 首次启动引导的**本地管理员账号名**(`TDC_BOOTSTRAP_ADMIN_ACCOUNT`)。
pub bootstrap_admin_account: String,
/// 首次启动引导的**本地管理员口令**(`TDC_BOOTSTRAP_ADMIN_PASSWORD`)。
///
/// 🔴 `None` = 未设 ⇒ 落回公开默认值 `admin`(本地调试用)
/// ⇒ 生产档必须设(`TDC_STRICT_SECRETS=1` 会因此拒绝启动)。
pub bootstrap_admin_password: Option<String>,
}
impl Default for TdcConfig {
/// 🔴 默认值与 [`TdcConfig::from_env`] 在**未设任何环境变量**时**完全一致**。
fn default() -> Self {
Self {
identity_code: DEFAULT_IDENTITY_CODE.to_string(),
identity_name: DEFAULT_IDENTITY_NAME.to_string(),
identity_secret: None,
bootstrap_admin_account: DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT.to_string(),
bootstrap_admin_password: None,
}
}
}
impl TdcConfig {
/// 从环境变量装配(装配层 `main.rs` 调用一次)。
pub fn from_env() -> Self {
Self::from_raw(
std::env::var(ENV_IDENTITY_CODE).ok(),
std::env::var(ENV_IDENTITY_NAME).ok(),
std::env::var(ENV_IDENTITY_SECRET).ok(),
std::env::var(ENV_BOOTSTRAP_ADMIN_ACCOUNT).ok(),
std::env::var(ENV_BOOTSTRAP_ADMIN_PASSWORD).ok(),
)
}
/// 🔴 **纯函数**(不读进程全局 env)⇒ 可单测、无并行竞态。
///
/// 口径与拆分前 `platform::config::Config::from_env` 的对应分支**逐字一致**。
pub fn from_raw(
identity_code: Option<String>,
identity_name: Option<String>,
identity_secret: Option<String>,
bootstrap_admin_account: Option<String>,
bootstrap_admin_password: Option<String>,
) -> Self {
let identity_code =
env_or_default(identity_code, DEFAULT_IDENTITY_CODE).trim().to_string();
let identity_name =
env_or_default(identity_name, DEFAULT_IDENTITY_NAME).trim().to_string();
let identity_secret = {
let v = env_or_default(identity_secret, "").trim().to_string();
if v.is_empty() {
None
} else {
Some(v)
}
};
let bootstrap_admin_account = env_or_default(
bootstrap_admin_account,
DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT,
)
.trim()
.to_string();
let bootstrap_admin_password = {
let v = env_or_default(bootstrap_admin_password, "").trim().to_string();
if v.is_empty() {
None
} else {
Some(v)
}
};
Self {
identity_code,
identity_name,
identity_secret,
bootstrap_admin_account,
bootstrap_admin_password,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 🔴 **未设任何环境变量** ⇒ 五项全部落回默认值(与拆分前一致)。
#[test]
fn unset_env_falls_back_to_the_business_defaults() {
let c = TdcConfig::from_raw(None, None, None, None, None);
assert_eq!(c.identity_code, DEFAULT_IDENTITY_CODE);
assert_eq!(c.identity_name, DEFAULT_IDENTITY_NAME);
assert_eq!(c.identity_secret, None);
assert_eq!(c.bootstrap_admin_account, DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT);
assert_eq!(c.bootstrap_admin_password, None);
}
/// 🔴 空白(`" "`)与空串都**回落默认值**(平台层的 `env_or_default` 口径)。
#[test]
fn blank_env_values_fall_back() {
let c = TdcConfig::from_raw(
Some(" ".into()),
Some(String::new()),
Some(" ".into()),
Some("\t\n".into()),
Some(" ".into()),
);
assert_eq!(c.identity_code, DEFAULT_IDENTITY_CODE);
assert_eq!(c.identity_name, DEFAULT_IDENTITY_NAME);
assert_eq!(c.identity_secret, None, "纯空白密钥 ⇒ None");
assert_eq!(c.bootstrap_admin_account, DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT);
assert_eq!(c.bootstrap_admin_password, None, "纯空白口令 ⇒ None");
}
/// 🔴 正常值原样取用(只去首尾空白),密钥与口令保留。
#[test]
fn explicit_values_are_kept() {
let c = TdcConfig::from_raw(
Some(" C-1 ".into()),
Some(" 连接器一 ".into()),
Some(" s3cret ".into()),
Some(" root ".into()),
Some(" pwd ".into()),
);
assert_eq!(c.identity_code, "C-1");
assert_eq!(c.identity_name, "连接器一");
assert_eq!(c.identity_secret.as_deref(), Some("s3cret"));
assert_eq!(c.bootstrap_admin_account, "root");
assert_eq!(c.bootstrap_admin_password.as_deref(), Some("pwd"));
}
/// 🔴 `Default` 与「未设任何环境变量」**完全一致**(测试里 `TdcConfig::default()` 即可用)。
#[test]
fn default_matches_unset_env() {
let d = TdcConfig::default();
let u = TdcConfig::from_raw(None, None, None, None, None);
assert_eq!(d.identity_code, u.identity_code);
assert_eq!(d.identity_name, u.identity_name);
assert_eq!(d.identity_secret, u.identity_secret);
assert_eq!(d.bootstrap_admin_account, u.bootstrap_admin_account);
assert_eq!(d.bootstrap_admin_password, u.bootstrap_admin_password);
}
}
+65
View File
@@ -0,0 +1,65 @@
//! 业务常量(**业务层** —— 对位上游 `ssw.tdc.constant`)。
//!
//! 🔴 **为什么在业务层**(v3 spec §2.3.1 C8):身份码 / 身份名 / 引导管理员这些
//! 是**业务口径**,不是平台运行参数 ⇒ 平台层 `platform::config` 只保留
//! 「端口 / 数据目录 / 令牌 / 出向地址 / 单机模式 / 密钥守卫」。
//!
//! 平台层仍提供**机制**(`platform::config::env_or_default`:空白 ⇒ 回落默认值),
//! **清单**(环境变量名 + 默认值)归本模块 ⇒ 一处定义,平台与业务都不重复。
/// 本连接器的默认身份码(`TDC_IDENTITY_CODE`)。
pub const DEFAULT_IDENTITY_CODE: &str = "LOCAL-CONNECTOR";
/// 本连接器的默认身份名(`TDC_IDENTITY_NAME`)。
pub const DEFAULT_IDENTITY_NAME: &str = "本地连接器";
/// 首次启动引导的本地管理员**账号名**默认值(`TDC_BOOTSTRAP_ADMIN_ACCOUNT`)。
pub const DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT: &str = "admin";
// ── 环境变量名(业务口径 ⇒ 归业务层;平台层的 env 名是「平台自己的」)──
/// 身份码的环境变量名。
pub const ENV_IDENTITY_CODE: &str = "TDC_IDENTITY_CODE";
/// 身份名的环境变量名。
pub const ENV_IDENTITY_NAME: &str = "TDC_IDENTITY_NAME";
/// 身份密钥的环境变量名(**不设** ⇒ 引导时随机签发一次)。
pub const ENV_IDENTITY_SECRET: &str = "TDC_IDENTITY_SECRET";
/// 引导管理员账号名的环境变量名。
pub const ENV_BOOTSTRAP_ADMIN_ACCOUNT: &str = "TDC_BOOTSTRAP_ADMIN_ACCOUNT";
/// 引导管理员口令的环境变量名(**不设** ⇒ 落回公开默认值 `admin`,仅限本地调试)。
pub const ENV_BOOTSTRAP_ADMIN_PASSWORD: &str = "TDC_BOOTSTRAP_ADMIN_PASSWORD";
#[cfg(test)]
mod tests {
use super::*;
/// 🔴 业务常量的**字面值**必须钉死(部署脚本 / 文档都按这两个值写)。
#[test]
fn business_defaults_are_pinned() {
assert_eq!(DEFAULT_IDENTITY_CODE, "LOCAL-CONNECTOR");
assert_eq!(DEFAULT_IDENTITY_NAME, "本地连接器");
assert_eq!(DEFAULT_BOOTSTRAP_ADMIN_ACCOUNT, "admin");
}
/// 🔴 环境变量名**不许**与平台层的 env 名撞车(撞车 ⇒ 平台/业务配置串味)。
#[test]
fn business_env_names_do_not_collide_with_platform_ones() {
let platform = [
"PORT",
"TDC_DATA_DIR",
"SSW_INTERNAL_TOKEN",
"SSW_TDS_INTERNAL_TOKEN",
"SSW_TDS_BASE_URL",
"TDC_LOCAL_STANDALONE",
"TDC_STANDALONE",
"TDC_STRICT_SECRETS",
];
for name in [
ENV_IDENTITY_CODE,
ENV_IDENTITY_NAME,
ENV_IDENTITY_SECRET,
ENV_BOOTSTRAP_ADMIN_ACCOUNT,
ENV_BOOTSTRAP_ADMIN_PASSWORD,
] {
assert!(!platform.contains(&name), "业务 env 名与平台 env 名撞车: {}", name);
}
}
}
+3
View File
@@ -9,12 +9,15 @@
//! | `support/` | `ssw.tdc.support` | 公共放行清单 / 管理员闸门 / 内部令牌等 |
//! | `util/` | `ssw.tdc.util` | **业务**工具(业务编码生成器 `code.rs`) |
//! | `client/` | `ssw.tdc.client` | TDS 出向客户端 |
//! | `config.rs` `constant.rs` | `ssw.tdc.config` / `ssw.tdc.constant` | **业务**配置与常量(v3 spec §2.3.1 C8) |
//! | `policy/` `engine/` `schedule/` `notify/` `heartbeat/` `sso/` | 同名包 | **占位**,后续批 |
//!
//! 🔴 **边界规约(v3 spec §2.3)**:`src/platform/` 里不许出现业务知识;
//! 本层**不许出现平台能力的第二份实现**。
pub mod client;
pub mod config;
pub mod constant;
pub mod controller;
pub mod engine;
pub mod entity;
+1 -2
View File
@@ -820,8 +820,7 @@ mod tests {
crate::platform::db::ensure_schema(db.as_ref())
.await
.expect("建表失败");
let mut config = Config::from_env(std::env::current_dir().unwrap_or_default());
config.identity_code = "TEST-CONNECTOR".to_string();
let config = Config::from_env(std::env::current_dir().unwrap_or_default());
let state = AppState::new(
config,
db.clone(),
+8 -5
View File
@@ -19,6 +19,7 @@ use crate::platform::db::query_json_params;
use crate::platform::envelope::{ActionResult, CODE_SERVER_ERROR};
use crate::platform::ids::next_id;
use crate::platform::state::{AppState, BootstrapIdentity};
use crate::tdc::config::TdcConfig;
/// 冻结态(登录拒)。
pub const STATUS_FROZEN: &str = "FROZEN";
@@ -78,11 +79,14 @@ pub fn space_view(id: &str, name: &str, space_code: &str) -> Value {
///
/// 幂等:已有存活身份时不新建、不打印。
///
/// 🔴 **业务配置走显式入参**(v3 spec §2.3.1 C8):身份码 / 身份名 / 身份密钥是
/// **业务口径**,不在平台层的 `Config` 里 ⇒ 由装配层把 `TdcConfig` 递进来。
///
/// 🔴 **检查与插入在同一把 `db_lock` 里**(pglite 单 backend;且「查不到 ⇒ 插入」
/// 必须是原子的,否则并发启动会建出两条身份)。
pub async fn bootstrap_identity(state: &AppState) -> BootstrapIdentity {
let identity_code = state.config.identity_code.clone();
let identity_name = state.config.identity_name.clone();
pub async fn bootstrap_identity(state: &AppState, tdc_config: &TdcConfig) -> BootstrapIdentity {
let identity_code = tdc_config.identity_code.clone();
let identity_name = tdc_config.identity_name.clone();
// 🔴 「查不到 ⇒ 插入」必须**在同一把锁里**完成,否则并发启动会建出两条身份。
let _g = state.db_lock.lock().await;
@@ -132,8 +136,7 @@ pub async fn bootstrap_identity(state: &AppState) -> BootstrapIdentity {
// 🔴 密钥**只在真的要建身份时**才生成 ⇒ 「签发即落库」是结构上的不变量,
// 幂等启动不再白烧一次 RNG 抽样。
// (运维显式配置的 `TDC_IDENTITY_SECRET` 仍然优先。)
let secret = state
.config
let secret = tdc_config
.identity_secret
.clone()
.unwrap_or_else(|| hex::encode(random_bytes()));
-1
View File
@@ -49,7 +49,6 @@ async fn build(tag: &str) -> (Router, Arc<AccountStore>) {
// 🔴 `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 文件 ⇒ 先清干净(否则上一轮残留账号影响断言)。
+1 -2
View File
@@ -37,8 +37,7 @@ async fn shared_db() -> Arc<PGlite> {
/// 构造一个带鉴权中间件的 router,并返回当前生效的内部令牌与状态。
async fn build() -> (Router, String, AppState) {
let db = shared_db().await;
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
let config = Config::from_env(std::env::current_dir().unwrap());
let sessions = Arc::new(SessionStore::new());
let token = config.internal_token.clone();
let state = AppState::new(
+21 -13
View File
@@ -13,6 +13,7 @@ use serde_json::{json, Value};
use tdc_connector::platform::auth::{auth_middleware, AuthState};
use tdc_connector::platform::config::Config;
use tdc_connector::tdc::service::identity;
use tdc_connector::tdc::config::TdcConfig;
use tdc_connector::tdc::controller::build_router;
use tdc_connector::tdc::support::public_paths;
use tdc_connector::platform::session::SessionStore;
@@ -42,13 +43,21 @@ async fn test_state() -> AppState {
/// 与 `main.rs` 一致:**登录签发的会话与鉴权中间件必须共用同一个 store**。
async fn test_state_with(sessions: Arc<SessionStore>) -> AppState {
let db = shared_db().await;
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
config.identity_name = "测试连接器".to_string();
config.identity_secret = Some("test-secret-key".to_string());
let config = Config::from_env(std::env::current_dir().unwrap());
AppState::new(config, db, sessions, BootstrapIdentity::default())
}
/// 🔴 业务配置(身份与引导)**不在平台 Config 里**(v3 spec §2.3.1 C8)⇒ 单独造一份。
fn test_tdc_config() -> TdcConfig {
TdcConfig {
identity_code: "TEST-CONNECTOR".to_string(),
identity_name: "测试连接器".to_string(),
identity_secret: Some("test-secret-key".to_string()),
bootstrap_admin_account: "admin".to_string(),
bootstrap_admin_password: None,
}
}
/// 🔴 同一个 PGlite 上的所有 `AppState` 必须共享**同一把** `db_lock`。
///
/// pglite-rs 每进程只允许一个 PGlite ⇒ 一个进程只需要一把锁 ⇒ 锁的粒度是**进程**。
@@ -58,8 +67,7 @@ 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 config = Config::from_env(std::env::current_dir().unwrap());
let s1 = AppState::new(
config.clone(),
@@ -114,12 +122,12 @@ async fn bootstrap_creates_one_identity_and_is_idempotent() {
// 先清空 ⇒ 本用例一定走「首次引导」分支(否则并发下可能被别人抢先建过)。
clear_identities(&state).await;
let first = identity::bootstrap_identity(&state).await;
let first = identity::bootstrap_identity(&state, &test_tdc_config()).await;
assert!(!first.identity_id.is_empty(), "应创建出身份");
assert_eq!(first.identity_code, "TEST-CONNECTOR");
assert!(first.issued_secret.is_some(), "首次引导应签发一次密钥");
let second = identity::bootstrap_identity(&state).await;
let second = identity::bootstrap_identity(&state, &test_tdc_config()).await;
assert_eq!(second.identity_id, first.identity_id, "引导必须幂等");
assert!(second.issued_secret.is_none(), "已有身份时不得再签发密钥");
}
@@ -128,7 +136,7 @@ async fn bootstrap_creates_one_identity_and_is_idempotent() {
async fn login_rejects_unknown_identity_and_wrong_secret() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
identity::bootstrap_identity(&state).await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let resp = identity::login(
State(state.clone()),
@@ -165,7 +173,7 @@ async fn login_rejects_unknown_identity_and_wrong_secret() {
async fn login_succeeds_and_me_returns_identity_without_secret() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
identity::bootstrap_identity(&state).await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let resp = identity::login(
State(state.clone()),
@@ -200,7 +208,7 @@ async fn login_succeeds_and_me_returns_identity_without_secret() {
async fn me_carries_every_field_the_upstream_frontend_reads() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
identity::bootstrap_identity(&state).await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let resp = identity::me(State(state.clone()), None).await;
let body = body_of(resp).await;
@@ -228,7 +236,7 @@ async fn me_carries_every_field_the_upstream_frontend_reads() {
async fn spaces_returns_a_bare_array_of_space_views() {
let _guard = SERIAL.lock().await;
let state = test_state().await;
identity::bootstrap_identity(&state).await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let resp = identity::spaces(State(state.clone())).await;
let body = body_of(resp).await;
@@ -256,7 +264,7 @@ async fn business_failure_is_http_200_while_auth_failure_is_http_401() {
// 装配带鉴权中间件的真实路由(与 `main.rs` 同一套:会话 store 必须共用)。
let sessions = Arc::new(SessionStore::new());
let state = test_state_with(sessions.clone()).await;
identity::bootstrap_identity(&state).await;
identity::bootstrap_identity(&state, &test_tdc_config()).await;
let auth_state = AuthState {
internal_token: "test-internal-token".to_string(),
sessions: sessions.clone(),
+11 -3
View File
@@ -7,6 +7,7 @@ use std::sync::Arc;
use pglite::PGlite;
use tdc_connector::platform::config::Config;
use tdc_connector::tdc::config::TdcConfig;
use tdc_connector::tdc::service::identity::bootstrap_identity;
use tdc_connector::platform::session::SessionStore;
use tdc_connector::platform::state::{AppState, BootstrapIdentity};
@@ -21,8 +22,7 @@ async fn bootstrap_insert_failure_yields_no_secret() {
// (`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 config = Config::from_env(std::env::current_dir().unwrap());
let state = AppState::new(
config,
db,
@@ -30,7 +30,15 @@ async fn bootstrap_insert_failure_yields_no_secret() {
BootstrapIdentity::default(),
);
let bootstrap = bootstrap_identity(&state).await;
// 🔴 业务配置走显式入参(v3 spec §2.3.1 C8)⇒ 身份码不再挂在平台 Config 上。
let tdc_config = TdcConfig {
identity_code: "TEST-CONNECTOR".to_string(),
identity_name: "测试连接器".to_string(),
identity_secret: Some("test-secret-key".to_string()),
bootstrap_admin_account: "admin".to_string(),
bootstrap_admin_password: None,
};
let bootstrap = bootstrap_identity(&state, &tdc_config).await;
// 🔴 失败 ⇒ 不得有密钥、不得有 id
assert!(
bootstrap.issued_secret.is_none(),
+1 -2
View File
@@ -51,8 +51,7 @@ async fn shared_db() -> Arc<PGlite> {
async fn test_state() -> AppState {
let db = shared_db().await;
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
let config = Config::from_env(std::env::current_dir().unwrap());
AppState::new(
config,
db,
+1 -2
View File
@@ -31,8 +31,7 @@ async fn shared_db() -> Arc<PGlite> {
async fn test_state() -> AppState {
let db = shared_db().await;
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
let config = Config::from_env(std::env::current_dir().unwrap());
AppState::new(
config,
db,
+1 -2
View File
@@ -173,8 +173,7 @@ async fn shared_db() -> Arc<PGlite> {
/// 造一台指向 `base_url` 的连接器。
async fn build(base_url: Option<String>) -> (Router, String) {
let db = shared_db().await;
let mut config = Config::from_env(std::env::current_dir().unwrap());
config.identity_code = "TEST-CONNECTOR".to_string();
let config = Config::from_env(std::env::current_dir().unwrap());
let sessions = Arc::new(SessionStore::new());
let token = config.internal_token.clone();
let state = AppState::new(