fix: save llm key without extra secret
This commit is contained in:
@@ -9,11 +9,11 @@ public sealed class LlmSecretProtectorTests
|
||||
[Fact]
|
||||
public void Protect_RoundTripsWithoutEmbeddingPlaintext()
|
||||
{
|
||||
var encryptionKey = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Secrets:EncryptionKey"] = encryptionKey,
|
||||
["Jwt:Secret"] = Convert.ToBase64String(
|
||||
RandomNumberGenerator.GetBytes(48)),
|
||||
})
|
||||
.Build();
|
||||
var protector = new LlmSecretProtector(configuration);
|
||||
@@ -26,14 +26,14 @@ public sealed class LlmSecretProtectorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Protect_RejectsMissingEncryptionKey()
|
||||
public void Protect_RejectsMissingServerSecret()
|
||||
{
|
||||
var protector = new LlmSecretProtector(new ConfigurationBuilder().Build());
|
||||
|
||||
var exception = Assert.Throws<InvalidOperationException>(
|
||||
() => protector.Protect("sk-test"));
|
||||
|
||||
Assert.Contains("Secrets__EncryptionKey", exception.Message);
|
||||
Assert.Contains("JWT 密钥", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -65,13 +65,11 @@ public sealed class LlmSecretProtector(IConfiguration configuration)
|
||||
|
||||
private byte[] ReadEncryptionKey()
|
||||
{
|
||||
var raw = configuration["Secrets:EncryptionKey"];
|
||||
byte[]? key = null;
|
||||
try { key = string.IsNullOrWhiteSpace(raw) ? null : Convert.FromBase64String(raw); }
|
||||
catch (FormatException) { }
|
||||
if (key?.Length != 32)
|
||||
throw new InvalidOperationException(
|
||||
"请通过 Secrets__EncryptionKey 配置 base64 编码的 32 字节密钥后再保存 API Key");
|
||||
return key;
|
||||
var jwtSecret = configuration["Jwt:Secret"];
|
||||
if (string.IsNullOrWhiteSpace(jwtSecret) || jwtSecret.Length < 32)
|
||||
throw new InvalidOperationException("服务端 JWT 密钥配置无效,无法保护 API Key");
|
||||
return HMACSHA256.HashData(
|
||||
Encoding.UTF8.GetBytes(jwtSecret),
|
||||
Encoding.UTF8.GetBytes("jizhi:llm-api-key-encryption:v1"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user