feat: encrypt provider credentials

This commit is contained in:
wlx committed 2026-09-07 17:23:18 +08:00
1 parent 31a34757be
commit 7949f29f1a
6 files changed
+97 -7

No files matched your search

@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.auth.AuthService;
import com.moyi.controlplane.auth.AuthService.UserView;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.security.SecretCipher;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
@@ -32,11 +33,13 @@ public class CatalogService {
private static final List<String> SOURCE_TYPES = List.of("official", "relay", "self-hosted", "custom");
private final JdbcTemplate jdbc;
private final ObjectMapper objectMapper;
private final SecretCipher secretCipher;
private final SecureRandom secureRandom = new SecureRandom();
public CatalogService(JdbcTemplate jdbc, ObjectMapper objectMapper) {
public CatalogService(JdbcTemplate jdbc, ObjectMapper objectMapper, SecretCipher secretCipher) {
this.jdbc = jdbc;
this.objectMapper = objectMapper;
this.secretCipher = secretCipher;
}
public List<Map<String, Object>> listProviders(boolean includeDisabled) {
@@ -67,7 +70,7 @@ public class CatalogService {
String masked = secret == null ? null : mask(secret);
jdbc.update(
"INSERT INTO model_providers (id, code, name, protocol, source_type, base_url, description, credential_type, credential_ciphertext, credential_masked, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')",
id, code, name, protocol, sourceType, baseUrl, description, credentialType, null, masked
id, code, name, protocol, sourceType, baseUrl, description, credentialType, secret == null ? null : secretCipher.encrypt(secret), masked
);
auth.audit("provider.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("providerId", id));
return findProvider(id);
@@ -3,6 +3,7 @@ package com.moyi.controlplane.provider;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.security.SecretCipher;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
@@ -11,20 +12,28 @@ import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class OpenAiCompatibleProvider {
private final ObjectMapper objectMapper;
private final HttpClient httpClient;
private final JdbcTemplate jdbc;
private final SecretCipher secretCipher;
private final Map<String, ProviderConfig> providers;
public OpenAiCompatibleProvider(
ObjectMapper objectMapper,
org.springframework.core.env.Environment environment
org.springframework.core.env.Environment environment,
JdbcTemplate jdbc,
SecretCipher secretCipher
) {
this.objectMapper = objectMapper;
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
this.jdbc = jdbc;
this.secretCipher = secretCipher;
this.providers = Map.of(
"provider-deepseek", new ProviderConfig(environment.getProperty("moyi.providers.deepseek.api-key", ""), environment.getProperty("moyi.providers.deepseek.base-url", "https://api.deepseek.com")),
"provider-kimi", new ProviderConfig(environment.getProperty("moyi.providers.kimi.api-key", ""), environment.getProperty("moyi.providers.kimi.base-url", "https://api.moonshot.ai/v1")),
@@ -33,12 +42,12 @@ public class OpenAiCompatibleProvider {
}
public boolean isConfigured(String providerId) {
ProviderConfig provider = providers.get(providerId);
ProviderConfig provider = resolve(providerId);
return provider != null && !provider.apiKey().isBlank();
}
public Map<String, Object> chat(String providerId, String upstreamModel, List<?> messages) {
ProviderConfig provider = providers.get(providerId);
ProviderConfig provider = resolve(providerId);
if (provider == null || provider.apiKey().isBlank()) {
throw new ApiException("PROVIDER_NOT_CONFIGURED", "该模型的供应商尚未配置服务端 API Key", 503);
}
@@ -74,6 +83,20 @@ public class OpenAiCompatibleProvider {
return value == null ? "" : value.replaceAll("/+$", "");
}
private ProviderConfig resolve(String providerId) {
ProviderConfig fixed = providers.get(providerId);
if (fixed != null && !fixed.apiKey().isBlank()) return fixed;
try {
Map<String, Object> row = jdbc.queryForMap("SELECT base_url, credential_ciphertext FROM model_providers WHERE id = ? AND status = 'active'", providerId);
String ciphertext = row.get("credential_ciphertext") == null ? "" : String.valueOf(row.get("credential_ciphertext"));
String apiKey = ciphertext.isBlank() ? "" : secretCipher.decrypt(ciphertext);
String baseUrl = row.get("base_url") == null ? "" : String.valueOf(row.get("base_url"));
return new ProviderConfig(apiKey, baseUrl);
} catch (EmptyResultDataAccessException exception) {
return fixed;
}
}
private String writeJson(Object value) {
try {
return objectMapper.writeValueAsString(value);
@@ -0,0 +1,62 @@
package com.moyi.controlplane.security;
import com.moyi.controlplane.common.ApiException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class SecretCipher {
private static final int NONCE_LENGTH = 12;
private static final int TAG_LENGTH = 128;
private final SecureRandom secureRandom = new SecureRandom();
private final SecretKeySpec key;
public SecretCipher(@Value("${moyi.credentials.encryption-key}") String encryptionKey) {
if (encryptionKey == null || encryptionKey.isBlank()) {
this.key = null;
} else {
this.key = new SecretKeySpec(hash(encryptionKey), "AES");
}
}
public String encrypt(String plaintext) {
if (key == null) throw new ApiException("CREDENTIAL_ENCRYPTION_NOT_CONFIGURED", "请先配置供应商凭证加密密钥", 500);
try {
byte[] nonce = new byte[NONCE_LENGTH];
secureRandom.nextBytes(nonce);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_LENGTH, nonce));
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return "v1$" + encode(nonce) + "$" + encode(ciphertext);
} catch (Exception exception) {
throw new ApiException("CREDENTIAL_ENCRYPTION_FAILED", "供应商凭证加密失败", 500);
}
}
public String decrypt(String encoded) {
if (key == null) throw new ApiException("CREDENTIAL_ENCRYPTION_NOT_CONFIGURED", "请先配置供应商凭证加密密钥", 500);
try {
String[] parts = encoded.split("\\$", 3);
if (parts.length != 3 || !"v1".equals(parts[0])) throw new IllegalArgumentException("invalid ciphertext");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_LENGTH, Base64.getUrlDecoder().decode(parts[1])));
return new String(cipher.doFinal(Base64.getUrlDecoder().decode(parts[2])), StandardCharsets.UTF_8);
} catch (Exception exception) {
throw new ApiException("CREDENTIAL_DECRYPTION_FAILED", "供应商凭证解密失败", 500);
}
}
private String encode(byte[] value) { return Base64.getUrlEncoder().withoutPadding().encodeToString(value); }
private byte[] hash(String value) {
try { return MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); }
catch (Exception exception) { throw new IllegalStateException(exception); }
}
}