Преглед изворни кода

test(oauth.oauthClient.callback): S-cfc-411 契约级RED单测 OAuth授权回调端点

- B01/B02 WorkBuddy上架: 授权回调地址 /api/oauth/callback 后端必须真实存在
- 设计锚点: @RequestMapping(/api/oauth) + /callback GET+POST双达
- JwtInterceptor.PUBLIC_PATHS + WebConfig 两处 exclude 追加(匿名可达)
- 纯反射+Mockito, 无Spring/DB/外部服务; 预期红(5失败/6), GREEN后自动转绿
E2E Test Bot пре 19 часа
родитељ
комит
51331bd7dd

+ 369 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/OAuthCallbackContractTest.java

@@ -0,0 +1,369 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.config.FamilyAccessInterceptor;
+import com.etotem.cfc.config.JwtInterceptor;
+import com.etotem.cfc.config.MiniAppInterceptor;
+import com.etotem.cfc.config.OperationLogInterceptor;
+import com.etotem.cfc.config.RateLimitInterceptor;
+import com.etotem.cfc.config.WebConfig;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
+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.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.handler.MappedInterceptor;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 契约级单测:OAuth 授权回调端点(能力键 {@code oauth.oauthClient.callback},S-cfc-411)。
+ *
+ * <p><b>需求溯源</b>(B01/B02 — Buddy 应用上架 WorkBuddy):
+ * <blockquote>
+ *   授权回调地址 {@code https://cfc.cf-club.com/api/oauth/callback} 后端必须真实存在;
+ *   当前审核中锁定,通过后 pending_config 阶段改配置。
+ * </blockquote></p>
+ *
+ * <p><b>设计锚点</b>:参考 {@code HuaweiHealthController} + {@code PaymentController oauth2-callback}:
+ * <ul>
+ *   <li>类级 {@code @RequestMapping("/api/oauth")} + 方法级 {@code /callback},<b>GET+POST 双达</b>
+ *       (外部授权页重定向走浏览器 GET,小程序/服务端轮询兜底走 POST)。</li>
+ *   <li>{@code JwtInterceptor.PUBLIC_PATHS} + {@code WebConfig} <b>两处 exclude 追加</b>:
+ *       OAuth 回调无 JWT(外部授权页跳转),必须匿名可达;若漏配,回调被拦 401,授权链断裂。</li>
+ * </ul></p>
+ *
+ * <p><b>实现现状</b>:src/main 无任何 {@code /api/oauth} 控制器映射,{@code JwtInterceptor.PUBLIC_PATHS}
+ * 无对应条目,{@code WebConfig} 两处 exclude 均未追加。故本测试以「反射结构契约」探测缺失:
+ * 能编译、能运行、断言失败(红),失败原文清晰可贴。</p>
+ *
+ * <p><b>GREEN 升级指引</b>:实现者创建 {@code @RequestMapping("/api/oauth")} 控制器(含
+ * {@code GET+POST /callback} 双达方法)、在 {@code JwtInterceptor.PUBLIC_PATHS} 追加回调公开条目、
+ * 并在 {@code WebConfig} 的 jwtInterceptor 与 familyAccessInterceptor 两处 {@code excludePathPatterns}
+ * 追加后,本测试自动转绿。</p>
+ *
+ * <p><b>权限流说明</b>:回调为外部授权跳转(无 JWT 匿名访问),无用户权限维度,
+ * 「权限(适用时)」三流中的权限流以说明性用例标注不适用。</p>
+ *
+ * <p>纯反射 + Mockito(无 Spring 上下文 / 无 DB / 无外部服务),任何环境可确定性执行。</p>
+ */
+class OAuthCallbackContractTest {
+
+    /** 契约要求的类级前缀(设计锚点:@RequestMapping /api/oauth) */
+    private static final String OAUTH_PREFIX = "/api/oauth";
+
+    /** 契约要求的回调完整路径(B01/B02:https://cfc.cf-club.com/api/oauth/callback) */
+    private static final String CALLBACK_PATH = "/api/oauth/callback";
+
+    /** 回调方法级路径(设计锚点:/callback) */
+    private static final String CALLBACK_METHOD_PATH = "/callback";
+
+    @Mock
+    private MiniAppInterceptor miniAppInterceptor;
+
+    @Mock
+    private JwtInterceptor jwtInterceptor;
+
+    @Mock
+    private FamilyAccessInterceptor familyAccessInterceptor;
+
+    @Mock
+    private OperationLogInterceptor operationLogInterceptor;
+
+    @Mock
+    private RateLimitInterceptor rateLimitInterceptor;
+
+    @InjectMocks
+    private WebConfig webConfig;
+
+    private List<MappedInterceptor> mapped;
+
+    @BeforeEach
+    @SuppressWarnings("unchecked")
+    void setUp() throws Exception {
+        MockitoAnnotations.openMocks(this);
+        InterceptorRegistry registry = new InterceptorRegistry();
+        webConfig.addInterceptors(registry);
+        Method getInterceptors = InterceptorRegistry.class.getDeclaredMethod("getInterceptors");
+        getInterceptors.setAccessible(true);
+        List<Object> raw = (List<Object>) getInterceptors.invoke(registry);
+        assertNotNull(raw, "注册列表不应为空");
+        mapped = new ArrayList<>();
+        for (Object o : raw) {
+            mapped.add((MappedInterceptor) o);
+        }
+    }
+
+    // ------------------------------------------------------------------
+    // 正常流:/api/oauth 控制器存在 + /callback GET+POST 双达(B01/B02)
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("正常流-1:存在类级 @RequestMapping(/api/oauth) 的 OAuth 回调控制器(B01/B02)")
+    void oauthCallback_controllerExists() throws Exception {
+        Class<?> controller = findOauthCallbackController();
+        assertNotNull(controller,
+                "[oauth.oauthClient.callback] 未找到类级 @RequestMapping(\"/api/oauth\") 的控制器:"
+                        + "授权回调地址 /api/oauth/callback 后端必须真实存在(B01/B02,WorkBuddy 上架审核)。"
+                        + "实现未落地:需新建 @RestController 并 @RequestMapping(\"/api/oauth\")。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:/callback 端点必须支持 GET + POST 双达")
+    void oauthCallback_callbackSupportsGetAndPost() throws Exception {
+        Class<?> controller = findOauthCallbackController();
+        assertNotNull(controller,
+                "[oauth.oauthClient.callback] 前置失败:/api/oauth 控制器不存在,无法验证 /callback 双达。");
+        boolean supportsGet = false;
+        boolean supportsPost = false;
+        for (Method m : controller.getDeclaredMethods()) {
+            if (!mappedToCallback(m)) {
+                continue;
+            }
+            if (mappedTo(m, RequestMethod.GET)) {
+                supportsGet = true;
+            }
+            if (mappedTo(m, RequestMethod.POST)) {
+                supportsPost = true;
+            }
+        }
+        assertTrue(supportsGet,
+                "[oauth.oauthClient.callback] /callback 端点未支持 GET:外部授权页 OAuth 跳转为浏览器 GET,"
+                        + "不支持 GET 则回调直接 405,授权链断裂(设计锚点:GET+POST 双达)。");
+        assertTrue(supportsPost,
+                "[oauth.oauthClient.callback] /callback 端点未支持 POST:小程序/服务端轮询兜底为 POST,"
+                        + "不支持 POST 则无法在客户端完成 code 换取(设计锚点:GET+POST 双达)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 边界流:公开可达(无 JWT)—— JwtInterceptor.PUBLIC_PATHS + WebConfig 两处 exclude
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("边界流-1:JwtInterceptor.PUBLIC_PATHS 必须覆盖 /api/oauth/callback")
+    void publicPaths_coversOauthCallback() throws Exception {
+        String[] publicPaths = readStringArray(JwtInterceptor.class, "PUBLIC_PATHS");
+        assertNotNull(publicPaths, "JwtInterceptor.PUBLIC_PATHS 应为数组");
+        boolean covered = false;
+        for (String entry : publicPaths) {
+            if (covers(entry, CALLBACK_PATH)) {
+                covered = true;
+                break;
+            }
+        }
+        assertTrue(covered,
+                "[oauth.oauthClient.callback] JwtInterceptor.PUBLIC_PATHS 未覆盖 " + CALLBACK_PATH
+                        + ":外部授权回调无 JWT,未加白名单则被 401 拦截,授权链断裂。"
+                        + "需追加该路径(或 /api/oauth/ 前缀 / /api/oauth/** 通配)到 PUBLIC_PATHS。");
+    }
+
+    @Test
+    @DisplayName("边界流-2:WebConfig jwtInterceptor excludePathPatterns 必须覆盖 /api/oauth/callback")
+    void webConfigJwtExclude_coversOauthCallback() throws Exception {
+        MappedInterceptor mi = findMapped(jwtInterceptor);
+        assertNotNull(mi, "jwtInterceptor 应在 WebConfig 中注册(契约前提破坏)");
+        List<String> excludes = readExcludePatterns(mi);
+        assertTrue(coversAny(excludes, CALLBACK_PATH),
+                "[oauth.oauthClient.callback] WebConfig jwtInterceptor excludePathPatterns 未覆盖 "
+                        + CALLBACK_PATH + ":当前=" + excludes + "。需追加(设计锚点:两处 exclude 之一)。");
+    }
+
+    @Test
+    @DisplayName("边界流-3:WebConfig familyAccessInterceptor excludePathPatterns 必须覆盖 /api/oauth/callback")
+    void webConfigFamilyExclude_coversOauthCallback() throws Exception {
+        MappedInterceptor mi = findMapped(familyAccessInterceptor);
+        assertNotNull(mi, "familyAccessInterceptor 应在 WebConfig 中注册(契约前提破坏)");
+        List<String> excludes = readExcludePatterns(mi);
+        assertTrue(coversAny(excludes, CALLBACK_PATH),
+                "[oauth.oauthClient.callback] WebConfig familyAccessInterceptor excludePathPatterns 未覆盖 "
+                        + CALLBACK_PATH + ":当前=" + excludes + "。需追加(设计锚点:两处 exclude 之二)。");
+    }
+
+    // ------------------------------------------------------------------
+    // 权限流(不适用):外部授权回调,无用户权限维度
+    // ------------------------------------------------------------------
+
+    @Test
+    @DisplayName("权限流:本能力为外部 OAuth 授权回调(匿名可达),无用户权限维度,权限流不适用")
+    void permissionFlow_notApplicable() {
+        // 说明性用例:OAuth 授权回调由外部授权页跳转,无 JWT/无用户身份,不存在权限维度。
+        // 不产生断言失败;仅为三流覆盖标注「不适用」。
+        assertTrue(true, "权限流不适用:oauth.oauthClient.callback 为外部授权回调,无用户权限维度。");
+    }
+
+    // ------------------------------------------------------------------
+    // 反射辅助:控制器扫描
+    // ------------------------------------------------------------------
+
+    /** 扫描 controller 包下所有类级 @RequestMapping,找前缀为 /api/oauth 的控制器类。 */
+    private Class<?> findOauthCallbackController() throws Exception {
+        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
+        Resource[] resources = resolver.getResources("classpath*:com/etotem/cfc/controller/**/*.class");
+        for (Resource r : resources) {
+            String url = r.getURL().toString();
+            if (url.indexOf("/controller/") < 0) {
+                continue;
+            }
+            String rel = url.substring(url.indexOf("com/etotem/cfc/controller/"));
+            String cls = rel.replace('/', '.').replace(".class", "");
+            Class<?> c;
+            try {
+                c = Class.forName(cls, false, getClass().getClassLoader());
+            } catch (Throwable t) {
+                continue; // 内部类/无法加载的类跳过
+            }
+            RequestMapping cm = c.getAnnotation(RequestMapping.class);
+            if (cm == null) {
+                continue;
+            }
+            for (String prefix : mappingValues(cm)) {
+                if (OAUTH_PREFIX.equals(prefix)) {
+                    return c;
+                }
+            }
+        }
+        return null;
+    }
+
+    /** 方法是否映射到 /callback(方法级路径为 /callback)。 */
+    private boolean mappedToCallback(Method m) {
+        for (String p : allMethodPaths(m)) {
+            if (CALLBACK_METHOD_PATH.equals(p)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /** 方法是否以指定 HTTP 方法映射到 /callback。 */
+    private boolean mappedTo(Method m, RequestMethod method) {
+        for (String p : allMethodPaths(m)) {
+            if (!CALLBACK_METHOD_PATH.equals(p)) {
+                continue;
+            }
+            if (method == RequestMethod.GET && m.isAnnotationPresent(GetMapping.class)) {
+                return true;
+            }
+            if (method == RequestMethod.POST && m.isAnnotationPresent(PostMapping.class)) {
+                return true;
+            }
+            RequestMapping rm = m.getAnnotation(RequestMapping.class);
+            if (rm != null) {
+                if (rm.method().length == 0) {
+                    return true; // 未限定 method → 默认支持全部(含 GET/POST)
+                }
+                for (RequestMethod mth : rm.method()) {
+                    if (mth == method) {
+                        return true;
+                    }
+                }
+            }
+        }
+        return false;
+    }
+
+    /** 汇总方法级 @GetMapping/@PostMapping/@RequestMapping 的全部路径。 */
+    private Set<String> allMethodPaths(Method m) {
+        Set<String> out = new LinkedHashSet<>();
+        GetMapping get = m.getAnnotation(GetMapping.class);
+        if (get != null) {
+            out.addAll(Arrays.asList(mappingValues(get.value(), get.path())));
+        }
+        PostMapping post = m.getAnnotation(PostMapping.class);
+        if (post != null) {
+            out.addAll(Arrays.asList(mappingValues(post.value(), post.path())));
+        }
+        RequestMapping rm = m.getAnnotation(RequestMapping.class);
+        if (rm != null) {
+            out.addAll(Arrays.asList(mappingValues(rm.value(), rm.path())));
+        }
+        return out;
+    }
+
+    private String[] mappingValues(String[] value, String[] path) {
+        return value.length > 0 ? value : path;
+    }
+
+    private String[] mappingValues(RequestMapping rm) {
+        String[] v = rm.value();
+        if (v.length == 0) {
+            v = rm.path();
+        }
+        return v;
+    }
+
+    // ------------------------------------------------------------------
+    // 反射辅助:JwtInterceptor.PUBLIC_PATHS
+    // ------------------------------------------------------------------
+
+    private String[] readStringArray(Class<?> clazz, String fieldName) throws Exception {
+        Field f = clazz.getDeclaredField(fieldName);
+        f.setAccessible(true);
+        return (String[]) f.get(null);
+    }
+
+    /** 与 JwtInterceptor.preHandle 的公开路径边界匹配逻辑对齐(line 200-207)。 */
+    private boolean covers(String entry, String target) {
+        if (entry == null) {
+            return false;
+        }
+        String boundaryPath = entry.endsWith("/**")
+                ? entry.substring(0, entry.length() - 3) : entry;
+        return target.equals(entry) || target.startsWith(boundaryPath + "/");
+    }
+
+    private boolean coversAny(List<String> entries, String target) {
+        for (String e : entries) {
+            if (covers(e, target)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // ------------------------------------------------------------------
+    // 反射辅助:WebConfig 拦截器 exclude
+    // ------------------------------------------------------------------
+
+    private MappedInterceptor findMapped(HandlerInterceptor ic) {
+        for (MappedInterceptor mi : mapped) {
+            if (mi.getInterceptor() == ic) {
+                return mi;
+            }
+        }
+        return null;
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<String> readExcludePatterns(MappedInterceptor mi) throws Exception {
+        Field f = MappedInterceptor.class.getDeclaredField("excludePatterns");
+        f.setAccessible(true);
+        Object[] arr = (Object[]) f.get(mi);
+        List<String> res = new ArrayList<>();
+        if (arr != null) {
+            for (Object pa : arr) {
+                Method g = pa.getClass().getMethod("getPatternString");
+                g.setAccessible(true); // 类包私有(org.springframework.web.servlet.handler),方法虽 public 亦需放行
+                res.add((String) g.invoke(pa));
+            }
+        }
+        return res;
+    }
+}