refactor(b1b-c11): 常量时间比较上收到平台层 —— 两份实现合一

影响:全仓只剩一份 constant_time_eq 实现;对外行为零变化
(239 条测试全绿、冒烟断言数仍 75)。

改动:
- src/platform/compare.rs(新):常量时间比较的唯一实现 + 2 条单测
  (含多字节 UTF-8 用例)
- src/tdc/service/identity.rs / src/tdc/service/account.rs:
  各自的本地实现换成 pub use 复用平台那一份 ⇒ 调用方路径不变、实现只有一份
- src/platform/mod.rs:挂上新模块
- CLAUDE.md / .workbuddy/memory/2026-10-26.md 同步

设计:比较(compare)与加解密(cipher)分成两个平台件,不混在一起。
This commit is contained in:
admin committed 2026-10-26 22:31:31 +08:00
1 parent 3076bdae7a
commit fbee7ae860
6 files changed
+64 -28

No files matched your search

+8 -3
View File
@@ -123,7 +123,8 @@ cargo test → exit 0(全绿)
| C7 | `/api/health` 补 `baseTables`(W5 契约的账号层表数) | `f8764b2` |
| C8 | 配置分家:平台 `Config` 削掉 5 个业务字段,业务配置进 `tdc::config::TdcConfig` | `1797aa0` |
| C9 | 状态分家:平台 `AppState` 只留配置/db/锁/会话,业务态进 `tdc::state::TdcState`(Deref + FromRef) | `49e5fce` |
| C10 | `tdc_identity` 领域 SQL 收进 `tdc::service::identity`(控制器不再自己拼);只 SELECT 明确列 | 本次提交 |
| C10 | `tdc_identity` 领域 SQL 收进 `tdc::service::identity`(控制器不再自己拼);只 SELECT 明确列 | `3076bda` |
| C11 | `constant_time_eq` 上收到 `src/platform/compare.rs`(两份实现合一) | 本次提交 |
**关键决定**
@@ -146,6 +147,11 @@ cargo test → exit 0(全绿)
`tdc_identity` 因此**有两条读写路径**(领域 SQL + 通用引擎)⇒ 新建 `docs/known-limitations.md` 记 L1
(上游无「通用引擎」概念,硬收会失真 ⇒ 显式承认 + 收口 + 记账 = 决策 D15)。
**C11 的做法**:常量时间比较的实现上收到**新平台件** `src/platform/compare.rs`
(不是塞进 `cipher.rs` —— cipher 是「加解密」,compare 是「比较」,两件事)。
业务侧用 `pub use` 复用 ⇒ `identity::constant_time_eq` / `account::constant_time_eq`
两个旧路径都还在,调用方零改动,但**实现只有一份**。
**C9 的技术选型**:业务层 `TdcState` **deref 到** `platform::state::AppState`(⇒ `state.db` 等字段访问零改动)
+ `impl FromRef<TdcState> for AppState`(⇒ axum 里 `State<AppState>` 可用,平台端点不必认识业务类型)。
🔴 `FromRef` 在 **`axum::extract::FromRef`**(`axum::core::extract::FromRef` 不存在)。
@@ -172,8 +178,7 @@ CP1 只查「表名前缀 / 端点前缀」,查不出模块引用 ⇒ 必须
## 当前状态
- 分支 `feat/mvc-align-v3`;**回退点 = `06f5a79`**(v3 spec 落点)。
- B1b 已完成 **C1–C10**;下一条 = **C11**(`constant_time_eq` 上收到平台)/
**C12**(`civil_from_days`/`now_iso` 换 `chrono`,口径 **UTC**)。
- B1b 已完成 **C1–C11**;下一条 = **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 每数据目录只允许一个进程)。
+4
View File
@@ -41,6 +41,7 @@ tdc-rs/
│ │ ├── envelope.rs # 业务信封 ActionResult(HTTP 200 + {code,msg,data})
│ │ ├── auth.rs # 入向鉴权中间件 + 三道门 + 主体(Principal)
│ │ ├── cipher.rs # 登录口令加解密(MD5 + AES-256-ECB,对齐上游 cipher.ts)
│ │ ├── compare.rs # 常量时间比较(**全仓唯一一份实现**,业务侧 pub use 复用)
│ │ ├── ids.rs # id 生成
│ │ ├── protocol.rs # 协议版本闸门
│ │ ├── body.rs # 宽松 JSON 体
@@ -277,6 +278,9 @@ bash scripts/check-entity.sh # ③ 实体静态(加实体的接触点完
永不 `SELECT *`(别把 `f_secret_key` 整行拖进内存)。
🔴 `tdc_identity` 因此**有两条读写路径**(领域 SQL + 通用 CRUD 引擎)⇒ 已记进
`docs/known-limitations.md` L1(上游无「通用引擎」概念,硬收会失真 ⇒ 显式承认 + 收口)。
19. **常量时间比较只有一份实现**(C11):实现住在 `src/platform/compare.rs`;
业务侧(`tdc::service::identity` / `tdc::service::account`)用
`pub use crate::platform::compare::constant_time_eq;` 复用 ⇒ **不许再抄一份**。
## 数据模型
+45
View File
@@ -0,0 +1,45 @@
//! **平台层**:常量时间比较(与业务无关的**机制**)。
//!
//! 🔴 **只有一份实现**(v3 spec §2.3.1 C11):此前 `tdc::service::identity` 与
//! `tdc::service::account` 各写了一份几乎相同的 `constant_time_eq`
//! ⇒ 两份实现将来会漂移。统一上收到平台层,业务侧 `pub use` 复用。
/// 常量时间字符串比较。
///
/// 🔴 **长度不同直接返回 false**:长度本身不是秘密(口令长度会被上游的 400 暴露),
/// 但**逐字节比较的时间**不能随「第一个不同字节的位置」变化
/// ⇒ 避免按字节短路泄漏信息。
///
/// 🔴 语义等价于上游的 `String.equals`,但**比上游严**(上游是短路比较)。
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
}
#[cfg(test)]
mod tests {
use super::constant_time_eq;
#[test]
fn matches_only_identical_strings() {
assert!(constant_time_eq("abc", "abc"));
assert!(!constant_time_eq("abc", "abd"));
assert!(!constant_time_eq("abc", "abcd"));
assert!(!constant_time_eq("", "x"));
assert!(constant_time_eq("", ""));
}
#[test]
fn handles_multibyte_utf8() {
assert!(constant_time_eq("密码", "密码"));
assert!(!constant_time_eq("密码", "口令"));
assert!(!constant_time_eq("密码", "密码x"));
}
}
+2
View File
@@ -14,6 +14,7 @@
//! | 模块 | 职责 | 对位上游 |
//! |---|---|---|
//! | `state` | `AppState`(配置 + db + 锁 + 会话)—— **业务态在 `tdc::state::TdcState`** | — |
//! | `compare` | 常量时间比较(**唯一一份实现**,业务侧 `pub use` 复用) | — |
//! | `config` | 环境变量配置 + 密钥守卫 | — |
//! | `db` | PGlite 封装 + SQL 切分 + `f_`↔camelCase 映射契约 | — |
//! | `session` | 内存会话(`Identity` / `Account` 两种 kind) | — |
@@ -29,6 +30,7 @@
pub mod auth;
pub mod body;
pub mod cipher;
pub mod compare;
pub mod config;
pub mod db;
pub mod envelope;
+2 -12
View File
@@ -31,18 +31,8 @@ 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
}
/// 常量时间比较(**实现上收到平台层**,v3 spec §2.3.1 C11 ⇒ 全仓只有一份)。
pub use crate::platform::compare::constant_time_eq;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Account {
+3 -13
View File
@@ -45,19 +45,8 @@ pub fn str_field(payload: &Value, key: &str) -> Option<String> {
}
}
/// 常量时间字符串比较。
pub fn constant_time_eq(a: &str, b: &str) -> bool {
let ab = a.as_bytes();
let bb = b.as_bytes();
if ab.len() != bb.len() {
return false;
}
let mut diff = 0u8;
for i in 0..ab.len() {
diff |= ab[i] ^ bb[i];
}
diff == 0
}
/// 常量时间字符串比较(**实现上收到平台层**,v3 spec §2.3.1 C11 ⇒ 全仓只有一份)。
pub use crate::platform::compare::constant_time_eq;
/// 身份是否可登录。
pub fn loginable(status: &str, register_status: &str) -> bool {
@@ -547,6 +536,7 @@ mod tests {
#[test]
fn constant_time_eq_matches_only_identical_strings() {
// 🔴 实现已上收到平台层(`platform::compare`)⇒ 这里只验「业务侧复用同一份」。
assert!(constant_time_eq("abc", "abc"));
assert!(!constant_time_eq("abc", "abd"));
assert!(!constant_time_eq("abc", "abcd"));