fix(密钥配置): 保存沿用刚检测过的输入值结果,消除「三项检测通过却提示未检测」死循环

- 服务端:对「输入值(未保存)」的检测结果按 uid+模块+值指纹暂存 Redis(TTL 30min,
  Redis 异常降级为需重新检测,不阻断保存);保存同一个值时落库该结果
  (passed/failed/error 一并沿用),改过值或从未检测则维持未检测
- 前端:保存后清理本地「输入值(未保存)」绿字,展示统一走服务端快照,避免展示与门禁矛盾;
  门禁提示改列「模块名(掩码):未检测 / 检测失败:原因 / 未配置」,同名掩码也能分辨模块
- 测试:UserApiSecretServiceTest 补沿用 / 值不一致 / Redis 降级用例;
  新增前后端一致性守卫测试(保存后必须清检测结果、提示必须带模块名)
This commit is contained in:
2026-09-14 13:49:25 +08:00
parent 9cac49cf58
commit 9b79d6b5db
6 changed files with 321 additions and 16 deletions
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.usersecret.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.common.security.AdminAuthSupport;
@@ -16,16 +17,24 @@ import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretMigrateReques
import com.nanri.aiimage.modules.usersecret.model.entity.UserApiSecretEntity;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
@@ -43,6 +52,11 @@ class UserApiSecretServiceTest {
private final UserDataScopeSupport userDataScopeSupport = mock(UserDataScopeSupport.class);
private final NotificationDispatchService notificationDispatchService = mock(NotificationDispatchService.class);
private final UserSecretProperties userSecretProperties = new UserSecretProperties();
private final StringRedisTemplate stringRedisTemplate = mock(StringRedisTemplate.class);
private final ObjectMapper objectMapper = new ObjectMapper();
/** 内存版 Redis 值操作:让「检测暂存 → 保存读取」的 JSON 往返在单测里真实走一遍。 */
private final Map<String, String> redisValues = new HashMap<>();
private ValueOperations<String, String> valueOps;
private UserApiSecretService newService() {
when(crypto.encrypt(anyString())).thenAnswer(inv -> "enc:" + inv.getArgument(0, String.class));
@@ -52,9 +66,24 @@ class UserApiSecretServiceTest {
});
// 默认按主管(admin)判定;超管用例里单独改打桩。
when(adminAuthSupport.currentRole(any())).thenReturn("admin");
redisValues.clear();
valueOps = mockValueOps();
when(stringRedisTemplate.opsForValue()).thenReturn(valueOps);
return new UserApiSecretService(
mapper, crypto, checkService, jikipProxyClient, adminUserMapper, adminAuthSupport, adminGroupMapper,
userDataScopeSupport, notificationDispatchService, userSecretProperties);
userDataScopeSupport, notificationDispatchService, userSecretProperties,
stringRedisTemplate, objectMapper);
}
@SuppressWarnings("unchecked")
private ValueOperations<String, String> mockValueOps() {
ValueOperations<String, String> ops = mock(ValueOperations.class);
doAnswer(inv -> {
redisValues.put(inv.getArgument(0, String.class), inv.getArgument(1, String.class));
return null;
}).when(ops).set(anyString(), anyString(), any(Duration.class));
when(ops.get(anyString())).thenAnswer(inv -> redisValues.get(inv.getArgument(0, String.class)));
return ops;
}
@Test
@@ -79,6 +108,94 @@ class UserApiSecretServiceTest {
assertThat(updated.getCheckCode()).isEmpty();
}
/**
* 用户在输入框里对待保存的值做的检测不能丢:
* 保存同一个值时沿用那次检测结果,页面不需要再检一次。
*/
@Test
void saveCarriesPassedCheckOfSameInputValue() {
UserApiSecretService service = newService();
UserApiSecretEntity existing = existingRow("enc:old-key");
when(mapper.selectOne(any())).thenReturn(existing);
when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 1678));
service.check(7L, "similar-asin", "sk-input");
// 输入值检测只暂存,不落库
verify(mapper, never()).updateById(any(UserApiSecretEntity.class));
service.save(7L, "similar-asin", "sk-input");
// 先按保存语义重置为未检测,再沿用暂存结果落回 passed
verify(mapper, times(2)).updateById(any(UserApiSecretEntity.class));
assertThat(existing.getSecretValue()).isEqualTo("enc:sk-input");
assertThat(existing.getCheckStatus()).isEqualTo("passed");
assertThat(existing.getCheckCode()).isEqualTo("ok");
assertThat(existing.getCheckLatencyMs()).isEqualTo(1678);
assertThat(existing.getCheckedAt()).isNotNull();
}
/** 检测后改过值:暂存的是另一个值的结果,不得沿用,必须重新检测。 */
@Test
void saveKeepsUnknownWhenSavedValueDiffersFromCheckedOne() {
UserApiSecretService service = newService();
UserApiSecretEntity existing = existingRow("enc:old-key");
when(mapper.selectOne(any())).thenReturn(existing);
when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 900));
service.check(7L, "similar-asin", "sk-input");
service.save(7L, "similar-asin", "sk-changed");
verify(mapper, times(1)).updateById(any(UserApiSecretEntity.class));
assertThat(existing.getSecretValue()).isEqualTo("enc:sk-changed");
assertThat(existing.getCheckStatus()).isEqualTo("unknown");
assertThat(existing.getCheckedAt()).isNull();
}
/** 沿用失败也要如实回落到「未检测」:检测不通过同样沿用,页面据此展示失败原因。 */
@Test
void saveCarriesFailedCheckOfSameInputValue() {
UserApiSecretService service = newService();
UserApiSecretEntity existing = existingRow("enc:old-key");
when(mapper.selectOne(any())).thenReturn(existing);
when(checkService.probe(any(), anyString())).thenReturn(outcome("failed", "invalid_key", "密钥无效", 300));
service.check(7L, "similar-asin", "sk-bad");
service.save(7L, "similar-asin", "sk-bad");
assertThat(existing.getCheckStatus()).isEqualTo("failed");
assertThat(existing.getCheckMessage()).isEqualTo("密钥无效");
}
/** Redis 不可用时降级:检测与保存照常成功,状态保持未检测(只影响体验,不阻断落库)。 */
@Test
void saveDegradesQuietlyWhenVerifiedCacheUnavailable() {
UserApiSecretService service = newService();
UserApiSecretEntity existing = existingRow("enc:old-key");
when(mapper.selectOne(any())).thenReturn(existing);
when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 500));
when(valueOps.get(anyString())).thenThrow(new IllegalStateException("redis down"));
assertThat(service.check(7L, "similar-asin", "sk-input").getCheckStatus()).isEqualTo("passed");
service.save(7L, "similar-asin", "sk-input");
assertThat(existing.getCheckStatus()).isEqualTo("unknown");
assertThat(existing.getCheckedAt()).isNull();
}
private UserApiSecretEntity existingRow(String cipher) {
UserApiSecretEntity existing = new UserApiSecretEntity();
existing.setId(5L);
existing.setUserId(7L);
existing.setModuleKey("similar-asin");
existing.setSecretValue(cipher);
return existing;
}
private UserApiSecretCheckService.CheckOutcome outcome(String status, String code, String message, Integer latency) {
return new UserApiSecretCheckService.CheckOutcome(status, code, message, latency, false);
}
@Test
void findPlainValueReturnsEmptyWhenDecryptFails() {
UserApiSecretService service = newService();