Przeglądaj źródła

test(S-cfc-277): assessment.appointment.create 取消越权 CFC-AP RED 契约测试(SC-P-38)

Sisyphus Agent 1 dzień temu
rodzic
commit
b9a956e13

+ 179 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/AssessmentAppointmentCancelAuthzContractTest.java

@@ -0,0 +1,179 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.assessment.AssessmentAppointmentController;
+import com.etotem.cfc.service.AssessmentAppointmentService;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Parameter;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 契约级单测(TDD-RED):能力键 {@code assessment.appointment.create}(S-cfc-277)——
+ * 子契约 SC-P-38「取消预约(越权校验)」的 <b>取消越权守卫(CFC-AP)</b>。
+ *
+ * <p>契约来源(tests/user-scenarios/应用场景总览.md SC-P-38 + deep-dive-assessment-appointment.md):
+ * <blockquote>
+ *   SC-P-38:取消预约。边界:<b>非本人 / 非绑定规划师取消被拒(CFC-AP 取消越权)</b>;取消不退款逻辑。<br>
+ *   TC-DV-01(P0 权限):家长 A、B 各登录;A 有预约 id=X;B 调 {@code POST /cancel/{X}} →
+ *   <b>期望 403/拒绝</b>(当前:越权成功,缺陷 F1)。<br>
+ *   修复建议(deep-dive §6-1):{@code cancelAppointment} 增加 {@code @RequestAttribute("userId")}
+ *   并校验 {@code appointment.userId == 调用者 || 调用者 ∈ {assessorId, guideId}}。
+ * </blockquote></p>
+ *
+ * <p><b>实现现状(当前分支 src/main 核实)</b>:
+ * <ul>
+ *   <li>控制器 {@code controller/assessment/AssessmentAppointmentController.java:131-136}——
+ *       {@code cancelAppointment(@PathVariable Long id)} <b>仅接收预约 id</b>,无
+ *       {@code @RequestAttribute("userId")} 身份参数,无归属/角色校验,一律 {@code Result.success} 放行;</li>
+ *   <li>服务 {@code service/AssessmentAppointmentService.java:112-122}——
+ *       {@code cancelAppointment(Long id)} <b>仅做状态守卫(0/1→3)</b>,不接收调用者身份,
+ *       任何登录用户凭 id 即可取消他人预约(缺陷 F1,deep-dive R196 复核仍未修)。</li>
+ * </ul></p>
+ *
+ * <p><b>既有覆盖对照</b>:SC-P-36(创建消耗额度)/ SC-P-37(状态机)已实现并有绿测
+ * ({@code AssessmentQuotaAppointmentContractTest} / {@code TeacherAppointmentGuardContractTest});
+ * SC-P-38 在当前主链仅有「观察钉住」用例({@code AssessmentQuotaAppointmentContractTest}
+ * 的 {@code appointmentService_观察_取消无越权},断言的是<b>缺陷行为</b>而非契约),
+ * 无任何「越权取消应被拒」的契约断言 → 本测试补齐该契约缺口。</p>
+ *
+ * <p><b>RED 预期</b>:以下用例断言契约要求的越权取消拒绝能力,当前实现一律放行 → 断言失败(红)。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:
+ * <ol>
+ *   <li>控制器 {@code cancelAppointment} 增加 {@code @RequestAttribute("userId") Long userId} 参数;
+ *       服务层对应增加携带身份的 {@code cancelAppointment(id, userId)}(或等价身份载体)——
+ *       校验 {@code userId.equals(appointment.userId) || userId.equals(assessorId) || userId.equals(guideId)},
+ *       非本人/非被指派规划师返回 false,控制器映射为越权拒绝业务提示(非 200);</li>
+ *   <li>保持「取消不退款」:cancel 仅改 {@code status=3},不触发放回额度和任何退款副作用;</li>
+ *   <li>实现后本测试自动转绿(届时第 3 例需按新签名改写为「非本人调用 → 拒绝」行为断言)。</li>
+ * </ol></p>
+ *
+ * <p>纯 Mockito / 反射(无 Spring / 无 DB),风格对齐同批 RED 契约测试
+ * (TeamProfitHookContractTest / TeacherAppointmentGuardContractTest)。</p>
+ */
+class AssessmentAppointmentCancelAuthzContractTest {
+
+    /** 契约要求的服务层取消方法(含身份参数版本的最小签名形态:id + 调用者身份) */
+    private static final String SERVICE_CANCEL_METHOD = "cancelAppointment";
+
+    /** 契约要求的控制器身份注解载体 */
+    private static final String REQUEST_ATTRIBUTE_ANNOTATION =
+            "org.springframework.web.bind.annotation.RequestAttribute";
+
+    // ==================== 权限流:SC-P-38 取消越权(CFC-AP)应被拒 ====================
+
+    @Test
+    @DisplayName("SC-P-38 权限:服务层 cancelAppointment 应携带调用者身份参数(当前仅 id 单参 → 无法校验越权)")
+    void service_cancelAppointment_应携带身份参数() {
+        Class<?> clazz = loadClass("com.etotem.cfc.service.AssessmentAppointmentService");
+        assertTrue(clazz != null,
+                "[assessment.appointment.create/SC-P-38] AssessmentAppointmentService 类不存在。");
+
+        boolean carriesIdentity = false;
+        for (Method m : clazz.getDeclaredMethods()) {
+            if (m.getName().equals(SERVICE_CANCEL_METHOD) && m.getParameterCount() >= 2) {
+                carriesIdentity = true;
+                break;
+            }
+        }
+        assertTrue(carriesIdentity,
+                "[assessment.appointment.create/SC-P-38] 契约要求取消预约必须能校验调用者身份"
+                        + "(非本人/非被指派规划师取消被拒,CFC-AP);当前 cancelAppointment 仅 "
+                        + "cancelAppointment(Long id) 单参,无法区分调用者,任何登录用户凭 id 即可取消他人预约(缺陷 F1)。"
+                        + " GREEN 需提供携带身份的取消方法(如 cancelAppointment(id, userId))并在落库前校验归属。");
+    }
+
+    @Test
+    @DisplayName("SC-P-38 权限:控制器 cancel/{id} 应声明 @RequestAttribute(\"userId\") 身份参数(当前仅 @PathVariable id)")
+    void controller_cancelAppointment_应声明身份参数() {
+        Class<?> clazz = loadClass("com.etotem.cfc.controller.assessment.AssessmentAppointmentController");
+        assertTrue(clazz != null,
+                "[assessment.appointment.create/SC-P-38] AssessmentAppointmentController 类不存在。");
+
+        boolean hasUserIdAttribute = false;
+        for (Method m : clazz.getDeclaredMethods()) {
+            if (m.getName().equals("cancelAppointment")) {
+                for (Parameter p : m.getParameters()) {
+                    if (isRequestAttributeUserId(p)) {
+                        hasUserIdAttribute = true;
+                        break;
+                    }
+                }
+            }
+            if (hasUserIdAttribute) {
+                break;
+            }
+        }
+        assertTrue(hasUserIdAttribute,
+                "[assessment.appointment.create/SC-P-38] 契约要求取消接口(POST /api/assessment/appointment/cancel/{id})"
+                        + " 携带调用者身份(@RequestAttribute(\"userId\"),API_REFERENCE §4.10 / SC-P-38 越权边界);"
+                        + " 当前 cancelAppointment(@PathVariable Long id) 无身份参数,"
+                        + " 无法执行「非本人/非绑定规划师取消被拒」的越权校验(缺陷 F1 / TC-DV-01)。");
+    }
+
+    @Test
+    @DisplayName("SC-P-38 权限:无法验证调用者身份的取消请求应被拒(fail-closed),而非一律放行成功")
+    void controller_cancelAppointment_无身份验证_应拒绝() throws Exception {
+        AssessmentAppointmentService apptSvc = Mockito.mock(AssessmentAppointmentService.class);
+        AssessmentAppointmentController c = new AssessmentAppointmentController();
+        inject(c, "appointmentService", apptSvc);
+
+        // 契约不足裁决:当前取消接口不读取 @RequestAttribute("userId")(前置结构探测已证),
+        // 因此本次调用(无人可证明是本人/被指派规划师)按契约必须被拒 —— fail-closed,
+        // 即「身份不可验证 = 越权」,不得 200 放行(TC-DV-01:B 越权取消 A 的预约应被拒)。
+        Result<Boolean> r = c.cancelAppointment(101L);
+        assertEquals(500, r.getCode(),
+                "[assessment.appointment.create/SC-P-38] 无法验证调用者身份的取消请求应被拒绝(fail-closed,"
+                        + " 对应 TC-DV-01:B 调用 POST /cancel/{X} 取消 A 的预约应被拒);"
+                        + " 当前取消接口不携带身份、一律 Result.success 放行,越权可成功(缺陷 F1)。");
+    }
+
+    // ==================== 反射辅助 ====================
+
+    private static boolean isRequestAttributeUserId(Parameter p) {
+        for (Annotation a : p.getAnnotations()) {
+            if (!REQUEST_ATTRIBUTE_ANNOTATION.equals(a.annotationType().getName())) {
+                continue;
+            }
+            try {
+                Method valueMethod = a.annotationType().getMethod("value");
+                Object v = valueMethod.invoke(a);
+                return "userId".equals(String.valueOf(v));
+            } catch (Exception e) {
+                // 注解 value 不可读则不算命中
+            }
+        }
+        return false;
+    }
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private static void inject(Object target, String fieldName, Object value) throws Exception {
+        Class<?> clazz = target.getClass();
+        while (clazz != null) {
+            try {
+                Field f = clazz.getDeclaredField(fieldName);
+                f.setAccessible(true);
+                f.set(target, value);
+                return;
+            } catch (NoSuchFieldException e) {
+                clazz = clazz.getSuperclass();
+            }
+        }
+        throw new IllegalStateException("字段不存在: " + fieldName);
+    }
+}