S8TenantIsolationContractTests.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. using Admin.NET.Plugin.AiDOP.Dto.S8;
  2. using Admin.NET.Plugin.AiDOP.Entity.S8;
  3. using Admin.NET.Plugin.AiDOP.Infrastructure;
  4. using Admin.NET.Plugin.AiDOP.Job;
  5. using Admin.NET.Plugin.AiDOP.Service.S8;
  6. using Admin.NET.Plugin.AiDOP.Service.S8.Rules;
  7. using System.Reflection;
  8. using Xunit;
  9. namespace Admin.NET.Plugin.AiDOP.Tests.S8;
  10. public class S8TenantIsolationContractTests
  11. {
  12. private const BindingFlags Instance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
  13. [Fact]
  14. public void AutoExceptionCreation_RequiresExplicitTenantAndFactory()
  15. {
  16. Assert.NotNull(typeof(S8ManualReportService).GetMethod(
  17. nameof(S8ManualReportService.CreateFromWatchAsync),
  18. [typeof(long), typeof(long), typeof(S8WatchHitResult)]));
  19. Assert.NotNull(typeof(S8ManualReportService).GetMethod(
  20. nameof(S8ManualReportService.CreateFromHitAsync),
  21. [typeof(long), typeof(long), typeof(S8RuleHit)]));
  22. }
  23. /// <summary>
  24. /// S8-TENANT-ONLY-BATCH5:规则调度的遍历维度已从 (租户, 工厂) 收敛为租户。
  25. /// 断言的是「新形态存在 + 旧形态不存在」——只断言新方法在,挡不住有人把旧方法加回来。
  26. ///
  27. /// <para><c>S8ActiveFlowWatchService.ListActiveScopesAsync</c> 仍是 (租户, 工厂):
  28. /// 它属于异常侧,归 Batch 6,本批刻意不动。</para>
  29. /// </summary>
  30. [Fact]
  31. public void SchedulerDiscoversTenants_NotTenantFactoryPairs()
  32. {
  33. Assert.NotNull(typeof(S8WatchSchedulerService).GetMethod(
  34. nameof(S8WatchSchedulerService.ListEnabledTenantsAsync)));
  35. Assert.Null(typeof(S8WatchSchedulerService).GetMethod("ListEnabledScopesAsync"));
  36. Assert.NotNull(typeof(S8ActiveFlowWatchService).GetMethod(
  37. nameof(S8ActiveFlowWatchService.ListActiveScopesAsync)));
  38. }
  39. [Fact]
  40. public void ManualReport_ResolvesTenantAndFactoryFromServerContext()
  41. {
  42. Assert.NotNull(typeof(S8ManualReportService).GetMethod(
  43. "ResolveTrustedScopeAsync", BindingFlags.Instance | BindingFlags.NonPublic));
  44. }
  45. [Fact]
  46. public void BackgroundJobs_DoNotKeepLegacyDefaultTenantConstants()
  47. {
  48. const BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
  49. Assert.Null(typeof(S8WatchSchedulerJob).GetField("DefaultTenantId", flags));
  50. Assert.Null(typeof(S8ActiveFlowStuckScanJob).GetField("DefaultTenantId", flags));
  51. }
  52. // ───────────────────────── S8-TENANT-FACTORY-P0-CLOSURE-1 ─────────────────────────
  53. /// <summary>可信作用域解析器必须存在,且只暴露无参解析入口(不接受调用方传入 tenant / factory)。</summary>
  54. [Fact]
  55. public void TrustedScopeResolver_ExposesParameterlessServerSideResolve()
  56. {
  57. var resolve = typeof(S8TrustedScopeResolver).GetMethod(nameof(S8TrustedScopeResolver.ResolveAsync));
  58. Assert.NotNull(resolve);
  59. Assert.Empty(resolve!.GetParameters());
  60. // 工厂口径锁定为「租户内工厂类型组织」,不是 SysTenant.OrgId。
  61. Assert.Equal("501", S8TrustedScopeResolver.FactoryOrgType);
  62. var scope = new S8TrustedScope(11L, 22L);
  63. Assert.Equal(11L, scope.TenantId);
  64. Assert.Equal(22L, scope.FactoryId);
  65. }
  66. /// <summary>
  67. /// 所有 tenant+factory-owned 配置对象的写入口必须强制要求 <see cref="S8TrustedScope"/>;
  68. /// 缺参数即编译期失败,杜绝「按裸 Id 改 / 删 / 重归属」回归。
  69. /// </summary>
  70. [Theory]
  71. // S8-STANDARD-DATASET-HARD-CUTOVER-1:AlertRule 与 DataSource 两组服务/实体已物理删除,
  72. // 其条目随之移除——类型都不存在了,「写入口必须带作用域」自然无从违反。
  73. // 这些功能的消失本身由 S8LegacySymbolsRemovedTests 断言。
  74. [InlineData(typeof(S8SceneConfigService), typeof(AdoS8SceneConfig))]
  75. [InlineData(typeof(S8NotificationLayerService), typeof(AdoS8NotificationLayer))]
  76. [InlineData(typeof(S8RoleConfigService), typeof(AdoS8RolePermissionConfig))]
  77. [InlineData(typeof(S8DashboardCellConfigService), typeof(AdoS8DashboardCellConfig))]
  78. [InlineData(typeof(S8ExceptionTypeService), typeof(AdoS8ExceptionType))]
  79. // S8-RULE-GOVERNANCE-BATCH3:S8WatchRuleService 已移出本用例 ——
  80. // 它的 Create / Update / Delete 三个业务写入口全部退役,不再存在"带作用域的写入口"这回事。
  81. // 取而代之的断言见 S8RuleCreationRetiredTests:业务根本不能创建 / 删除规则。
  82. public void ConfigWrites_RequireTrustedScope(Type serviceType, Type entityType)
  83. {
  84. // CreateAsync 用「前两个形参匹配」而非精确签名匹配。
  85. // 触发原因(origin 可选形参)已随 S8-STANDARD-DATASET-HARD-CUTOVER-1 消失,
  86. // 但前缀匹配予以保留:真正要保证的契约是「entity + S8TrustedScope 必须显式出现在最前」,
  87. // 后置可选形参不破坏该契约。改回精确匹配只会让下一次同类扩展再次误报。
  88. Assert.True(
  89. HasScopedWriteEntry(serviceType, "CreateAsync", entityType),
  90. $"{serviceType.Name}.CreateAsync 必须以 ({entityType.Name}, S8TrustedScope) 开头");
  91. Assert.NotNull(serviceType.GetMethod("UpdateAsync", [typeof(long), entityType, typeof(S8TrustedScope)]));
  92. Assert.NotNull(serviceType.GetMethod("DeleteAsync", [typeof(long), typeof(S8TrustedScope)]));
  93. // 旧的无作用域重载必须彻底消失,否则调用方可能悄悄退回不安全路径。
  94. Assert.Null(serviceType.GetMethod("CreateAsync", [entityType]));
  95. Assert.Null(serviceType.GetMethod("UpdateAsync", [typeof(long), entityType]));
  96. Assert.Null(serviceType.GetMethod("DeleteAsync", [typeof(long)]));
  97. }
  98. /// <summary>
  99. /// 写入口是否以 (entity, S8TrustedScope) 开头。允许其后存在形参,
  100. /// 但作用域必须是第 2 个形参且不可省略——调用方无法只传实体就完成写入。
  101. /// </summary>
  102. private static bool HasScopedWriteEntry(Type serviceType, string methodName, Type entityType) =>
  103. serviceType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
  104. .Where(m => m.Name == methodName)
  105. .Any(m =>
  106. {
  107. var p = m.GetParameters();
  108. return p.Length >= 2
  109. && p[0].ParameterType == entityType
  110. && p[1].ParameterType == typeof(S8TrustedScope)
  111. && !p[1].IsOptional;
  112. });
  113. /// <summary>监视规则的每个按 Id 的运行态动作都必须带可信作用域。</summary>
  114. [Theory]
  115. [InlineData("RunNowAsync")]
  116. [InlineData("PauseAsync")]
  117. [InlineData("ResumeAsync")]
  118. // S8-RULE-GOVERNANCE-BATCH3:TestAsync 已物理移除(能力被 GET /{id}/preview 完全覆盖)。
  119. [InlineData("EnableAsync")]
  120. [InlineData("DisableAsync")]
  121. public void WatchRuleRuntimeActions_RequireTrustedScope(string method)
  122. {
  123. Assert.NotNull(typeof(S8WatchRuleService).GetMethod(method, [typeof(long), typeof(S8TrustedScope)]));
  124. Assert.Null(typeof(S8WatchRuleService).GetMethod(method, [typeof(long)]));
  125. }
  126. // S8-RULE-GOVERNANCE-BATCH3:原 ConfigDraft_ByIdEntryPoints_RequireTrustedScope 已删除 ——
  127. // S8ConfigDraftService / AdoS8ConfigDraftsController / 草稿 DTO 已整体退役。
  128. // 「草稿的入口要不要带作用域」这个问题随入口一起消失了;
  129. // 「草稿链路不存在」由 S8RuleCreationRetiredTests 断言。
  130. /// <summary>
  131. /// 异常时间线 / 决策 / 证据三张子表无自有 tenant_id / factory_id 列,
  132. /// 归属必须由父异常派生;因此必须提供作用域校验入口。
  133. /// </summary>
  134. [Fact]
  135. public void ExceptionSubResources_ExposeParentScopeGuard()
  136. {
  137. var guard = typeof(S8DecisionService).GetMethod(
  138. nameof(S8DecisionService.IsExceptionInScopeAsync),
  139. [typeof(long), typeof(long), typeof(long)]);
  140. Assert.NotNull(guard);
  141. Assert.Equal(typeof(Task<bool>), guard!.ReturnType);
  142. }
  143. /// <summary>异常流转的补充说明同样按可信作用域绑行,不得只按裸 Id 写他租户时间线。</summary>
  144. [Fact]
  145. public void ExceptionComment_RequiresTenantAndFactory()
  146. {
  147. Assert.NotNull(typeof(S8TaskFlowService).GetMethod(
  148. nameof(S8TaskFlowService.CommentAsync),
  149. [typeof(long), typeof(long), typeof(long), typeof(string)]));
  150. Assert.Null(typeof(S8TaskFlowService).GetMethod(
  151. nameof(S8TaskFlowService.CommentAsync), [typeof(long), typeof(string)]));
  152. }
  153. /// <summary>
  154. /// 越权 Id 与不存在 Id 必须给出同一响应(404),不泄露「他租户存在该资源」;
  155. /// 同时继承 S8BizException,保证既有只捕获 S8BizException 的调用方安全降级为 400 而不是 500。
  156. /// </summary>
  157. [Fact]
  158. public void NotFound_IsIndistinguishableAndBackwardCompatible()
  159. {
  160. Assert.True(typeof(S8BizException).IsAssignableFrom(typeof(S8NotFoundException)));
  161. var ex = new S8NotFoundException();
  162. Assert.IsAssignableFrom<S8BizException>(ex);
  163. }
  164. /// <summary>OrderFlow / ManualReport 两条既有正确范式不得回退为信任客户端作用域。</summary>
  165. [Fact]
  166. public void ReferenceTrustedPaths_DoNotRegress()
  167. {
  168. // OrderFlow:服务端自解析租户与工厂,且不暴露任何接受 tenant/factory 的公共查询入口。
  169. var orderFlow = typeof(Admin.NET.Plugin.AiDOP.Service.S8.OrderFlow.S8OrderFlowService);
  170. Assert.NotNull(orderFlow.GetMethod("ResolveTenantId", Instance));
  171. Assert.NotNull(orderFlow.GetMethod("ResolveFactoryIdAsync", Instance));
  172. Assert.NotNull(orderFlow.GetMethod("ResolveScopeAsync", Instance));
  173. // ManualReport:建单与表单选项都必须经服务端可信作用域。
  174. Assert.NotNull(typeof(S8ManualReportService).GetMethod(
  175. "ResolveTrustedScopeAsync", BindingFlags.Instance | BindingFlags.NonPublic));
  176. }
  177. // S8-STANDARD-DATASET-HARD-CUTOVER-1:此处原有两条数据源用例
  178. // · DataSourceEndpoint_NeverExposesPlaintextSecret(连接串脱敏)
  179. // · DataSourceEndpoint_CannotBeOverwritten_BecauseAllWritesAreRetired(写入口已退役)
  180. // 二者守的都是「S8 存了含凭据的连接串,别泄露、别被覆盖」这一风险。
  181. // 该风险随 ado_s8_data_source 与 S8DataSourceService 一并物理消失 ——
  182. // S8 已不再持有任何连接串,因此没有可脱敏、也没有可覆盖的东西。
  183. // 「数据源功能不存在」由 S8LegacySymbolsRemovedTests 断言。
  184. /// <summary>
  185. /// 兼容性:查询 DTO 仍保留 TenantId / FactoryId 字段(老前端继续发送不报错),
  186. /// 但它们已不承担安全边界——由 Controller 在调用 Service 前用可信作用域覆盖。
  187. /// </summary>
  188. [Fact]
  189. public void QueryDtos_KeepScopeFieldsForCompatibilityOnly()
  190. {
  191. foreach (var t in new[]
  192. {
  193. typeof(AdoS8ExceptionQueryDto),
  194. typeof(AdoS8MonitoringSummaryQueryDto),
  195. typeof(AdoS8DetectionLogQueryDto),
  196. typeof(AdoS8NotificationLogQueryDto),
  197. typeof(AdoS8IssueLedgerQueryDto),
  198. typeof(AdoS8CellDataQueryDto),
  199. })
  200. {
  201. var tenant = t.GetProperty("TenantId");
  202. var factory = t.GetProperty("FactoryId");
  203. Assert.NotNull(tenant);
  204. Assert.NotNull(factory);
  205. // 必须可写,Controller 才能用可信作用域覆盖客户端传入值。
  206. Assert.True(tenant!.CanWrite, $"{t.Name}.TenantId 必须可写,否则 Controller 无法覆盖客户端作用域");
  207. Assert.True(factory!.CanWrite, $"{t.Name}.FactoryId 必须可写,否则 Controller 无法覆盖客户端作用域");
  208. }
  209. }
  210. }