S8TenantIsolationContractTests.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. // S8-STANDARD-DATASET-HARD-CUTOVER-1:S8AlertRuleService / AdoS8AlertRule 已物理删除,
  64. // 其条目随之移除——类型都不存在了,「写入口必须带作用域」自然无从违反。
  65. // 该功能的消失本身由 S8LegacySymbolsRemovedTests 断言。
  66. [InlineData(typeof(S8SceneConfigService), typeof(AdoS8SceneConfig))]
  67. [InlineData(typeof(S8DataSourceService), typeof(AdoS8DataSource))]
  68. [InlineData(typeof(S8NotificationLayerService), typeof(AdoS8NotificationLayer))]
  69. [InlineData(typeof(S8RoleConfigService), typeof(AdoS8RolePermissionConfig))]
  70. [InlineData(typeof(S8DashboardCellConfigService), typeof(AdoS8DashboardCellConfig))]
  71. [InlineData(typeof(S8ExceptionTypeService), typeof(AdoS8ExceptionType))]
  72. [InlineData(typeof(S8WatchRuleService), typeof(AdoS8WatchRule))]
  73. public void ConfigWrites_RequireTrustedScope(Type serviceType, Type entityType)
  74. {
  75. // CreateAsync 用「前两个形参匹配」而非精确签名匹配:
  76. // S8-LEGACY-SQL-RESIDUAL-CLEANUP-3 给 S8WatchRuleService.CreateAsync 追加了
  77. // 可选形参 origin(string origin = S8RuleCreationOrigin.ExternalApi),
  78. // 精确 2 参的 GetMethod 会返回 null,导致本用例误报。
  79. // 真正要保证的契约是「entity + S8TrustedScope 必须显式出现在最前」,
  80. // 后置可选形参不破坏该契约,故放宽为前缀匹配。
  81. Assert.True(
  82. HasScopedWriteEntry(serviceType, "CreateAsync", entityType),
  83. $"{serviceType.Name}.CreateAsync 必须以 ({entityType.Name}, S8TrustedScope) 开头");
  84. Assert.NotNull(serviceType.GetMethod("UpdateAsync", [typeof(long), entityType, typeof(S8TrustedScope)]));
  85. Assert.NotNull(serviceType.GetMethod("DeleteAsync", [typeof(long), typeof(S8TrustedScope)]));
  86. // 旧的无作用域重载必须彻底消失,否则调用方可能悄悄退回不安全路径。
  87. Assert.Null(serviceType.GetMethod("CreateAsync", [entityType]));
  88. Assert.Null(serviceType.GetMethod("UpdateAsync", [typeof(long), entityType]));
  89. Assert.Null(serviceType.GetMethod("DeleteAsync", [typeof(long)]));
  90. }
  91. /// <summary>
  92. /// 写入口是否以 (entity, S8TrustedScope) 开头。允许其后存在形参(如可选的 origin),
  93. /// 但作用域必须是第 2 个形参且不可省略——调用方无法只传实体就完成写入。
  94. /// </summary>
  95. private static bool HasScopedWriteEntry(Type serviceType, string methodName, Type entityType) =>
  96. serviceType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
  97. .Where(m => m.Name == methodName)
  98. .Any(m =>
  99. {
  100. var p = m.GetParameters();
  101. return p.Length >= 2
  102. && p[0].ParameterType == entityType
  103. && p[1].ParameterType == typeof(S8TrustedScope)
  104. && !p[1].IsOptional;
  105. });
  106. /// <summary>监视规则的每个按 Id 的运行态动作都必须带可信作用域。</summary>
  107. [Theory]
  108. [InlineData("RunNowAsync")]
  109. [InlineData("PauseAsync")]
  110. [InlineData("ResumeAsync")]
  111. [InlineData("TestAsync")]
  112. public void WatchRuleRuntimeActions_RequireTrustedScope(string method)
  113. {
  114. Assert.NotNull(typeof(S8WatchRuleService).GetMethod(method, [typeof(long), typeof(S8TrustedScope)]));
  115. Assert.Null(typeof(S8WatchRuleService).GetMethod(method, [typeof(long)]));
  116. }
  117. /// <summary>草稿全部按 Id 的入口都必须带可信作用域。</summary>
  118. [Fact]
  119. public void ConfigDraft_ByIdEntryPoints_RequireTrustedScope()
  120. {
  121. var t = typeof(S8ConfigDraftService);
  122. Assert.NotNull(t.GetMethod("GetAsync", [typeof(long), typeof(S8TrustedScope)]));
  123. Assert.NotNull(t.GetMethod("DeleteAsync", [typeof(long), typeof(S8TrustedScope)]));
  124. Assert.NotNull(t.GetMethod("CreateAsync", [typeof(AdoS8ConfigDraftCreateDto), typeof(S8TrustedScope)]));
  125. Assert.NotNull(t.GetMethod("UpdateAsync", [typeof(long), typeof(AdoS8ConfigDraftUpdateDto), typeof(S8TrustedScope)]));
  126. Assert.NotNull(t.GetMethod("GenerateRuleAsync", [typeof(long), typeof(AdoS8ConfigDraftGenerateRuleDto), typeof(S8TrustedScope)]));
  127. Assert.Null(t.GetMethod("GetAsync", [typeof(long)]));
  128. Assert.Null(t.GetMethod("DeleteAsync", [typeof(long)]));
  129. }
  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. /// <summary>
  178. /// 数据源响应不得出现明文密码:Pwd= / Password= 一律脱敏,其它连接字段保留以便同租户配置管理员识别。
  179. /// </summary>
  180. [Theory]
  181. [InlineData("Server=h;Database=d;Uid=u;Pwd=S3cr3tValue;SslMode=None;")]
  182. [InlineData("Server=h;Database=d;User Id=u;Password=S3cr3tValue;Encrypt=false;")]
  183. [InlineData("server=h;pwd=S3cr3tValue")]
  184. public void DataSourceEndpoint_NeverExposesPlaintextSecret(string endpoint)
  185. {
  186. var mask = typeof(S8DataSourceService).GetMethod(
  187. "MaskSecret", BindingFlags.Static | BindingFlags.NonPublic);
  188. Assert.NotNull(mask);
  189. var masked = (string)mask!.Invoke(null, [endpoint]);
  190. Assert.DoesNotContain("S3cr3tValue", masked);
  191. Assert.Contains("******", masked);
  192. // 非敏感字段保留(供同租户管理员识别是哪一条连接)。
  193. Assert.Contains("Server=h", masked, StringComparison.OrdinalIgnoreCase);
  194. }
  195. /// <summary>
  196. /// 原用例 DataSourceEndpoint_MaskedPlaceholderDoesNotOverwriteStoredSecret 断言
  197. /// <c>MergeEndpointPreservingSecret</c> 在前端回填 "******" 时保留库中真实密码。
  198. ///
  199. /// S8-LEGACY-RUNTIME-RETIREMENT-1 之后该辅助方法连同 <c>UpdateAsync</c> 的实现一并移除:
  200. /// 数据源写入口全部退役,**不存在任何能改写 endpoint 的路径**。
  201. /// 原保障("别把占位符当密码写进去")因此被更强的保障取代 ——
  202. /// 不是"写的时候小心",而是"根本不能写"。
  203. ///
  204. /// 用反射断言写方法不可绕过,而不是简单删掉本用例:删掉会让
  205. /// "凭据不会被覆盖" 这条安全属性失去看守,将来有人恢复写入口时无人报警。
  206. /// </summary>
  207. [Fact]
  208. public void DataSourceEndpoint_CannotBeOverwritten_BecauseAllWritesAreRetired()
  209. {
  210. // 写方法必须仍然存在(签名契约),但必须在任何 DB 访问前抛退役异常。
  211. var svc = (S8DataSourceService)System.Runtime.CompilerServices.RuntimeHelpers
  212. .GetUninitializedObject(typeof(S8DataSourceService));
  213. var scope = new S8TrustedScope(838257186181189L, 838257186320453L);
  214. Assert.Throws<S8WriteRetiredException>(() =>
  215. {
  216. _ = svc.UpdateAsync(1L, new AdoS8DataSource
  217. {
  218. DataSourceCode = "UT_DS",
  219. Type = "SQL",
  220. Endpoint = "Server=h;Uid=u;Pwd=AttackerSuppliedValue;"
  221. }, scope);
  222. });
  223. Assert.Throws<S8WriteRetiredException>(() =>
  224. {
  225. _ = svc.CreateAsync(new AdoS8DataSource
  226. {
  227. DataSourceCode = "UT_DS",
  228. Type = "SQL",
  229. Endpoint = "Server=h;Uid=u;Pwd=AttackerSuppliedValue;"
  230. }, scope);
  231. });
  232. // 合并辅助方法已随写路径一并移除;若它重新出现,说明写路径可能被恢复,需要复核。
  233. Assert.Null(typeof(S8DataSourceService).GetMethod(
  234. "MergeEndpointPreservingSecret", BindingFlags.Static | BindingFlags.NonPublic));
  235. }
  236. /// <summary>
  237. /// 兼容性:查询 DTO 仍保留 TenantId / FactoryId 字段(老前端继续发送不报错),
  238. /// 但它们已不承担安全边界——由 Controller 在调用 Service 前用可信作用域覆盖。
  239. /// </summary>
  240. [Fact]
  241. public void QueryDtos_KeepScopeFieldsForCompatibilityOnly()
  242. {
  243. foreach (var t in new[]
  244. {
  245. typeof(AdoS8ExceptionQueryDto),
  246. typeof(AdoS8MonitoringSummaryQueryDto),
  247. typeof(AdoS8DetectionLogQueryDto),
  248. typeof(AdoS8NotificationLogQueryDto),
  249. typeof(AdoS8IssueLedgerQueryDto),
  250. typeof(AdoS8CellDataQueryDto),
  251. })
  252. {
  253. var tenant = t.GetProperty("TenantId");
  254. var factory = t.GetProperty("FactoryId");
  255. Assert.NotNull(tenant);
  256. Assert.NotNull(factory);
  257. // 必须可写,Controller 才能用可信作用域覆盖客户端传入值。
  258. Assert.True(tenant!.CanWrite, $"{t.Name}.TenantId 必须可写,否则 Controller 无法覆盖客户端作用域");
  259. Assert.True(factory!.CanWrite, $"{t.Name}.FactoryId 必须可写,否则 Controller 无法覆盖客户端作用域");
  260. }
  261. }
  262. }