按 v3 spec §2.1 的目录映射,把 9810 行代码重组成「平台层 + 业务层」两段: **平台层 `src/platform/`**(12 个文件,与业务零知识) - state / config / db / session / envelope / cipher / ids / protocol - body / mw / fallback(原 `src/routes/`,是通用响应改写与兜底,不是业务) **业务层 `src/tdc/`**(对位上游 `ssw.tdc.*` 包族) - `entity/` —— `registry.rs` 拆成 **18 个实体各一文件** + `mod.rs`(`ALL_SPECS` / `validate` / 权限键) - `mapper.rs` —— 原 `crud.rs` 的 SQL 组装/投影/序列化半边(机械活、实体无关) - `service/crud.rs` —— 原 `crud.rs` 的写路径规则/分档判定半边 - `service/identity.rs` / `service/account.rs` —— 原 `domain/identity.rs` / `account.rs` - `controller/` —— 原 `routes/`(crud / health / auth / account / tds_biz) - `client/tds.rs` —— 原 `tds/mod.rs`(TDS 出向客户端) - `util/code.rs` —— 原 `codec.rs`(**业务**编码生成器,非平台件) - `support/public_paths.rs` —— 免鉴权端点清单(业务侧持有,C5 接线) - `policy/ engine/ schedule/ notify/ heartbeat/ sso/` —— 上游同名包占位 **行为零变化**:HTTP 契约、响应形状、SQL、口令算法、权限判定全部不动。 - `cargo test` 223 passed / 0 failed / 1 ignored(与 B1a 基线一致) - `scripts/smoke.sh` PASS=75 / FAIL=0(断言数 == 基线 N=75,不增不减) - `scripts/check-boundary.sh` exit 0(账本 7 条 B1b 待清 + 2 条永久豁免) - `scripts/check-entity.sh` PASS=15 / FAIL=0 **边界账本同步**:CP3 的 `routes/crud.rs` 条目改为 `controller/crud.rs`(账本按路径后缀匹配,搬家不失效)。 **为什么搬家必须一个 commit**:`check-boundary.sh` 的 NEW_LAYOUT/LEGACY 判定是**全有或全无** (`src/platform/` 目录存在即切新布局)⇒ 分批搬会让账本条目在中间态失效 ⇒ 尺子当场红。 ⇒ 搬家一个 commit,之后 C1–C12 各一个 commit。 Co-Authored-By: Claude Code <[email protected]>
171 lines
6.2 KiB
Rust
171 lines
6.2 KiB
Rust
//! 权限键:能力集解析 + 写操作二次校验。
|
||
//!
|
||
//! ⚠️ 本测试二进制内共用一个 PGlite 实例(pglite-rs 每进程只允许一个)。
|
||
|
||
use std::sync::Arc;
|
||
|
||
use axum::http::StatusCode;
|
||
use pglite::PGlite;
|
||
use tdc_connector::platform::auth::Principal;
|
||
use tdc_connector::platform::config::Config;
|
||
use tdc_connector::tdc::service::crud::require_write_permission;
|
||
use tdc_connector::tdc::service::identity;
|
||
use tdc_connector::tdc::entity;
|
||
use tdc_connector::platform::session::SessionStore;
|
||
use tdc_connector::platform::state::{AppState, BootstrapIdentity};
|
||
use tokio::sync::OnceCell;
|
||
|
||
static DB: OnceCell<Arc<PGlite>> = OnceCell::const_new();
|
||
|
||
async fn shared_db() -> Arc<PGlite> {
|
||
DB.get_or_init(|| async {
|
||
let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败"));
|
||
tdc_connector::platform::db::ensure_schema(db.as_ref())
|
||
.await
|
||
.expect("建表失败");
|
||
db
|
||
})
|
||
.await
|
||
.clone()
|
||
}
|
||
|
||
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();
|
||
AppState::new(
|
||
config,
|
||
db,
|
||
Arc::new(SessionStore::new()),
|
||
BootstrapIdentity::default(),
|
||
)
|
||
}
|
||
|
||
/// 插入一条测试身份;`capability` 为 `None` 时该列为 NULL。
|
||
async fn upsert_identity(code: &str, capability: Option<&str>) {
|
||
let state = test_state().await;
|
||
let cap = match capability {
|
||
Some(c) => format!("'{}'", c),
|
||
None => "NULL".to_string(),
|
||
};
|
||
let id = format!("ID-{}", code);
|
||
let sql = format!(
|
||
"INSERT INTO tdc_identity (f_id, f_identity_code, f_name, f_capability) \
|
||
VALUES ('{}', '{}', '测试身份', {})",
|
||
id, code, cap
|
||
);
|
||
// 🔴 所有 DB 访问必须持 `state.db_lock`(PGlite 单 in-process backend,CLAUDE.md 红线)
|
||
// —— 测试代码也不例外,否则与并行的 `capabilities()` 查询在同一个 backend 上抢。
|
||
let _g = state.db_lock.lock().await;
|
||
state.db.exec(&sql).await.expect("插入测试身份失败");
|
||
}
|
||
|
||
fn session(code: &str) -> Principal {
|
||
Principal::Session {
|
||
identity_id: format!("ID-{}", code),
|
||
identity_code: code.to_string(),
|
||
}
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn missing_capability_fails_open() {
|
||
upsert_identity("NO-CAP", None).await;
|
||
let state = test_state().await;
|
||
let caps = identity::capabilities(&state, "NO-CAP").await;
|
||
assert!(caps.is_none(), "空能力集应解析为 None(⇒ fail-open)");
|
||
|
||
let spec = entity::find("Product").expect("Product 应在注册表里");
|
||
let r = require_write_permission(&state, spec, Some(&session("NO-CAP"))).await;
|
||
assert!(r.is_ok(), "能力集解析不出时必须 fail-open 放行");
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn parsed_capability_is_enforced_on_write() {
|
||
upsert_identity("ONLY-PRODUCT", Some("product")).await;
|
||
let state = test_state().await;
|
||
|
||
let caps = identity::capabilities(&state, "ONLY-PRODUCT").await;
|
||
assert_eq!(caps, Some(vec!["product".to_string()]));
|
||
|
||
let product = entity::find("Product").expect("Product 应在注册表里");
|
||
assert!(
|
||
require_write_permission(&state, product, Some(&session("ONLY-PRODUCT")))
|
||
.await
|
||
.is_ok(),
|
||
"命中权限键应放行"
|
||
);
|
||
|
||
let contract = entity::find("Contract").expect("Contract 应在注册表里");
|
||
assert!(
|
||
require_write_permission(&state, contract, Some(&session("ONLY-PRODUCT")))
|
||
.await
|
||
.is_err(),
|
||
"未命中权限键必须被拒"
|
||
);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn wildcard_capability_allows_everything() {
|
||
upsert_identity("ROOT", Some("*")).await;
|
||
let state = test_state().await;
|
||
let spec = entity::find("Contract").expect("Contract 应在注册表里");
|
||
assert!(
|
||
require_write_permission(&state, spec, Some(&session("ROOT")))
|
||
.await
|
||
.is_ok(),
|
||
"通配符应放行全部实体"
|
||
);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn internal_principal_bypasses_the_gate() {
|
||
let state = test_state().await;
|
||
let spec = entity::find("Contract").expect("Contract 应在注册表里");
|
||
assert!(
|
||
require_write_permission(&state, spec, Some(&Principal::Internal { operator: None }))
|
||
.await
|
||
.is_ok(),
|
||
"内部令牌必须直接放行"
|
||
);
|
||
assert!(
|
||
require_write_permission(&state, spec, None).await.is_err(),
|
||
"无凭证必须被拒"
|
||
);
|
||
}
|
||
|
||
/// 🔴 **接线自证**:三个**写路径**(`create` / `update` / `delete`)真的走了权限键判定。
|
||
///
|
||
/// 三个写函数都把权限判定放在**函数最开头**(在任何 DB 访问之前)⇒
|
||
/// 即便 id 不存在,被拒的也应该是 **403**,而不是业务层的「记录不存在或已删除」(200)。
|
||
/// ⇒ 这条用例是「把 `create` 里的 `require_write_permission` 换回 `require_menu_permission`」
|
||
/// 那次变异的**红点**(没有它,CRUD 写路径的接线是**测不到**的)。
|
||
#[tokio::test]
|
||
async fn crud_write_paths_enforce_the_permission_key() {
|
||
// ⚠️ 身份码要**唯一**:本测试二进制里的用例并行跑、共用同一个库 ⇒
|
||
// 复用别的用例的 `f_identity_code` 会撞主键。
|
||
upsert_identity("CAP-PRODUCT-ONLY", Some("product")).await;
|
||
let state = test_state().await;
|
||
let contract = entity::find("Contract").expect("Contract 应在注册表里");
|
||
let p = session("CAP-PRODUCT-ONLY");
|
||
let body = serde_json::json!({});
|
||
|
||
let r = tdc_connector::tdc::service::crud::create(&state, contract, &body, Some(&p)).await;
|
||
assert_eq!(
|
||
r.status(),
|
||
StatusCode::FORBIDDEN,
|
||
"create 未命中权限键必须 403"
|
||
);
|
||
let r = tdc_connector::tdc::service::crud::update(&state, contract, "NOT-EXIST", &body, Some(&p)).await;
|
||
assert_eq!(
|
||
r.status(),
|
||
StatusCode::FORBIDDEN,
|
||
"update 未命中权限键必须 403"
|
||
);
|
||
let r = tdc_connector::tdc::service::crud::delete(&state, contract, "NOT-EXIST", Some(&p)).await;
|
||
assert_eq!(
|
||
r.status(),
|
||
StatusCode::FORBIDDEN,
|
||
"delete 未命中权限键必须 403"
|
||
);
|
||
}
|