Просмотр исходного кода

fix(k8): 审查修复 C1(@Component防启动失败)/I1(admin接口role守卫)/I2(status归属+白名单)/I3(tags拼summary识别), 补3回归测试(34/34绿)

Xiaogang Liao 4 дней назад
Родитель
Сommit
eb897e161a

+ 37 - 17
cfc-backend/src/main/java/com/etotem/cfc/controller/DeviceMaintenanceController.java

@@ -8,6 +8,7 @@ import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import java.time.LocalDate;
+import java.util.Collections;
 import java.util.List;
 import java.util.stream.Collectors;
 
@@ -21,15 +22,14 @@ public class DeviceMaintenanceController {
     @Resource
     private DeviceMaintenanceReminderMapper mapper;
 
-    /**
-     * 查询当前用户/家庭的待办提醒:仅 pending 且今天已进入窗口(含逾期)。
-     * 测试直接传 userId/familyId/today;生产入口由重载方法从请求上下文取。
-     */
+    /** 查询当前用户/家庭的待办提醒:仅 pending 且今天已进入窗口(含逾期)。 */
     public Result<?> list(Long userId, Long familyId, LocalDate today) {
+        // 双 null 不加 where 会泄露全表 → 直接返回空(与 K8RecommendationService.activeReminders 对齐)
+        if (userId == null && familyId == null) return Result.success(Collections.emptyList());
         LambdaQueryWrapper<DeviceMaintenanceReminder> qw = new LambdaQueryWrapper<>();
         qw.eq(DeviceMaintenanceReminder::getStatus, "pending");
         if (familyId != null) qw.eq(DeviceMaintenanceReminder::getFamilyId, familyId);
-        else if (userId != null) qw.eq(DeviceMaintenanceReminder::getBuyerId, userId);
+        else qw.eq(DeviceMaintenanceReminder::getBuyerId, userId);
         List<DeviceMaintenanceReminder> all = mapper.selectList(qw);
         LocalDate now = today != null ? today : LocalDate.now();
         List<DeviceMaintenanceReminder> result = all.stream()
@@ -39,15 +39,39 @@ public class DeviceMaintenanceController {
         return Result.success(result);
     }
 
-    /** HTTP 入口:从请求上下文取 familyId/userId,今天取系统日期。 */
     @PostMapping("/list")
-    public Result<?> listHttp(@RequestAttribute(value = "familyId", required = false) Long familyId,
-                              @RequestAttribute(value = "userId", required = false) Long userId) {
+    public Result<?> listHttp(@RequestAttribute(value = "userId", required = false) Long userId,
+                              @RequestAttribute(value = "familyId", required = false) Long familyId) {
         return list(userId, familyId, LocalDate.now());
     }
 
-    /** 更新提醒状态为 done/dismissed。 */
+    /** 后端管理员全量查询(需 admin 角色)。 */
+    public Result<?> adminList(String role) {
+        if (!"admin".equals(role)) return Result.error(403, "无权限");
+        return Result.success(mapper.selectList(null));
+    }
+
+    @PostMapping("/admin/list")
+    public Result<?> adminListHttp(@RequestAttribute(value = "role", required = false) String role) {
+        return adminList(role);
+    }
+
+    /** 更新提醒状态:校验归属 + status 白名单。 */
+    public Result<?> updateStatus(Long id, String status, Long userId, Long familyId) {
+        if (!"done".equals(status) && !"dismissed".equals(status)) return Result.error("status 非法");
+        DeviceMaintenanceReminder r = mapper.selectById(id);
+        if (r == null) return Result.error("提醒不存在");
+        boolean owner = (familyId != null && familyId.equals(r.getFamilyId()))
+                || (userId != null && userId.equals(r.getBuyerId()));
+        if (!owner) return Result.error(403, "无权操作他人提醒");
+        r.setStatus(status);
+        mapper.updateById(r);
+        return Result.success(r);
+    }
+
+    /** 测试/内部用的无归属校验重载(单测直构兼容),生产 HTTP 入口走带归属校验版本。 */
     public Result<?> updateStatus(Long id, String status) {
+        if (!"done".equals(status) && !"dismissed".equals(status)) return Result.error("status 非法");
         DeviceMaintenanceReminder r = mapper.selectById(id);
         if (r == null) return Result.error("提醒不存在");
         r.setStatus(status);
@@ -56,14 +80,10 @@ public class DeviceMaintenanceController {
     }
 
     @PostMapping("/{id}/status")
-    public Result<?> updateStatusHttp(@PathVariable Long id, @RequestBody java.util.Map<String, Object> body) {
+    public Result<?> updateStatusHttp(@PathVariable Long id, @RequestBody java.util.Map<String, Object> body,
+                                      @RequestAttribute(value = "userId", required = false) Long userId,
+                                      @RequestAttribute(value = "familyId", required = false) Long familyId) {
         Object s = body.get("status");
-        return updateStatus(id, s == null ? "done" : String.valueOf(s));
-    }
-
-    /** 后台全量查询(分页沿用现有约定,此处返回全量 pending+已完成)。 */
-    @PostMapping("/admin/list")
-    public Result<?> adminList() {
-        return Result.success(mapper.selectList(null));
+        return updateStatus(id, s == null ? "done" : String.valueOf(s), userId, familyId);
     }
 }

+ 4 - 1
cfc-backend/src/main/java/com/etotem/cfc/service/ContentRecommendService.java

@@ -199,7 +199,10 @@ public class ContentRecommendService {
             RecommendItemVO vo = new RecommendItemVO();
             vo.setId(a.getId());
             vo.setTitle(a.getTitle());
-            vo.setSummary(a.getSummary());
+            // K8 §6.2:tags 拼入 summary 供还原水关键词识别(纯逻辑按 title+summary 匹配)
+            String tags = a.getTags();
+            vo.setSummary((a.getSummary() == null ? "" : a.getSummary())
+                    + (tags == null || tags.trim().isEmpty() ? "" : " " + tags));
             vo.setCoverImage(a.getCoverImage());
             vo.setDimensionCode(dimensionCode);
             vo.setRecommendScore(score);

+ 4 - 2
cfc-backend/src/main/java/com/etotem/cfc/service/K8RecommendationBoostService.java

@@ -2,16 +2,18 @@ package com.etotem.cfc.service;
 
 import com.etotem.cfc.dto.RecommendItemVO;
 import com.etotem.cfc.entity.DeviceMaintenanceReminder;
+import org.springframework.stereotype.Component;
 
 import java.util.ArrayList;
 import java.util.Comparator;
 import java.util.List;
 
 /**
- * 还原水机 K8 推荐增强纯逻辑(spec §5.2/§6.2)。
+ * 还原水机 K8 推荐增强逻辑(spec §5.2/§6.2)。
  *
- * <p>与 Spring 解耦:接收「提醒列表 + 配置值 + 推荐项列表」做后处理,便于单测与两处挂点复用。</p>
+ * <p>由 K8RecommendationService 注入使用(故注册为 Spring Bean);逻辑本身无外部依赖,便于单测。</p>
  */
+@Component
 public class K8RecommendationBoostService {
 
     /**

+ 10 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/K8ArticleRecommendationTest.java

@@ -58,6 +58,16 @@ class K8ArticleRecommendationTest {
         assertEquals(-100, r.get(0).getRecommendScore(), "原分-200(<min)读完→赋-100(直接赋值,非Math.min)");
     }
 
+    @Test
+    void tags_in_summary_also_match_keyword() {
+        // spec §6.2: tags 拼入 summary 后,标题不含关键词但含标签词也应加分
+        RecommendItemVO v = item(1L, "某篇文章", 10);
+        v.setSummary("标签: 还原水, 健康");
+        List<RecommendItemVO> r = svc.applyArticleRules(new ArrayList<>(Collections.singletonList(v)),
+                KEYWORDS, 50, -100, NO_COMPLETED);
+        assertEquals(60, r.get(0).getRecommendScore(), "summary(含tags)命中关键词+50");
+    }
+
     @Test
     void not_mutate_input() {
         List<RecommendItemVO> items = new ArrayList<>(Arrays.asList(item(1L, "还原水", 10)));

+ 35 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/K8BeanWiringTest.java

@@ -0,0 +1,35 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.service.K8RecommendationBoostService;
+import com.etotem.cfc.service.K8RecommendationService;
+import com.etotem.cfc.service.K8MaintenanceCalculator;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * 回归防护(审查 C1):K8 服务必须被 Spring 管理,否则 @Resource 注入失败导致上下文启动崩溃。
+ * 纯反射断言注解,不连 Spring 上下文(环境限制)。
+ */
+class K8BeanWiringTest {
+
+    @Test
+    void boost_service_is_spring_component() {
+        assertTrue(K8RecommendationBoostService.class.isAnnotationPresent(org.springframework.stereotype.Component.class)
+                        || K8RecommendationBoostService.class.isAnnotationPresent(org.springframework.stereotype.Service.class),
+                "K8RecommendationBoostService 必须有 @Component/@Service,否则 K8RecommendationService 的 @Resource 注入失败");
+    }
+
+    @Test
+    void facade_is_spring_component() {
+        assertTrue(K8RecommendationService.class.isAnnotationPresent(org.springframework.stereotype.Component.class)
+                        || K8RecommendationService.class.isAnnotationPresent(org.springframework.stereotype.Service.class),
+                "K8RecommendationService 必须被 Spring 管理");
+    }
+
+    @Test
+    void calculator_is_spring_component() {
+        assertTrue(K8MaintenanceCalculator.class.isAnnotationPresent(org.springframework.stereotype.Component.class),
+                "K8MaintenanceCalculator 应有 @Component");
+    }
+}

+ 59 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/K8ReminderAuthTest.java

@@ -0,0 +1,59 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.controller.DeviceMaintenanceController;
+import com.etotem.cfc.entity.DeviceMaintenanceReminder;
+import com.etotem.cfc.mapper.DeviceMaintenanceReminderMapper;
+import com.etotem.cfc.common.Result;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * 回归防护(审查 I1/I2):admin 提醒接口需 role 守卫;status 更新需归属校验 + status 白名单。
+ */
+class K8ReminderAuthTest {
+
+    private static void inject(Object t, String f, Object v) throws Exception {
+        Field x = t.getClass().getDeclaredField(f); x.setAccessible(true); x.set(t, v);
+    }
+
+    @Test
+    void admin_list_rejects_non_admin_role() throws Exception {
+        DeviceMaintenanceController c = new DeviceMaintenanceController();
+        DeviceMaintenanceReminderMapper m = mock(DeviceMaintenanceReminderMapper.class);
+        inject(c, "mapper", m);
+        // 普通用户 role=user 调 admin 列表 → 应拒绝
+        Result<?> r = c.adminList("user");
+        assertNotEquals(200, r.getCode(), "非admin角色调用admin全量接口应被拒绝");
+        verify(m, never()).selectList(null);
+    }
+
+    @Test
+    void update_status_rejects_wrong_owner() throws Exception {
+        DeviceMaintenanceController c = new DeviceMaintenanceController();
+        DeviceMaintenanceReminderMapper m = mock(DeviceMaintenanceReminderMapper.class);
+        inject(c, "mapper", m);
+        DeviceMaintenanceReminder r = new DeviceMaintenanceReminder();
+        r.setId(1L); r.setBuyerId(99L); r.setFamilyId(99L); r.setStatus("pending");
+        when(m.selectById(1L)).thenReturn(r);
+        // 当前用户 family=57 试图改 family=99 的提醒 → 拒绝
+        Result<?> res = c.updateStatus(1L, "done", 54L, 57L);
+        assertNotEquals(200, res.getCode(), "跨归属改状态应拒绝");
+        verify(m, never()).updateById(any());
+    }
+
+    @Test
+    void update_status_rejects_invalid_status() throws Exception {
+        DeviceMaintenanceController c = new DeviceMaintenanceController();
+        DeviceMaintenanceReminderMapper m = mock(DeviceMaintenanceReminderMapper.class);
+        inject(c, "mapper", m);
+        DeviceMaintenanceReminder r = new DeviceMaintenanceReminder();
+        r.setId(1L); r.setBuyerId(54L); r.setFamilyId(57L); r.setStatus("pending");
+        when(m.selectById(1L)).thenReturn(r);
+        Result<?> res = c.updateStatus(1L, "bogus", 54L, 57L);
+        assertNotEquals(200, res.getCode(), "非法 status 应拒绝");
+    }
+}