S8AuthorizationGuardTests.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. using Admin.NET.Plugin.AiDOP.Const.S8;
  2. using Admin.NET.Plugin.AiDOP.Controllers.S8;
  3. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.AspNetCore.Mvc.Filters;
  6. using Microsoft.AspNetCore.Mvc.Routing;
  7. using System.Reflection;
  8. using Xunit;
  9. namespace Admin.NET.Plugin.AiDOP.Tests.S8;
  10. /// <summary>
  11. /// S8-P0-4-API-AUTHORIZATION-1:S8 接口鉴权守卫。
  12. ///
  13. /// <para>修复前实测(业务账号 <c>UATExceptionA</c>,2026-09-02):
  14. /// <c>PUT /config/watch-rules/{id}/params</c> 与 <c>POST /config/operator-bindings</c>
  15. /// 都直达业务校验返回 <b>400</b> 而非 403 —— 鉴权层根本没拦。
  16. /// 根因是平台 <c>JwtHandler</c> 用「路由路径逐字转权限名」匹配,
  17. /// 而 S8 是带路径参数的 RESTful 路由(<c>…/exceptions/{id}/claim</c> → <c>…:1329909430019:claim</c>),
  18. /// 静态权限码永远不可能相等;又因末行「未登记路由默认放行」,全部 S8 接口变成登录即可调用。</para>
  19. ///
  20. /// <para>本测试全部走**反射元数据**(不是字符串 grep),逐个枚举 S8 Controller 的 Action,
  21. /// 保证:① 每个 Action 都声明了能力码;② 能力码在正式目录内;
  22. /// ③ 写动作不得落到只读能力上;④ 各类动作落到正确的能力分组;
  23. /// ⑤ 不回退到已死的 <c>ado_s8_role_permission_config.permission_codes</c>。</para>
  24. /// </summary>
  25. public class S8AuthorizationGuardTests
  26. {
  27. private static readonly Assembly PluginAssembly = typeof(AdoS8ExceptionsController).Assembly;
  28. /// <summary>S8 命名空间下的全部 Controller。</summary>
  29. public static IEnumerable<Type> S8Controllers => PluginAssembly
  30. .GetTypes()
  31. .Where(t => t.Namespace == typeof(AdoS8ExceptionsController).Namespace
  32. && typeof(ControllerBase).IsAssignableFrom(t)
  33. && !t.IsAbstract)
  34. .OrderBy(t => t.Name);
  35. public static TheoryData<Type> ControllerData()
  36. {
  37. var data = new TheoryData<Type>();
  38. foreach (var t in S8Controllers) data.Add(t);
  39. return data;
  40. }
  41. private sealed record ActionInfo(Type Controller, MethodInfo Method, string Verb, string Template, string? Permission);
  42. private static IEnumerable<ActionInfo> AllActions()
  43. {
  44. foreach (var c in S8Controllers)
  45. {
  46. foreach (var m in c.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
  47. {
  48. var http = m.GetCustomAttributes().OfType<IActionHttpMethodProvider>().FirstOrDefault();
  49. if (http == null) continue;
  50. var verb = http.HttpMethods.FirstOrDefault() ?? "GET";
  51. var template = (http as IRouteTemplateProvider)?.Template ?? string.Empty;
  52. var perm = m.GetCustomAttribute<S8PermissionAttribute>()?.Code;
  53. yield return new ActionInfo(c, m, verb.ToUpperInvariant(), template, perm);
  54. }
  55. }
  56. }
  57. private static bool IsReadCapability(string code) =>
  58. code is S8PermissionCatalog.ExceptionRead
  59. or S8PermissionCatalog.ConfigRead
  60. or S8PermissionCatalog.DashboardRead;
  61. // ───────────────────────── ① 全量覆盖 ─────────────────────────
  62. /// <summary>S8 Controller 必须被枚举到(防止命名空间搬家后本测试静默空跑)。</summary>
  63. [Fact]
  64. public void AllS8ControllersAreDiscovered()
  65. {
  66. var controllers = S8Controllers.ToList();
  67. Assert.True(controllers.Count >= 25, $"仅发现 {controllers.Count} 个 S8 Controller,疑似枚举失效");
  68. Assert.Contains(controllers, t => t == typeof(AdoS8ExceptionsController));
  69. Assert.Contains(controllers, t => t == typeof(AdoS8WatchDebugController));
  70. }
  71. /// <summary>每一个 Action 都必须有确定的授权要求,一个都不许漏。</summary>
  72. [Fact]
  73. public void EveryS8Action_DeclaresAPermission()
  74. {
  75. var missing = AllActions()
  76. .Where(a => string.IsNullOrWhiteSpace(a.Permission))
  77. .Select(a => $"{a.Controller.Name}.{a.Method.Name} [{a.Verb} {a.Template}]")
  78. .ToList();
  79. Assert.True(missing.Count == 0,
  80. "以下 S8 Action 未声明 [S8Permission],将退回平台『未登记路由默认放行』:\n" + string.Join('\n', missing));
  81. }
  82. /// <summary>声明的权限码必须在正式目录内,杜绝写错字符串导致永远匹配不到。</summary>
  83. [Fact]
  84. public void EveryDeclaredPermission_ExistsInCatalog()
  85. {
  86. var known = S8PermissionCatalog.All.Select(x => x.Code).ToHashSet(StringComparer.Ordinal);
  87. var unknown = AllActions()
  88. .Where(a => a.Permission != null && !known.Contains(a.Permission))
  89. .Select(a => $"{a.Controller.Name}.{a.Method.Name} → {a.Permission}")
  90. .Distinct().ToList();
  91. Assert.True(unknown.Count == 0, "以下权限码不在 S8PermissionCatalog 内:\n" + string.Join('\n', unknown));
  92. }
  93. // ───────────────────────── ② 写动作不得落到只读能力 ─────────────────────────
  94. /// <summary>
  95. /// 所有 mutation(非 GET)Action 都不得使用只读能力码,
  96. /// 否则「有查看权限的人」就能改配置 / 改业务状态。
  97. /// </summary>
  98. [Fact]
  99. public void MutationActions_DoNotUseReadOnlyCapabilities()
  100. {
  101. var offenders = AllActions()
  102. .Where(a => a.Verb != "GET" && a.Permission != null && IsReadCapability(a.Permission))
  103. .Select(a => $"{a.Controller.Name}.{a.Method.Name} [{a.Verb}] → {a.Permission}")
  104. .ToList();
  105. Assert.True(offenders.Count == 0, "以下写动作落在只读能力上:\n" + string.Join('\n', offenders));
  106. }
  107. // ───────────────────────── ③ 分组正确性 ─────────────────────────
  108. /// <summary>配置类 Controller 的写动作必须落在 config 组,不得使用 operator / verification 能力。</summary>
  109. [Theory]
  110. [InlineData(typeof(AdoS8ConfigWatchRulesController), S8PermissionCatalog.ConfigWatchRule)]
  111. [InlineData(typeof(AdoS8ConfigDataSourcesController), S8PermissionCatalog.ConfigDataSource)]
  112. [InlineData(typeof(AdoS8ConfigExceptionTypesController), S8PermissionCatalog.ConfigExceptionType)]
  113. [InlineData(typeof(AdoS8ConfigNotificationLayersController), S8PermissionCatalog.ConfigNotification)]
  114. [InlineData(typeof(AdoS8ConfigScenesController), S8PermissionCatalog.ConfigScene)]
  115. [InlineData(typeof(AdoS8ConfigKpiTargetsController), S8PermissionCatalog.ConfigKpi)]
  116. [InlineData(typeof(AdoS8ConfigDashboardCellsController), S8PermissionCatalog.ConfigDashboard)]
  117. [InlineData(typeof(AdoS8ConfigBindingsController), S8PermissionCatalog.ConfigOperatorBind)]
  118. [InlineData(typeof(AdoS8ConfigRolesController), S8PermissionCatalog.ConfigRoleWrite)]
  119. public void ConfigController_MutationsUseItsOwnConfigCapability(Type controller, string expected)
  120. {
  121. var mutations = AllActions().Where(a => a.Controller == controller && a.Verb != "GET").ToList();
  122. Assert.NotEmpty(mutations);
  123. Assert.All(mutations, a => Assert.Equal(expected, a.Permission));
  124. }
  125. /// <summary>配置类 Controller 一律不得出现 operator / verification 能力码。</summary>
  126. [Fact]
  127. public void ConfigControllers_NeverUseOperatorOrQualityCapabilities()
  128. {
  129. var operatorOrQuality = new[]
  130. {
  131. S8PermissionCatalog.ExceptionClaim, S8PermissionCatalog.ExceptionStart,
  132. S8PermissionCatalog.ExceptionAssign, S8PermissionCatalog.ExceptionUpgrade,
  133. S8PermissionCatalog.ExceptionReject, S8PermissionCatalog.ExceptionClose,
  134. S8PermissionCatalog.VerificationSubmit, S8PermissionCatalog.VerificationApprove,
  135. S8PermissionCatalog.VerificationReject,
  136. }.ToHashSet(StringComparer.Ordinal);
  137. var offenders = AllActions()
  138. .Where(a => a.Controller.Name.Contains("Config", StringComparison.Ordinal)
  139. && a.Permission != null && operatorOrQuality.Contains(a.Permission))
  140. .Select(a => $"{a.Controller.Name}.{a.Method.Name} → {a.Permission}")
  141. .ToList();
  142. Assert.True(offenders.Count == 0, string.Join('\n', offenders));
  143. }
  144. /// <summary>复检通过 / 退回必须是 quality 能力;提交复检、认领、开始处理必须是 operator 能力。</summary>
  145. [Theory]
  146. [InlineData("approve-verification", S8PermissionCatalog.VerificationApprove)]
  147. [InlineData("reject-verification", S8PermissionCatalog.VerificationReject)]
  148. [InlineData("submit-verification", S8PermissionCatalog.VerificationSubmit)]
  149. [InlineData("claim", S8PermissionCatalog.ExceptionClaim)]
  150. [InlineData("start-progress", S8PermissionCatalog.ExceptionStart)]
  151. [InlineData("transfer", S8PermissionCatalog.ExceptionAssign)]
  152. [InlineData("upgrade", S8PermissionCatalog.ExceptionUpgrade)]
  153. [InlineData("comment", S8PermissionCatalog.ExceptionComment)]
  154. public void ExceptionAction_MapsToExpectedCapability(string routeFragment, string expected)
  155. {
  156. var action = AllActions().SingleOrDefault(a =>
  157. a.Controller == typeof(AdoS8ExceptionsController)
  158. && a.Verb != "GET"
  159. && a.Template.EndsWith(routeFragment, StringComparison.Ordinal));
  160. Assert.NotNull(action);
  161. Assert.Equal(expected, action!.Permission);
  162. }
  163. /// <summary>「检验通过 / 退回」绝不能与「提交复检」共用能力码,否则处理人可自检自过。</summary>
  164. [Fact]
  165. public void QualityApproval_IsSeparatedFromOperatorSubmission()
  166. {
  167. Assert.NotEqual(S8PermissionCatalog.VerificationSubmit, S8PermissionCatalog.VerificationApprove);
  168. Assert.NotEqual(S8PermissionCatalog.VerificationSubmit, S8PermissionCatalog.VerificationReject);
  169. }
  170. // ───────────────────────── ④ 调试接口 ─────────────────────────
  171. /// <summary>
  172. /// 调试 / 运维接口必须要求独立的 debug 能力,且不得复用任何业务能力码。
  173. /// 该接口历史上是「任意登录用户可调用」,且能对**任意 tenantId/factoryId** 触发自动建单主链。
  174. /// </summary>
  175. [Fact]
  176. public void DebugEndpoints_RequireDedicatedDebugCapability()
  177. {
  178. var actions = AllActions().Where(a => a.Controller == typeof(AdoS8WatchDebugController)).ToList();
  179. Assert.NotEmpty(actions);
  180. Assert.All(actions, a => Assert.Equal(S8PermissionCatalog.DebugRun, a.Permission));
  181. // debug 能力码不得被任何业务接口复用。
  182. var leaked = AllActions()
  183. .Where(a => a.Permission == S8PermissionCatalog.DebugRun
  184. && a.Controller != typeof(AdoS8WatchDebugController))
  185. .Select(a => a.Controller.Name + "." + a.Method.Name)
  186. .ToList();
  187. Assert.True(leaked.Count == 0, string.Join('\n', leaked));
  188. }
  189. // ───────────────────────── ⑤ 不回退到死表 ─────────────────────────
  190. /// <summary>
  191. /// 授权判定必须走平台 SysMenu 按钮权限(<c>SysMenuService.GetOwnBtnPermList</c>),
  192. /// 不得把已确认 0 消费方的 <c>ado_s8_role_permission_config.permission_codes</c> 接回运行链。
  193. /// </summary>
  194. [Fact]
  195. public void AuthorizationDoesNotRevivePermissionCodesTable()
  196. {
  197. var root = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../Admin.NET.Plugin.AiDOP"));
  198. var src = File.ReadAllText(Path.Combine(root, "Infrastructure/S8/S8PermissionAttribute.cs"));
  199. Assert.Contains("GetOwnBtnPermList", src);
  200. Assert.DoesNotContain("AdoS8RolePermissionConfig", src);
  201. Assert.DoesNotContain("PermissionCodes", src);
  202. }
  203. /// <summary>权限门必须 fail-closed:拿不到权限服务 / 抛异常时一律 403,绝不放行。</summary>
  204. [Fact]
  205. public void PermissionGate_IsFailClosed()
  206. {
  207. var root = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../Admin.NET.Plugin.AiDOP"));
  208. var src = File.ReadAllText(Path.Combine(root, "Infrastructure/S8/S8PermissionAttribute.cs"));
  209. Assert.Contains("Status403Forbidden", src);
  210. Assert.Contains("catch", src);
  211. // 空码构造必须抛,防止 [S8Permission("")] 变成静默放行。
  212. Assert.Throws<ArgumentException>(() => new S8PermissionAttribute(""));
  213. }
  214. /// <summary>
  215. /// 目录内每个**未废弃**能力码都应至少被一个 Action 使用,避免目录与实现漂移出孤儿码。
  216. /// (<c>s8:exception:close</c> 已标 deprecated:S8 无独立关闭接口,关闭由 approve-verification
  217. /// 经状态机达成;既有 SysMenu 行与授权保持不动,故不从目录删除。)
  218. /// </summary>
  219. [Fact]
  220. public void CatalogHasNoOrphanCapability()
  221. {
  222. var used = AllActions().Where(a => a.Permission != null).Select(a => a.Permission!).ToHashSet(StringComparer.Ordinal);
  223. var orphans = S8PermissionCatalog.All
  224. .Where(x => !x.Deprecated)
  225. .Select(x => x.Code)
  226. .Where(c => !used.Contains(c))
  227. .ToList();
  228. Assert.True(orphans.Count == 0, "以下能力码在目录内但无任何 Action 使用:\n" + string.Join('\n', orphans));
  229. }
  230. /// <summary>已废弃能力码不得被任何 Action 引用(否则等于用一个没人维护的码当门禁)。</summary>
  231. [Fact]
  232. public void DeprecatedCapabilitiesAreNotReferencedByAnyAction()
  233. {
  234. var deprecated = S8PermissionCatalog.All.Where(x => x.Deprecated).Select(x => x.Code)
  235. .ToHashSet(StringComparer.Ordinal);
  236. Assert.NotEmpty(deprecated); // 防止标记体系被误删后本测试空跑
  237. var offenders = AllActions()
  238. .Where(a => a.Permission != null && deprecated.Contains(a.Permission))
  239. .Select(a => $"{a.Controller.Name}.{a.Method.Name} → {a.Permission}")
  240. .ToList();
  241. Assert.True(offenders.Count == 0, string.Join('\n', offenders));
  242. }
  243. }