feat(密钥管理): 后台可代填并锁定用户代理设置,客户端只读并回填本地配置

代理是选配、不进 items 也不参与门禁,但客户端各任务链读的是本地 app.json 的
proxy_url,用户自填值与后台不一致时排查成本高。改法:

- 后台 PUT/DELETE /api/admin/user-secrets/{userId}/modules/{moduleKey} 代填/解锁,
  写入后该行 source=admin;数据权限走 resolveVisibleUserIds,超管不限;
- 客户端 save/clear 命中锁定行时服务端直接拒绝并给出原因(只置灰挡不住直接调接口);
- 密钥包把代理单独放 proxy 字段下发(仍不进 items、不影响 complete 判定),
  锁定时带 full 明文,客户端据此幂等地对齐本地配置;解锁 = 删除该行。

只开放代理代填:密钥模块要客户端提交任务时携带本地明文,代填会把用户卡死。
This commit is contained in:
2026-09-28 19:39:08 +08:00
parent 5dd11f7048
commit 8b4425dcbf
12 changed files with 583 additions and 20 deletions
@@ -5,6 +5,8 @@ import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretQuery;
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretSaveRequest;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretPageVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
@@ -12,11 +14,14 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -26,12 +31,13 @@ import java.util.Map;
/**
* 后台密钥管理:一行一用户(货源查询密钥 / 外观专利密钥 / 代理设置 三字段列),
* 管理员查看脱敏值、立即检测、清空。不提供查看明文与代填编辑能力。
* 管理员查看脱敏值、立即检测、清空,并可为用户代填并锁定代理设置
* (锁定后客户端只能查看,清空/修改会被服务端拒绝;密钥列不下发明文,故不开放代填)。
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/admin/user-secrets")
@Tag(name = "后台密钥管理", description = "按用户查看密钥与代理配置(脱敏)、立即检测连通性、清空。")
@Tag(name = "后台密钥管理", description = "按用户查看密钥与代理配置(脱敏)、立即检测连通性、代填并锁定代理、清空。")
public class AdminUserApiSecretController {
private final UserApiSecretService userApiSecretService;
@@ -76,6 +82,30 @@ public class AdminUserApiSecretController {
return ApiResponse.success("已清空", deleted);
}
@PutMapping("/{userId}/modules/{moduleKey}")
@Operation(summary = "代填并锁定该用户某模块配置",
description = "当前仅支持代理设置:写入后客户端只能查看,清空/修改会被拒绝。主管仅能操作自己数据权限范围内的用户。")
public ApiResponse<AdminUserSecretModuleVo> saveModule(
HttpServletRequest request,
@Parameter(description = "用户ID", required = true) @PathVariable Long userId,
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey,
@Valid @RequestBody UserApiSecretSaveRequest body) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
return ApiResponse.success("已代填并锁定",
userApiSecretService.adminSaveModule(operator, userId, moduleKey, body.getValue()));
}
@DeleteMapping("/{userId}/modules/{moduleKey}")
@Operation(summary = "清空该用户某模块配置并解除锁定", description = "解锁后该用户可在客户端自行配置。")
public ApiResponse<Void> clearModule(
HttpServletRequest request,
@Parameter(description = "用户ID", required = true) @PathVariable Long userId,
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
userApiSecretService.adminClearModule(operator, userId, moduleKey);
return ApiResponse.success("已清空并解除锁定", null);
}
@PostMapping("/check-all")
@Operation(summary = "手动触发一轮全量巡检", description = "同步执行,受巡检条数与时间预算配置约束,请勿频繁调用。")
public ApiResponse<Map<String, Integer>> checkAll(HttpServletRequest request) {
@@ -24,6 +24,9 @@ public class AdminUserSecretModuleVo {
@Schema(description = "是否已配置")
private Boolean exists;
@Schema(description = "是否由后台代填并锁定:锁定时客户端不可修改或清空")
private Boolean locked;
@Schema(description = "连通性状态:unknown/passed/failed/error")
private String checkStatus;
@@ -15,6 +15,9 @@ public class UserApiSecretBundleVo {
@Schema(description = "必须配置的模块 key 列表(服务端下发,客户端不硬编码)")
private List<String> requiredModules;
@Schema(description = "代理设置状态:不在 items 内(不参与门禁);后台代填并锁定时 full 下发完整地址")
private UserApiSecretItemVo proxy;
@Schema(description = "是否配置完整:全部 required 模块均检测通过(error 状态视为放行)")
private Boolean complete;
}
@@ -18,9 +18,15 @@ public class UserApiSecretItemVo {
@Schema(description = "脱敏值,如 sk-a****1234")
private String masked;
@Schema(description = "完整明文值:仅代理模块被后台代填并锁定时下发(客户端写入本地配置用),其余情况为空")
private String full;
@Schema(description = "是否已配置")
private Boolean exists;
@Schema(description = "是否由后台代填并锁定:锁定时客户端不可修改或清空")
private Boolean locked;
@Schema(description = "连通性状态:unknown/passed/failed/error")
private String checkStatus;
@@ -101,7 +101,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
/** 当前用户密钥包:仅必填模块(代理为选配,不下发)+ 服务端下发的必填清单 + 完整性判定。 */
/** 当前用户密钥包:items 仅必填模块(代理为选配,单独走 proxy 字段不参与门禁)+ 必填清单 + 完整性判定。 */
public UserApiSecretBundleVo bundle(Long userId) {
requireUserId(userId);
List<UserSecretModule> required = UserSecretModule.requiredModules();
@@ -113,6 +113,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
vo.setItems(items);
vo.setRequiredModules(required.stream().map(UserSecretModule::key).toList());
vo.setComplete(isComplete(items));
vo.setProxy(toItem(UserSecretModule.PROXY, selectOne(userId, UserSecretModule.PROXY.key())));
return vo;
}
@@ -120,11 +121,13 @@ public class UserApiSecretService implements UserSecretCleanupPort {
* 保存密钥:加密落库并重置检测状态为 unknown;
* 若该值与用户刚检测过的输入值完全一致,则沿用那次检测结果(见 {@link #applyPendingVerification}),
* 其余情况仍由用户在保存后手动点「检测」确认。
* 后台代填并锁定的模块(source=admin)客户端不可覆盖。
*/
@Transactional
public UserApiSecretItemVo save(Long userId, String moduleKey, String value) {
requireUserId(userId);
UserSecretModule module = requireModule(moduleKey);
requireNotAdminLocked(userId, module, "修改");
String plainValue = normalize(value);
if (plainValue.isEmpty()) {
throw new BusinessException(module == UserSecretModule.PROXY ? "代理地址不能为空" : "密钥不能为空");
@@ -138,17 +141,78 @@ public class UserApiSecretService implements UserSecretCleanupPort {
return toItem(module, selectOne(userId, module.key()));
}
/** 清空密钥。 */
/** 清空密钥。后台代填并锁定的模块不可清空。 */
@Transactional
public void clear(Long userId, String moduleKey) {
requireUserId(userId);
UserSecretModule module = requireModule(moduleKey);
requireNotAdminLocked(userId, module, "清空");
userApiSecretMapper.delete(new LambdaQueryWrapper<UserApiSecretEntity>()
.eq(UserApiSecretEntity::getUserId, userId)
.eq(UserApiSecretEntity::getModuleKey, module.key()));
log.info("[user-secret] 密钥已清空 userId={} module={}", userId, module.key());
}
/**
* 后台代填并锁定:写入后该模块 source=admin,客户端不可修改或清空。
* 目前仅开放代理设置——密钥模块要由客户端提交任务时携带本地明文,代填会让用户用不了。
* 数据权限:超管可操作全部用户,其余管理员限自己数据权限范围内的用户。
*/
@Transactional
public AdminUserSecretModuleVo adminSaveModule(AdminUserEntity operator, Long userId, String moduleKey, String value) {
requireUserId(userId);
requireVisibleUser(operator, userId);
UserSecretModule module = requireModule(moduleKey);
if (module != UserSecretModule.PROXY) {
throw new BusinessException("当前仅支持后台代填并锁定代理设置");
}
String plainValue = normalize(value);
if (plainValue.isEmpty()) {
throw new BusinessException("代理地址不能为空");
}
validateProxyValue(plainValue);
upsert(userId, module.key(), plainValue, SOURCE_ADMIN);
log.info("[user-secret] 后台代填并锁定配置 userId={} module={} operatorId={}",
userId, module.key(), operator == null ? null : operator.getId());
return toModuleVo(module, selectOne(userId, module.key()));
}
/** 后台清空某模块配置并解除锁定;解锁后客户端恢复自行配置。 */
@Transactional
public void adminClearModule(AdminUserEntity operator, Long userId, String moduleKey) {
requireUserId(userId);
requireVisibleUser(operator, userId);
UserSecretModule module = requireModule(moduleKey);
int deleted = userApiSecretMapper.delete(new LambdaQueryWrapper<UserApiSecretEntity>()
.eq(UserApiSecretEntity::getUserId, userId)
.eq(UserApiSecretEntity::getModuleKey, module.key()));
log.info("[user-secret] 后台清空并解除锁定 userId={} module={} 删除={} 条 operatorId={}",
userId, module.key(), deleted, operator == null ? null : operator.getId());
}
/** 是否后台代填并锁定:锁定行客户端不可改也不可清。 */
private boolean isAdminLocked(UserApiSecretEntity row) {
return row != null && row.getSource() != null && SOURCE_ADMIN.equalsIgnoreCase(row.getSource().trim());
}
/** 客户端写操作前置校验:锁定行直接拒绝并说明原因。 */
private void requireNotAdminLocked(Long userId, UserSecretModule module, String action) {
if (isAdminLocked(selectOne(userId, module.key()))) {
throw new BusinessException("该配置已由管理员设置并锁定,无法" + action + ";如需变更请联系管理员");
}
}
/** 数据权限:超管可操作全部;其余管理员只能操作自己数据权限范围内的用户。 */
private void requireVisibleUser(AdminUserEntity operator, Long userId) {
if (operator != null && "super_admin".equals(adminAuthSupport.currentRole(operator))) {
return;
}
Long operatorId = operator == null ? null : operator.getId();
if (!userDataScopeSupport.resolveVisibleUserIds(operatorId).contains(userId)) {
throw new BusinessException("无权操作该用户");
}
}
/** 本地密钥首次迁移:只写服务端空缺的模块,绝不覆盖已有值;忽略已废弃模块 key(如专利汇)。 */
@Transactional
public int migrateIfAbsent(Long userId, List<UserApiSecretMigrateRequest.Item> items) {
@@ -864,6 +928,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
if (row == null) {
vo.setMasked("");
vo.setExists(false);
vo.setLocked(false);
vo.setCheckStatus(STATUS_UNKNOWN);
vo.setCheckCode("");
vo.setCheckMessage("");
@@ -876,6 +941,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
vo.setFull(plain);
}
vo.setExists(hasText(plain));
vo.setLocked(isAdminLocked(row));
vo.setCheckStatus(hasText(row.getCheckStatus()) ? row.getCheckStatus() : STATUS_UNKNOWN);
vo.setCheckCode(row.getCheckCode());
vo.setCheckMessage(row.getCheckMessage());
@@ -892,6 +958,7 @@ public class UserApiSecretService implements UserSecretCleanupPort {
if (row == null) {
vo.setMasked("");
vo.setExists(false);
vo.setLocked(false);
vo.setCheckStatus(STATUS_UNKNOWN);
vo.setCheckCode("");
vo.setCheckMessage("");
@@ -899,7 +966,12 @@ public class UserApiSecretService implements UserSecretCleanupPort {
}
String plain = decryptQuietly(row.getSecretValue());
vo.setMasked(maskValue(module, plain));
// 锁定代理要下发完整地址:客户端据此把本地配置对齐到后台值(其余模块不下发明文)
if (module == UserSecretModule.PROXY && isAdminLocked(row)) {
vo.setFull(plain);
}
vo.setExists(hasText(plain));
vo.setLocked(isAdminLocked(row));
vo.setCheckStatus(hasText(row.getCheckStatus()) ? row.getCheckStatus() : STATUS_UNKNOWN);
vo.setCheckCode(row.getCheckCode());
vo.setCheckMessage(row.getCheckMessage());