scoped_select.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. use bos_core::{BosError, RoleCode};
  2. use bos_platform::clients::uds::{de, UdsClient};
  3. use seoh_service_sdk::InstanceUpperBound;
  4. use serde::{Deserialize, Serialize};
  5. use std::collections::HashSet;
  6. use std::sync::{Arc, Mutex};
  7. use crate::grant::ScopeMode;
  8. use crate::roles_policy::{visible_customer_strategy, VisibilitySource};
  9. #[derive(Debug, Clone, Serialize, Deserialize)]
  10. pub struct SubjectRef {
  11. pub subject_type: String,
  12. pub subject_id: String,
  13. }
  14. /// 同请求内可见 ID 集合缓存(列表常对 scope 打两遍;缓存后只付 1 次 UDS)。
  15. ///
  16. /// `Arc` 使 `AuthContext` clone 后仍共享同一格;同请求内串行调用为主,竞态双取只浪费一跳、结果一致。
  17. #[derive(Clone, Default)]
  18. pub struct ScopeIdCache(Arc<Mutex<Option<Vec<String>>>>);
  19. impl std::fmt::Debug for ScopeIdCache {
  20. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  21. let n = self.0.lock().ok().and_then(|g| g.as_ref().map(|v| v.len()));
  22. f.debug_struct("ScopeIdCache").field("len", &n).finish()
  23. }
  24. }
  25. impl ScopeIdCache {
  26. pub fn get(&self) -> Option<Vec<String>> {
  27. self.0.lock().ok().and_then(|g| g.clone())
  28. }
  29. pub fn set(&self, ids: Vec<String>) {
  30. if let Ok(mut g) = self.0.lock() {
  31. *g = Some(ids);
  32. }
  33. }
  34. }
  35. #[derive(Debug, Clone)]
  36. pub struct AuthContext {
  37. pub user_id: String,
  38. pub role: RoleCode,
  39. pub subject: SubjectRef,
  40. pub entry_only: bool,
  41. pub scope_mode: Option<ScopeMode>,
  42. /// 通道②:平台侧下发的已授权实例(真源 HTTP 列举)。
  43. ///
  44. /// 2026-11-08 起不再恒为空集(工单回件 §4 N-5/§5.2 B2):由 `bos_api::load_binding` 从
  45. /// **网关注入到请求体根级**的 `__granted_resource_grant`/`__granted_resource_instances`
  46. /// 解析而来(注入键⛔ 信任客户端自报:网关转发前先 `remove` 同名键,
  47. /// `seoh-api-gateway/src/proxy.rs:1665-1698`);仍⛔ 从请求头自报授权范围
  48. /// (《外部项目服务接入约束》§8.3 红线 6)。
  49. ///
  50. /// 口径(⛔ 当「空集=全放行」用,既有消费方的失败关闭语义不变):
  51. /// * 非空=平台**逐个点名**下发了授权实例(上界=`Exact`,线格式 `{"scope":"ids"}`/扁平数组),
  52. /// 集合即这批实例 id;
  53. /// * 空集=**本次没有可逐点点名的实例集合**,含四种情形:未注入(`grant_bound`=`None`)、
  54. /// 上界为零(`Some(Empty)`)、上界不限(`Some(Unrestricted)`)、上界是**锚点**
  55. /// (`Some(Rules)`——语义=锚点子树减 deny,须沿 RM 父链展开,⛔ 当精确实例用,
  56. /// 投影理由见 `bos_api::grant::usable_instance_ids`)。四者一律按现状处理:
  57. /// 「无授权⇒拒绝/判空,或回落本地 `bos_data_scope`」,⛔ 借「不限」放大可见范围。
  58. pub granted_resource_instances: HashSet<String>,
  59. /// 通道②的**结构化**授权上界(=平台 SDK `resolve_upper_bound` 的产物,复用它、⛔ 平行实现)。
  60. ///
  61. /// 与 `granted_resource_instances` 的分工:本字段表达**口径**,前者表达**可直接判定的 id 集合**。
  62. /// * `None`=本次请求**没有**上界可依据(路由未声明 `x-enumeration-kind`/AC 未下发/
  63. /// 绕网关直连/注入键形状不认识);
  64. /// * `Some(Empty)`=确已下发上界且上界为零。
  65. ///
  66. /// 两者语义不同 ⇒ 页面须分开说明(⛔ 把「未注入」写成「您无权查看任何数据」,
  67. /// 工单回件 §5.2 B2「可区分未注入与注入后为空」)。
  68. pub grant_bound: Option<InstanceUpperBound>,
  69. pub username: Option<String>,
  70. /// 本次请求携带的**最终用户 JWT 原文**(`Authorization: Bearer` 去掉前缀后的票面),
  71. /// 由 `bos_api::extract` 从请求头**原样**取出,⛔ 在此验签、⛔ 在此解 `sub`
  72. /// (身份判定只走 AC 上下文,见 `extract.rs` 头注;本字段只用于**出站转发**)。
  73. ///
  74. /// 用途=`U-103` 反转后的客体树写链路:客户端 → 业务服务 → 平台,**原样转发最终用户 JWT**
  75. /// (`rt.node.*`/`rt.resource.*` 授在 `end_user` 档位,⛔ 服务身份代持、⛔ 内部令牌兜底)。
  76. /// `None`=该请求没带 Bearer(多为绕网关直连),消费方一律**显式失败**(见 [`AuthContext::end_user_token`])。
  77. pub raw_token: Option<String>,
  78. /// 本请求内 `visible_region_node_ids` 结果(未命中前为 `None`)。
  79. pub region_ids_cache: ScopeIdCache,
  80. /// 本请求内 `visible_customer_ids` 结果(未命中前为 `None`)。
  81. pub customer_ids_cache: ScopeIdCache,
  82. }
  83. impl AuthContext {
  84. pub fn require_roles(&self, allowed: &[RoleCode]) -> Result<(), BosError> {
  85. if allowed.contains(&self.role) {
  86. Ok(())
  87. } else {
  88. Err(BosError::forbidden_role(format!(
  89. "角色 {} 无权执行此操作",
  90. self.role.as_str()
  91. )))
  92. }
  93. }
  94. /// 取[`raw_token`](Self::raw_token):缺失或空白 ⇒ **显式失败**。
  95. ///
  96. /// ⛔ 拿服务账号令牌顶替(那是服务身份自发起动作的凭证,总则§8.1 `:12`)——
  97. /// 顶上去只会把「最终用户没登录」伪装成「平台拒了」,正是 `U-103` 要消灭的形态。
  98. pub fn end_user_token(&self) -> Result<&str, BosError> {
  99. self.raw_token
  100. .as_deref()
  101. .map(str::trim)
  102. .filter(|t| !t.is_empty())
  103. .ok_or_else(|| {
  104. BosError::biz(
  105. bos_core::ErrorCode::Unauthorized,
  106. "本次请求未携带最终用户令牌(Authorization: Bearer),客体树写接口不回退服务账号令牌(U-103)",
  107. )
  108. })
  109. }
  110. }
  111. /// 导出器与列表只接收本 trait,拒绝裸 SQL。
  112. #[async_trait::async_trait]
  113. pub trait ScopedSelect: Send + Sync {
  114. /// 按角色策略解析可见客户 ID 集合。
  115. /// ⛔ 禁止「先取编号再 IN」作为联邦列表退路;U-80 未明时联邦页暂不提供。
  116. async fn visible_customer_ids(&self, auth: &AuthContext) -> Result<Vec<String>, BosError>;
  117. /// 区域节点可见性(子树裁剪);区域树未就绪时诚实降级为空。
  118. async fn visible_region_node_ids(&self, auth: &AuthContext) -> Result<Vec<String>, BosError>;
  119. }
  120. #[derive(Debug, Deserialize)]
  121. struct IdRow {
  122. #[serde(deserialize_with = "de::as_string")]
  123. id: String,
  124. }
  125. /// 进程内默认实现:Owner/Bind 走业务库;Tree 依赖 dim_node_ancestor / 注入 granted。
  126. pub struct DbScopedSelect {
  127. pub db: Arc<UdsClient>,
  128. }
  129. /// `Tree ∪ Picked`(总则§6.3/§12.3)的取数 SQL。
  130. ///
  131. /// * `Tree`=该持有者在 `bos_data_scope` 的 `region` 行 ⇒ 经 `dim_node_ancestor` **含下级**展开
  132. /// ⇒ 展开后节点上的当期在册客户(`customer_region_mount`,⛔ 已软删客户);
  133. /// * `Picked`=该持有者在 `bos_data_scope` 的 `customer` 行(逐人点选)。
  134. ///
  135. /// `holder_types`=本分支合法的 `holder_type` **字面量**清单。⚠️ 这里刻意⛔ 参数化:
  136. /// `A7`/`A7b` 是对**生成 SQL 文本**的静态断言,值藏进绑定参数就断言不到(失效形态=
  137. /// 范围行「能存能回显、谓词不读」=只写不读,纪律清单 §8.3/§8.5)。
  138. /// `ph_a`/`ph_b`=两个持有者 id 占位符(同一自然人可能以 `user_id` 或 `subject_id` 落范围行,
  139. /// 两个键⛔ 二选一猜,一律同传)。
  140. pub fn sql_customer_ids_union(holder_types: &str, ph_a: &str, ph_b: &str) -> String {
  141. format!(
  142. "SELECT m.customer_id AS id FROM customer_region_mount m \
  143. JOIN customer c ON c.customer_id = m.customer_id \
  144. JOIN bos_data_scope s ON s.target_type = 'region' \
  145. AND s.holder_type IN ({holder_types}) AND s.holder_id IN ({ph_a}::text, {ph_b}::text) \
  146. JOIN dim_node_ancestor a ON a.ancestor_id = s.target_id AND a.node_id = m.parent_node_id \
  147. WHERE c.deleted_at IS NULL AND m.customer_id IS NOT NULL \
  148. UNION \
  149. SELECT s2.target_id AS id FROM bos_data_scope s2 \
  150. WHERE s2.holder_type IN ({holder_types}) \
  151. AND s2.holder_id IN ({ph_a}::text, {ph_b}::text) AND s2.target_type = 'customer'"
  152. )
  153. }
  154. /// 区域授权行(`target_type='region'`)的 `holder_type` 值域——**字面量**清单。
  155. ///
  156. /// ⚠️ 刻意⛔ 参数化(同 [`sql_customer_ids_union`]:谓词得能被**生成 SQL 文本**上的静态断言看到,
  157. /// 藏进绑定参数就断言不到)。**必须**含 `ops_member`(`ops_team.rs:166-167`:成员行=
  158. /// `holder_type='ops_member'`+`holder_id=member_id`);缺这一项=运维成员的负责范围
  159. /// **只写不读**(`U-102` ②,纪律清单 §8.3 要拦的形态)。
  160. pub const REGION_HOLDER_TYPES: &str = "'user','ops_member','ent_team','ops_team','partner'";
  161. /// 某自然人的区域授权节点集合(`Tree` 轴),产出**可嵌进 `IN (…)` 的 SELECT**。
  162. ///
  163. /// 持有者键同 [`sql_customer_ids_union`]:同一自然人可能以 `user_id` 或 `subject_id` 落范围行,
  164. /// 两个键⛔ 二选一猜,一律同传(`ph_a`/`ph_b`=已生成好的占位符,调用方的 `Params` 负责编号)。
  165. ///
  166. /// 为什么做成"一条 SELECT"而不是"先取 id 再传 IN":区域树承载量要把收窄条件**下推进 SQL**,
  167. /// 使这一趟 UDS 不依赖上一趟的返回值,从而与"取平台树"那一趟并行(`handlers::region::tree_inner`,
  168. /// 串行 3 趟→2 趟)。口径与 [`ScopedSelect::visible_region_node_ids`] 的非 Admin 分支**同一真源**,
  169. /// ⛔ 在调用方另起一套授权判据。
  170. ///
  171. /// ✅ **2026-11-21 D-12**:集合=授权种子经 `dim_node_ancestor` **含下级**展开(含自身)。
  172. /// 只回种子(如两省)会让 `/region/tree@v1` 挂载下拉看不到区县,与写侧 `region_in_scope`
  173. /// (把可见 ID 当祖先、含下级)打架。
  174. pub fn sql_region_scope_ids(ph_a: &str, ph_b: &str) -> String {
  175. format!(
  176. "SELECT DISTINCT a.node_id AS target_id FROM bos_data_scope s \
  177. JOIN dim_node_ancestor a ON a.ancestor_id = s.target_id \
  178. WHERE s.holder_type IN ({REGION_HOLDER_TYPES}) \
  179. AND s.holder_id IN ({ph_a}::text, {ph_b}::text) AND s.target_type = 'region'"
  180. )
  181. }
  182. /// 把一组区域种子 ID 展开为「含下级」闭包(`dim_node_ancestor`,含自身)。
  183. ///
  184. /// 供通道②(网关注入 `granted_resource_instances`)与 [`sql_region_scope_ids`] 同口径使用。
  185. pub fn sql_expand_region_descendants(ph_ids: &str) -> String {
  186. format!(
  187. "SELECT DISTINCT node_id AS id FROM dim_node_ancestor \
  188. WHERE ancestor_id = ANY({ph_ids}::text[])"
  189. )
  190. }
  191. /// 全树节点集合(Admin 的可见集合口径=本地闭包投影的自反行),同样产出 `IN (…)` 可用的 SELECT。
  192. pub fn sql_region_all_node_ids() -> String {
  193. "SELECT node_id FROM dim_node_ancestor WHERE ancestor_id = node_id".to_string()
  194. }
  195. /// `for_operator`(总则§12.3):归属字段等值,**⛔ 不读区域树**(`A7`=本函数产出的 SQL
  196. /// ⛔ 出现 `dim_node_ancestor`;运营商可见范围⛔ 因区域分配而放大)。
  197. pub fn sql_customer_ids_owner(col: &str) -> String {
  198. format!("SELECT customer_id AS id FROM customer WHERE {col} = $1::text AND deleted_at IS NULL")
  199. }
  200. /// 通道②上界收窄:注入了可逐点点名的实例集时,本地范围**与之取交**(总则§12.3 步骤 3
  201. /// `Tree ← bos_data_scope ∩ 上界节点`),⛔ 拿注入值**替换**本地范围(替换=本地范围行重新变成
  202. /// 只写不读),也⛔ 借「不限」放大。未注入/上界为零/上界不限/上界是锚点 ⇒ 集合为空 ⇒ 原样返回。
  203. fn intersect_granted(auth: &AuthContext, ids: Vec<String>) -> Vec<String> {
  204. if auth.granted_resource_instances.is_empty() {
  205. return ids;
  206. }
  207. ids.into_iter()
  208. .filter(|id| auth.granted_resource_instances.contains(id))
  209. .collect()
  210. }
  211. #[async_trait::async_trait]
  212. impl ScopedSelect for DbScopedSelect {
  213. async fn visible_customer_ids(&self, auth: &AuthContext) -> Result<Vec<String>, BosError> {
  214. if let Some(ids) = auth.customer_ids_cache.get() {
  215. return Ok(ids);
  216. }
  217. let ids = self.visible_customer_ids_uncached(auth).await?;
  218. auth.customer_ids_cache.set(ids.clone());
  219. Ok(ids)
  220. }
  221. async fn visible_region_node_ids(&self, auth: &AuthContext) -> Result<Vec<String>, BosError> {
  222. if let Some(ids) = auth.region_ids_cache.get() {
  223. return Ok(ids);
  224. }
  225. let ids = self.visible_region_node_ids_uncached(auth).await?;
  226. auth.region_ids_cache.set(ids.clone());
  227. Ok(ids)
  228. }
  229. }
  230. impl DbScopedSelect {
  231. async fn visible_customer_ids_uncached(&self, auth: &AuthContext) -> Result<Vec<String>, BosError> {
  232. match visible_customer_strategy(auth.role) {
  233. VisibilitySource::Owner => {
  234. let col = match auth.role {
  235. RoleCode::Operator => "operator_id",
  236. other => {
  237. return Err(BosError::internal(format!(
  238. "角色 {} 不走归属等值分支(总则§6.3 只允许 operator)",
  239. other.as_str()
  240. )))
  241. }
  242. };
  243. let rows = self
  244. .db
  245. .query_all::<IdRow>(
  246. &sql_customer_ids_owner(col),
  247. &[serde_json::json!(&auth.subject.subject_id)],
  248. )
  249. .await?;
  250. Ok(intersect_granted(auth, rows.into_iter().map(|r| r.id).collect()))
  251. }
  252. // 客户主账号/运维:主体号即客户 ID。
  253. //
  254. // ⚠️ `Sub` 是**例外**(2026-11-14 静态定位):分账号的主体行是 `sub_account`
  255. // (`subject_type='sub_account'`,见 `account.rs` 里 `RoleCode::Sub => &["sub_account"]`),
  256. // 主体号=`sub_account_id`。把它当 `customer_id` 等值比较恒不命中 ⇒ 分账号在任何走
  257. // `Bind`/`customer_scope_pred` 的通路上都拿到 **0 行**(本公司工单、订阅、审计全空)。
  258. // 分账号的可见范围=**其所属客户**的范围 ⇒ 先按 `sub_account.customer_id` 解析父主体;
  259. // 解析不到(分账号行缺失/已软删)一律回空集=失败关闭,⛔ 拿主体号本身去当客户 ID 猜。
  260. VisibilitySource::Bind => match auth.role {
  261. RoleCode::Sub => {
  262. let rows = self
  263. .db
  264. .query_all::<IdRow>(
  265. "SELECT customer_id AS id FROM sub_account \
  266. WHERE sub_account_id = $1::text LIMIT 1",
  267. &[serde_json::json!(&auth.subject.subject_id)],
  268. )
  269. .await?;
  270. Ok(rows.into_iter().map(|r| r.id).collect())
  271. }
  272. _ => Ok(vec![auth.subject.subject_id.clone()]),
  273. },
  274. // `for_partner`(总则§12.3,✅ 2026-11-08 业主改判)=Tree ∪ Picked,`holder_type='partner'`。
  275. VisibilitySource::Partner => {
  276. let rows = self
  277. .db
  278. .query_all::<IdRow>(
  279. &sql_customer_ids_union("'partner'", "$1", "$2"),
  280. &[
  281. serde_json::json!(&auth.subject.subject_id),
  282. serde_json::json!(&auth.user_id),
  283. ],
  284. )
  285. .await?;
  286. Ok(intersect_granted(auth, rows.into_iter().map(|r| r.id).collect()))
  287. }
  288. VisibilitySource::TreeUnionPicked => {
  289. // 区域轴主体:`holder_type` 值域见迁移注释(`bos_core_tables.sql:80`)与
  290. // `ops_team.rs:166-167`(成员行=`ops_member`+`member_id`,⛔ `user`+`user_id`)。
  291. let rows = self
  292. .db
  293. .query_all::<IdRow>(
  294. &sql_customer_ids_union("'user','ops_member','ops_team','ent_team'", "$1", "$2"),
  295. &[
  296. serde_json::json!(&auth.user_id),
  297. serde_json::json!(&auth.subject.subject_id),
  298. ],
  299. )
  300. .await?;
  301. Ok(intersect_granted(auth, rows.into_iter().map(|r| r.id).collect()))
  302. }
  303. }
  304. }
  305. async fn visible_region_node_ids_uncached(&self, auth: &AuthContext) -> Result<Vec<String>, BosError> {
  306. if auth.role == RoleCode::Admin {
  307. let sql = format!("SELECT node_id AS id FROM ({}) n", sql_region_all_node_ids());
  308. let rows = self.db.query_all::<IdRow>(&sql, &[]).await?;
  309. return Ok(rows.into_iter().map(|r| r.id).collect());
  310. }
  311. if !auth.granted_resource_instances.is_empty() {
  312. // 通道②:注入种子同样含下级展开(与 [`sql_region_scope_ids`]/写侧 region_in_scope 同口径)。
  313. let seeds: Vec<String> = auth.granted_resource_instances.iter().cloned().collect();
  314. let sql = sql_expand_region_descendants("$1");
  315. let rows = self
  316. .db
  317. .query_all::<IdRow>(&sql, &[serde_json::json!(&seeds)])
  318. .await?;
  319. return Ok(rows.into_iter().map(|r| r.id).collect());
  320. }
  321. // 集合口径=[`sql_region_scope_ids`](已含下级;与区域树承载量的下推谓词同一真源)。
  322. let sql = format!(
  323. "SELECT target_id AS id FROM ({}) s",
  324. sql_region_scope_ids("$1", "$2")
  325. );
  326. let rows = self
  327. .db
  328. .query_all::<IdRow>(
  329. &sql,
  330. &[
  331. serde_json::json!(&auth.user_id),
  332. serde_json::json!(&auth.subject.subject_id),
  333. ],
  334. )
  335. .await?;
  336. Ok(rows.into_iter().map(|r| r.id).collect())
  337. }
  338. }
  339. /// I4:自定义范围展开后 ⊆ 团队范围。
  340. pub fn check_scope_containment(
  341. member_expanded: &HashSet<String>,
  342. team_expanded: &HashSet<String>,
  343. ) -> Result<(), BosError> {
  344. let overflow: Vec<_> = member_expanded.difference(team_expanded).cloned().collect();
  345. if overflow.is_empty() {
  346. Ok(())
  347. } else {
  348. Err(BosError::bad_params(format!(
  349. "成员负责范围超出团队范围: {}",
  350. overflow.join(",")
  351. )))
  352. }
  353. }
  354. #[cfg(test)]
  355. mod tests {
  356. use super::*;
  357. use crate::roles_policy::visible_customer_strategy;
  358. fn auth(role: RoleCode, granted: &[&str]) -> AuthContext {
  359. AuthContext {
  360. user_id: "1001".to_string(),
  361. role,
  362. subject: SubjectRef {
  363. subject_type: role.as_str().to_string(),
  364. subject_id: "S-1".to_string(),
  365. },
  366. entry_only: false,
  367. scope_mode: None,
  368. granted_resource_instances: granted.iter().map(|s| s.to_string()).collect(),
  369. grant_bound: None,
  370. username: None,
  371. raw_token: None,
  372. region_ids_cache: Default::default(),
  373. customer_ids_cache: Default::default(),
  374. }
  375. }
  376. /// `A7`(总则§17):`for_operator` 生成的 SQL ⛔ 出现 `dim_node_ancestor`
  377. /// ——失效形态=运营商被误接区域轴,可见范围随区域分配放大(总则§6.3/§12.3)。
  378. #[test]
  379. fn a7_for_operator_sql_must_not_read_the_region_tree() {
  380. let sql = sql_customer_ids_owner("operator_id");
  381. assert!(!sql.contains("dim_node_ancestor"), "for_operator 不读树: {sql}");
  382. assert!(sql.contains("operator_id"), "归属等值列丢失: {sql}");
  383. assert!(
  384. visible_customer_strategy(RoleCode::Operator) == VisibilitySource::Owner,
  385. "operator 不走 Owner 之外的分支"
  386. );
  387. }
  388. /// `A7b`(总则§17,2026-11-08 新增,承接被撤销的 `A7` 合伙人半边):
  389. /// `for_partner` 生成的 SQL **必须**含 `dim_node_ancestor`(区域行**含下级**展开)
  390. /// 且 `holder_type` 取 `'partner'`;反向=⛔ 再按 `customer.partner_id` 等值取数。
  391. /// 失效形态=合伙人的区域分配「能存能回显、谓词不读」=只写不读(纪律清单 §8.3/§8.5)。
  392. #[test]
  393. fn a7b_for_partner_sql_must_expand_region_scope() {
  394. let sql = sql_customer_ids_union("'partner'", "$1", "$2");
  395. assert!(sql.contains("dim_node_ancestor"), "for_partner 必须含下级展开: {sql}");
  396. assert!(sql.contains("bos_data_scope"), "for_partner 必须读范围行: {sql}");
  397. assert!(sql.contains("'partner'"), "holder_type 必须取 'partner': {sql}");
  398. assert!(sql.contains("target_type = 'customer'"), "Picked 半边不得丢: {sql}");
  399. assert!(!sql.contains("partner_id"), "不回到 customer.partner_id 等值: {sql}");
  400. assert!(
  401. visible_customer_strategy(RoleCode::Partner) == VisibilitySource::Partner,
  402. "partner 的可见策略必须是 Tree ∪ Picked(总则§6.3 2026-11-08 改判)"
  403. );
  404. }
  405. /// 区域轴 `holder_type` 值域**必须**含 `ops_member`(`U-102` ②=缺它=成员范围只写不读)。
  406. #[test]
  407. fn region_axis_holder_types_include_ops_member() {
  408. let sql = sql_customer_ids_union("'user','ops_member','ops_team','ent_team'", "$1", "$2");
  409. assert!(sql.contains("'ops_member'"), "成员范围行不落空: {sql}");
  410. }
  411. /// D-12:区域可见集合 SQL **必须**经 `dim_node_ancestor` 含下级展开。
  412. /// 失效形态=`/region/tree@v1` 只回授权种子(如两省),挂载下拉看不到区县,
  413. /// 与写侧 `region_in_scope`(祖先含下级)打架。
  414. #[test]
  415. fn region_scope_ids_expand_descendants() {
  416. let sql = sql_region_scope_ids("$1", "$2");
  417. assert!(sql.contains("dim_node_ancestor"), "区域授权须含下级展开: {sql}");
  418. assert!(sql.contains("bos_data_scope"), "须读范围行: {sql}");
  419. assert!(sql.contains("target_type = 'region'"), "只扩 region 轴: {sql}");
  420. let expand = sql_expand_region_descendants("$1");
  421. assert!(expand.contains("dim_node_ancestor"), "通道②展开须读闭包: {expand}");
  422. assert!(expand.contains("ANY("), "通道②用数组绑定种子: {expand}");
  423. }
  424. /// 通道②注入=**取交**而非替换:注入了上界时本地范围仍参与判定(⛔ 只写不读),
  425. /// 注入集外的本地客户被剪掉;未注入 ⇒ 本地范围原样透出。
  426. #[test]
  427. fn granted_upper_bound_intersects_instead_of_replacing() {
  428. let local = vec!["C-1".to_string(), "C-2".to_string()];
  429. let a = intersect_granted(&auth(RoleCode::Partner, &["C-2", "C-9"]), local.clone());
  430. assert_eq!(a, vec!["C-2".to_string()], "注入上界须取交(本地范围不被整体顶替)");
  431. let b = intersect_granted(&auth(RoleCode::Partner, &[]), local.clone());
  432. assert_eq!(b, local, "未注入(空集)⇒ 本地范围原样透出");
  433. }
  434. /// `U-103`:缺最终用户令牌 ⇒ 显式失败,⛔ 回退服务账号令牌。
  435. #[test]
  436. fn missing_end_user_token_fails_closed() {
  437. assert!(auth(RoleCode::Admin, &[]).end_user_token().is_err());
  438. let mut a = auth(RoleCode::Admin, &[]);
  439. a.raw_token = Some(" ".to_string());
  440. assert!(a.end_user_token().is_err(), "空白票面不当有效令牌");
  441. let mut b = auth(RoleCode::Admin, &[]);
  442. b.raw_token = Some("eyJhbGciOi.eyJzdWIiOi.sig".to_string());
  443. assert_eq!(b.end_user_token().unwrap(), "eyJhbGciOi.eyJzdWIiOi.sig");
  444. }
  445. }