diff --git a/docs/qweather-configuration.md b/docs/qweather-configuration.md new file mode 100644 index 000000000..1e1a4d246 --- /dev/null +++ b/docs/qweather-configuration.md @@ -0,0 +1,42 @@ +# QWeather 天气插件配置 + +天气插件使用 QWeather GeoAPI v2 和天气 API v7,支持 API Key 与 Ed25519 JWT 两种认证方式。 + +## API Key + +```yaml +plugins: + get_weather: + api_host: "你的API Host" + auth_type: "api_key" + api_key: "你的API Key" + default_location: "广州" +``` + +API Key 通过 `X-QW-Api-Key` 请求头发送。请使用 QWeather 控制台分配的 API Host。 + +## JWT + +先在 QWeather 控制台创建 JWT 凭据并登记 Ed25519 公钥,然后配置对应的 Project ID、Credential ID 和 PKCS#8 私钥: + +```yaml +plugins: + get_weather: + api_host: "你的API Host" + auth_type: "jwt" + project_id: "你的Project ID" + credential_id: "你的Credential ID" + private_key_path: "/安全目录/ed25519-private.pem" + default_location: "广州" +``` + +使用 manager-api 时,在智能体的天气插件配置中上传私钥。manager-api 需要配置项目主密钥: + +```yaml +xiaozhi: + secret: + # `openssl rand -base64 32` 生成,解码后必须为 32 字节。 + master-key: "Base64编码的项目主密钥" +``` + +也可通过环境变量 `XIAOZHI_SECRET_MASTER_KEY` 提供。主密钥只应配置在 manager-api;请勿提交主密钥、API Key 或私钥到代码仓库。 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentPluginMappingService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentPluginMappingService.java index 8e892ad71..984d0cb7a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentPluginMappingService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentPluginMappingService.java @@ -1,6 +1,7 @@ package xiaozhi.modules.agent.service; import java.util.List; +import java.util.Map; import com.baomidou.mybatisplus.extension.repository.IRepository; @@ -20,6 +21,13 @@ public interface AgentPluginMappingService extends IRepository agentPluginParamsByAgentId(String agentId); + Map prepareParamsForStorage(String agentId, String pluginId, + Map submittedParams, String existingParamInfo); + + void redactCredentialsForAdmin(List mappings); + + String resolveParamsForServer(AgentPluginMapping mapping); + /** * 根据智能体id删除插件参数 * diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java index 7a518fb16..d8479d113 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java @@ -1,6 +1,14 @@ package xiaozhi.modules.agent.service.impl; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -13,6 +21,7 @@ import com.baomidou.mybatisplus.spring.repository.CrudRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import xiaozhi.common.exception.RenException; import xiaozhi.common.utils.JsonUtils; import xiaozhi.modules.agent.dao.AgentPluginMappingMapper; import xiaozhi.modules.agent.entity.AgentPluginMapping; @@ -21,6 +30,7 @@ import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity; import xiaozhi.modules.knowledge.service.KnowledgeBaseService; import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; +import xiaozhi.modules.security.secret.ProjectSecretService; /** * @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Service实现 @@ -31,9 +41,187 @@ import xiaozhi.modules.model.service.ModelConfigService; @Slf4j public class AgentPluginMappingServiceImpl extends CrudRepository implements AgentPluginMappingService { + private static final String WEATHER_PLUGIN_ID = "SYSTEM_PLUGIN_WEATHER"; + private static final String WEATHER_PROVIDER_CODE = "get_weather"; + private static final String API_KEY = "api_key"; + private static final String PRIVATE_KEY = "private_key"; + private static final String SNAPSHOT_SECRET_PLACEHOLDER = "__SNAPSHOT_SECRET_REDACTED__"; + private final AgentPluginMappingMapper agentPluginMappingMapper; private final KnowledgeBaseService knowledgeBaseService; private final ModelConfigService modelConfigService; + private final ProjectSecretService projectSecretService; + + @Override + public Map prepareParamsForStorage(String agentId, String pluginId, + Map submittedParams, String existingParamInfo) { + Map submitted = submittedParams == null ? new HashMap<>() : new HashMap<>(submittedParams); + if (!WEATHER_PLUGIN_ID.equals(pluginId)) { + return submitted; + } + + Map existing = parseParams(existingParamInfo); + submitted.remove("api_key_configured"); + submitted.remove("private_key_configured"); + + String authType = stringValue(submitted.get("auth_type")); + if (StringUtils.isBlank(authType)) { + authType = "api_key"; + } + if (!"api_key".equals(authType) && !"jwt".equals(authType)) { + throw new RenException("QWeather auth_type must be api_key or jwt"); + } + submitted.put("auth_type", authType); + + preserveOrEncryptSecret(agentId, pluginId, API_KEY, submitted, existing, false); + preserveOrEncryptSecret(agentId, pluginId, PRIVATE_KEY, submitted, existing, true); + return submitted; + } + + @Override + public void redactCredentialsForAdmin(List mappings) { + if (mappings == null) { + return; + } + mappings.stream() + .filter(this::isWeatherMapping) + .forEach(mapping -> { + Map params = parseParams(mapping.getParamInfo()); + redactCredential(params, API_KEY); + redactCredential(params, PRIVATE_KEY); + mapping.setParamInfo(JsonUtils.toJsonString(params)); + }); + } + + @Override + public String resolveParamsForServer(AgentPluginMapping mapping) { + if (!isWeatherMapping(mapping)) { + return mapping.getParamInfo(); + } + Map params = parseParams(mapping.getParamInfo()); + resolveSecret(mapping, params, API_KEY, true); + resolveSecret(mapping, params, PRIVATE_KEY, false); + params.remove("api_key_configured"); + params.remove("private_key_configured"); + params.remove("private_key_fingerprint"); + return JsonUtils.toJsonString(params); + } + + private void preserveOrEncryptSecret(String agentId, String pluginId, String field, + Map submitted, Map existing, boolean encryptionRequired) { + String value = stringValue(submitted.get(field)); + String existingValue = stringValue(existing.get(field)); + if (StringUtils.isBlank(value) || SNAPSHOT_SECRET_PLACEHOLDER.equals(value)) { + if (StringUtils.isNotBlank(existingValue)) { + submitted.put(field, existingValue); + if (PRIVATE_KEY.equals(field) && existing.containsKey("private_key_fingerprint")) { + submitted.put("private_key_fingerprint", existing.get("private_key_fingerprint")); + } + } else { + submitted.remove(field); + } + return; + } + if (projectSecretService.isEncrypted(value)) { + throw new RenException("Encrypted credentials cannot be submitted directly"); + } + + String normalized = PRIVATE_KEY.equals(field) ? validateAndNormalizePrivateKey(value) : value.trim(); + if (encryptionRequired && !projectSecretService.isConfigured()) { + throw new RenException("xiaozhi.secret.master-key is required for QWeather JWT credentials"); + } + String stored = projectSecretService.isConfigured() + ? projectSecretService.encrypt(normalized, purpose(field), aad(agentId, pluginId, field)) + : normalized; + submitted.put(field, stored); + if (PRIVATE_KEY.equals(field)) { + submitted.put("private_key_fingerprint", fingerprint(normalized)); + } + } + + private void resolveSecret(AgentPluginMapping mapping, Map params, String field, + boolean allowLegacyPlaintext) { + String value = stringValue(params.get(field)); + if (StringUtils.isBlank(value)) { + params.remove(field); + return; + } + try { + if (projectSecretService.isEncrypted(value)) { + params.put(field, projectSecretService.decrypt(value, purpose(field), + aad(mapping.getAgentId(), mapping.getPluginId(), field))); + } else if (!allowLegacyPlaintext) { + log.warn("Ignoring plaintext QWeather private key for agent {}", mapping.getAgentId()); + params.remove(field); + } + } catch (RuntimeException exception) { + log.warn("Unable to resolve QWeather {} for agent {}", field, mapping.getAgentId()); + params.remove(field); + } + } + + private void redactCredential(Map params, String field) { + boolean configured = StringUtils.isNotBlank(stringValue(params.remove(field))); + params.put(field + "_configured", configured); + params.put(field, ""); + } + + private boolean isWeatherMapping(AgentPluginMapping mapping) { + return mapping != null && (WEATHER_PLUGIN_ID.equals(mapping.getPluginId()) + || WEATHER_PROVIDER_CODE.equals(mapping.getProviderCode())); + } + + private Map parseParams(String paramInfo) { + if (StringUtils.isBlank(paramInfo)) { + return new HashMap<>(); + } + Map parsed = JsonUtils.toStringObjectMap(JsonUtils.parseObject(paramInfo, Map.class)); + return parsed == null ? new HashMap<>() : new HashMap<>(parsed); + } + + private String validateAndNormalizePrivateKey(String pem) { + String normalized = pem.replace("\r\n", "\n").trim(); + String begin = "-----BEGIN PRIVATE KEY-----"; + String end = "-----END PRIVATE KEY-----"; + if (!normalized.startsWith(begin) || !normalized.endsWith(end)) { + throw new RenException("QWeather private key must be an Ed25519 PKCS#8 PEM"); + } + try { + String base64 = normalized.substring(begin.length(), normalized.length() - end.length()) + .replaceAll("\\s", ""); + byte[] der = Base64.getDecoder().decode(base64); + PrivateKey privateKey = KeyFactory.getInstance("Ed25519") + .generatePrivate(new PKCS8EncodedKeySpec(der)); + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(privateKey); + signature.update("xiaozhi-qweather-key-check".getBytes(StandardCharsets.UTF_8)); + signature.sign(); + return normalized + "\n"; + } catch (Exception exception) { + throw new RenException("QWeather private key must be an Ed25519 PKCS#8 PEM", exception); + } + } + + private String fingerprint(String value) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest, 0, 8); + } catch (Exception exception) { + throw new IllegalStateException("Unable to fingerprint QWeather private key", exception); + } + } + + private String purpose(String field) { + return "agent-plugin-secret:v1:" + WEATHER_PROVIDER_CODE + ":" + field; + } + + private String aad(String agentId, String pluginId, String field) { + return String.join("|", StringUtils.defaultString(agentId), StringUtils.defaultString(pluginId), field); + } + + private String stringValue(Object value) { + return value == null ? null : String.valueOf(value); + } @Override public List agentPluginParamsByAgentId(String agentId) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index 8001c205f..d929a3a92 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -115,6 +115,10 @@ public class AgentServiceImpl extends BaseServiceImpl imp agent.setCorrectWordFileIds(correctWordFileIds); agent.setCurrentVersionNo(agentSnapshotService.getCurrentVersionNo(id)); + if (agent.getFunctions() != null && !agent.getFunctions().isEmpty()) { + agentPluginMappingService.redactCredentialsForAdmin(agent.getFunctions()); + } + // 无需额外查询插件列表,已通过SQL查询出来 return agent; } @@ -461,13 +465,15 @@ public class AgentServiceImpl extends BaseServiceImpl imp .collect(Collectors.toMap(AgentPluginMapping::getPluginId, Function.identity())); // 3. 构造所有要 保存或更新 的实体 - List allToPersist = functions.stream().map(info -> { - AgentPluginMapping m = new AgentPluginMapping(); - m.setAgentId(agentId); - m.setPluginId(info.getPluginId()); - m.setParamInfo(JsonUtils.toJsonString(info.getParamInfo())); - AgentPluginMapping old = existMap.get(info.getPluginId()); - if (old != null) { + List allToPersist = functions.stream().map(info -> { + AgentPluginMapping m = new AgentPluginMapping(); + m.setAgentId(agentId); + m.setPluginId(info.getPluginId()); + AgentPluginMapping old = existMap.get(info.getPluginId()); + Map protectedParams = agentPluginMappingService.prepareParamsForStorage( + agentId, info.getPluginId(), info.getParamInfo(), old == null ? null : old.getParamInfo()); + m.setParamInfo(JsonUtils.toJsonString(protectedParams)); + if (old != null) { // 已存在,设置id表示更新 m.setId(old.getId()); } @@ -683,7 +689,8 @@ public class AgentServiceImpl extends BaseServiceImpl imp paramInfo.put((String) field.get("key"), field.get("default")); } } - mapping.setParamInfo(JsonUtils.toJsonString(paramInfo)); + mapping.setParamInfo(JsonUtils.toJsonString(agentPluginMappingService.prepareParamsForStorage( + entity.getId(), pluginId, paramInfo, null))); mapping.setAgentId(entity.getId()); toInsert.add(mapping); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java index 45e465f27..93ebd65f2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java @@ -198,7 +198,8 @@ public class ConfigServiceImpl implements ConfigService { if (pluginMappings != null && !pluginMappings.isEmpty()) { Map pluginParams = new HashMap<>(); for (AgentPluginMapping pluginMapping : pluginMappings) { - pluginParams.put(pluginMapping.getProviderCode(), pluginMapping.getParamInfo()); + pluginParams.put(pluginMapping.getProviderCode(), + agentPluginMappingService.resolveParamsForServer(pluginMapping)); } result.put("plugins", pluginParams); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ProjectSecretService.java b/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ProjectSecretService.java new file mode 100644 index 000000000..5ee626628 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ProjectSecretService.java @@ -0,0 +1,132 @@ +package xiaozhi.modules.security.secret; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Base64; + +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * Encrypts project secrets with purpose-separated keys derived from one master key. + */ +@Component +public class ProjectSecretService { + private static final String PREFIX = "enc:v1:a256gcm:"; + private static final byte[] HKDF_SALT = "xiaozhi-project-secret-v1".getBytes(StandardCharsets.UTF_8); + private static final int NONCE_LENGTH = 12; + private static final int TAG_LENGTH_BITS = 128; + + private final byte[] masterKey; + private final SecureRandom secureRandom; + + @Autowired + public ProjectSecretService(@Value("${xiaozhi.secret.master-key:}") String encodedMasterKey) { + this(encodedMasterKey, new SecureRandom()); + } + + ProjectSecretService(String encodedMasterKey, SecureRandom secureRandom) { + this.secureRandom = secureRandom; + if (StringUtils.isBlank(encodedMasterKey)) { + this.masterKey = null; + return; + } + try { + this.masterKey = Base64.getDecoder().decode(encodedMasterKey.trim()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("xiaozhi.secret.master-key must be valid Base64", exception); + } + if (this.masterKey.length != 32) { + throw new IllegalStateException("xiaozhi.secret.master-key must decode to exactly 32 bytes"); + } + } + + public boolean isConfigured() { + return masterKey != null; + } + + public boolean isEncrypted(String value) { + return value != null && value.startsWith(PREFIX); + } + + public String encrypt(String plaintext, String purpose, String aad) { + requireConfigured(); + if (plaintext == null) { + return null; + } + byte[] nonce = new byte[NONCE_LENGTH]; + secureRandom.nextBytes(nonce); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(deriveKey(purpose), "AES"), + new GCMParameterSpec(TAG_LENGTH_BITS, nonce)); + cipher.updateAAD(requireText(aad, "aad").getBytes(StandardCharsets.UTF_8)); + byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return PREFIX + encoder.encodeToString(nonce) + ":" + encoder.encodeToString(ciphertext); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("Project secret encryption failed", exception); + } + } + + public String decrypt(String envelope, String purpose, String aad) { + requireConfigured(); + if (!isEncrypted(envelope)) { + throw new IllegalArgumentException("Unsupported project secret envelope"); + } + String payload = envelope.substring(PREFIX.length()); + String[] parts = payload.split(":", 2); + if (parts.length != 2) { + throw new IllegalArgumentException("Malformed project secret envelope"); + } + try { + Base64.Decoder decoder = Base64.getUrlDecoder(); + byte[] nonce = decoder.decode(parts[0]); + if (nonce.length != NONCE_LENGTH) { + throw new IllegalArgumentException("Malformed project secret nonce"); + } + byte[] ciphertext = decoder.decode(parts[1]); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(deriveKey(purpose), "AES"), + new GCMParameterSpec(TAG_LENGTH_BITS, nonce)); + cipher.updateAAD(requireText(aad, "aad").getBytes(StandardCharsets.UTF_8)); + return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8); + } catch (IllegalArgumentException exception) { + throw exception; + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("Project secret decryption failed", exception); + } + } + + private byte[] deriveKey(String purpose) throws GeneralSecurityException { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(HKDF_SALT, "HmacSHA256")); + byte[] pseudorandomKey = mac.doFinal(masterKey); + + mac.init(new SecretKeySpec(pseudorandomKey, "HmacSHA256")); + mac.update(requireText(purpose, "purpose").getBytes(StandardCharsets.UTF_8)); + mac.update((byte) 1); + return mac.doFinal(); + } + + private void requireConfigured() { + if (!isConfigured()) { + throw new IllegalStateException("xiaozhi.secret.master-key is not configured"); + } + } + + private static String requireText(String value, String name) { + if (StringUtils.isBlank(value)) { + throw new IllegalArgumentException(name + " must not be blank"); + } + return value; + } +} diff --git a/main/manager-api/src/main/resources/db/changelog/202608111200.sql b/main/manager-api/src/main/resources/db/changelog/202608111200.sql new file mode 100644 index 000000000..02b55a5dd --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202608111200.sql @@ -0,0 +1,60 @@ +UPDATE sys_params +SET param_value = '' +WHERE param_code = 'plugins.get_weather.api_key' + AND param_value = 'a861d0d5e7bf4ee1a83d9a9e4f96d4da'; + +UPDATE ai_model_provider +SET fields = JSON_ARRAY( + JSON_OBJECT( + 'key', 'auth_type', + 'type', 'select', + 'label', '认证方式', + 'default', 'api_key', + 'options', JSON_ARRAY( + JSON_OBJECT('label', 'API Key', 'value', 'api_key'), + JSON_OBJECT('label', 'JWT', 'value', 'jwt') + ) + ), + JSON_OBJECT( + 'key', 'api_key', + 'type', 'password', + 'label', '天气插件 API Key', + 'default', (SELECT param_value FROM sys_params WHERE param_code = 'plugins.get_weather.api_key'), + 'visible_when', JSON_OBJECT('auth_type', 'api_key') + ), + JSON_OBJECT( + 'key', 'project_id', + 'type', 'string', + 'label', 'QWeather Project ID', + 'default', '', + 'visible_when', JSON_OBJECT('auth_type', 'jwt') + ), + JSON_OBJECT( + 'key', 'credential_id', + 'type', 'string', + 'label', 'QWeather Credential ID', + 'default', '', + 'visible_when', JSON_OBJECT('auth_type', 'jwt') + ), + JSON_OBJECT( + 'key', 'private_key', + 'type', 'file', + 'label', 'Ed25519 PKCS#8 私钥', + 'default', '', + 'accept', '.pem', + 'visible_when', JSON_OBJECT('auth_type', 'jwt') + ), + JSON_OBJECT( + 'key', 'default_location', + 'type', 'string', + 'label', '默认查询城市', + 'default', (SELECT param_value FROM sys_params WHERE param_code = 'plugins.get_weather.default_location') + ), + JSON_OBJECT( + 'key', 'api_host', + 'type', 'string', + 'label', '开发者 API Host', + 'default', (SELECT param_value FROM sys_params WHERE param_code = 'plugins.get_weather.api_host') + ) +) +WHERE id = 'SYSTEM_PLUGIN_WEATHER'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 90a5148dc..6577dacd9 100644 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -725,3 +725,10 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202608061030.sql + - changeSet: + id: 202608111200 + author: tairan + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202608111200.sql diff --git a/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImplTest.java new file mode 100644 index 000000000..67885106a --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImplTest.java @@ -0,0 +1,122 @@ +package xiaozhi.modules.agent.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.security.KeyPairGenerator; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import xiaozhi.common.exception.RenException; +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.agent.dao.AgentPluginMappingMapper; +import xiaozhi.modules.agent.entity.AgentPluginMapping; +import xiaozhi.modules.knowledge.service.KnowledgeBaseService; +import xiaozhi.modules.model.service.ModelConfigService; +import xiaozhi.modules.security.secret.ProjectSecretService; + +class AgentPluginMappingServiceImplTest { + private static final String AGENT_ID = "agent-a"; + private static final String PLUGIN_ID = "SYSTEM_PLUGIN_WEATHER"; + + @Test + void encryptsJwtPrivateKeyAndResolvesItOnlyForServerConfig() throws Exception { + AgentPluginMappingServiceImpl service = newService(masterKey()); + String privateKey = privateKeyPem(); + Map submitted = new HashMap<>(); + submitted.put("auth_type", "jwt"); + submitted.put("project_id", "project"); + submitted.put("credential_id", "credential"); + submitted.put("private_key", privateKey); + + Map stored = service.prepareParamsForStorage(AGENT_ID, PLUGIN_ID, submitted, null); + + String envelope = String.valueOf(stored.get("private_key")); + assertTrue(envelope.startsWith("enc:v1:a256gcm:")); + assertFalse(envelope.contains("BEGIN PRIVATE KEY")); + assertTrue(String.valueOf(stored.get("private_key_fingerprint")).matches("[0-9a-f]{16}")); + + AgentPluginMapping mapping = weatherMapping(JsonUtils.toJsonString(stored)); + Map runtime = JsonUtils.parseMap(service.resolveParamsForServer(mapping)); + assertEquals(privateKey.trim(), String.valueOf(runtime.get("private_key")).trim()); + assertFalse(runtime.containsKey("private_key_fingerprint")); + + service.redactCredentialsForAdmin(List.of(mapping)); + Map admin = JsonUtils.parseMap(mapping.getParamInfo()); + assertEquals("", admin.get("private_key")); + assertEquals(true, admin.get("private_key_configured")); + assertFalse(mapping.getParamInfo().contains("enc:v1")); + } + + @Test + void preservesStoredCredentialsWhenAdminSubmitsMaskedBlankValues() throws Exception { + AgentPluginMappingServiceImpl service = newService(masterKey()); + Map first = service.prepareParamsForStorage( + AGENT_ID, + PLUGIN_ID, + Map.of("auth_type", "jwt", "private_key", privateKeyPem()), + null); + Map masked = new HashMap<>(); + masked.put("auth_type", "jwt"); + masked.put("private_key", ""); + masked.put("private_key_configured", true); + + Map saved = service.prepareParamsForStorage( + AGENT_ID, PLUGIN_ID, masked, JsonUtils.toJsonString(first)); + + assertEquals(first.get("private_key"), saved.get("private_key")); + assertEquals(first.get("private_key_fingerprint"), saved.get("private_key_fingerprint")); + assertFalse(saved.containsKey("private_key_configured")); + } + + @Test + void keepsLegacyApiKeyWorkingWithoutMasterKeyButRejectsJwtPrivateKey() throws Exception { + AgentPluginMappingServiceImpl service = newService(""); + + Map apiKey = service.prepareParamsForStorage( + AGENT_ID, PLUGIN_ID, Map.of("auth_type", "api_key", "api_key", "legacy"), null); + + assertEquals("legacy", apiKey.get("api_key")); + assertThrows(RenException.class, + () -> service.prepareParamsForStorage( + AGENT_ID, PLUGIN_ID, Map.of("auth_type", "jwt", "private_key", privateKeyPem()), null)); + } + + private static AgentPluginMappingServiceImpl newService(String masterKey) { + return new AgentPluginMappingServiceImpl( + mock(AgentPluginMappingMapper.class), + mock(KnowledgeBaseService.class), + mock(ModelConfigService.class), + new ProjectSecretService(masterKey)); + } + + private static AgentPluginMapping weatherMapping(String paramInfo) { + AgentPluginMapping mapping = new AgentPluginMapping(); + mapping.setAgentId(AGENT_ID); + mapping.setPluginId(PLUGIN_ID); + mapping.setProviderCode("get_weather"); + mapping.setParamInfo(paramInfo); + return mapping; + } + + private static String masterKey() { + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) { + key[index] = (byte) index; + } + return Base64.getEncoder().encodeToString(key); + } + + private static String privateKeyPem() throws Exception { + byte[] der = KeyPairGenerator.getInstance("Ed25519").generateKeyPair().getPrivate().getEncoded(); + String base64 = Base64.getMimeEncoder(64, new byte[] { '\n' }).encodeToString(der); + return "-----BEGIN PRIVATE KEY-----\n" + base64 + "\n-----END PRIVATE KEY-----\n"; + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/security/secret/ProjectSecretServiceTest.java b/main/manager-api/src/test/java/xiaozhi/modules/security/secret/ProjectSecretServiceTest.java new file mode 100644 index 000000000..489097222 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/security/secret/ProjectSecretServiceTest.java @@ -0,0 +1,52 @@ +package xiaozhi.modules.security.secret; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Base64; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +class ProjectSecretServiceTest { + @Test + void productionConstructorIsExplicitlyAutowired() throws Exception { + assertNotNull(ProjectSecretService.class.getConstructor(String.class).getAnnotation(Autowired.class)); + } + + private static final String MASTER_KEY = Base64.getEncoder().encodeToString(new byte[32]); + + @Test + void encryptsWithRandomNonceAndRequiresMatchingContext() { + ProjectSecretService service = new ProjectSecretService(MASTER_KEY); + + String first = service.encrypt("private", "weather-key", "agent-a"); + String second = service.encrypt("private", "weather-key", "agent-a"); + + assertTrue(service.isEncrypted(first)); + assertNotEquals(first, second); + assertEquals("private", service.decrypt(first, "weather-key", "agent-a")); + assertThrows(IllegalStateException.class, + () -> service.decrypt(first, "weather-key", "agent-b")); + } + + @Test + void allowsLegacyModeOnlyWhenMasterKeyIsAbsent() { + ProjectSecretService service = new ProjectSecretService(""); + + assertFalse(service.isConfigured()); + assertThrows(IllegalStateException.class, + () -> service.encrypt("private", "weather-key", "agent-a")); + } + + @Test + void rejectsWrongLengthMasterKey() { + String shortKey = Base64.getEncoder().encodeToString(new byte[16]); + + assertThrows(IllegalStateException.class, () -> new ProjectSecretService(shortKey)); + } +} diff --git a/main/manager-web/src/components/FunctionDialog.vue b/main/manager-web/src/components/FunctionDialog.vue index 3599cd9da..1d3dee377 100644 --- a/main/manager-web/src/components/FunctionDialog.vue +++ b/main/manager-web/src/components/FunctionDialog.vue @@ -70,7 +70,7 @@
-