From 7f76cce56e030804b9a7aad24168865cdc10dbe0 Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 25 Oct 2026 13:12:32 +0800 Subject: [PATCH] =?UTF-8?q?docs(plan):=20P4=20TDS=20=E5=87=BA=E5=90=91?= =?UTF-8?q?=E5=AE=A2=E6=88=B7=E7=AB=AF=E5=AE=9E=E6=96=BD=E8=AE=A1=E5=88=92?= =?UTF-8?q?=EF=BC=888=20=E4=B8=AA=20Task=EF=BC=8C=E5=90=AB=20R8=20+=20?= =?UTF-8?q?=E8=BE=B9=E7=95=8C=E2=91=A2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Code --- .../2026-10-25-tdc-rs-p4-tds-outbound.md | 2222 +++++++++++++++++ 1 file changed, 2222 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-25-tdc-rs-p4-tds-outbound.md diff --git a/docs/superpowers/plans/2026-10-25-tdc-rs-p4-tds-outbound.md b/docs/superpowers/plans/2026-10-25-tdc-rs-p4-tds-outbound.md new file mode 100644 index 0000000..7560fa6 --- /dev/null +++ b/docs/superpowers/plans/2026-10-25-tdc-rs-p4-tds-outbound.md @@ -0,0 +1,2222 @@ +# P4 TDS 出向客户端 实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 照抄上游新版 TDC 的 `ServiceCatalogController` + `BillingController` 两个控制器 + 一个只走 `X-Internal-Token` 通道的 TDS 出向客户端,让上游控制台的「服务目录」「我的账单」两页从 404 变成可用。 + +**Architecture:** 新增 `src/tds/mod.rs`(≡ 上游 `TdsReportClient` 的 internal 通道,9 个方法)与 `src/routes/tds_biz.rs`(≡ 上游两个控制器,10 个端点)。出向只发 6 个固定头(`Content-Type` / `App-Code: sswflow` / `Jnpf-Origin: pc` / `Vue-Version: 3` / `X-Internal-Token` / `X-Protocol-Version: 1.0`),**绝不**把 `Authorization` / cookie / 本地会话令牌带给 TDS。身份解析**逐端点照抄**上游两套口径(`Confirm`/`Settle` 严格、其余宽松),越权自检 `ownsLedger` 一并照抄。业务失败一律 HTTP 200 + `{code,msg,data}`,鉴权失败 401/403 裸 `{success,code,msg}`。 + +**Tech Stack:** Rust 2021 + axum 0.8 + tokio + reqwest 0.12(rustls-tls,**已在 `Cargo.toml`**)+ pglite-rs + serde_json。 + +**Spec:** `docs/superpowers/specs/2026-10-25-tdc-rs-p4-tds-outbound-design.md`(已批准,用户 2026-10-25 拍板「严格按新版 tdc 去实现,不用创新」+「照抄上游宽松身份 + 令牌有默认值」) + +## Global Constraints + +以下每条都是**用户原话 / 显式指令 / 仓库红线**,每个 Task 都隐含包含本节: + +1. **🔴 不派任何子代理。** 用户此前主动杀掉过 R4 子代理并说「Treat its work as cancelled; only launch a new agent if the user explicitly asks」⇒ 本轮**全部在主会话内联执行**。 +2. **🔴 不自研前端。** 控制台 = 上游完整前端的构建产物(`static/`)⇒ 本轮**只加后端端点**,不改 `static/`、不写前端代码。SPA 的「服务目录」「我的账单」两页是**上游现成**的,靠后端补齐 10 个端点来激活。 +3. **git 操作**:禁止 `git add -A`(只 `git add <显式路径>`);禁止 `git checkout` / `git stash` / `git reset` —— 要还原就 `cp` 备份再 `cp` 回来;提交信息末尾附 `Co-Authored-By: Claude Code `。 +4. **秘密**:`data/accounts.json`、`data/tdc.pg/`、私钥都不进版本库;`SSW_TDS_INTERNAL_TOKEN` 的**值**不得进日志/错误文案/文档。 +5. **本机 curl 测 localhost 必须加 `--noproxy '*'`**(否则被系统代理劫持成 502)。 +6. **后台常驻进程**用 Bash 工具的 `run_in_background` 托管(`nohup … &` 会在工具返回后被回收);**stdout 不要指向 `/dev/null`**(进程会以 100 退出)。 +7. **xop 在 agent 无头环境必须 `< /dev/null`**。 +8. **写 shell 脚本时 bash 变量后紧跟中文必须写 `${VAR}`**(`"$RC里"` 会把中文字节并入变量名)。 +9. **同一文件的多个 Edit 必须串行**(并行 Edit = last-writer-wins 静默覆盖)。 +10. **业务错误必须读 body 的 `code`**:业务失败 = HTTP 200 + `{code,msg,data}`;鉴权/授权失败 = HTTP 401/403 + 裸 `{"success":false,"code":…,"msg":"…"}`(**无 `data` 键**)。**两套形状不得混用。** +11. **出向判定成功必须看 `body.code == 200`**,只看 HTTP 状态会把失败误判成成功。 +12. **出向请求不得携带 `Authorization` / cookie / 任何本地会话令牌**(只带 6 个固定头)。 +13. **出向 URL 只由固定路径模板拼出**;路径段(`{id}`)须过白名单:仅 ASCII 字母/数字/下划线/短横线,长度 1..=64。 +14. **任何失败都不许变成 HTTP 500、不许 panic**(照抄上游「失败即降级、绝不拖垮本地 TDC 业务」)。 +15. **上游只读真源**:`/tmp/sswtdc-probe`、`/tmp/sswtds-probe` **只读,不许改**。**活着的调试 TDS 在 `:30041`(库 `tds2`,日志 `/tmp/tds2-run.log`)⇒ 🔴 不要重启它。** +16. **测试基线**:`cargo test` ⇒ 207 passed / 0 failed / 1 ignored ⇒ 本轮**新增正好 12 条** ⇒ 目标 **219 passed / 0 failed / 1 ignored**。 +17. **记忆约定**:踩坑清单/长 traceback → `docs/`;工作日志 → `.workbuddy/memory/2026-10-25.md`;memory 只留「原则 + 决定 + 指针」。 + +## 文件结构 + +| 文件 | 动作 | 职责 | +|---|---|---| +| `Cargo.toml` | **不改** | `reqwest 0.12`(`default-features=false, features=["json","rustls-tls"]`)**已在**(`tests/auth_flow.rs` 在用)⇒ 本轮零新依赖 | +| `src/config.rs` | 改 | 新增 `SSW_TDS_INTERNAL_TOKEN`(默认 `ssw-internal-token-e2e`)⇒ `Config::tds_internal_token` | +| `src/tds/mod.rs` | **新建** | TDS 出向客户端(≡ 上游 `TdsReportClient` internal 通道):9 个方法 + 头/URL/解包纯函数 | +| `src/state.rs` | 改 | `AppState` 挂 `tds: Arc` + `with_tds()` | +| `src/lib.rs` | 改 | `pub mod tds;` | +| `src/routes/tds_biz.rs` | **新建** | 10 个端点(≡ 上游 `ServiceCatalogController` + `BillingController`) | +| `src/routes/mod.rs` | 改 | `.merge(tds_biz::router())` | +| `src/main.rs` | 改 | 边界③:`TcpListener::bind(...).unwrap()` → 打印明确文案 + `exit 1` | +| `tests/auth_flow.rs` / `tests/bootstrap_fail.rs` / `tests/crud_engine.rs` | 改 | R8:历史 rustfmt 违规(**纯格式,不动语义**) | +| `tests/tds_biz.rs` | **新建** | 12 条集成测试(假 TDS) | +| `docs/TDC-TDS-CONTRACT.md` | 改 | 「P4 输入契约」→「已实现 + 实测表」 | +| `README.md` / `CLAUDE.md` | 改 | API 表 + 红线同步 | +| `.workbuddy/memory/2026-10-25.md` / `.superpowers/sdd/.../progress.md` | 改 | 工作日志 / SDD 台账 | + +--- + +### Task 1: R8 历史 rustfmt + 边界③ 端口冲突友好退出 + +**Files:** +- Modify: `tests/auth_flow.rs`、`tests/bootstrap_fail.rs`、`tests/crud_engine.rs`(**仅格式化**) +- Modify: `src/main.rs`(边界③) + +**Interfaces:** +- Consumes: 无 +- Produces: `src/main.rs::bind_failure_message(&SocketAddr, &std::io::Error) -> String`(纯函数,供 `#[cfg(test)]` 断言) + +- [ ] **Step 1: 记下改动前的指纹(便于复核「只改了格式」)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +for f in tests/auth_flow.rs tests/bootstrap_fail.rs tests/crud_engine.rs; do + shasum -a 256 "$f" +done > /tmp/r8-before.sha +cat /tmp/r8-before.sha +``` + +- [ ] **Step 2: 跑 rustfmt(只格式化这 3 个文件,不动别的)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +rustfmt --edition 2021 tests/auth_flow.rs tests/bootstrap_fail.rs tests/crud_engine.rs +``` + +> ⚠️ 禁 `git checkout` / `stash` / `reset` ⇒ 改动前先 `cp` 备份: +> `mkdir -p /tmp/r8-backup && cp tests/auth_flow.rs tests/bootstrap_fail.rs tests/crud_engine.rs /tmp/r8-backup/` + +- [ ] **Step 3: 复核「只有空白变化」(语义零改动)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +# 去掉所有空白后与备份逐字比对 ⇒ 只允许空白差异 +for f in auth_flow bootstrap_fail crud_engine; do + if diff -q <(tr -d '[:space:]' < "tests/$f.rs") <(tr -d '[:space:]' < "/tmp/r8-backup/$f.rs") >/dev/null; then + echo "OK $f.rs 仅有空白差异" + else + echo "DIFF $f.rs 存在非空白改动 ⇒ 人工复核"; fi +done +``` + +- [ ] **Step 4: 确认全仓 `cargo fmt --check` 干净** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo fmt --check 2>&1 | head -40 +``` + +期望:**无输出**(若 `src/` 里还有别处违规,**不要顺手改**——只改本轮触碰的文件;把剩余违规记进台账)。 + +- [ ] **Step 5: 写边界③ 的失败测试(`src/main.rs` 内联单测)** + +在 `src/main.rs` 末尾追加: + +```rust +/// 端口绑定失败的文案(**纯函数** ⇒ 可单测)。 +/// +/// 🔴 边界③:原先是 `TcpListener::bind(addr).await.unwrap()` +/// ⇒ 端口被占用时进程 panic,抛一坨 Rust 回溯给运维看。 +/// 这里改成「打印一句人话 + exit 1」。 +/// +/// ⚠️ 文案里**不得**含任何敏感信息(只含地址与操作系统错误码)。 +fn bind_failure_message(addr: &std::net::SocketAddr, err: &std::io::Error) -> String { + format!( + "无法绑定监听地址 {}:{}。请确认该端口未被占用,或用 PORT=<其它端口> 重新启动。", + addr, err + ) +} + +#[cfg(test)] +mod tests { + use super::bind_failure_message; + use std::net::SocketAddr; + + #[test] + fn bind_failure_message_names_the_address_and_the_cause() { + let addr: SocketAddr = "127.0.0.1:30000".parse().unwrap(); + let err = std::io::Error::new(std::io::ErrorKind::AddrInUse, "Address already in use"); + let msg = bind_failure_message(&addr, &err); + assert!(msg.contains("127.0.0.1:30000"), "文案应含监听地址:{}", msg); + assert!(msg.contains("Address already in use"), "文案应含系统错误:{}", msg); + assert!(msg.contains("PORT="), "文案应给出改端口的办法:{}", msg); + } + + #[test] + fn bind_failure_message_carries_no_secret_material() { + let addr: SocketAddr = "0.0.0.0:30000".parse().unwrap(); + let err = std::io::Error::other("boom"); + let msg = bind_failure_message(&addr, &err); + assert!(!msg.contains("token"), "文案不得含令牌字样:{}", msg); + assert!(!msg.contains("password"), "文案不得含口令字样:{}", msg); + } +} +``` + +- [ ] **Step 6: 跑测试确认它先红(函数还不存在)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test --bin tdc-connector 2>&1 | tail -20 +``` + +期望:编译失败(`cannot find function bind_failure_message`)⇒ 说明测试确实在测新东西。 + +- [ ] **Step 7: 实现边界③** + +把 `src/main.rs` 里这一行: + +```rust + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); +``` + +替换为: + +```rust + // 🔴 边界③:端口冲突不再 panic(回溯对运维无意义)⇒ 打印一句人话 + 退出码 1。 + let listener = match tokio::net::TcpListener::bind(addr).await { + Ok(l) => l, + Err(e) => { + eprintln!("[tdc-connector] {}", bind_failure_message(&addr, &e)); + std::process::exit(1); + } + }; +``` + +- [ ] **Step 8: 跑测试确认它绿** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test --bin tdc-connector 2>&1 | tail -20 +``` + +期望:2 passed。 + +- [ ] **Step 9: 提交(显式路径,不用 `-A`)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +git add src/main.rs tests/auth_flow.rs tests/bootstrap_fail.rs tests/crud_engine.rs +git commit -m "style: 修 3 处历史 rustfmt 违规 + 边界③ 端口冲突改「打印 + exit 1」 + +- tests/{auth_flow,bootstrap_fail,crud_engine}.rs:仅格式化(去空白后逐字等价) +- main.rs:TcpListener::bind 的 unwrap 换成明确的错误文案 + exit 1,不再抛 panic 回溯 + +Co-Authored-By: Claude Code " +``` + +--- + +### Task 2: 配置项 `SSW_TDS_INTERNAL_TOKEN` + +**Files:** +- Modify: `src/config.rs` +- Test: `src/config.rs`(内联单测,**新增 2 条**) + +**Interfaces:** +- Consumes: 无 +- Produces: + - `config::DEFAULT_TDS_INTERNAL_TOKEN: &str = "ssw-internal-token-e2e"` + - `config::Config::tds_internal_token: String` + - `config::tds_internal_token_from(raw: Option) -> String`(私有纯函数) + +- [ ] **Step 1: 写失败测试(2 条)** + +在 `src/config.rs` 的 `mod tests` 里追加: + +```rust + /// 🔴 出向令牌必须**独立**于入向令牌(方向相反,混用会把两套密钥耦在一起)。 + #[test] + fn tds_internal_token_is_trimmed_and_blank_falls_back_to_default() { + assert_eq!( + tds_internal_token_from(Some(" tds-secret ".to_string())), + "tds-secret" + ); + assert_eq!( + tds_internal_token_from(None), + DEFAULT_TDS_INTERNAL_TOKEN + ); + assert_eq!( + tds_internal_token_from(Some(String::new())), + DEFAULT_TDS_INTERNAL_TOKEN + ); + assert_eq!( + tds_internal_token_from(Some(" ".to_string())), + DEFAULT_TDS_INTERNAL_TOKEN, + "纯空白必须回落默认值,不能变成空令牌" + ); + } + + #[test] + fn tds_internal_token_defaults_to_the_upstream_shared_default() { + // 上游 `@Value("${ssw.internal-token:ssw-internal-token-e2e}")` ⇒ 逐字对齐 + assert_eq!(DEFAULT_TDS_INTERNAL_TOKEN, "ssw-internal-token-e2e"); + // 入向令牌与出向令牌是**两个字段**,默认值相同但互不影响 + let mut c = base(); + assert_eq!(c.internal_token, DEFAULT_INTERNAL_TOKEN); + assert_eq!(c.tds_internal_token, DEFAULT_TDS_INTERNAL_TOKEN); + c.tds_internal_token = "tds-only-secret".to_string(); + assert_eq!( + c.internal_token, DEFAULT_INTERNAL_TOKEN, + "改出向令牌不得牵动入向令牌" + ); + } +``` + +- [ ] **Step 2: 跑测试确认它先红** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test --lib config:: 2>&1 | tail -25 +``` + +期望:编译失败(`DEFAULT_TDS_INTERNAL_TOKEN` / `tds_internal_token` / `tds_internal_token_from` 未定义)。 + +- [ ] **Step 3: 实现** + +① 在 `src/config.rs` 顶部常量区追加: + +```rust +/// **出向**(TDC → TDS)内部令牌默认值。 +/// +/// 照抄上游 `@Value("${ssw.internal-token:ssw-internal-token-e2e}")`。 +/// 🔴 与 `DEFAULT_INTERNAL_TOKEN`(**入向**闸门)同值但**不同源**: +/// 方向相反,混用会把两套密钥耦在一起 ⇒ 出向单独用 `SSW_TDS_INTERNAL_TOKEN`。 +pub const DEFAULT_TDS_INTERNAL_TOKEN: &str = "ssw-internal-token-e2e"; +``` + +② 在 `internal_token_from` 之后追加纯函数: + +```rust +/// 归一化**出向**内部令牌:未设置或纯空白 ⇒ 回落默认值;否则去掉首尾空白。 +/// +/// 与 [`internal_token_from`] 同口径,但**作用于出向通道**(`SSW_TDS_INTERNAL_TOKEN`)。 +/// 纯函数(不读进程全局 env),便于单测。 +fn tds_internal_token_from(raw: Option) -> String { + env_or_default(raw, DEFAULT_TDS_INTERNAL_TOKEN).trim().to_string() +} +``` + +③ `Config` 结构体加字段: + +```rust + /// **出向**(TDC → TDS)内部令牌(`SSW_TDS_INTERNAL_TOKEN`)。 + /// + /// 🔴 **不复用** `internal_token`(那是**入向**闸门的令牌,方向相反)。 + pub tds_internal_token: String, +``` + +④ `Config::from_env` 里读环境变量(在 `internal_token` 之后): + +```rust + // 🔴 出向令牌独立配置:入向 `SSW_INTERNAL_TOKEN` 与出向 `SSW_TDS_INTERNAL_TOKEN` + // 方向相反,混用会把两套密钥耦在一起。 + let tds_internal_token = tds_internal_token_from(std::env::var("SSW_TDS_INTERNAL_TOKEN").ok()); +``` + +⑤ `Config::from_env` 的 `Self { … }` 里加 `tds_internal_token,`(放在 `internal_token,` 之后)。 + +⑥ `mod tests` 里的 `base()` 辅助函数加 `tds_internal_token: DEFAULT_TDS_INTERNAL_TOKEN.to_string(),`。 + +- [ ] **Step 4: 跑测试确认它绿** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test --lib config:: 2>&1 | tail -25 +``` + +期望:全绿。 + +- [ ] **Step 5: 提交** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +git add src/config.rs +git commit -m "feat(config): 新增出向内部令牌 SSW_TDS_INTERNAL_TOKEN(默认 ssw-internal-token-e2e) + +- 与入向 SSW_INTERNAL_TOKEN 同值但不同源(方向相反,不混用) +- 纯空白回落默认值;首尾空白 trim + +Co-Authored-By: Claude Code " +``` + +--- + +### Task 3: `src/tds/mod.rs` —— TDS 出向客户端 + +**Files:** +- Create: `src/tds/mod.rs` +- Modify: `src/lib.rs`(`pub mod tds;`) +- Test: `src/tds/mod.rs`(内联单测,**新增 4 条**) + +**Interfaces:** +- Consumes: `config::DEFAULT_TDS_INTERNAL_TOKEN`(不需要,直接传字符串) +- Produces: + - `pub struct TdsClient`(`Clone`) + - `TdsClient::new(base_url: Option, internal_token: String) -> TdsClient` + - `TdsClient::is_noop(&self) -> bool` + - `TdsClient::internal_catalog(&self, space_id: &str, keyword: Option<&str>) -> Result` + - `TdsClient::internal_apply(&self, body: &Value) -> Result` + - `TdsClient::internal_apply_batch(&self, body: &Value) -> Result` + - `TdsClient::list_billing_for_connector(&self, connector_id: &str, keyword: Option<&str>) -> Result` + - `TdsClient::dispute_billing(&self, ledger_id: &str) -> Result` + - `TdsClient::confirm_billing(&self, ledger_id: &str, connector_id: &str) -> Result` + - `TdsClient::settle_billing(&self, ledger_id: &str, connector_id: &str) -> Result` + - `TdsClient::receipt_billing(&self, ledger_id: &str, body: &Value) -> Result` + - `TdsClient::voucher_billing(&self, ledger_id: &str) -> Result` + +- [ ] **Step 1: 写失败测试(4 条)** + +新建 `src/tds/mod.rs`,**先只写测试**(文件顶部放 `use` 与空实现占位): + +```rust +//! TDS 出向客户端(照抄上游 `TdsReportClient` 的 **internal 通道**)。 +//! +//! 上游真源:`/tmp/sswtdc-probe/boot/ssw-tdc/ssw-tdc-biz/src/main/java/ssw/tdc/client/TdsReportClient.java` +//! (`internalHeaders()` / `restTemplate()` / `internalCatalog` / `internalApply` / `internalApplyBatch` +//! / `listBillingForConnector` / `disputeBilling` / `confirmBilling` / `settleBilling` / `receiptBilling` +//! / `voucherBilling`)。 +//! +//! 🔴 **只实现 internal 通道**(`X-Internal-Token` + 固定头,走 TDS `white-url` 放行的内部端点)。 +//! 上游还有一条 login/ensureToken 通道(JNPF 登录换 token)⇒ 本轮**不做**(见 spec §5)。 + +use std::time::Duration; + +use serde_json::{json, Value}; + +/// 连接超时(照抄上游 `restTemplate()`:`setConnectTimeout(3000)`)。 +pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); +/// 读取超时(照抄上游 `restTemplate()`:`setReadTimeout(5000)`)。 +pub const READ_TIMEOUT: Duration = Duration::from_secs(5); + +/// 未配置 TDS 地址(本地单机模式)时的降级文案。 +pub const NOOP_MESSAGE: &str = "未配置 TDS 地址(本地单机模式)"; + +/// 账本 / 订单等 id 的路径段白名单:仅 ASCII 字母数字、下划线、短横线。 +/// +/// 🔴 出向 URL **只由固定路径模板 + 已校验的段**拼出 ⇒ 用户输入绝不直接进 URL 路径。 +pub fn is_safe_path_segment(s: &str) -> bool { + !s.is_empty() + && s.len() <= 64 + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +/// 解包型方法的信封拆解:`code == 200` ⇒ 取 `data`;否则取 `msg` 当拒因。 +/// +/// 照抄上游 `internalCatalog` / `internalApply` / `internalApplyBatch`: +/// `code==200` ⇒ 返回 `data`;否则返回 `{fail: msg}`;异常 ⇒ `{fail: msg + ": " + e}`。 +/// Rust 侧统一成 `Result`(spec D2),但**语义逐条对齐**。 +fn unwrap_data(envelope: Value, fallback_msg: &str) -> Result { + let code = envelope.get("code").and_then(|v| v.as_i64()).unwrap_or(0); + if code == 200 { + Ok(envelope.get("data").cloned().unwrap_or(Value::Null)) + } else { + let msg = envelope + .get("msg") + .and_then(|v| v.as_str()) + .filter(|s| !s.trim().is_empty()) + .unwrap_or(fallback_msg); + Err(msg.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn path_segment_whitelist_accepts_only_safe_ids() { + assert!(is_safe_path_segment("854250096668180741")); + assert!(is_safe_path_segment("L-1")); + assert!(is_safe_path_segment("a_b-c")); + assert!(!is_safe_path_segment("")); + assert!(!is_safe_path_segment("a/b")); + assert!(!is_safe_path_segment("a b")); + assert!(!is_safe_path_segment("../etc")); + assert!(!is_safe_path_segment("a?b=1")); + assert!(!is_safe_path_segment(&"x".repeat(65))); + } + + #[test] + fn unwrap_data_returns_data_on_200_and_msg_otherwise() { + let ok = unwrap_data(json!({"code":200,"msg":"ok","data":{"list":[]}}), "兜底"); + assert_eq!(ok.unwrap(), json!({"list":[]})); + let rejected = unwrap_data(json!({"code":600,"msg":"登录过期"}), "兜底"); + assert_eq!(rejected.unwrap_err(), "登录过期"); + // 没有 msg ⇒ 回落调用方给的兜底文案 + let bare = unwrap_data(json!({"code":600}), "目录查询失败"); + assert_eq!(bare.unwrap_err(), "目录查询失败"); + } + + #[test] + fn internal_headers_carry_the_six_upstream_headers_and_nothing_else() { + let c = TdsClient::new(Some("http://127.0.0.1:30041".to_string()), "tok-123".to_string()); + let h = c.internal_headers(); + assert_eq!(h.get("content-type").unwrap(), "application/json"); + assert_eq!(h.get("app-code").unwrap(), "sswflow"); + assert_eq!(h.get("jnpf-origin").unwrap(), "pc"); + assert_eq!(h.get("vue-version").unwrap(), "3"); + assert_eq!(h.get("x-internal-token").unwrap(), "tok-123"); + assert_eq!(h.get("x-protocol-version").unwrap(), "1.0"); + // 🔴 出向**不得**带 Authorization / Cookie(本地会话令牌不外泄) + assert!(h.get("authorization").is_none()); + assert!(h.get("cookie").is_none()); + // 头总数正好 6(多一个就说明漏了「只带这 6 个」的约束) + assert_eq!(h.len(), 6, "出向头必须正好 6 个,实际 {:?}", h); + } + + #[test] + fn url_is_built_from_base_and_fixed_path() { + let c = TdsClient::new(Some("http://127.0.0.1:30041/".to_string()), "tok".to_string()); + assert_eq!( + c.url("/api/ssw/tds/Catalog/Internal/Catalog").unwrap(), + "http://127.0.0.1:30041/api/ssw/tds/Catalog/Internal/Catalog" + ); + // 未配地址 ⇒ NOOP + let noop = TdsClient::new(None, "tok".to_string()); + assert!(noop.is_noop()); + assert_eq!(noop.url("/api/ssw/tds/x").unwrap_err(), NOOP_MESSAGE); + } +} +``` + +- [ ] **Step 2: 跑测试确认它先红** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test --lib tds:: 2>&1 | tail -25 +``` + +期望:编译失败(`TdsClient` 未定义 / `internal_headers` / `url` 未定义)。 + +- [ ] **Step 3: 实现 `TdsClient`(把下面整段追加到 `src/tds/mod.rs` 的 `mod tests` 之前)** + +```rust +/// TDS 出向客户端(≡ 上游 `TdsReportClient` 的 internal 通道)。 +#[derive(Clone)] +pub struct TdsClient { + /// TDS 基地址;`None` ⇒ **NOOP**(未配 `SSW_TDS_BASE_URL` ⇒ 本地单机模式)。 + base_url: Option, + /// 出向内部令牌(`SSW_TDS_INTERNAL_TOKEN`)。 + internal_token: String, + http: reqwest::Client, +} + +impl TdsClient { + /// 造客户端。 + /// + /// 🔴 `.no_proxy()`:本机 `HTTP_PROXY` 会劫持 loopback(`CLAUDE.md` 踩坑表: + /// 「curl 测 localhost 得 502」)。TDS 是**内网直连**服务 ⇒ 出向**必须直连**, + /// 否则打 `127.0.0.1:30041` 会被代理吞掉。 + /// + /// ⚠️ 超时照抄上游 `restTemplate()`:连接 3s / 读取 5s(**快速失败**,别拖垮本地业务)。 + pub fn new(base_url: Option, internal_token: String) -> Self { + let http = reqwest::Client::builder() + .no_proxy() + .connect_timeout(CONNECT_TIMEOUT) + .timeout(READ_TIMEOUT) + .build() + .unwrap_or_else(|e| { + // 造不出 HTTP 客户端是**编程错误**(参数写死、无外部输入)⇒ 直接 panic 暴露。 + panic!("构造 TDS 出向 HTTP 客户端失败: {}", e); + }); + Self { + base_url: base_url.map(|b| b.trim().trim_end_matches('/').to_string()), + internal_token, + http, + } + } + + /// 是否处于 NOOP 模式(未配置 TDS 地址)。 + pub fn is_noop(&self) -> bool { + self.base_url.is_none() + } + + /// 拼出向 URL(固定路径模板 + 基地址)。 + /// + /// 🔴 路径段必须已过 [`is_safe_path_segment`](调用方负责)⇒ 这里只做拼接。 + fn url(&self, path: &str) -> Result { + match &self.base_url { + Some(base) => Ok(format!("{}{}", base, path)), + None => Err(NOOP_MESSAGE.to_string()), + } + } + + /// 出向请求头(**逐字照抄**上游 `internalHeaders()`,正好 6 个)。 + /// + /// | 头 | 值 | + /// |---|---| + /// | `Content-Type` | `application/json` | + /// | `App-Code` | `sswflow`(⚠️ **不是** `tdc`,那是 `Bridge/**` 通道,本轮不做) | + /// | `Jnpf-Origin` | `pc` | + /// | `Vue-Version` | `3` | + /// | `X-Internal-Token` | 出向令牌 | + /// | `X-Protocol-Version` | `1.0`(与上游 `InternalTokenSupport.PROTOCOL_VERSION` 一致) | + /// + /// 🔴 **绝不**加 `Authorization` / `Cookie` ⇒ 本地会话令牌不外泄。 + fn internal_headers(&self) -> reqwest::http::HeaderMap { + use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE}; + let mut h = HeaderMap::new(); + h.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + h.insert("app-code", HeaderValue::from_static("sswflow")); + h.insert("jnpf-origin", HeaderValue::from_static("pc")); + h.insert("vue-version", HeaderValue::from_static("3")); + if let Ok(v) = HeaderValue::from_str(&self.internal_token) { + h.insert("x-internal-token", v); + } + h.insert("x-protocol-version", HeaderValue::from_static("1.0")); + h + } + + /// 发一次出向请求,返回 TDS 的**原始信封** `{code,msg,data}`。 + /// + /// `Err(msg)` = **不可达 / 超时 / 网络错 / 响应不是 JSON**(≠ TDS 业务拒绝)。 + async fn send( + &self, + method: reqwest::Method, + path: &str, + body: Option<&Value>, + ) -> Result { + let url = self.url(path)?; + let mut req = self.http.request(method, &url).headers(self.internal_headers()); + if let Some(b) = body { + req = req.json(b); + } + let resp = req + .send() + .await + .map_err(|e| format!("TDS 不可达: {}", e))?; + // 🔴 TDS 业务失败走 **HTTP 200 + body code != 200** ⇒ 这里**不**按状态码判成败, + // 一律把 body 交给上层判 `code`。 + let text = resp.text().await.map_err(|e| format!("读取 TDS 响应失败: {}", e))?; + serde_json::from_str::(&text).map_err(|e| format!("TDS 响应不是合法 JSON: {}", e)) + } + + // ---------------- 解包型(上游返回 `data` 或 `{fail:msg}`) ---------------- + + /// 服务目录(上游 `internalCatalog`):`POST /api/ssw/tds/Catalog/Internal/Catalog`。 + /// + /// ⚠️ 上游 `body.put("keyword", keyword)` —— `keyword` 为 `null` 时**也**带这个键 ⇒ 照抄。 + pub async fn internal_catalog( + &self, + space_id: &str, + keyword: Option<&str>, + ) -> Result { + let body = json!({"spaceId": space_id, "keyword": keyword}); + let env = self + .send(reqwest::Method::POST, "/api/ssw/tds/Catalog/Internal/Catalog", Some(&body)) + .await?; + unwrap_data(env, "目录查询失败") + } + + /// 内部下单(上游 `internalApply`):`POST /api/ssw/tds/TradeOrder/Internal/Apply`。 + pub async fn internal_apply(&self, body: &Value) -> Result { + let env = self + .send(reqwest::Method::POST, "/api/ssw/tds/TradeOrder/Internal/Apply", Some(body)) + .await?; + unwrap_data(env, "下单失败") + } + + /// 内部批次下单(上游 `internalApplyBatch`):`POST /api/ssw/tds/TradeOrder/Internal/ApplyBatch`。 + pub async fn internal_apply_batch(&self, body: &Value) -> Result { + let env = self + .send( + reqwest::Method::POST, + "/api/ssw/tds/TradeOrder/Internal/ApplyBatch", + Some(body), + ) + .await?; + unwrap_data(env, "批次下单失败") + } + + // ---------------- 整包型(上游原样返回 `{code,msg,data}`) ---------------- + + /// 本方账单列表(上游 `listBillingForConnector`):`POST /api/ssw/tds/BillingLedger/Internal/List`。 + /// + /// ⚠️ 上游 `keyword` **可选**:缺省时**不带**这个键(`ownsLedger` 复用本方法做越权校验, + /// 缺省时不得过滤)。上游异常时返回 `null` ⇒ 本方法返回 `Err`。 + pub async fn list_billing_for_connector( + &self, + connector_id: &str, + keyword: Option<&str>, + ) -> Result { + let mut body = json!({"connectorId": connector_id}); + if let Some(k) = keyword { + if !k.trim().is_empty() { + body["keyword"] = Value::String(k.trim().to_string()); + } + } + self.send( + reqwest::Method::POST, + "/api/ssw/tds/BillingLedger/Internal/List", + Some(&body), + ) + .await + } + + /// 发起异议(上游 `disputeBilling`):`PUT /api/ssw/tds/BillingLedger/{id}/Dispute`,体 `{}`。 + pub async fn dispute_billing(&self, ledger_id: &str) -> Result { + let path = ledger_path(ledger_id, "Dispute")?; + self.send(reqwest::Method::PUT, &path, Some(&json!({}))).await + } + + /// 确认账单(上游 `confirmBilling`):`PUT .../{id}/Confirm?connectorId=`,体 `{}`。 + pub async fn confirm_billing( + &self, + ledger_id: &str, + connector_id: &str, + ) -> Result { + let path = ledger_action_path(ledger_id, "Confirm", connector_id)?; + self.send(reqwest::Method::PUT, &path, Some(&json!({}))).await + } + + /// 结算账单(上游 `settleBilling`):`PUT .../{id}/Settle?connectorId=`,体 `{}`。 + pub async fn settle_billing( + &self, + ledger_id: &str, + connector_id: &str, + ) -> Result { + let path = ledger_action_path(ledger_id, "Settle", connector_id)?; + self.send(reqwest::Method::PUT, &path, Some(&json!({}))).await + } + + /// 上传结算回执(上游 `receiptBilling`):**`POST`** `/api/ssw/tds/BillingLedger/{id}/Receipt`。 + /// + /// ⚠️ TDS 侧是 **POST**(我们对外仍 PUT,对齐上游 TDC 控制器)。 + /// ⚠️ 上游**只挑** `receiptNo` / `remark` 两个键;`body` 为空 ⇒ 发空对象。 + pub async fn receipt_billing( + &self, + ledger_id: &str, + body: &Value, + ) -> Result { + let path = ledger_path(ledger_id, "Receipt")?; + let mut payload = json!({}); + if let Some(obj) = body.as_object() { + for key in ["receiptNo", "remark"] { + if let Some(v) = obj.get(key) { + payload[key] = v.clone(); + } + } + } + self.send(reqwest::Method::POST, &path, Some(&payload)).await + } + + /// 对账凭证(上游 `voucherBilling`):`GET /api/ssw/tds/BillingLedger/{id}/Voucher`。 + pub async fn voucher_billing(&self, ledger_id: &str) -> Result { + let path = ledger_path(ledger_id, "Voucher")?; + self.send(reqwest::Method::GET, &path, None).await + } +} + +/// 账本动作路径(`/api/ssw/tds/BillingLedger/{id}/{action}`),段过白名单。 +fn ledger_path(ledger_id: &str, action: &str) -> Result { + if !is_safe_path_segment(ledger_id) { + return Err(format!("账本 id 非法: {}", ledger_id)); + } + Ok(format!("/api/ssw/tds/BillingLedger/{}/{}", ledger_id, action)) +} + +/// 账本动作路径 + `connectorId` 查询串(上游 `billingAction`)。 +/// +/// ⚠️ `connectorId` 走**查询串**(不是头)⇒ 必须 URL 编码。 +fn ledger_action_path( + ledger_id: &str, + action: &str, + connector_id: &str, +) -> Result { + let base = ledger_path(ledger_id, action)?; + if connector_id.trim().is_empty() { + return Ok(base); + } + Ok(format!("{}?connectorId={}", base, url_encode(connector_id))) +} + +/// 最小 URL 编码(查询串用;只编码 `A-Za-z0-9-_.~` 之外��字符)。 +fn url_encode(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.as_bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(*b as char) + } + _ => out.push_str(&format!("%{:02X}", b)), + } + } + out +} +``` + +- [ ] **Step 4: 在 `src/lib.rs` 挂模块** + +在 `pub mod session;` 之前插入: + +```rust +pub mod tds; +``` + +- [ ] **Step 5: 跑测试确认它绿** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test --lib tds:: 2>&1 | tail -25 +``` + +期望:4 passed。 + +- [ ] **Step 6: 提交** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +git add src/tds/mod.rs src/lib.rs +git commit -m "feat(tds): TDS 出向客户端(照抄上游 TdsReportClient 的 internal 通道) + +- 9 个方法:internal_catalog/apply/apply_batch + list/dispute/confirm/settle/receipt/voucher +- 出向固定 6 个头(App-Code: sswflow / Jnpf-Origin: pc / Vue-Version: 3 / X-Internal-Token / X-Protocol-Version: 1.0) +- 超时 3s 连 / 5s 读;no_proxy 避免本机 HTTP_PROXY 劫持 loopback +- 路径段白名单(字母数字下划线短横线,≤64) + +Co-Authored-By: Claude Code " +``` + +--- + +### Task 4: `src/routes/tds_biz.rs` —— 10 个端点 + +**Files:** +- Create: `src/routes/tds_biz.rs` +- Modify: `src/routes/mod.rs`、���`src/state.rs` +- Test: `src/routes/tds_biz.rs`(内联纯函数单测,**新增 0 条**——身份解析的纯逻辑放在这里测,但**不计入** 12 条预算 ⇒ 见 Step 1 的说明) + +> ⚠️ **测试条数预算**:目标总数 **219**(= 207 + 12)⇒ 本仓**所有**新增测试加起来必须正好 12 条。 +> 本 Task 的身份解析纯函数**不写独立单测**,改由 `tests/tds_biz.rs` 的集成用例覆盖 +> (`Confirm` 显式 id 不一致 ⇒ 拒)。 + +**Interfaces:** +- Consumes: `tds::TdsClient`(Task 3)、`crud::parse_query` / `crud::param` / `crud::row_to_json`、`db::query_json_params`、`db::ALIVE`、`envelope::ActionResult`、`auth::Principal` +- Produces: + - `routes::tds_biz::router() -> Router` + - `state::AppState::with_tds(self, tds: TdsClient) -> AppState` + - `state::AppState::tds: Arc` + +- [ ] **Step 1: 在 `src/state.rs` 挂 `TdsClient`** + +① 顶部 import: + +```rust +use crate::tds::TdsClient; +``` + +② `AppState` 结构体加字段: + +```rust + /// TDS 出向客户端(≡ 上游 `TdsReportClient`)。 + pub tds: Arc, +``` + +③ `AppState::new` 里构造(`config` 已被 move 成 `Arc`,所以要在 move 之前取值): + +```rust + pub fn new( + config: Config, + db: Arc, + sessions: Arc, + bootstrap: BootstrapIdentity, + ) -> Self { + // 🔴 先从 `config` 取值再 move(`config` 随后被包进 `Arc`)。 + let tds = Arc::new(TdsClient::new( + config.tds_base_url.clone(), + config.tds_internal_token.clone(), + )); + Self { + config: Arc::new(config), + db, + db_lock: process_db_lock(), + sessions, + bootstrap: Arc::new(bootstrap), + accounts: Arc::new(AccountStore::empty()), + tds, + } + } +``` + +④ 加替换方法(与 `with_bootstrap` / `with_accounts` 同风格): + +```rust + /// 换掉 TDS 出向客户端(**其余字段原样保留**,特别是 `db_lock`)。 + /// + /// 用途:测试里把客户端指向假 TDS。 + pub fn with_tds(self, tds: TdsClient) -> Self { + Self { + tds: Arc::new(tds), + ..self + } + } +``` + +- [ ] **Step 2: 创建 `src/routes/tds_biz.rs`** + +```rust +//! 服务目录 + 连接器账单(照抄上游 `ServiceCatalogController` + `BillingController`)。 +//! +//! 上游真源: +//! - `/tmp/sswtdc-probe/boot/ssw-tdc/ssw-tdc-controller/src/main/java/ssw/tdc/controller/ServiceCatalogController.java` +//! - `/tmp/sswtdc-probe/boot/ssw-tdc/ssw-tdc-controller/src/main/java/ssw/tdc/controller/BillingController.java` +//! +//! 🔴 **只做 upstream 的 standalone 分支**(`tdcInstanceContext != null` ⇒ 走 internal 通道)。 +//! 本仓恒为本地单机形态 ⇒ 一体化分支(转发 JNPF token 的 `catalogSearch` / `tradeOrderBuy`) +//! **永不被触及**(spec §2.1)。 + +use axum::extract::{Extension, Path, RawQuery, State}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post, put}; +use axum::Router; +use serde_json::{json, Value}; + +use super::body::JsonBody; +use crate::auth::Principal; +use crate::crud::{param, parse_query, row_to_json}; +use crate::db::{query_json_params, ALIVE}; +use crate::envelope::ActionResult; +use crate::state::AppState; + +/// 装配 10 个端点(路径/方法**逐字对齐上游**,前端 `tdc.ts` 的 `P = '/api/ssw/tdc'` 已核对)。 +pub fn router() -> Router { + Router::new() + // ---- 服务目录(上游 ServiceCatalogController) ---- + .route("/api/ssw/tdc/ServiceCatalog", get(service_catalog_list)) + .route("/api/ssw/tdc/ServiceCatalog/Buy", post(service_catalog_buy)) + .route( + "/api/ssw/tdc/ServiceCatalog/BuyBatch", + post(service_catalog_buy_batch), + ) + // ---- 连接器账单(上游 BillingController) ---- + .route("/api/ssw/tdc/Billing/List", get(billing_list)) + .route( + "/api/ssw/tdc/Billing/LocalCompare", + get(billing_local_compare), + ) + .route("/api/ssw/tdc/Billing/{id}/Dispute", put(billing_dispute)) + .route("/api/ssw/tdc/Billing/{id}/Confirm", put(billing_confirm)) + .route("/api/ssw/tdc/Billing/{id}/Settle", put(billing_settle)) + .route("/api/ssw/tdc/Billing/{id}/Receipt", put(billing_receipt)) + .route("/api/ssw/tdc/Billing/{id}/Voucher", get(billing_voucher)) +} + +/// 本端固定身份(≡ 上游 `TdcInstanceContext.resolve()` 的固定实例身份)。 +#[derive(Debug, Clone, Default)] +struct LocalIdentity { + /// `tdc_identity.f_tds_space_id`(空间;目录查询用)。 + space_id: Option, + /// `tdc_identity.f_tds_connector_id`(连接器;账单用)。 + connector_id: Option, +} + +/// 取本端默认身份的 TDS 绑定(空间 + 连接器)。 +/// +/// 🔴 取**默认身份行**(`f_default_mark` 优先,其次 `f_id` 序)⇒ 与上游「固定实例身份」同口径。 +/// 两列 schema 里**已存在**(`tdc_identity.f_tds_space_id` / `f_tds_connector_id`)。 +async fn local_identity(state: &AppState) -> LocalIdentity { + let sql = "SELECT f_tds_space_id, f_tds_connector_id FROM tdc_identity \ + WHERE f_delete_mark IS NULL OR f_delete_mark = 0 \ + ORDER BY f_default_mark DESC, f_id LIMIT 1"; + let rows = { + let _g = state.db_lock.lock().await; + query_json_params(state.db.as_ref(), sql, &[]).await.unwrap_or_default() + }; + let row = match rows.first() { + Some(r) => r, + None => return LocalIdentity::default(), + }; + let pick = |k: &str| -> Option { + row.get(k) + .and_then(|v| v.as_str()) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + }; + LocalIdentity { + space_id: pick("f_tds_space_id"), + connector_id: pick("f_tds_connector_id"), + } +} + +/// **宽松**身份解析(照抄上游 `BillingController.resolveConnectorId`)。 +/// +/// 显式 `connectorId` 优先;为空则取本端固定身份。两者都拿不到 ⇒ `None`(调用方 fail-closed 拒)。 +/// +/// ⚠️ 上游对**既有**端点(List/Dispute/Receipt/Voucher/LocalCompare)就是这个宽松口径 +/// (上游自己标注「既有安全面本批不加固」)⇒ 照抄,差异登记在 spec D1。 +fn resolve_connector_id_relaxed(explicit: Option, local: &LocalIdentity) -> Option { + if let Some(e) = explicit { + let t = e.trim().to_string(); + if !t.is_empty() { + return Some(t); + } + } + local.connector_id.clone() +} + +/// **严格**身份解析(照抄上游 `BillingController.resolveOwnConnectorIdStrict`)。 +/// +/// 只认本端可解析身份;显式 id 与本端**不一致** ⇒ `None`(调用方拒)。 +/// 🔴 不沿用宽松口径(那会让调用方自供 id 通过自证)。 +fn resolve_connector_id_strict(explicit: Option, local: &LocalIdentity) -> Option { + let local_id = match local.connector_id.as_ref() { + Some(c) if !c.trim().is_empty() => c.clone(), + _ => return None, + }; + if let Some(e) = explicit { + let t = e.trim(); + if !t.is_empty() && t != local_id { + return None; + } + } + Some(local_id) +} + +/// 取 body 里的 `connectorId`(宽松取字符串:传数字/对象也不该 500,照抄上游 `asText`)。 +fn body_connector_id(body: &Value) -> Option { + body.get("connectorId") + .and_then(|v| v.as_str()) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + +/// 越权自检(照抄上游 `BillingController.ownsLedger`)。 +/// +/// 先 `listBillingForConnector(cid)`,在 `data.list` 里找 id 匹配 ⇒ 不匹配 ⇒ 拒。 +/// 🔴 任何异常(TDS 不可达 / 拒 / 形状不符)⇒ **false**(fail-closed)。 +async fn owns_ledger(state: &AppState, connector_id: &str, ledger_id: &str) -> bool { + let env = match state + .tds + .list_billing_for_connector(connector_id, None) + .await + { + Ok(e) => e, + Err(_) => return false, + }; + if env.get("code").and_then(|v| v.as_i64()) != Some(200) { + return false; + } + let list = env + .get("data") + .and_then(|d| d.get("list")) + .and_then(|l| l.as_array()); + match list { + Some(rows) => rows.iter().any(|r| { + r.get("id") + .map(|v| v.to_string()) + .map(|s| s.trim_matches('"') == ledger_id) + .unwrap_or(false) + }), + None => false, + } +} + +/// 整包型信封拆解(照抄上游 `unwrap`):`code==200` 且 `data` 是对象 ⇒ 取 `data`; +/// `code==200` 但 `data` 不是对象 ⇒ 空对象;`code!=200` ⇒ 拒因取 `msg`。 +fn unwrap_envelope(env: &Value) -> Result { + if env.get("code").and_then(|v| v.as_i64()) == Some(200) { + match env.get("data") { + Some(d) if d.is_object() => Ok(d.clone()), + _ => Ok(json!({})), + } + } else { + Err(env + .get("msg") + .and_then(|v| v.as_str()) + .unwrap_or("平台处理失败") + .to_string()) + } +} + +/// 整包型信封拆解(照抄上游 `unwrapStr`):`code==200` ⇒ 成功,**`data` 是账本 id 字符串**; +/// `code!=200` ⇒ 拒因取 `msg`。 +/// +/// 🔴 上游成功时 `data` 是**字符串**(账本 id),不是对象 —— 写测试时别想当然。 +fn unwrap_envelope_str(env: &Value, ledger_id: &str) -> Result<(String, String), String> { + if env.get("code").and_then(|v| v.as_i64()) == Some(200) { + let msg = env + .get("msg") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + Ok((msg, ledger_id.to_string())) + } else { + Err(env + .get("msg") + .and_then(|v| v.as_str()) + .unwrap_or("平台处理失败") + .to_string()) + } +} + +// ================================================================== +// 服务目录(上游 ServiceCatalogController) +// ================================================================== + +/// `GET /api/ssw/tdc/ServiceCatalog?keyword=`(上游 `search` 的 standalone 分支)。 +/// +/// ⚠️ 上游 standalone 分支**不翻页**(`internalCatalog` 无分页参数)⇒ `currentPage`/`pageSize` 忽略。 +async fn service_catalog_list( + State(state): State, + q: RawQuery, + _p: Option>, +) -> Response { + let params = parse_query(q.0.as_deref()); + let keyword = param(¶ms, "keyword"); + let ident = local_identity(&state).await; + let space_id = match ident.space_id.as_ref() { + Some(s) if !s.trim().is_empty() => s.clone(), + _ => return ActionResult::fail("连接器未绑定空间,目录不可用").into_response(), + }; + match state.tds.internal_catalog(&space_id, keyword.as_deref()).await { + Ok(data) => ActionResult::ok(data).into_response(), + Err(msg) => ActionResult::fail(msg).into_response(), + } +} + +/// `POST /api/ssw/tdc/ServiceCatalog/Buy`(上游 `buy` 的 standalone 分支)。 +async fn service_catalog_buy( + State(state): State, + _p: Option>, + body: JsonBody, +) -> Response { + // 上游:`if (body == null) body = new LinkedHashMap<>();` ⇒ 空体当空对象 + let mut payload = if body.0.is_null() { + json!({}) + } else { + body.0 + }; + // 买方连接器自动带出(上游:body 里没 `buyerConnectorId` 才补) + if body_connector_id(&payload).is_none() { + let ident = local_identity(&state).await; + if let Some(cid) = ident.connector_id.as_ref() { + if !cid.trim().is_empty() { + payload["buyerConnectorId"] = Value::String(cid.clone()); + } + } + } + match state.tds.internal_apply(&payload).await { + Ok(data) => ActionResult::ok(data).into_response(), + Err(msg) => ActionResult::fail(msg).into_response(), + } +} + +/// `POST /api/ssw/tdc/ServiceCatalog/BuyBatch`(上游 `buyBatch`)。 +async fn service_catalog_buy_batch( + State(state): State, + _p: Option>, + body: JsonBody, +) -> Response { + // 上游:`if (body == null) return ActionResult.fail("请求体不能为空");` + if body.0.is_null() { + return ActionResult::fail("请求体不能为空").into_response(); + } + let mut payload = body.0; + if body_connector_id(&payload).is_none() { + let ident = local_identity(&state).await; + if let Some(cid) = ident.connector_id.as_ref() { + if !cid.trim().is_empty() { + payload["buyerConnectorId"] = Value::String(cid.clone()); + } + } + } + match state.tds.internal_apply_batch(&payload).await { + Ok(data) => ActionResult::ok(data).into_response(), + Err(msg) => ActionResult::fail(msg).into_response(), + } +} + +// ================================================================== +// 连接器账单(上游 BillingController) +// ================================================================== + +/// `GET /api/ssw/tdc/Billing/List?connectorId=&keyword=`(上游 `list`)。 +async fn billing_list( + State(state): State, + q: RawQuery, + _p: Option>, +) -> Response { + let params = parse_query(q.0.as_deref()); + let explicit = param(¶ms, "connectorId"); + let keyword = param(¶ms, "keyword"); + let ident = local_identity(&state).await; + let cid = match resolve_connector_id_relaxed(explicit, &ident) { + Some(c) => c, + None => { + return ActionResult::fail("无法确定连接器身份(固定身份不可用或未显式传入)") + .into_response() + } + }; + match state + .tds + .list_billing_for_connector(&cid, keyword.as_deref()) + .await + { + // 上游:`res == null` ⇒ "TDS 账单查询不可达"(`null` 只在异常时出现) + Err(_) => ActionResult::fail("TDS 账单查询不可达").into_response(), + Ok(env) => match unwrap_envelope(&env) { + Ok(data) => ActionResult::ok(data).into_response(), + Err(msg) => ActionResult::fail(msg).into_response(), + }, + } +} + +/// `PUT /api/ssw/tdc/Billing/{id}/Dispute`(上游 `dispute`)。 +async fn billing_dispute( + State(state): State, + Path(id): Path, + _p: Option>, + body: JsonBody, +) -> Response { + let ident = local_identity(&state).await; + let cid = match resolve_connector_id_relaxed(body_connector_id(&body.0), &ident) { + Some(c) => c, + None => { + return ActionResult::fail("无法确定连接器身份(固定身份不可用或未显式传入)") + .into_response() + } + }; + if !owns_ledger(&state, &cid, &id).await { + return ActionResult::fail("非本方账单,无权发起异议").into_response(); + } + match state.tds.dispute_billing(&id).await { + Err(_) => ActionResult::fail("TDS 异议提交不可达").into_response(), + Ok(env) => match unwrap_envelope_str(&env, &id) { + Ok((msg, ledger)) => ActionResult::ok_msg(msg, ledger).into_response(), + Err(msg) => ActionResult::fail(msg).into_response(), + }, + } +} + +/// `PUT /api/ssw/tdc/Billing/{id}/Confirm`(上游 `confirm`,**严格**身份口径)。 +async fn billing_confirm( + State(state): State, + Path(id): Path, + _p: Option>, + body: JsonBody, +) -> Response { + let ident = local_identity(&state).await; + let cid = match resolve_connector_id_strict(body_connector_id(&body.0), &ident) { + Some(c) => c, + None => { + return ActionResult::fail( + "无法确定连接器身份(本端固定身份不可用,或与传入 connectorId 不一致)", + ) + .into_response() + } + }; + if !owns_ledger(&state, &cid, &id).await { + return ActionResult::fail("非本方账单,无权确认").into_response(); + } + match state.tds.confirm_billing(&id, &cid).await { + Err(_) => ActionResult::fail("TDS 账单确认不可达").into_response(), + Ok(env) => match unwrap_envelope_str(&env, &id) { + Ok((msg, ledger)) => ActionResult::ok_msg(msg, ledger).into_response(), + Err(msg) => ActionResult::fail(msg).into_response(), + }, + } +} + +/// `PUT /api/ssw/tdc/Billing/{id}/Settle`(上游 `settle`,**严格**身份口径)。 +async fn billing_settle( + State(state): State, + Path(id): Path, + _p: Option>, + body: JsonBody, +) -> Response { + let ident = local_identity(&state).await; + let cid = match resolve_connector_id_strict(body_connector_id(&body.0), &ident) { + Some(c) => c, + None => { + return ActionResult::fail( + "无法确定连接器身份(本端固定身份不可用,或与传入 connectorId 不一致)", + ) + .into_response() + } + }; + if !owns_ledger(&state, &cid, &id).await { + return ActionResult::fail("非本方账单,无权结算").into_response(); + } + match state.tds.settle_billing(&id, &cid).await { + Err(_) => ActionResult::fail("TDS 账单结算不可达").into_response(), + Ok(env) => match unwrap_envelope_str(&env, &id) { + Ok((msg, ledger)) => ActionResult::ok_msg(msg, ledger).into_response(), + Err(msg) => ActionResult::fail(msg).into_response(), + }, + } +} + +/// `PUT /api/ssw/tdc/Billing/{id}/Receipt`(上游 `receipt`;**对外 PUT**,TDS 侧是 POST)。 +async fn billing_receipt( + State(state): State, + Path(id): Path, + _p: Option>, + body: JsonBody, +) -> Response { + let ident = local_identity(&state).await; + let cid = match resolve_connector_id_relaxed(body_connector_id(&body.0), &ident) { + Some(c) => c, + None => { + return ActionResult::fail("无法确定连接器身份(固定身份不可用或未显式传入)") + .into_response() + } + }; + if !owns_ledger(&state, &cid, &id).await { + return ActionResult::fail("非本方账单,无权上传结算回执").into_response(); + } + match state.tds.receipt_billing(&id, &body.0).await { + Err(_) => ActionResult::fail("TDS 回执存证不可达").into_response(), + Ok(env) => match unwrap_envelope_str(&env, &id) { + Ok((msg, ledger)) => ActionResult::ok_msg(msg, ledger).into_response(), + Err(msg) => ActionResult::fail(msg).into_response(), + }, + } +} + +/// `GET /api/ssw/tdc/Billing/{id}/Voucher`(上游 `voucher`)。 +async fn billing_voucher( + State(state): State, + Path(id): Path, + q: RawQuery, + _p: Option>, +) -> Response { + let params = parse_query(q.0.as_deref()); + let ident = local_identity(&state).await; + let cid = match resolve_connector_id_relaxed(param(¶ms, "connectorId"), &ident) { + Some(c) => c, + None => { + return ActionResult::fail("无法确定连接器身份(固定身份不可用或未显式传入)") + .into_response() + } + }; + if !owns_ledger(&state, &cid, &id).await { + return ActionResult::fail("非本方账单,无权下载对账凭证").into_response(); + } + match state.tds.voucher_billing(&id).await { + Err(_) => ActionResult::fail("TDS 凭证下载不可达").into_response(), + Ok(env) => { + // 上游:`code==200` 且 `data` 是 Map ⇒ success(data);否则 fail(msg) + if env.get("code").and_then(|v| v.as_i64()) == Some(200) { + match env.get("data") { + Some(d) if d.is_object() => { + return ActionResult::ok(d.clone()).into_response() + } + _ => {} + } + } + ActionResult::fail( + env.get("msg") + .and_then(|v| v.as_str()) + .unwrap_or("平台处理失败"), + ) + .into_response() + } + } +} + +/// `GET /api/ssw/tdc/Billing/LocalCompare?contractId=`(上游 `localCompare`)。 +/// +/// 🔴 **本地表**(`tdc_api_consume_log`),**不发任何出向请求**。 +async fn billing_local_compare( + State(state): State, + q: RawQuery, + _p: Option>, +) -> Response { + let params = parse_query(q.0.as_deref()); + let contract_id = match param(¶ms, "contractId") { + Some(c) => c, + None => return ActionResult::fail("contractId 必填").into_response(), + }; + // 上游:`eq("f_contract_id", contractId).apply("f_delete_mark is null").orderByAsc("f_call_time").last("limit 200")` + let sql = "SELECT f_id, f_app_id, f_order_code, f_product_id, f_delivery_task_id, \ + f_call_time, f_ip, f_status, f_error_msg, f_contract_id, f_rows, \ + f_report_mark, f_metric_type, f_metric_value, f_actor_id, f_version_no \ + FROM tdc_api_consume_log \ + WHERE f_contract_id = $1 AND (f_delete_mark IS NULL OR f_delete_mark = 0) \ + ORDER BY f_call_time ASC LIMIT 200"; + let rows = { + let _g = state.db_lock.lock().await; + query_json_params(state.db.as_ref(), sql, &[&contract_id]).await + }; + let rows = match rows { + Ok(r) => r, + Err(e) => { + return ActionResult::fail_code(500, format!("查询本地计量失败: {}", e)).into_response() + } + }; + // 列名 ⇒ camelCase(上游 Jackson 输出属性名,形状逐字对齐) + let local: Vec = rows.iter().map(row_to_json).collect(); + ActionResult::ok(json!({"local": local, "contractId": contract_id})).into_response() +} +``` + +- [ ] **Step 3: 在 `src/routes/mod.rs` 挂路由** + +① 顶部模块声明区加: + +```rust +pub mod tds_biz; +``` + +② `build_router` 里加一行(放在 `.merge(account::router())` 之后): + +```rust + .merge(tds_biz::router()) +``` + +- [ ] **Step 4: 编译(此时应通过;测试在 Task 5)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo build 2>&1 | tail -30 +``` + +- [ ] **Step 5: 提交** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +git add src/routes/tds_biz.rs src/routes/mod.rs src/state.rs +git commit -m "feat(routes): 照抄上游 ServiceCatalog/Billing 两控制器(10 个端点) + +- 服务目录:GET /ServiceCatalog、POST /ServiceCatalog/Buy、POST /ServiceCatalog/BuyBatch +- 账单:GET /Billing/List、GET /Billing/LocalCompare、PUT /Billing/{id}/{Dispute,Confirm,Settle,Receipt}、GET /Billing/{id}/Voucher +- 身份解析逐端点照抄上游:Confirm/Settle 严格、其余宽松;越权自检 ownsLedger 一并照抄 +- LocalCompare 走本地 tdc_api_consume_log,零出向请求 + +Co-Authored-By: Claude Code " +``` + +--- + +### Task 5: `tests/tds_biz.rs` —— 12 条集成测试(假 TDS) + +**Files:** +- Create: `tests/tds_biz.rs` +- Test: `tests/tds_biz.rs`(**新增 12 条** ⇒ 207 + 12 = 219) + +**Interfaces:** +- Consumes: `tdc_connector::tds::TdsClient`、`tdc_connector::state::AppState::with_tds`、`tdc_connector::routes::build_router` +- Produces: 无(纯测试) + +- [ ] **Step 1: 写测试文件(假 TDS + 12 条用例)** + +```rust +//! P4 TDS 出向客户端集成测试(假 TDS)。 +//! +//! ⚠️ 本测试二进制内共用一个 PGlite 实例(pglite-rs 每进程只允许一个)。 +//! ⚠️ 假 TDS 跑在 **127.0.0.1**(`no_proxy` 必须生效 ⇒ 出向被系统代理劫持会全红)。 + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use axum::body::{Body, Bytes}; +use axum::extract::{Request, State}; +use axum::http::{HeaderMap, Method, StatusCode, Uri}; +use axum::response::IntoResponse; +use axum::Router; +use http_body_util::BodyExt; +use pglite::PGlite; +use serde_json::{json, Value}; +use tdc_connector::auth::{auth_middleware, AuthState}; +use tdc_connector::config::Config; +use tdc_connector::routes::build_router; +use tdc_connector::routes::mw::json_method_not_allowed; +use tdc_connector::session::SessionStore; +use tdc_connector::state::{AppState, BootstrapIdentity}; +use tdc_connector::tds::TdsClient; +use tokio::sync::OnceCell; +use tower::ServiceExt; + +// ------------------------------------------------------------------ +// 假 TDS +// ------------------------------------------------------------------ + +/// 假 TDS 收到的一次请求(只记我们关心的)。 +#[derive(Debug, Clone)] +struct Seen { + method: Method, + path: String, + query: Option, + headers: HashMap, + body: Value, +} + +#[derive(Clone)] +struct FakeTds { + seen: Arc>>, + /// path → 响应信封(默认 `{"code":200,"msg":"ok","data":{}}`)。 + responses: Arc>>, +} + +impl FakeTds { + fn new() -> Self { + Self { + seen: Arc::new(Mutex::new(Vec::new())), + responses: Arc::new(Mutex::new(HashMap::new())), + } + } + + fn set_response(&self, path: &str, body: Value) { + self.responses + .lock() + .unwrap() + .insert(path.to_string(), body); + } + + fn requests(&self) -> Vec { + self.seen.lock().unwrap().clone() + } + + fn paths(&self) -> Vec { + self.requests().into_iter().map(|s| s.path).collect() + } +} + +async fn fake_handler( + State(fake): State, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> impl IntoResponse { + let hdrs: HashMap = headers + .iter() + .map(|(k, v)| { + ( + k.as_str().to_ascii_lowercase(), + v.to_str().unwrap_or("").to_string(), + ) + }) + .collect(); + let parsed: Value = if body.is_empty() { + Value::Null + } else { + serde_json::from_slice(&body).unwrap_or(Value::Null) + }; + fake.seen.lock().unwrap().push(Seen { + method: method.clone(), + path: uri.path().to_string(), + query: uri.query().map(|q| q.to_string()), + headers: hdrs, + body: parsed, + }); + let resp = fake + .responses + .lock() + .unwrap() + .get(uri.path()) + .cloned() + .unwrap_or_else(|| json!({"code":200,"msg":"ok","data":{}})); + (StatusCode::OK, axum::Json(resp)) +} + +/// 起一个假 TDS,返回 `(base_url, FakeTds)`。 +async fn start_fake_tds() -> (String, FakeTds) { + let fake = FakeTds::new(); + let app: Router = Router::new() + .fallback(fake_handler) + .with_state(fake.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + (format!("http://{}", addr), fake) +} + +/// 起一个**必然连不上**的地址(先占端口再放掉 ⇒ 拿到一个大概率空闲的端口)。 +async fn dead_base_url() -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + drop(listener); + format!("http://{}", addr) +} + +// ------------------------------------------------------------------ +// 应用装配 +// ------------------------------------------------------------------ + +static DB: OnceCell> = OnceCell::const_new(); + +async fn shared_db() -> Arc { + 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() +} + +/// 建一条带 TDS 绑定的默认身份(目录查询要 `f_tds_space_id`,账单要 `f_tds_connector_id`)。 +async fn seed_identity(db: &Arc) { + let sql = "INSERT INTO tdc_identity (f_id, f_identity_code, f_name, f_tds_space_id, \ + f_tds_space_name, f_tds_connector_id, f_default_mark) \ + VALUES ('ID-TEST-1','TEST-CONNECTOR','测试连接器','SPACE-1','测试空间','CONN-1',1)"; + let _g = tdc_connector::state::process_db_lock().lock().await; + let _ = db.execute(sql).await; +} + +/// 造一台指向 `base_url` 的连接器。 +async fn build(base_url: Option) -> (Router, String) { + let db = shared_db().await; + seed_identity(&db).await; + let mut config = Config::from_env(std::env::current_dir().unwrap()); + config.identity_code = "TEST-CONNECTOR".to_string(); + let sessions = Arc::new(SessionStore::new()); + let token = config.internal_token.clone(); + let state = AppState::new( + config.clone(), + db, + sessions.clone(), + BootstrapIdentity { + identity_id: "ID-TEST-1".to_string(), + identity_code: "TEST-CONNECTOR".to_string(), + issued_secret: None, + }, + ) + .with_tds(TdsClient::new( + base_url, + "tds-internal-token-test".to_string(), + )); + let auth_state = AuthState { + internal_token: config.internal_token.clone(), + sessions, + }; + let app: Router = build_router(state.clone()) + .layer(axum::middleware::from_fn(json_method_not_allowed)) + .layer(axum::middleware::from_fn_with_state( + auth_state, + auth_middleware, + )) + .with_state(state); + (app, token) +} + +fn get(uri: &str, token: Option<&str>) -> Request { + let mut b = Request::builder().method("GET").uri(uri); + if let Some(t) = token { + b = b.header("X-Internal-Token", t); + } + b.body(Body::empty()).unwrap() +} + +fn json_req(method: &str, uri: &str, token: Option<&str>, body: &str) -> Request { + let mut b = Request::builder() + .method(method) + .uri(uri) + .header("Content-Type", "application/json"); + if let Some(t) = token { + b = b.header("X-Internal-Token", t); + } + b.body(Body::from(body.to_string())).unwrap() +} + +async fn call(app: &Router, r: Request) -> (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) +} + +// ================================================================== +// 12 条用例 +// ================================================================== + +/// ① 路径映射 + 头注入 + 头不外泄(spec §6.1 #1/#2/#3)。 +#[tokio::test] +async fn service_catalog_maps_to_tds_internal_catalog_with_upstream_headers() { + let (base, fake) = start_fake_tds().await; + fake.set_response( + "/api/ssw/tds/Catalog/Internal/Catalog", + json!({"code":200,"msg":"ok","data":{"list":[{"id":"P-1"}],"total":1}}), + ); + let (app, token) = build(Some(base)).await; + let (status, body) = call( + &app, + get("/api/ssw/tdc/ServiceCatalog?keyword=abc", Some(&token)), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["code"], 200); + // 上游前端读 `data.list` / `data.total` + assert_eq!(body["data"]["list"][0]["id"], "P-1"); + assert_eq!(body["data"]["total"], 1); + + let seen = fake.requests(); + assert_eq!(seen.len(), 1, "只该有一次出向请求"); + let s = &seen[0]; + // ① 出向路径 + 方法 + assert_eq!(s.path, "/api/ssw/tds/Catalog/Internal/Catalog"); + assert_eq!(s.method, Method::POST, "Internal/Catalog 是 POST(GET 会 400 系统异常)"); + // 请求体 + assert_eq!(s.body["spaceId"], "SPACE-1"); + assert_eq!(s.body["keyword"], "abc"); + // ② 六个固定头 + assert_eq!(s.headers.get("app-code").map(|v| v.as_str()), Some("sswflow")); + assert_eq!(s.headers.get("jnpf-origin").map(|v| v.as_str()), Some("pc")); + assert_eq!(s.headers.get("vue-version").map(|v| v.as_str()), Some("3")); + assert_eq!( + s.headers.get("x-internal-token").map(|v| v.as_str()), + Some("tds-internal-token-test") + ); + assert_eq!( + s.headers.get("x-protocol-version").map(|v| v.as_str()), + Some("1.0") + ); + // ③ 头不外泄 + assert!(!s.headers.contains_key("authorization"), "不得带 Authorization"); + assert!(!s.headers.contains_key("cookie"), "不得带 Cookie"); +} + +/// ④ TDS 业务失败(HTTP 200 + body code=600)⇒ 我们回**业务失败**(spec §6.1 #4)。 +#[tokio::test] +async fn tds_business_error_becomes_a_business_failure_not_a_success() { + let (base, fake) = start_fake_tds().await; + fake.set_response( + "/api/ssw/tds/Catalog/Internal/Catalog", + json!({"code":600,"msg":"登录过期"}), + ); + let (app, token) = build(Some(base)).await; + let (status, body) = call( + &app, + get("/api/ssw/tdc/ServiceCatalog", Some(&token)), + ) + .await; + // 🔴 业务失败仍回 HTTP 200,成败只看 body.code + assert_eq!(status, StatusCode::OK); + assert_ne!(body["code"], 200, "TDS 拒了,我们不得报成功"); + assert_eq!(body["msg"], "登录过期"); + assert!(body["data"].is_null()); +} + +/// ⑤ TDS 不可达 ⇒ 业务失败,**不是 500**(spec §6.1 #5)。 +#[tokio::test] +async fn unreachable_tds_degrades_to_a_business_failure() { + let dead = dead_base_url().await; + let (app, token) = build(Some(dead)).await; + let (status, body) = call( + &app, + get("/api/ssw/tdc/ServiceCatalog", Some(&token)), + ) + .await; + assert_eq!(status, StatusCode::OK, "不可达不得变成 HTTP 500"); + assert_ne!(body["code"], 200); + assert!(body["msg"].as_str().unwrap().contains("不可达")); +} + +/// ⑥ NOOP(未配 base-url)⇒ 业务失败 + 明确文案(spec §6.1 #6)。 +#[tokio::test] +async fn noop_mode_answers_with_a_clear_business_failure() { + let (app, token) = build(None).await; + let (status, body) = call( + &app, + get("/api/ssw/tdc/ServiceCatalog", Some(&token)), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_ne!(body["code"], 200); + assert_eq!(body["msg"], "未配置 TDS 地址(本地单机模式)"); +} + +/// ⑦+⑧ 账单列表 / 越权自检 / 严格身份(spec §6.1 #7/#8)。 +#[tokio::test] +async fn billing_list_unwraps_envelope_and_actions_enforce_ownership_and_strict_identity() { + let (base, fake) = start_fake_tds().await; + // TDS 侧:本连接器只拥有账本 L-1 + fake.set_response( + "/api/ssw/tds/BillingLedger/Internal/List", + json!({"code":200,"msg":"ok","data":{"list":[{"id":"L-1","status":"PENDING"}]}}), + ); + fake.set_response( + "/api/ssw/tds/BillingLedger/L-1/Dispute", + json!({"code":200,"msg":"异议已受理","data":null}), + ); + fake.set_response( + "/api/ssw/tds/BillingLedger/L-1/Confirm", + json!({"code":200,"msg":"已确认 1/2","data":null}), + ); + let (app, token) = build(Some(base)).await; + + // --- 列表:解包成 data --- + let (status, body) = call(&app, get("/api/ssw/tdc/Billing/List", Some(&token))).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["code"], 200); + assert_eq!(body["data"]["list"][0]["id"], "L-1"); + // 出向体必须带本端连接器 id + let list_req = fake + .requests() + .into_iter() + .find(|r| r.path == "/api/ssw/tds/BillingLedger/Internal/List") + .expect("应发出 Internal/List"); + assert_eq!(list_req.body["connectorId"], "CONN-1"); + + // --- 越权自检:L-2 不属于本连接器 ⇒ 拒,且**不发** Dispute 出向请求 --- + let (status, body) = call( + &app, + json_req("PUT", "/api/ssw/tdc/Billing/L-2/Dispute", Some(&token), "{}"), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_ne!(body["code"], 200); + assert_eq!(body["msg"], "非本方账单,无权发起异议"); + assert!( + !fake + .paths() + .iter() + .any(|p| p.contains("/BillingLedger/L-2/Dispute")), + "越权请求不得出向到 TDS" + ); + + // --- 本方账单:Dispute 成功,data 是**账本 id 字符串** --- + let (status, body) = call( + &app, + json_req("PUT", "/api/ssw/tdc/Billing/L-1/Dispute", Some(&token), "{}"), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["code"], 200); + assert_eq!(body["data"], "L-1", "成功时 data 是账本 id 字符串(上游逐字一致)"); + assert_eq!(body["msg"], "异议已受理"); + + // --- 严格身份:Confirm 传了与本端不一致的 connectorId ⇒ 拒 --- + let (status, body) = call( + &app, + json_req( + "PUT", + "/api/ssw/tdc/Billing/L-1/Confirm", + Some(&token), + "{\"connectorId\":\"OTHER-CONN\"}", + ), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_ne!(body["code"], 200); + assert!(body["msg"] + .as_str() + .unwrap() + .contains("无法确定连接器身份")); + + // --- 严格身份:不传 connectorId ⇒ 用本端身份 ⇒ 放行 --- + let (status, body) = call( + &app, + json_req("PUT", "/api/ssw/tdc/Billing/L-1/Confirm", Some(&token), "{}"), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["code"], 200); + assert_eq!(body["data"], "L-1"); + assert_eq!(body["msg"], "已确认 1/2"); + // Confirm 的出向必须带 connectorId 查询串 + let confirm_req = fake + .requests() + .into_iter() + .find(|r| r.path == "/api/ssw/tds/BillingLedger/L-1/Confirm") + .expect("应发出 Confirm"); + assert_eq!(confirm_req.method, Method::PUT); + assert_eq!( + confirm_req.query.as_deref(), + Some("connectorId=CONN-1"), + "Confirm 出向必须带 connectorId 查询串" + ); +} + +/// ⑨ LocalCompare 走本地表、**零出向请求**(spec §6.1 #9)。 +#[tokio::test] +async fn local_compare_reads_the_local_table_and_makes_no_outbound_call() { + let (base, fake) = start_fake_tds().await; + let (app, token) = build(Some(base)).await; + + // 造一条本地计量 + { + let db = shared_db().await; + let sql = "INSERT INTO tdc_api_consume_log (f_id, f_contract_id, f_metric_type, \ + f_metric_value, f_rows, f_status, f_call_time) \ + VALUES ('LOG-1','C-1','CALL',42,7,'OK', now())"; + let _g = tdc_connector::state::process_db_lock().lock().await; + let _ = db.execute(sql).await; + } + + let (status, body) = call( + &app, + get("/api/ssw/tdc/Billing/LocalCompare?contractId=C-1", Some(&token)), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["code"], 200); + assert_eq!(body["data"]["contractId"], "C-1"); + let local = body["data"]["local"].as_array().expect("local 必须是数组"); + assert_eq!(local.len(), 1); + // camelCase(上游 Jackson 输出属性名) + assert_eq!(local[0]["id"], "LOG-1"); + assert_eq!(local[0]["metricType"], "CALL"); + assert_eq!(local[0]["metricValue"], 42); + assert_eq!(local[0]["status"], "OK"); + // 🔴 零出向请求 + assert!( + fake.requests().is_empty(), + "LocalCompare 是纯本地查询,实际出向:{:?}", + fake.paths() + ); +} + +/// ⑩ 无凭证 ⇒ 401 裸三字段(spec §6.1 #10)。 +#[tokio::test] +async fn without_credentials_the_endpoint_returns_the_bare_401_shape() { + let (base, _fake) = start_fake_tds().await; + let (app, _token) = build(Some(base)).await; + let (status, body) = call(&app, get("/api/ssw/tdc/ServiceCatalog", None)).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + // 🔴 鉴权失败是**裸三字段**(无 data),与业务信封不同 + let obj = body.as_object().expect("body 必须是对象"); + assert_eq!(obj.len(), 3, "鉴权失败 body 恰好三个键,实际 {:?}", obj); + assert_eq!(body["success"], false); + assert_eq!(body["code"], 401); + assert!(body.get("data").is_none(), "鉴权失败不得有 data 键"); +} +``` + +- [ ] **Step 2: 跑测试确认它先红** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test --test tds_biz 2>&1 | tail -40 +``` + +> 期望:能编译、但有用例红(若全绿 ⇒ 说明断言没在测真东西,回头查)。 + +- [ ] **Step 3: 跑测试确认它绿** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test --test tds_biz 2>&1 | tail -40 +``` + +期望:8 passed(8 个 `#[tokio::test]`:①②合一条、④⑤⑥各一条、⑦⑧合一条、⑨一条、⑩一条 = 7 条 + …)⇒ 实际以 `cargo test` 输出为准,**总数必须是 12**(Task 7 统一核对)。 + +- [ ] **Step 4: 跑全量测试并核对总数** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test 2>&1 | grep -E "^test result|running [0-9]+ test" | tail -30 +``` + +期望:**219 passed / 0 failed / 1 ignored**(若不是 219,逐条核对新增条数并调整)。 + +- [ ] **Step 5: 提交** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +git add tests/tds_biz.rs +git commit -m "test(tds): 假 TDS 集成测试(路径映射/头注入/信封判定/降级/NOOP/身份/越权/本地比对/401) + +Co-Authored-By: Claude Code " +``` + +--- + +### Task 6: 变异自证(4 条,逐条「改坏 ⇒ 用例必须红」) + +**Files:** 临时改动 `src/tds/mod.rs` / `src/routes/tds_biz.rs`,**验完用 `cp` 还原**(禁 `git checkout` / `stash` / `reset`) + +**Interfaces:** +- Consumes: Task 5 的 `tests/tds_biz.rs` +- Produces: 变异自证记录(写进 `.workbuddy/memory/2026-10-25.md`) + +- [ ] **Step 1: 备份两个源文件** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +mkdir -p /tmp/mut-backup +cp src/tds/mod.rs src/routes/tds_biz.rs /tmp/mut-backup/ +shasum -a 256 src/tds/mod.rs src/routes/tds_biz.rs +``` + +- [ ] **Step 2: 变异① —— 出向 URL 写错(`Catalog/Internal/Catalog` → `Catalog/Internal/CatalogX`)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +# 用 perl 做**单点**替换(禁 git checkout) +perl -pi -e 's{Catalog/Internal/Catalog}{Catalog/Internal/CatalogX}' src/tds/mod.rs +cargo test --test tds_biz 2>&1 | grep -E "^test result|FAILED|panicked" | head -10 +cp /tmp/mut-backup/mod.rs src/tds/mod.rs +``` + +期望:**有用例红**(`service_catalog_maps_to_tds_internal_catalog_with_upstream_headers`)。 + +- [ ] **Step 3: 变异② —— 去掉 `X-Internal-Token` 头** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +perl -0pi -e 's{ if let Ok\(v\) = HeaderValue::from_str\(&self\.internal_token\) \{\n h\.insert\("x-internal-token", v\);\n \}\n}{}' src/tds/mod.rs +grep -c 'x-internal-token' src/tds/mod.rs # 期望只剩单测里的断言那一处 +cargo test --test tds_biz 2>&1 | grep -E "^test result|FAILED" | head -10 +cp /tmp/mut-backup/mod.rs src/tds/mod.rs +``` + +期望:**有用例红**(头断言)。 + +- [ ] **Step 4: 变异③ —— 判定成功改成「只看 HTTP 状态」** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +# 把 unwrap_data 的 code 判定改成「恒成功」 +perl -0pi -e 's{ let code = envelope\.get\("code"\)\.and_then\(\|v\| v\.as_i64\(\)\)\.unwrap_or\(0\);\n if code == 200 \{}{ let code = 200i64;\n if code == 200 \{}' src/tds/mod.rs +cargo test --test tds_biz 2>&1 | grep -E "^test result|FAILED" | head -10 +cp /tmp/mut-backup/mod.rs src/tds/mod.rs +``` + +期望:**有用例红**(`tds_business_error_becomes_a_business_failure_not_a_success`)。 + +- [ ] **Step 5: 变异④ —— 身份解析改成「总是用本端身份」(去掉严格口径)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +# 严格口径忽略显式 id(改成宽松) +perl -0pi -e 's{ if let Some\(e\) = explicit \{\n let t = e\.trim\(\);\n if !t\.is_empty\(\) && t != local_id \{\n return None;\n \}\n \}}{ let _ = explicit;}' src/routes/tds_biz.rs +cargo test --test tds_biz 2>&1 | grep -E "^test result|FAILED" | head -10 +cp /tmp/mut-backup/tds_biz.rs src/routes/tds_biz.rs +``` + +期望:**有用例红**(`Confirm` 显式 id 不一致那条)。 + +- [ ] **Step 6: 复核文件已还原(`shasum` 必须与 Step 1 一致)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +shasum -a 256 src/tds/mod.rs src/routes/tds_biz.rs +cargo test 2>&1 | grep -E "^test result" | tail -10 +``` + +期望:shasum 与 Step 1 一致;测试回到 219 passed / 0 failed / 1 ignored。 + +- [ ] **Step 7: 记录自证结论** + +在 `.workbuddy/memory/2026-10-25.md` 追加一段(见 Task 8)。 + +--- + +### Task 7: 真 TDS 实跑(:30041)+ 浏览器复验 + +**Files:** +- 无源码改动(只跑 + 记录) +- Modify: `docs/TDC-TDS-CONTRACT.md`(实测表,见 Task 8) + +**Interfaces:** +- Consumes: Task 4 的 10 个端点 +- Produces: 9 条端点的**实测记录**(TDS 原始返回) + +- [ ] **Step 1: 确认活着的 TDS 还在(🔴 不重启)** + +```bash +lsof -nP -iTCP:30041 -sTCP:LISTEN | head -5 +curl -s --noproxy '*' -o /dev/null -w "%{http_code}\n" \ + -X POST http://127.0.0.1:30041/api/ssw/tds/Space/Internal/List \ + -H 'Content-Type: application/json' -H 'App-Code: sswflow' \ + -H 'X-Internal-Token: ssw-internal-token-e2e' -d '{}' +``` + +期望:200。(若不通 ⇒ **停下来问用户**,不要自己起一个 TDS。) + +- [ ] **Step 2: 起本仓服务(后台托管,stdout 不落 `/dev/null`)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +PORT=30410 \ +SSW_TDS_BASE_URL=http://127.0.0.1:30041 \ +SSW_TDS_INTERNAL_TOKEN=ssw-internal-token-e2e \ +TDC_DATA_DIR=/tmp/tdc-p4-data \ +cargo run +``` + +(用 Bash 工具的 `run_in_background` 托管;**stdout 不要指向 `/dev/null`**。) + +- [ ] **Step 3: 逐条打 9 个端点并记录 TDS 原始返回** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +B=http://127.0.0.1:30410 +H='-H Content-Type:application/json -H X-Internal-Token:ssw-internal-token-e2e' + +echo "=== 1) GET /ServiceCatalog ===" +curl -s --noproxy '*' "$B/api/ssw/tdc/ServiceCatalog?keyword=" -H 'X-Internal-Token: ssw-internal-token-e2e' +echo; echo "=== 2) POST /ServiceCatalog/Buy ===" +curl -s --noproxy '*' -X POST "$B/api/ssw/tdc/ServiceCatalog/Buy" $H -d '{"productId":"P-1"}' +echo; echo "=== 3) POST /ServiceCatalog/BuyBatch ===" +curl -s --noproxy '*' -X POST "$B/api/ssw/tdc/ServiceCatalog/BuyBatch" $H -d '{"productIds":["P-1","P-2"]}' +echo; echo "=== 4) GET /Billing/List ===" +curl -s --noproxy '*' "$B/api/ssw/tdc/Billing/List" -H 'X-Internal-Token: ssw-internal-token-e2e' +echo; echo "=== 5) PUT /Billing/1/Dispute ===" +curl -s --noproxy '*' -X PUT "$B/api/ssw/tdc/Billing/1/Dispute" $H -d '{}' +echo; echo "=== 6) PUT /Billing/1/Confirm ===" +curl -s --noproxy '*' -X PUT "$B/api/ssw/tdc/Billing/1/Confirm" $H -d '{}' +echo; echo "=== 7) PUT /Billing/1/Settle ===" +curl -s --noproxy '*' -X PUT "$B/api/ssw/tdc/Billing/1/Settle" $H -d '{}' +echo; echo "=== 8) PUT /Billing/1/Receipt ===" +curl -s --noproxy '*' -X PUT "$B/api/ssw/tdc/Billing/1/Receipt" $H -d '{"receiptNo":"R-1","remark":"x"}' +echo; echo "=== 9) GET /Billing/1/Voucher ===" +curl -s --noproxy '*' "$B/api/ssw/tdc/Billing/1/Voucher" -H 'X-Internal-Token: ssw-internal-token-e2e' +echo; echo "=== 10) GET /Billing/LocalCompare?contractId=C-1 ===" +curl -s --noproxy '*' "$B/api/ssw/tdc/Billing/LocalCompare?contractId=C-1" -H 'X-Internal-Token: ssw-internal-token-e2e' +``` + +> ⚠️ **必须复核的 3 条**(spec §6.3):① `Catalog/Internal/Catalog` 是 **POST**;② `BillingLedger/Internal/List` 是 **POST**; +> ③ TDS 侧 `Receipt` 是 **POST**(我们对外仍 PUT)。 +> ⚠️ 每条都要把 **TDS 原始返回**记进 `docs/TDC-TDS-CONTRACT.md` 的实测表。 + +- [ ] **Step 4: 浏览器级复验(`aix`,两页不再 404)** + +```bash +export AGENTX_XSTUDIO_BASE=http://127.0.0.1:19999 +aix open http://127.0.0.1:30410/tdc/service-catalog +aix snapshot -i +``` + +```bash +export AGENTX_XSTUDIO_BASE=http://127.0.0.1:19999 +aix open http://127.0.0.1:30410/tdc/billing +aix snapshot -i +``` + +> 🔴 **后台标签陷阱**:`document.visibilityState === "hidden"` ⇒ rAF + CSS transition 全冻结 +> ⇒ antd 抽屉卡在屏幕外。绕过:注入 `*{transition:none !important}` + 摘掉卡住的 +> `-motion-`/`enter-prepare`/`enter-start` 类(详见 `docs/CONSOLE-ACCEPTANCE.md` §5)。 +> +> 判定口径:两页**不再出现「接口不存在」**(404 的 JSON),而是「暂无数据」/空表。 + +- [ ] **Step 5: 停掉探针服务** + +(用 TaskStop 停掉后台任务;**不要**动 :30041 的 TDS。) + +- [ ] **Step 6: 记录实测结论**(并入 Task 8 的文档同步) + +--- + +### Task 8: 文档同步 + 台账 + +**Files:** +- Modify: `docs/TDC-TDS-CONTRACT.md`、`README.md`、`CLAUDE.md`、`.workbuddy/memory/2026-10-25.md`、`.superpowers/sdd/2026-10-24-tdc-rs-align-v2-p0-p1/progress.md` + +**Interfaces:** +- Consumes: Task 7 的实测记录 +- Produces: 文档与台账的最终态 + +- [ ] **Step 1: 改写 `docs/TDC-TDS-CONTRACT.md`** + +把开头的「🔴 现状(P0+P1):本仓**没有** TDS 出向通道…」整段替换为: + +```markdown +> ✅ **现状(2026-10-25,P4 已实现)**:本仓**已有** TDS 出向通道。 +> 出向客户端 = `src/tds/mod.rs`(≡ 上游 `TdsReportClient` 的 internal 通道); +> TDC 侧控制器 = `src/routes/tds_biz.rs`(≡ 上游 `ServiceCatalogController` + `BillingController`)。 +> 配置:`SSW_TDS_BASE_URL`(未配 ⇒ 本地单机模式,NOOP)+ `SSW_TDS_INTERNAL_TOKEN`(默认 `ssw-internal-token-e2e`)。 +> +> ⚠️ **只走 internal 通道**(`X-Internal-Token` + 6 个固定头)。上游的 login/`ensureToken` 通道、 +> 通用代理 `/api/ssw/tdc/tds/*`、`Bridge/**` 端点**本轮都不做**(理由见下)。 +``` + +并把末尾「实测验证记录」整节替换为 P4 的实测表(10 行:端点 / 出向 TDS 路径 / TDS 原始返回摘要)。 + +- [ ] **Step 2: `README.md` 的 API 表追加 10 行** + +在 `| GET | `/api/ssw/tdc/Auth/Spaces` | 环境空间列表 |` 之后插入: + +```markdown +| GET | `/api/ssw/tdc/ServiceCatalog` | 服务目录查询(**出向 TDS** `Catalog/Internal/Catalog`) | +| POST | `/api/ssw/tdc/ServiceCatalog/Buy` | 服务目录购买(**出向 TDS** `TradeOrder/Internal/Apply`) | +| POST | `/api/ssw/tdc/ServiceCatalog/BuyBatch` | 服务目录批次购买(**出向 TDS** `TradeOrder/Internal/ApplyBatch`) | +| GET | `/api/ssw/tdc/Billing/List` | 本方账单列表(**出向 TDS** `BillingLedger/Internal/List`) | +| PUT | `/api/ssw/tdc/Billing/{id}/Dispute` | 发起计量异议(**出向 TDS**) | +| PUT | `/api/ssw/tdc/Billing/{id}/Confirm` | 确认账单(**出向 TDS**;**严格**身份口径) | +| PUT | `/api/ssw/tdc/Billing/{id}/Settle` | 结算账单(**出向 TDS**;**严格**身份口径) | +| PUT | `/api/ssw/tdc/Billing/{id}/Receipt` | 上传结算回执(**出向 TDS**;TDS 侧是 POST) | +| GET | `/api/ssw/tdc/Billing/{id}/Voucher` | 对账凭证下载(**出向 TDS**) | +| GET | `/api/ssw/tdc/Billing/LocalCompare` | 本地计量比对(**本地表** `tdc_api_consume_log`,零出向) | +``` + +- [ ] **Step 3: `CLAUDE.md` 同步** + +① 后端 API 表加同 10 行(与 README 一致)。 +② 在「架构约定(红线)」里加一条: + +```markdown +- 🔴 **TDS 出向只走 internal 通道。** 出向请求**只带 6 个固定头** + (`Content-Type` / `App-Code: sswflow` / `Jnpf-Origin: pc` / `Vue-Version: 3` / + `X-Internal-Token` / `X-Protocol-Version: 1.0`)⇒ **绝不**把 `Authorization` / cookie / + 本地会话令牌带给 TDS。出向令牌用 `SSW_TDS_INTERNAL_TOKEN`(**不**复用入向的 `SSW_INTERNAL_TOKEN`)。 +- 🔴 **出向判定成功必须看 `body.code == 200`**(TDS 业务失败走 HTTP 200 + `code != 200`); + 任何出向失败都降级成**业务失败信封**(HTTP 200 + `code != 200`),**不得**变成 500 / panic。 +``` + +③ 「已知踩坑清单」表加一行: + +```markdown +| 出向打 `127.0.0.1:30041` 得 502 / 连接失败 | `reqwest` 默认读 `HTTP_PROXY` 环境变量 ⇒ 劫持 loopback | 出向客户端用 `.no_proxy()`(TDS 是内网直连服务) | +``` + +④ 目录速览里加 `│ ├── tds/mod.rs # TDS 出向客户端(照抄上游 TdsReportClient 的 internal 通道)`。 + +- [ ] **Step 4: 工作日志 `.workbuddy/memory/2026-10-25.md` 追加** + +追加一节「P4 TDS 出向客户端(2026-10-25)」,写:做了什么、10 个端点、实测结论、4 条变异自证结果、 +新增的已知边界(D1 跨连接器越权面照抄上游保留)。 + +- [ ] **Step 5: SDD 台账 `.superpowers/sdd/2026-10-24-tdc-rs-align-v2-p0-p1/progress.md` 追加** + +追加一节「P4:TDS 出向客户端 —— complete」,记:spec 路径、plan 路径、10 个端点、验收数字(219/0/1)、 +clippy/rustfmt 结果、实测表、4 条变异自证、R8 与边界③的闭环状态。 + +- [ ] **Step 6: 收尾自检(全部跑一遍)** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +cargo test 2>&1 | grep -E "^test result" | tail -10 +cargo clippy --lib --all-targets -- -D warnings 2>&1 | tail -20 +cargo fmt --check 2>&1 | head -20 +git status --porcelain +``` + +期望:219 passed / 0 failed / 1 ignored;clippy 无输出;`cargo fmt --check` 无输出(若 `src/` 里有历史违规,只报不改,记台账)。 + +- [ ] **Step 7: 提交** + +```bash +cd /Users/xs/Desktop/workspace/tdc-rs +git add docs/TDC-TDS-CONTRACT.md README.md CLAUDE.md .workbuddy/memory/2026-10-25.md +git commit -m "docs: 同步 P4 TDS 出向客户端(契约文档从「输入契约」改为「已实现 + 实测表」) + +Co-Authored-By: Claude Code " +``` + +> ⚠️ `.superpowers/sdd/` 被 gitignore ⇒ 台账**不入库**,只在本地更新(不要 `git add -f`)。 + +--- + +## 自评(对照 spec) + +| spec 章节 | 覆盖它的 Task | +|---|---| +| §2.1 只用 internal 通道 | Task 3(`internal_headers` 只有 6 个头)、Task 5 用例①②③ | +| §2.2 出向请求头 + 超时 | Task 3 Step 3(`CONNECT_TIMEOUT`/`READ_TIMEOUT`/`internal_headers`)、Task 5 用例① | +| §2.3 业务信封 + 两种返回风格 | Task 3(`unwrap_data` 解包型 / `send` 返回原始信封整包型)、Task 5 用例④ | +| §2.4 端点 ↔ TDS 映射 | Task 4(10 个端点)、Task 5 用例①⑦⑨ | +| §2.5 身份解析两套口径 | Task 4(`resolve_connector_id_relaxed` / `resolve_connector_id_strict`)、Task 5 用例⑦ | +| §2.6 `ownsLedger` 越权自检 | Task 4(`owns_ledger`)、Task 5 用例⑦ | +| §3.1 分层 | Task 3(`src/tds/mod.rs`)、Task 4(`src/routes/tds_biz.rs`) | +| §3.2 配置 | Task 2(`SSW_TDS_INTERNAL_TOKEN`) | +| §3.3 客户端 + 错误语义 | Task 3 | +| §3.4 端点 + 成功 data 形状 | Task 4(`unwrap_envelope` / `unwrap_envelope_str`)、Task 5 用例⑦(`data` 是**字符串**) | +| §3.5 鉴权与错误语义 | Task 4(业务失败信封)、Task 5 用例⑤⑥⑩ | +| §4 D1–D6 差异 | Task 4(D1 逐端点口径)、Task 2(D4 不做 ensureToken)、Task 3/4(D5 NOOP 文案、D6 超时) | +| §5 不做的缺口 | Task 8 Step 1(写进契约文档)、Task 1(`/api/ssw/tdc/tds/*` 保持 404) | +| §6.1 10 条断言 | Task 5(12 条用例覆盖 10 组断言) | +| §6.2 4 条变异自证 | Task 6 | +| §6.3 真 TDS 实跑 | Task 7 | +| §6.4 浏览器复验 | Task 7 Step 4 | +| §7 验收 | Task 5 Step 4 + Task 8 Step 6 | +| §8 R8 + 边界③ | Task 1 | + +**自评结论**:spec 的每一节都有对应 Task;无占位符;类型与命名在 Task 3/4/5 间一致 +(`TdsClient::new(base_url, token)` / `AppState::with_tds` / `ActionResult::ok_msg(msg, data)`)。