Bladeren bron

test(cfc): S-cfc-411 oauth.oauthClient.callback 契约 RED 单测

新增 OAuthClientCallbackContractTest:为 WorkBuddy Buddy 应用 OAuth 授权回调端点
(/api/oauth/callback) 写契约级单测,断言 B01 路由注册(OAuthClientController 存在、
类级 @RequestMapping(/api/oauth)、方法级 /callback、@RequestMapping methods={GET,POST}
双达、禁止 @PostMapping/@GetMapping 一刀切、占位响应 data 含 received=true/state 回显/
timestamp)与 B02 匿名放行(JwtInterceptor.PUBLIC_PATHS 追加 + WebConfig 双 exclude)。
当前实现未落地,预期 RED(7/8 失败)。
Administrator 4 dagen geleden
bovenliggende
commit
c810fe4121
1 gewijzigde bestanden met toevoegingen van 379 en 0 verwijderingen
  1. 379 0
      cfc-backend/src/test/java/com/etotem/cfc/unit/OAuthClientCallbackContractTest.java

+ 379 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/OAuthClientCallbackContractTest.java

@@ -0,0 +1,379 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.common.Result;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+
+/**
+ * 契约级单测:WorkBuddy Buddy 应用 OAuth 授权回调端点(能力键 {@code oauth.oauthClient.callback},
+ * S-cfc-411)。
+ *
+ * <p><b>契约溯源</b>:{@code docs/tdd/orchestration/task-oauth-callback-20261116.md}
+ * <ul>
+ *   <li><b>B01</b>:{@code OAuthClientController} 初始真实现——包路径
+ *       {@code com.etotem.cfc.controller.oauth},类级 {@code @RequestMapping("/api/oauth")},
+ *       方法级 {@code /callback},即完整路径 {@code POST /api/oauth/callback};<b>同时支持 GET 与
+ *       POST</b>({@code @RequestMapping(value="/callback", method={GET,POST})},禁止
+ *       {@code @PostMapping}/{@code @GetMapping} 一刀切——授权回调属第三方回调 webhook 例外,与
+ *       {@code PaymentController.oauth2-callback} 同性质);入参宽松兼容(GET 从 query param 取
+ *       {@code code}/{@code state},POST 从 body 取同名字段,{@code state} 缺失不报错);初始真实现
+ *       只做日志 + 占位响应——返回 {@link Result#success},{@code data} 至少含 {@code received=true}、
+ *       {@code state} 回显、{@code timestamp};<b>不产 token、不落库、不调 WorkBuddy 换票接口</b>。</li>
+ *   <li><b>B02</b>:放行白名单——{@code JwtInterceptor.PUBLIC_PATHS} 追加 {@code /api/oauth/callback};
+ *       {@code WebConfig} 的 {@code jwtInterceptor} 与 {@code familyAccessInterceptor} 两处
+ *       {@code excludePathPatterns(...)} 各追加一次;保证 OAuth 回调<b>匿名无 token 可达 200</b>
+ *       (OAuth 授权回跳典型形态是平台 302 携带 code 到 redirect_uri,无用户 token、无家庭上下文)。</li>
+ * </ul></p>
+ *
+ * <p><b>实现现状(TDD-RED)</b>:本分支 src/main 中 {@code OAuthClientController} 类未落地,
+ * {@code JwtInterceptor.PUBLIC_PATHS} / {@code WebConfig} 亦未追加 {@code /api/oauth/callback}。
+ * 因此本测试以「反射结构契约 + 源码收录契约」探测实现缺失:能编译通过、能运行、断言失败(红),
+ * 且失败断言原文清晰可贴。纯 JUnit + Mockito/反射,无 Spring 上下文 / 无 DB / 无外部服务,
+ * 风格参考 {@code TeamProfitHookContractTest} / {@code CouponShareClaimContractTest}。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:实现者按 B01/B02 落地后本测试自动转绿。届时「匿名无 token 可达 200」
+ * 若需真跑 HTTP 可在集成层换 MockMvc(本测试为纯单元契约,以「路由注册 + 匿名放行配置齐备」的
+ * 结构断言代理「可达 200」)。</p>
+ */
+class OAuthClientCallbackContractTest {
+
+    /** B01:契约要求的控制器全限定名 */
+    private static final String CONTROLLER = "com.etotem.cfc.controller.oauth.OAuthClientController";
+
+    /** B01:类级基路径 */
+    private static final String BASE_PATH = "/api/oauth";
+
+    /** B01:方法级路径 */
+    private static final String METHOD_PATH = "/callback";
+
+    /** B01/B02:完整回调路径(放行白名单条目) */
+    private static final String CALLBACK_PATH = "/api/oauth/callback";
+
+    /** B02:JwtInterceptor 公开白名单字段 */
+    private static final String PUBLIC_PATHS_FIELD = "PUBLIC_PATHS";
+
+    /** B02:JwtInterceptor 必须登录路径字段(回调不得落入,否则无 token 401 而非 200) */
+    private static final String LOGIN_REQUIRED_FIELD = "LOGIN_REQUIRED_PATHS";
+
+    /** 行为断言用通用 state 值:无论 GREEN 从 query/body 哪个来源取 state,回显应一致 */
+    private static final String TEST_STATE = "S-CFC-411-TEST-STATE";
+
+    /** 行为断言用通用 code 值(契约不校验 code 值,仅保证入参宽松兼容) */
+    private static final String TEST_CODE = "S-CFC-411-TEST-CODE";
+
+    // ------------------------------------------------------------------
+    // 正常流:路由注册(B01)——控制器类存在、路径映射、GET+POST 双达
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-1:OAuthClientController 类应存在(com.etotem.cfc.controller.oauth)")
+    void controller_classExists() {
+        assertNotNull(loadClass(CONTROLLER),
+                "[oauth.oauthClient.callback] OAuthClientController 类不存在:契约要求"
+                        + " /api/oauth/callback 授权回调端点真实存在(B01)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:类级 @RequestMapping 应映射 /api/oauth")
+    void controller_classLevelBasePath() {
+        Class<?> clazz = loadClass(CONTROLLER);
+        if (clazz == null) {
+            fail("[oauth.oauthClient.callback] OAuthClientController 类不存在,无法验证类级路由(B01)。");
+        }
+        assertNotNull(clazz.getAnnotation(RestController.class),
+                "[oauth.oauthClient.callback] OAuthClientController 应为 @RestController(B01)。");
+        RequestMapping rm = clazz.getAnnotation(RequestMapping.class);
+        assertNotNull(rm,
+                "[oauth.oauthClient.callback] OAuthClientController 缺少类级 @RequestMapping(B01)。");
+        assertTrue(containsPath(rm, BASE_PATH),
+                "[oauth.oauthClient.callback] 类级 @RequestMapping 应映射 \"" + BASE_PATH
+                        + "\",实际=" + join(rm.value()) + "(B01)。");
+    }
+
+    @Test
+    @DisplayName("正常流-3:callback 方法应存在且映射 /callback")
+    void controller_callbackMethodMapped() {
+        Class<?> clazz = loadClass(CONTROLLER);
+        if (clazz == null) {
+            fail("[oauth.oauthClient.callback] OAuthClientController 类不存在,无法验证 callback 方法(B01)。");
+        }
+        Method callback = findCallbackMethod(clazz);
+        if (callback == null) {
+            fail("[oauth.oauthClient.callback] OAuthClientController 缺少 callback 方法:契约要求"
+                    + " 方法级 /callback(B01)。");
+        }
+        RequestMapping rm = callback.getAnnotation(RequestMapping.class);
+        assertNotNull(rm,
+                "[oauth.oauthClient.callback] callback 方法缺少 @RequestMapping(B01)。");
+        assertTrue(containsPath(rm, METHOD_PATH),
+                "[oauth.oauthClient.callback] callback 方法应映射 \"" + METHOD_PATH
+                        + "\",实际=" + join(rm.value()) + "(B01)。");
+    }
+
+    @Test
+    @DisplayName("正常流-4:callback 应 GET+POST 双达,且禁止 @PostMapping/@GetMapping 一刀切")
+    void controller_callbackGetPostDual() {
+        Class<?> clazz = loadClass(CONTROLLER);
+        if (clazz == null) {
+            fail("[oauth.oauthClient.callback] OAuthClientController 类不存在,无法验证 GET+POST(B01)。");
+        }
+        Method callback = findCallbackMethod(clazz);
+        if (callback == null) {
+            fail("[oauth.oauthClient.callback] OAuthClientController 缺少 callback 方法,无法验证 GET+POST(B01)。");
+        }
+        // 授权回调属第三方回调例外,必须用 @RequestMapping(method={GET,POST}),
+        // 禁止 @PostMapping/@GetMapping(验收标准:grep 不得出现)。
+        assertTrue(callback.getAnnotation(PostMapping.class) == null
+                        && callback.getAnnotation(GetMapping.class) == null,
+                "[oauth.oauthClient.callback] callback 不得用 @PostMapping/@GetMapping 一刀切:"
+                        + "OAuth 授权回跳是平台 302 携带 code 到 redirect_uri(query param,GET),"
+                        + "须用 @RequestMapping(method={GET,POST}) 双达(B01.2)。");
+        RequestMapping rm = callback.getAnnotation(RequestMapping.class);
+        assertNotNull(rm,
+                "[oauth.oauthClient.callback] callback 方法缺少 @RequestMapping(B01.2)。");
+        boolean hasGet = false;
+        boolean hasPost = false;
+        for (RequestMethod m : rm.method()) {
+            if (m == RequestMethod.GET) {
+                hasGet = true;
+            }
+            if (m == RequestMethod.POST) {
+                hasPost = true;
+            }
+        }
+        assertTrue(hasGet && hasPost,
+                "[oauth.oauthClient.callback] @RequestMapping methods 应含 GET 与 POST,实际="
+                        + java.util.Arrays.toString(rm.method()) + "(B01.2)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流:占位响应行为(B01.4)——data 含 received=true / state 回显 / timestamp
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-5:callback 返回 Result.success,data 含 received=true、state 回显、timestamp")
+    void callback_returnsPlaceholderResponse() throws Exception {
+        Class<?> clazz = loadClass(CONTROLLER);
+        if (clazz == null) {
+            fail("[oauth.oauthClient.callback] OAuthClientController 类不存在,无法验证占位响应(B01.4)。");
+        }
+        Method callback = findCallbackMethod(clazz);
+        if (callback == null) {
+            fail("[oauth.oauthClient.callback] OAuthClientController 缺少 callback 方法,无法验证占位响应(B01.4)。");
+        }
+        Object raw = invokeCallback(clazz, callback);
+        assertNotNull(raw, "[oauth.oauthClient.callback] callback 应返回非空 Result(B01.4)。");
+        assertTrue(raw instanceof Result,
+                "[oauth.oauthClient.callback] callback 应返回 Result,实际=" + raw.getClass().getName() + "(B01.4)。");
+        Result<?> result = (Result<?>) raw;
+        assertEquals(Integer.valueOf(200), result.getCode(),
+                "[oauth.oauthClient.callback] 占位实现应返回 success(code=200)(B01.4)。");
+        assertNotNull(result.getData(),
+                "[oauth.oauthClient.callback] data 不应为空(B01.4)。");
+        assertTrue(result.getData() instanceof Map,
+                "[oauth.oauthClient.callback] data 应为 Map,实际=" + result.getData().getClass().getName() + "(B01.4)。");
+        @SuppressWarnings("unchecked")
+        Map<String, Object> data = (Map<String, Object>) result.getData();
+        assertEquals(Boolean.TRUE, data.get("received"),
+                "[oauth.oauthClient.callback] data 应含 received=true(B01.4)。");
+        assertEquals(TEST_STATE, data.get("state"),
+                "[oauth.oauthClient.callback] data 应回显 state(B01.4)。");
+        assertNotNull(data.get("timestamp"),
+                "[oauth.oauthClient.callback] data 应含 timestamp(B01.4)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:匿名无 token 可达 200(B02)——PUBLIC_PATHS 放行 + WebConfig 双 exclude
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-1:JwtInterceptor.PUBLIC_PATHS 应含 /api/oauth/callback(匿名放行)")
+    void interceptor_publicPathWhitelisted() {
+        String[] publicPaths = readStringArrayField("com.etotem.cfc.config.JwtInterceptor", PUBLIC_PATHS_FIELD);
+        if (publicPaths == null) {
+            fail("[oauth.oauthClient.callback] 无法读取 JwtInterceptor.PUBLIC_PATHS(B02)。");
+        }
+        for (String p : publicPaths) {
+            if (CALLBACK_PATH.equals(p)) {
+                return;
+            }
+        }
+        fail("[oauth.oauthClient.callback] JwtInterceptor.PUBLIC_PATHS 缺少 " + CALLBACK_PATH
+                + ":OAuth 回调无用户 token,须匿名放行(B02)。");
+    }
+
+    @Test
+    @DisplayName("边界流-2:/api/oauth/callback 不得落入 LOGIN_REQUIRED_PATHS(否则无 token 401 而非 200)")
+    void interceptor_notLoginRequired() {
+        String[] loginRequired = readStringArrayField("com.etotem.cfc.config.JwtInterceptor", LOGIN_REQUIRED_FIELD);
+        if (loginRequired == null) {
+            fail("[oauth.oauthClient.callback] 无法读取 JwtInterceptor.LOGIN_REQUIRED_PATHS(B02)。");
+        }
+        for (String p : loginRequired) {
+            if (CALLBACK_PATH.equals(p)) {
+                fail("[oauth.oauthClient.callback] " + CALLBACK_PATH
+                        + " 不得落入 LOGIN_REQUIRED_PATHS:preHandle 中 loginRequired 先于 isPublicPath 判定,"
+                        + "会令匿名无 token 直接 401,破坏「可达 200」(B02)。");
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("边界流-3:WebConfig 应两处 excludePathPatterns 追加 /api/oauth/callback")
+    void webConfig_excludesCallbackTwice() {
+        String source = readMainSource("com/etotem/cfc/config/WebConfig.java");
+        if (source.isEmpty()) {
+            fail("[oauth.oauthClient.callback] 无法读取 WebConfig.java 源文件,无法验证 exclude 追加(B02)。");
+        }
+        int count = countOccurrences(source, "\"" + CALLBACK_PATH + "\"");
+        assertTrue(count >= 2,
+                "[oauth.oauthClient.callback] WebConfig 应在 jwtInterceptor 与 familyAccessInterceptor"
+                        + " 两处 excludePathPatterns 各追加一次 " + CALLBACK_PATH + ",实际出现 " + count
+                        + " 次(B02)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 反射/源码辅助
+    // ------------------------------------------------------------------
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private Method findCallbackMethod(Class<?> clazz) {
+        for (Method m : clazz.getDeclaredMethods()) {
+            if (m.getName().equals("callback")) {
+                return m;
+            }
+        }
+        return null;
+    }
+
+    private boolean containsPath(RequestMapping rm, String path) {
+        for (String v : rm.value()) {
+            if (path.equals(v)) {
+                return true;
+            }
+        }
+        for (String p : rm.path()) {
+            if (path.equals(p)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private String join(String[] arr) {
+        return java.util.Arrays.toString(arr);
+    }
+
+    /**
+     * 反射调用 callback:按方法形参类型自适应构建实参(Mockito mock 或默认值),
+     * 对契约声明的宽松入参(GET query param / POST body 均可)不做位置假设。
+     */
+    private Object invokeCallback(Class<?> clazz, Method callback) throws Exception {
+        Object controller = clazz.getDeclaredConstructor().newInstance();
+        Object[] args = buildArgs(callback);
+        return callback.invoke(controller, args);
+    }
+
+    private Object[] buildArgs(Method callback) {
+        Class<?>[] types = callback.getParameterTypes();
+        if (types.length == 0) {
+            return new Object[0];
+        }
+        Object[] args = new Object[types.length];
+        for (int i = 0; i < types.length; i++) {
+            Class<?> t = types[i];
+            if (t == HttpServletRequest.class) {
+                args[i] = mock(HttpServletRequest.class);
+            } else if (t == HttpServletResponse.class) {
+                args[i] = mock(HttpServletResponse.class);
+            } else if (Map.class.isAssignableFrom(t)) {
+                Map<String, Object> m = new HashMap<>();
+                m.put("code", TEST_CODE);
+                m.put("state", TEST_STATE);
+                args[i] = m;
+            } else if (t == String.class) {
+                args[i] = TEST_STATE; // 通用值:code/state 任一来源回显一致
+            } else if (t == long.class) {
+                args[i] = 0L;
+            } else if (t == int.class) {
+                args[i] = 0;
+            } else if (t == boolean.class) {
+                args[i] = false;
+            } else {
+                args[i] = null;
+            }
+        }
+        return args;
+    }
+
+    /** 读取 JwtInterceptor 的 private static final String[] 字段值(B02 白名单结构契约) */
+    private String[] readStringArrayField(String className, String fieldName) {
+        try {
+            Class<?> clazz = Class.forName(className, true, Thread.currentThread().getContextClassLoader());
+            Field f = clazz.getDeclaredField(fieldName);
+            f.setAccessible(true);
+            Object v = f.get(null);
+            return v instanceof String[] ? (String[]) v : null;
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
+    /** 读取 src/main 源文件(兼容 mvn 从 cfc-backend 或仓库根运行) */
+    private String readMainSource(String relative) {
+        String[] candidates = {
+                "src/main/java/" + relative,
+                "cfc-backend/src/main/java/" + relative
+        };
+        for (String c : candidates) {
+            Path p = Paths.get(c);
+            if (Files.exists(p)) {
+                try {
+                    return new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
+                } catch (Exception e) {
+                    return "";
+                }
+            }
+        }
+        return "";
+    }
+
+    private int countOccurrences(String source, String needle) {
+        int count = 0;
+        int idx = 0;
+        while ((idx = source.indexOf(needle, idx)) >= 0) {
+            count++;
+            idx += needle.length();
+        }
+        return count;
+    }
+}