mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 05:49:20 +08:00
feat: 新增agent
This commit is contained in:
+1
@@ -35,6 +35,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
return uri.startsWith("/api/open/")
|
||||
|| uri.equals("/mcp")
|
||||
|| uri.startsWith("/mcp/")
|
||||
|| uri.startsWith("/api/internal/agent/")
|
||||
|| uri.startsWith("/api/channel/pdd/auth/callback")
|
||||
|| uri.startsWith("/channel/pdd/auth/callback");
|
||||
}
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 租户模型 API Key 加解密与 Redis 缓存。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "ecom.agent.llm")
|
||||
public class AgentLlmProperties {
|
||||
|
||||
/** AES 密钥材料;空则回退 jwt.secret */
|
||||
private String secret = "";
|
||||
|
||||
/** Redis 运行时缓存 TTL 秒 */
|
||||
private long runtimeCacheTtlSeconds = 600;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||
|
||||
/**
|
||||
* 公司模型 API 配置(浏览器 JWT)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/company/agent-llm-settings")
|
||||
@RequiredArgsConstructor
|
||||
public class AgentCompanyLlmSettingsController {
|
||||
|
||||
private final AgentCompanyLlmSettingsService settingsService;
|
||||
|
||||
@GetMapping
|
||||
@RequirePermission(value = "agent:llm-settings", description = "查看模型配置", allowSuper = true)
|
||||
public ApiResponse<AgentLlmSettingsVO> get() {
|
||||
return ApiResponse.success(settingsService.getForCurrentCompany());
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
@RequirePermission(value = "agent:llm-settings", description = "更新模型配置", allowSuper = true)
|
||||
public ApiResponse<AgentLlmSettingsVO> upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) {
|
||||
return ApiResponse.success("保存成功", settingsService.upsertForCurrentCompany(dto));
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.config.AgentMcpProperties;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* Agent 内部拉取运行时模型配置(服务 Bearer,不下发浏览器)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/internal/agent")
|
||||
@RequiredArgsConstructor
|
||||
public class AgentInternalLlmController {
|
||||
|
||||
private final AgentCompanyLlmSettingsService settingsService;
|
||||
private final AgentMcpProperties mcpProperties;
|
||||
|
||||
@GetMapping("/llm-runtime")
|
||||
public ApiResponse<AgentLlmRuntimeVO> runtime(
|
||||
@RequestParam("companyId") Long companyId,
|
||||
HttpServletRequest request) {
|
||||
assertAgentBearer(request);
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("companyId 不能为空");
|
||||
}
|
||||
return ApiResponse.success(settingsService.getRuntime(companyId));
|
||||
}
|
||||
|
||||
private void assertAgentBearer(HttpServletRequest request) {
|
||||
String configured = mcpProperties.getBearerToken();
|
||||
if (!StringUtils.hasText(configured)) {
|
||||
throw new BusinessException("Agent 内部凭证未配置");
|
||||
}
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (!StringUtils.hasText(authorization) || !authorization.startsWith("Bearer ")) {
|
||||
throw new BusinessException("缺少 Agent Bearer");
|
||||
}
|
||||
String provided = authorization.substring(7).trim();
|
||||
byte[] a = configured.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] b = provided.getBytes(StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(a, b)) {
|
||||
throw new BusinessException("Agent Bearer 无效");
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmSettingsPO;
|
||||
|
||||
/**
|
||||
* 公司模型 API 配置 Mapper。
|
||||
*/
|
||||
@Mapper
|
||||
public interface AgentCompanyLlmSettingsMapper extends BaseMapper<AgentCompanyLlmSettingsPO> {
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 更新公司模型 API 配置。
|
||||
*/
|
||||
@Data
|
||||
public class UpsertAgentLlmSettingsDTO {
|
||||
|
||||
@NotBlank(message = "baseUrl 不能为空")
|
||||
private String baseUrl;
|
||||
|
||||
@NotBlank(message = "model 不能为空")
|
||||
private String model;
|
||||
|
||||
/** 首次必填;后续留空表示不改 Key */
|
||||
private String apiKey;
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 公司 Agent 模型 API 配置。
|
||||
*/
|
||||
@Data
|
||||
@TableName("agent_company_llm_settings")
|
||||
public class AgentCompanyLlmSettingsPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("base_url")
|
||||
private String baseUrl;
|
||||
|
||||
@TableField("api_key_encrypted")
|
||||
private String apiKeyEncrypted;
|
||||
|
||||
@TableField("api_key_suffix")
|
||||
private String apiKeySuffix;
|
||||
|
||||
@TableField("model")
|
||||
private String model;
|
||||
|
||||
@TableField("extra_headers_json")
|
||||
private String extraHeadersJson;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 仅供 Agent 内部拉取的运行时配置(含明文 apiKey)。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmRuntimeVO {
|
||||
private String baseUrl;
|
||||
private String apiKey;
|
||||
private String model;
|
||||
private Map<String, String> extraHeaders;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 对公司管理员可见的模型配置(Key 仅掩码)。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmSettingsVO {
|
||||
private boolean configured;
|
||||
private String baseUrl;
|
||||
private String model;
|
||||
private String apiKeyMasked;
|
||||
private String updateTime;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||
|
||||
/**
|
||||
* 公司模型 API 配置。
|
||||
*/
|
||||
public interface AgentCompanyLlmSettingsService {
|
||||
|
||||
AgentLlmSettingsVO getForCurrentCompany();
|
||||
|
||||
AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto);
|
||||
|
||||
/** Agent 内部:按公司取运行时明文配置 */
|
||||
AgentLlmRuntimeVO getRuntime(Long companyId);
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmSettingsMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmSettingsPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 公司模型 API:MySQL 存密文,Redis 缓存运行时明文供 Agent 注入。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettingsService {
|
||||
|
||||
private static final DateTimeFormatter ISO = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
|
||||
|
||||
private final AgentCompanyLlmSettingsMapper mapper;
|
||||
private final AgentLlmCrypto crypto;
|
||||
private final AgentLlmProperties llmProperties;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final CompanyMemberService companyMemberService;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public AgentLlmSettingsVO getForCurrentCompany() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
AgentCompanyLlmSettingsPO po = findByCompany(companyId);
|
||||
return toPublicVo(po);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
if (!currentUserContext.isCurrentUserSuper()
|
||||
&& !companyMemberService.isOwner(userId, companyId)) {
|
||||
throw new BusinessException("仅公司拥有者可配置模型 API");
|
||||
}
|
||||
|
||||
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||
String model = dto.getModel().trim();
|
||||
AgentCompanyLlmSettingsPO existing = findByCompany(companyId);
|
||||
|
||||
String encrypted;
|
||||
String suffix;
|
||||
String apiKey = dto.getApiKey();
|
||||
if (StringUtils.hasText(apiKey) && !apiKey.trim().startsWith("****")) {
|
||||
String plain = apiKey.trim();
|
||||
encrypted = crypto.encrypt(plain);
|
||||
suffix = plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain;
|
||||
} else if (existing != null) {
|
||||
encrypted = existing.getApiKeyEncrypted();
|
||||
suffix = existing.getApiKeySuffix();
|
||||
} else {
|
||||
throw new BusinessException("首次配置必须提供 apiKey");
|
||||
}
|
||||
|
||||
if (existing == null) {
|
||||
AgentCompanyLlmSettingsPO po = new AgentCompanyLlmSettingsPO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setBaseUrl(baseUrl);
|
||||
po.setApiKeyEncrypted(encrypted);
|
||||
po.setApiKeySuffix(suffix);
|
||||
po.setModel(model);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
mapper.insert(po);
|
||||
existing = po;
|
||||
} else {
|
||||
existing.setBaseUrl(baseUrl);
|
||||
existing.setApiKeyEncrypted(encrypted);
|
||||
existing.setApiKeySuffix(suffix);
|
||||
existing.setModel(model);
|
||||
existing.setUpdateBy(userId);
|
||||
mapper.updateById(existing);
|
||||
}
|
||||
|
||||
evictRuntimeCache(companyId);
|
||||
// 预热缓存,降低 Agent 首包延迟
|
||||
try {
|
||||
cacheRuntime(companyId, buildRuntime(existing));
|
||||
} catch (Exception e) {
|
||||
log.warn("预热 LLM 运行时缓存失败 companyId={}", companyId, e);
|
||||
}
|
||||
return toPublicVo(existing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AgentLlmRuntimeVO getRuntime(Long companyId) {
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("companyId 不能为空");
|
||||
}
|
||||
AgentLlmRuntimeVO cached = readRuntimeCache(companyId);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
AgentCompanyLlmSettingsPO po = findByCompany(companyId);
|
||||
if (po == null) {
|
||||
throw new BusinessException("公司尚未配置模型 API");
|
||||
}
|
||||
AgentLlmRuntimeVO runtime = buildRuntime(po);
|
||||
cacheRuntime(companyId, runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
private AgentLlmRuntimeVO buildRuntime(AgentCompanyLlmSettingsPO po) {
|
||||
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||
vo.setBaseUrl(po.getBaseUrl());
|
||||
vo.setApiKey(crypto.decrypt(po.getApiKeyEncrypted()));
|
||||
vo.setModel(po.getModel());
|
||||
vo.setExtraHeaders(parseHeaders(po.getExtraHeadersJson()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
private Map<String, String> parseHeaders(String json) {
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return Map.of();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {
|
||||
});
|
||||
} catch (Exception e) {
|
||||
return Map.of();
|
||||
}
|
||||
}
|
||||
|
||||
private AgentCompanyLlmSettingsPO findByCompany(Long companyId) {
|
||||
return mapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmSettingsPO>()
|
||||
.eq(AgentCompanyLlmSettingsPO::getCompanyId, companyId)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
private AgentLlmSettingsVO toPublicVo(AgentCompanyLlmSettingsPO po) {
|
||||
AgentLlmSettingsVO vo = new AgentLlmSettingsVO();
|
||||
if (po == null) {
|
||||
vo.setConfigured(false);
|
||||
return vo;
|
||||
}
|
||||
vo.setConfigured(true);
|
||||
vo.setBaseUrl(po.getBaseUrl());
|
||||
vo.setModel(po.getModel());
|
||||
vo.setApiKeyMasked("****" + (po.getApiKeySuffix() == null ? "" : po.getApiKeySuffix()));
|
||||
if (po.getUpdateTime() != null) {
|
||||
vo.setUpdateTime(po.getUpdateTime().format(ISO));
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
private static String redisKey(Long companyId) {
|
||||
return "agent:llm:rt:" + companyId;
|
||||
}
|
||||
|
||||
private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) {
|
||||
try {
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
payload.put("base_url", runtime.getBaseUrl());
|
||||
payload.put("api_key", runtime.getApiKey());
|
||||
payload.put("model", runtime.getModel());
|
||||
payload.put("extra_headers", runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||
stringRedisTemplate.opsForValue().set(
|
||||
redisKey(companyId),
|
||||
objectMapper.writeValueAsString(payload),
|
||||
Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds())));
|
||||
} catch (Exception e) {
|
||||
log.warn("写入 LLM Redis 缓存失败 companyId={}", companyId, e);
|
||||
}
|
||||
}
|
||||
|
||||
private AgentLlmRuntimeVO readRuntimeCache(Long companyId) {
|
||||
try {
|
||||
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId));
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> map = objectMapper.readValue(raw, new TypeReference<>() {
|
||||
});
|
||||
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||
vo.setBaseUrl(String.valueOf(map.get("base_url")));
|
||||
vo.setApiKey(String.valueOf(map.get("api_key")));
|
||||
vo.setModel(String.valueOf(map.get("model")));
|
||||
Object headers = map.get("extra_headers");
|
||||
if (headers instanceof Map<?, ?> m) {
|
||||
Map<String, String> h = new HashMap<>();
|
||||
m.forEach((k, v) -> h.put(String.valueOf(k), String.valueOf(v)));
|
||||
vo.setExtraHeaders(h);
|
||||
} else {
|
||||
vo.setExtraHeaders(Map.of());
|
||||
}
|
||||
return vo;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void evictRuntimeCache(Long companyId) {
|
||||
stringRedisTemplate.delete(redisKey(companyId));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.support;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* 租户 API Key AES-GCM 加解密(密钥由 ecom.agent.llm.secret 或 jwt.secret 派生)。
|
||||
*/
|
||||
@Component
|
||||
public class AgentLlmCrypto {
|
||||
|
||||
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
|
||||
private static final int GCM_IV_LENGTH = 12;
|
||||
private static final int GCM_TAG_LENGTH = 128;
|
||||
|
||||
private final AgentLlmProperties llmProperties;
|
||||
private final String jwtSecret;
|
||||
|
||||
public AgentLlmCrypto(AgentLlmProperties llmProperties,
|
||||
@Value("${jwt.secret}") String jwtSecret) {
|
||||
this.llmProperties = llmProperties;
|
||||
this.jwtSecret = jwtSecret;
|
||||
}
|
||||
|
||||
public String encrypt(String plain) {
|
||||
try {
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
new SecureRandom().nextBytes(iv);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||
byte[] cipherBytes = cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8));
|
||||
ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherBytes.length);
|
||||
buffer.put(iv);
|
||||
buffer.put(cipherBytes);
|
||||
return Base64.getEncoder().encodeToString(buffer.array());
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("加密 API Key 失败");
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String token) {
|
||||
try {
|
||||
byte[] all = Base64.getDecoder().decode(token);
|
||||
ByteBuffer buffer = ByteBuffer.wrap(all);
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
buffer.get(iv);
|
||||
byte[] cipherBytes = new byte[buffer.remaining()];
|
||||
buffer.get(cipherBytes);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||
return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("解密 API Key 失败,请检查 ecom.agent.llm.secret");
|
||||
}
|
||||
}
|
||||
|
||||
private SecretKey secretKey() throws Exception {
|
||||
String material = StringUtils.hasText(llmProperties.getSecret())
|
||||
? llmProperties.getSecret()
|
||||
: jwtSecret;
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest(material.getBytes(StandardCharsets.UTF_8));
|
||||
return new SecretKeySpec(digest, "AES");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -18,7 +18,7 @@ public class AgentMcpProperties {
|
||||
private String bearerToken = "";
|
||||
|
||||
/**
|
||||
* Agent 绑定的公司 ID(BI 等读模型按租户隔离);为空则业务 tool 会失败。
|
||||
* 本地单租户 fallback;生产应由请求头 X-Agent-Company-Id 注入。
|
||||
*/
|
||||
private Long companyId;
|
||||
}
|
||||
|
||||
+4
@@ -58,4 +58,8 @@ public class AgentMcpAuthentication implements Authentication {
|
||||
public Long getCompanyId() {
|
||||
return principal.companyId();
|
||||
}
|
||||
|
||||
public String getUserId() {
|
||||
return principal.userId();
|
||||
}
|
||||
}
|
||||
|
||||
+45
-6
@@ -19,13 +19,17 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* Agent MCP 鉴权:仅处理 /mcp,校验独立 Bearer,与 JWT / Open API Key 分离。
|
||||
* Agent 鉴权:处理 /mcp 与 /api/internal/agent/**;Bearer 为服务凭证,租户来自请求头。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String HEADER_COMPANY_ID = "X-Agent-Company-Id";
|
||||
public static final String HEADER_USER_ID = "X-Agent-User-Id";
|
||||
|
||||
private static final String MCP_PATH = "/mcp";
|
||||
private static final String INTERNAL_PREFIX = "/api/internal/agent";
|
||||
|
||||
private final AgentMcpProperties properties;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -41,7 +45,9 @@ public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||
if (uri == null) {
|
||||
return true;
|
||||
}
|
||||
return !(uri.equals(MCP_PATH) || uri.startsWith(MCP_PATH + "/"));
|
||||
return !(uri.equals(MCP_PATH)
|
||||
|| uri.startsWith(MCP_PATH + "/")
|
||||
|| uri.startsWith(INTERNAL_PREFIX));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -53,17 +59,26 @@ public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||
try {
|
||||
String configured = properties.getBearerToken();
|
||||
if (!StringUtils.hasText(configured)) {
|
||||
writeUnauthorized(response, "MCP 凭证未配置");
|
||||
writeUnauthorized(response, "Agent 凭证未配置");
|
||||
return;
|
||||
}
|
||||
|
||||
String provided = extractBearer(request);
|
||||
if (!StringUtils.hasText(provided) || !tokenEquals(configured, provided)) {
|
||||
writeUnauthorized(response, "MCP 凭证无效或缺失");
|
||||
writeUnauthorized(response, "Agent 凭证无效或缺失");
|
||||
return;
|
||||
}
|
||||
|
||||
AgentMcpPrincipal principal = new AgentMcpPrincipal("agent-mcp", properties.getCompanyId());
|
||||
Long companyId = resolveCompanyId(request);
|
||||
String userId = resolveUserId(request);
|
||||
// /mcp 业务 tool 必须有 company;内部 llm-runtime 可用 query companyId,头可空
|
||||
boolean mcpCall = isMcpPath(request.getRequestURI());
|
||||
if (mcpCall && companyId == null) {
|
||||
writeUnauthorized(response, "缺少租户头 " + HEADER_COMPANY_ID);
|
||||
return;
|
||||
}
|
||||
|
||||
AgentMcpPrincipal principal = new AgentMcpPrincipal("agent-mcp", companyId, userId);
|
||||
SecurityContextHolder.getContext().setAuthentication(new AgentMcpAuthentication(principal));
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
@@ -71,6 +86,31 @@ public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||
}
|
||||
}
|
||||
|
||||
private Long resolveCompanyId(HttpServletRequest request) {
|
||||
String header = request.getHeader(HEADER_COMPANY_ID);
|
||||
if (StringUtils.hasText(header)) {
|
||||
try {
|
||||
return Long.parseLong(header.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("非法 {}={}", HEADER_COMPANY_ID, header);
|
||||
}
|
||||
}
|
||||
// 兼容旧配置:无头时回退静态 company-id(仅建议本地单租户)
|
||||
return properties.getCompanyId();
|
||||
}
|
||||
|
||||
private String resolveUserId(HttpServletRequest request) {
|
||||
String header = request.getHeader(HEADER_USER_ID);
|
||||
if (StringUtils.hasText(header)) {
|
||||
return header.trim();
|
||||
}
|
||||
return "0";
|
||||
}
|
||||
|
||||
private static boolean isMcpPath(String uri) {
|
||||
return uri != null && (uri.equals(MCP_PATH) || uri.startsWith(MCP_PATH + "/"));
|
||||
}
|
||||
|
||||
private String extractBearer(HttpServletRequest request) {
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (StringUtils.hasText(authorization) && authorization.startsWith("Bearer ")) {
|
||||
@@ -79,7 +119,6 @@ public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 常量时间比较,降低侧信道风险。 */
|
||||
private static boolean tokenEquals(String expected, String actual) {
|
||||
byte[] a = expected.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] b = actual.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
+6
-2
@@ -1,7 +1,11 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||
|
||||
/**
|
||||
* MCP Agent 认证主体(m2m);companyId 绑定租户数据范围。
|
||||
* MCP / Agent 内部调用主体;companyId、userId 来自请求头(多租户)。
|
||||
*/
|
||||
public record AgentMcpPrincipal(String clientName, Long companyId) {
|
||||
public record AgentMcpPrincipal(String clientName, Long companyId, String userId) {
|
||||
|
||||
public AgentMcpPrincipal(String clientName, Long companyId) {
|
||||
this(clientName, companyId, "0");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.security.AgentMcpAuthentication;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.common.context.OpenApiContextHolder;
|
||||
@@ -61,10 +62,11 @@ public class CurrentUserContext {
|
||||
if (authentication instanceof AgentMcpAuthentication agentMcpAuthentication) {
|
||||
Long companyId = agentMcpAuthentication.getCompanyId();
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("MCP 未绑定公司,请配置 ecom.agent.mcp.company-id");
|
||||
throw new BusinessException("MCP 未绑定公司,请传请求头 X-Agent-Company-Id");
|
||||
}
|
||||
String userId = agentMcpAuthentication.getUserId();
|
||||
return TokenPayload.builder()
|
||||
.userId("0")
|
||||
.userId(StringUtils.hasText(userId) ? userId : "0")
|
||||
.companyId(companyId)
|
||||
.isSuper(false)
|
||||
.companyRole("owner")
|
||||
|
||||
@@ -92,13 +92,17 @@ ecom:
|
||||
admin-real-name: 超级管理员
|
||||
admin-phone: 13800000001
|
||||
admin-password: admin123
|
||||
# Agent → MCP 独立凭证(与浏览器 JWT、开放 API Key 分离)
|
||||
# Agent → MCP / 内部接口凭证(与浏览器 JWT、开放 API Key 分离)
|
||||
agent:
|
||||
mcp:
|
||||
# 为空则拒绝所有 MCP 请求;生产务必用环境变量覆盖
|
||||
# 为空则拒绝所有 MCP / 内部 Agent 请求;生产务必用环境变量覆盖
|
||||
bearer-token: ${AGENT_MCP_TOKEN:}
|
||||
# Agent 数据租户;BI tool 依赖此值
|
||||
# 仅本地单租户 fallback;多租户以请求头 X-Agent-Company-Id 为准
|
||||
company-id: ${AGENT_MCP_COMPANY_ID:}
|
||||
llm:
|
||||
# API Key 加解密材料;空则派生自 jwt.secret
|
||||
secret: ${AGENT_LLM_SECRET:}
|
||||
runtime-cache-ttl-seconds: 600
|
||||
|
||||
# JWT 令牌有效期(密钥见各环境配置)
|
||||
jwt:
|
||||
|
||||
@@ -933,3 +933,22 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON (p.code LIKE 'ec:
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'bi:workbench:read' WHERE m.name = '工作台';
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 14080, NULL, 0, 'AgentAssistant', '智能助手', '/agent/chat', '/agent/chat/index', '', 'lucide:bot', 'menu', 1, 1, 0, 14
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14080 OR `route_name` = 'AgentAssistant');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4800, (SELECT id FROM `sys_permission` WHERE `code` = 'data' LIMIT 1), 'agent', '智能助手', 'module', 1, '', 50
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4800 OR `code` = 'agent');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4801, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), 'agent:chat', '对话', 'api', 1, '', 1
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4801 OR `code` = 'agent:chat');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4802, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), 'agent:llm-settings', '模型配置', 'api', 1, '', 2
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4802 OR `code` = 'agent:llm-settings');
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('agent:chat', 'agent:llm-settings') WHERE m.route_name = 'AgentAssistant';
|
||||
|
||||
|
||||
Reference in New Issue
Block a user