S8TenantIsolationContractTests.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. [Fact]
  24. public void SchedulerServices_DiscoverValidTenantScopes()
  25. {
  26. Assert.NotNull(typeof(S8WatchSchedulerService).GetMethod(
  27. nameof(S8WatchSchedulerService.ListEnabledScopesAsync)));
  28. Assert.NotNull(typeof(S8ActiveFlowWatchService).GetMethod(
  29. nameof(S8ActiveFlowWatchService.ListActiveScopesAsync)));
  30. }
  31. [Fact]
  32. public void ManualReport_ResolvesTenantAndFactoryFromServerContext()
  33. {
  34. Assert.NotNull(typeof(S8ManualReportService).GetMethod(
  35. "ResolveTrustedScopeAsync", BindingFlags.Instance | BindingFlags.NonPublic));
  36. }
  37. [Fact]
  38. public void BackgroundJobs_DoNotKeepLegacyDefaultTenantConstants()
  39. {
  40. const BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
  41. Assert.Null(typeof(S8WatchSchedulerJob).GetField("DefaultTenantId", flags));
  42. Assert.Null(typeof(S8ActiveFlowStuckScanJob).GetField("DefaultTenantId", flags));
  43. }
  44. // ───────────────────────── S8-TENANT-FACTORY-P0-CLOSURE-1 ─────────────────────────
  45. /// <summary>可信作用域解析器必须存在,且只暴露无参解析入口(不接受调用方传入 tenant / factory)。</summary>
  46. [Fact]
  47. public void TrustedScopeResolver_ExposesParameterlessServerSideResolve()
  48. {
  49. var resolve = typeof(S8TrustedScopeResolver).GetMethod(nameof(S8TrustedScopeResolver.ResolveAsync));
  50. Assert.NotNull(resolve);
  51. Assert.Empty(resolve!.GetParameters());
  52. // 工厂口径锁定为「租户内工厂类型组织」,不是 SysTenant.OrgId。
  53. Assert.Equal("501", S8TrustedScopeResolver.FactoryOrgType);
  54. var scope = new S8TrustedScope(11L, 22L);
  55. Assert.Equal(11L, scope.TenantId);
  56. Assert.Equal(22L, scope.FactoryId);
  57. }
  58. /// <summary>
  59. /// 所有 tenant+factory-owned 配置对象的写入口必须强制要求 <see cref="S8TrustedScope"/>;
  60. /// 缺参数即编译期失败,杜绝「按裸 Id 改 / 删 / 重归属」回归。
  61. /// </summary>
  62. [Theory]
  63. [InlineData(typeof(S8SceneConfigService), typeof(AdoS8SceneConfig))]
  64. [InlineData(typeof(S8DataSourceService), typeof(AdoS8DataSource))]
  65. [InlineData(typeof(S8AlertRuleService), typeof(AdoS8AlertRule))]
  66. [InlineData(typeof(S8NotificationLayerService), typeof(AdoS8NotificationLayer))]
  67. [InlineData(typeof(S8RoleConfigService), typeof(AdoS8RolePermissionConfig))]
  68. [InlineData(typeof(S8DashboardCellConfigService), typeof(AdoS8DashboardCellConfig))]
  69. [InlineData(typeof(S8ExceptionTypeService), typeof(AdoS8ExceptionType))]
  70. [InlineData(typeof(S8WatchRuleService), typeof(AdoS8WatchRule))]
  71. public void ConfigWrites_RequireTrustedScope(Type serviceType, Type entityType)
  72. {
  73. // CreateAsync 用「前两个形参匹配」而非精确签名匹配:
  74. // S8-LEGACY-SQL-RESIDUAL-CLEANUP-3 给 S8WatchRuleService.CreateAsync 追加了
  75. // 可选形参 origin(string origin = S8RuleCreationOrigin.ExternalApi),
  76. // 精确 2 参的 GetMethod 会返回 null,导致本用例误报。
  77. // 真正要保证的契约是「entity + S8TrustedScope 必须显式出现在最前」,
  78. // 后置可选形参不破坏该契约,故放宽为前缀匹配。
  79. Assert.True(
  80. HasScopedWriteEntry(serviceType, "CreateAsync", entityType),
  81. $"{serviceType.Name}.CreateAsync 必须以 ({entityType.Name}, S8TrustedScope) 开头");
  82. Assert.NotNull(serviceType.GetMethod("UpdateAsync", [typeof(long), entityType, typeof(S8TrustedScope)]));
  83. Assert.NotNull(serviceType.GetMethod("DeleteAsync", [typeof(long), typeof(S8TrustedScope)]));
  84. // 旧的无作用域重载必须彻底消失,否则调用方可能悄悄退回不安全路径。
  85. Assert.Null(serviceType.GetMethod("CreateAsync", [entityType]));
  86. Assert.Null(serviceType.GetMethod("UpdateAsync", [typeof(long), entityType]));
  87. Assert.Null(serviceType.GetMethod("DeleteAsync", [typeof(long)]));
  88. }
  89. /// <summary>
  90. /// 写入口是否以 (entity, S8TrustedScope) 开头。允许其后存在形参(如可选的 origin),
  91. /// 但作用域必须是第 2 个形参且不可省略——调用方无法只传实体就完成写入。
  92. /// </summary>
  93. private static bool HasScopedWriteEntry(Type serviceType, string methodName, Type entityType) =>
  94. serviceType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
  95. .Where(m => m.Name == methodName)
  96. .Any(m =>
  97. {
  98. var p = m.GetParameters();
  99. return p.Length >= 2
  100. && p[0].ParameterType == entityType
  101. && p[1].ParameterType == typeof(S8TrustedScope)
  102. && !p[1].IsOptional;
  103. });
  104. /// <summary>监视规则的每个按 Id 的运行态动作都必须带可信作用域。</summary>
  105. [Theory]
  106. [InlineData("RunNowAsync")]
  107. [InlineData("PauseAsync")]
  108. [InlineData("ResumeAsync")]
  109. [InlineData("TestAsync")]
  110. public void WatchRuleRuntimeActions_RequireTrustedScope(string method)
  111. {
  112. Assert.NotNull(typeof(S8WatchRuleService).GetMethod(method, [typeof(long), typeof(S8TrustedScope)]));
  113. Assert.Null(typeof(S8WatchRuleService).GetMethod(method, [typeof(long)]));
  114. }
  115. /// <summary>草稿全部按 Id 的入口都必须带可信作用域。</summary>
  116. [Fact]
  117. public void ConfigDraft_ByIdEntryPoints_RequireTrustedScope()
  118. {
  119. var t = typeof(S8ConfigDraftService);
  120. Assert.NotNull(t.GetMethod("GetAsync", [typeof(long), typeof(S8TrustedScope)]));
  121. Assert.NotNull(t.GetMethod("DeleteAsync", [typeof(long), typeof(S8TrustedScope)]));
  122. Assert.NotNull(t.GetMethod("CreateAsync", [typeof(AdoS8ConfigDraftCreateDto), typeof(S8TrustedScope)]));
  123. Assert.NotNull(t.GetMethod("UpdateAsync", [typeof(long), typeof(AdoS8ConfigDraftUpdateDto), typeof(S8TrustedScope)]));
  124. Assert.NotNull(t.GetMethod("GenerateRuleAsync", [typeof(long), typeof(AdoS8ConfigDraftGenerateRuleDto), typeof(S8TrustedScope)]));
  125. Assert.Null(t.GetMethod("GetAsync", [typeof(long)]));
  126. Assert.Null(t.GetMethod("DeleteAsync", [typeof(long)]));
  127. }
  128. /// <summary>
  129. /// 异常时间线 / 决策 / 证据三张子表无自有 tenant_id / factory_id 列,
  130. /// 归属必须由父异常派生;因此必须提供作用域校验入口。
  131. /// </summary>
  132. [Fact]
  133. public void ExceptionSubResources_ExposeParentScopeGuard()
  134. {
  135. var guard = typeof(S8DecisionService).GetMethod(
  136. nameof(S8DecisionService.IsExceptionInScopeAsync),
  137. [typeof(long), typeof(long), typeof(long)]);
  138. Assert.NotNull(guard);
  139. Assert.Equal(typeof(Task<bool>), guard!.ReturnType);
  140. }
  141. /// <summary>异常流转的补充说明同样按可信作用域绑行,不得只按裸 Id 写他租户时间线。</summary>
  142. [Fact]
  143. public void ExceptionComment_RequiresTenantAndFactory()
  144. {
  145. Assert.NotNull(typeof(S8TaskFlowService).GetMethod(
  146. nameof(S8TaskFlowService.CommentAsync),
  147. [typeof(long), typeof(long), typeof(long), typeof(string)]));
  148. Assert.Null(typeof(S8TaskFlowService).GetMethod(
  149. nameof(S8TaskFlowService.CommentAsync), [typeof(long), typeof(string)]));
  150. }
  151. /// <summary>
  152. /// 越权 Id 与不存在 Id 必须给出同一响应(404),不泄露「他租户存在该资源」;
  153. /// 同时继承 S8BizException,保证既有只捕获 S8BizException 的调用方安全降级为 400 而不是 500。
  154. /// </summary>
  155. [Fact]
  156. public void NotFound_IsIndistinguishableAndBackwardCompatible()
  157. {
  158. Assert.True(typeof(S8BizException).IsAssignableFrom(typeof(S8NotFoundException)));
  159. var ex = new S8NotFoundException();
  160. Assert.IsAssignableFrom<S8BizException>(ex);
  161. }
  162. /// <summary>OrderFlow / ManualReport 两条既有正确范式不得回退为信任客户端作用域。</summary>
  163. [Fact]
  164. public void ReferenceTrustedPaths_DoNotRegress()
  165. {
  166. // OrderFlow:服务端自解析租户与工厂,且不暴露任何接受 tenant/factory 的公共查询入口。
  167. var orderFlow = typeof(Admin.NET.Plugin.AiDOP.Service.S8.OrderFlow.S8OrderFlowService);
  168. Assert.NotNull(orderFlow.GetMethod("ResolveTenantId", Instance));
  169. Assert.NotNull(orderFlow.GetMethod("ResolveFactoryIdAsync", Instance));
  170. Assert.NotNull(orderFlow.GetMethod("ResolveScopeAsync", Instance));
  171. // ManualReport:建单与表单选项都必须经服务端可信作用域。
  172. Assert.NotNull(typeof(S8ManualReportService).GetMethod(
  173. "ResolveTrustedScopeAsync", BindingFlags.Instance | BindingFlags.NonPublic));
  174. }
  175. /// <summary>
  176. /// 数据源响应不得出现明文密码:Pwd= / Password= 一律脱敏,其它连接字段保留以便同租户配置管理员识别。
  177. /// </summary>
  178. [Theory]
  179. [InlineData("Server=h;Database=d;Uid=u;Pwd=S3cr3tValue;SslMode=None;")]
  180. [InlineData("Server=h;Database=d;User Id=u;Password=S3cr3tValue;Encrypt=false;")]
  181. [InlineData("server=h;pwd=S3cr3tValue")]
  182. public void DataSourceEndpoint_NeverExposesPlaintextSecret(string endpoint)
  183. {
  184. var mask = typeof(S8DataSourceService).GetMethod(
  185. "MaskSecret", BindingFlags.Static | BindingFlags.NonPublic);
  186. Assert.NotNull(mask);
  187. var masked = (string)mask!.Invoke(null, [endpoint]);
  188. Assert.DoesNotContain("S3cr3tValue", masked);
  189. Assert.Contains("******", masked);
  190. // 非敏感字段保留(供同租户管理员识别是哪一条连接)。
  191. Assert.Contains("Server=h", masked, StringComparison.OrdinalIgnoreCase);
  192. }
  193. /// <summary>
  194. /// 前端回填脱敏占位符时不得把 "******" 当作真实密码写库;未提交新密码则保留原密码。
  195. /// </summary>
  196. [Fact]
  197. public void DataSourceEndpoint_MaskedPlaceholderDoesNotOverwriteStoredSecret()
  198. {
  199. var merge = typeof(S8DataSourceService).GetMethod(
  200. "MergeEndpointPreservingSecret", BindingFlags.Static | BindingFlags.NonPublic);
  201. Assert.NotNull(merge);
  202. const string stored = "Server=h;Uid=u;Pwd=RealSecret;";
  203. // 1) 回填脱敏值 → 保留原始密码
  204. var merged = (string)merge!.Invoke(null, ["Server=h;Uid=u;Pwd=******;", stored]);
  205. Assert.Contains("Pwd=RealSecret", merged);
  206. // 2) endpoint 为空 → 完全保留原值(不清空密码)
  207. var kept = (string)merge.Invoke(null, [null, stored]);
  208. Assert.Equal(stored, kept);
  209. // 3) 明确提交新密码 → 才真正替换
  210. var replaced = (string)merge.Invoke(null, ["Server=h;Uid=u;Pwd=BrandNew;", stored]);
  211. Assert.Contains("Pwd=BrandNew", replaced);
  212. Assert.DoesNotContain("RealSecret", replaced);
  213. }
  214. /// <summary>
  215. /// 兼容性:查询 DTO 仍保留 TenantId / FactoryId 字段(老前端继续发送不报错),
  216. /// 但它们已不承担安全边界——由 Controller 在调用 Service 前用可信作用域覆盖。
  217. /// </summary>
  218. [Fact]
  219. public void QueryDtos_KeepScopeFieldsForCompatibilityOnly()
  220. {
  221. foreach (var t in new[]
  222. {
  223. typeof(AdoS8ExceptionQueryDto),
  224. typeof(AdoS8MonitoringSummaryQueryDto),
  225. typeof(AdoS8DetectionLogQueryDto),
  226. typeof(AdoS8NotificationLogQueryDto),
  227. typeof(AdoS8IssueLedgerQueryDto),
  228. typeof(AdoS8CellDataQueryDto),
  229. })
  230. {
  231. var tenant = t.GetProperty("TenantId");
  232. var factory = t.GetProperty("FactoryId");
  233. Assert.NotNull(tenant);
  234. Assert.NotNull(factory);
  235. // 必须可写,Controller 才能用可信作用域覆盖客户端传入值。
  236. Assert.True(tenant!.CanWrite, $"{t.Name}.TenantId 必须可写,否则 Controller 无法覆盖客户端作用域");
  237. Assert.True(factory!.CanWrite, $"{t.Name}.FactoryId 必须可写,否则 Controller 无法覆盖客户端作用域");
  238. }
  239. }
  240. }