Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: support Bedrock API key auth (#16284)

YuTengjing479514d0ff5e
diff --git a/apps/server/src/modules/ModelRuntime/apiKeyManager.ts b/apps/server/src/modules/ModelRuntime/apiKeyManager.ts
index 97ad3cb82a7..b6b6e33870a 100644
--- a/apps/server/src/modules/ModelRuntime/apiKeyManager.ts
+++ b/apps/server/src/modules/ModelRuntime/apiKeyManager.ts
@@ -1,3 +1,5 @@
+import { randomInt } from 'node:crypto';
+
import { getLLMConfig } from '@/envs/llm';
interface KeyStore {
@@ -34,10 +36,12 @@ export class ApiKeyManager {
if (!apiKeys) return '';
const store = this.getKeyStore(apiKeys);
+ if (store.keyLen === 0) return '';
+
let index = 0;
if (this._mode === 'turn') index = store.index++ % store.keyLen;
- if (this._mode === 'random') index = Math.floor(Math.random() * store.keyLen);
+ if (this._mode === 'random') index = randomInt(store.keyLen);
return store.keys[index];
}
diff --git a/apps/server/src/modules/ModelRuntime/index.test.ts b/apps/server/src/modules/ModelRuntime/index.test.ts
index 027ed8f65ab..858bef09fda 100644
--- a/apps/server/src/modules/ModelRuntime/index.test.ts
+++ b/apps/server/src/modules/ModelRuntime/index.test.ts
@@ -28,6 +28,15 @@ import { describe, expect, it, vi } from 'vitest';
import { buildPayloadFromKeyVaults, initModelRuntimeWithUserPayload } from './index';
+interface InspectableBedrockRuntime {
+ client: {
+ config: {
+ token?: () => Promise<{ token: string }>;
+ };
+ };
+ region: string;
+}
+
// 模拟依赖项
vi.mock('@/envs/llm', () => ({
getLLMConfig: vi.fn(() => ({
@@ -172,6 +181,55 @@ describe('initModelRuntimeWithUserPayload method', () => {
expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
});
+ it('Bedrock AI provider: with API key only', async () => {
+ const jwtPayload: ClientSecretPayload = {
+ apiKey: 'user-bedrock-api-key',
+ awsRegion: 'us-east-1',
+ };
+ const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);
+
+ expect(runtime).toBeInstanceOf(ModelRuntime);
+ expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
+ });
+
+ it('Bedrock AI provider: picks one API key with server key selection', async () => {
+ const apiKey = 'user-bedrock-api-key-a,user-bedrock-api-key-b';
+ const jwtPayload: ClientSecretPayload = {
+ apiKey,
+ awsRegion: 'us-east-1',
+ };
+ const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);
+ const bedrockRuntime = runtime['_runtime'] as unknown as InspectableBedrockRuntime;
+ const token = await bedrockRuntime.client.config.token?.();
+
+ expect(apiKey.split(',')).toContain(token?.token);
+ });
+
+ it('Bedrock AI provider: with legacy AWS credentials only', async () => {
+ const jwtPayload: ClientSecretPayload = {
+ awsAccessKeyId: 'user-aws-id',
+ awsSecretAccessKey: 'user-aws-secret',
+ awsRegion: 'user-aws-region',
+ };
+ const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);
+
+ expect(runtime).toBeInstanceOf(ModelRuntime);
+ expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
+ });
+
+ it('Bedrock AI provider: falls back to env credentials when only region is provided', async () => {
+ const jwtPayload: ClientSecretPayload = {
+ awsRegion: 'custom-aws-region',
+ };
+ const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Bedrock, jwtPayload);
+
+ expect(runtime).toBeInstanceOf(ModelRuntime);
+ expect(runtime['_runtime']).toBeInstanceOf(LobeBedrockAI);
+ expect((runtime['_runtime'] as unknown as InspectableBedrockRuntime).region).toBe(
+ 'custom-aws-region',
+ );
+ });
+
it('Ollama provider: with endpoint', async () => {
const jwtPayload: ClientSecretPayload = { baseURL: 'http://user-ollama-url' };
const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Ollama, jwtPayload);
@@ -569,7 +627,7 @@ describe('buildPayloadFromKeyVaults', () => {
const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Bedrock);
expect(payload).toEqual({
- apiKey: 'aws-secret-keyaws-access-key',
+ apiKey: undefined,
awsAccessKeyId: 'aws-access-key',
awsRegion: 'us-east-1',
awsSecretAccessKey: 'aws-secret-key',
@@ -578,6 +636,23 @@ describe('buildPayloadFromKeyVaults', () => {
});
});
+ it('Bedrock: returns API key and runtimeProvider', () => {
+ const keyVaults = {
+ apiKey: 'bedrock-api-key',
+ region: 'us-east-1',
+ };
+ const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Bedrock);
+
+ expect(payload).toEqual({
+ apiKey: 'bedrock-api-key',
+ awsAccessKeyId: undefined,
+ awsRegion: 'us-east-1',
+ awsSecretAccessKey: undefined,
+ awsSessionToken: undefined,
+ runtimeProvider: ModelProvider.Bedrock,
+ });
+ });
+
it('Ollama: returns baseURL and runtimeProvider', () => {
const keyVaults = {
baseURL: 'http://localhost:11434',
diff --git a/apps/server/src/modules/ModelRuntime/index.ts b/apps/server/src/modules/ModelRuntime/index.ts
index 435d4a1fae3..a8e489c74d4 100644
--- a/apps/server/src/modules/ModelRuntime/index.ts
+++ b/apps/server/src/modules/ModelRuntime/index.ts
@@ -81,8 +81,7 @@ export const buildPayloadFromKeyVaults = (
// This handles both builtin providers and custom providers with sdkType
switch (runtimeProvider) {
case ModelProvider.Bedrock: {
- const { accessKeyId, region, secretAccessKey, sessionToken } = keyVaults;
- const apiKey = (secretAccessKey || '') + (accessKeyId || '');
+ const { accessKeyId, apiKey, region, secretAccessKey, sessionToken } = keyVaults;
return {
apiKey,
@@ -213,17 +212,28 @@ const getParamsFromPayload = (provider: string, payload: ClientSecretPayload) =>
case ModelProvider.Bedrock: {
const { AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, AWS_REGION, AWS_SESSION_TOKEN } = llmConfig;
- let accessKeyId: string | undefined = AWS_ACCESS_KEY_ID;
- let accessKeySecret: string | undefined = AWS_SECRET_ACCESS_KEY;
- let region = AWS_REGION;
- let sessionToken: string | undefined = AWS_SESSION_TOKEN;
- // if the payload has the api key, use user
- if (payload.apiKey) {
- accessKeyId = payload?.awsAccessKeyId;
- accessKeySecret = payload?.awsSecretAccessKey;
- sessionToken = payload?.awsSessionToken;
- region = payload?.awsRegion;
+
+ const hasUserBedrockAuth = !!(
+ payload.apiKey ||
+ payload.awsAccessKeyId ||
+ payload.awsSecretAccessKey
+ );
+
+ if (hasUserBedrockAuth) {
+ return {
+ accessKeyId: payload.awsAccessKeyId,
+ accessKeySecret: payload.awsSecretAccessKey,
+ apiKey: apiKeyManager.pick(payload.apiKey),
+ region: payload.awsRegion || AWS_REGION,
+ sessionToken: payload.awsSessionToken,
+ };
}
+
+ const accessKeyId: string | undefined = AWS_ACCESS_KEY_ID;
+ const accessKeySecret: string | undefined = AWS_SECRET_ACCESS_KEY;
+ const region = payload.awsRegion || AWS_REGION;
+ const sessionToken: string | undefined = payload.awsSessionToken || AWS_SESSION_TOKEN;
+
return { accessKeyId, accessKeySecret, region, sessionToken };
}
diff --git a/locales/en-US/modelProvider.json b/locales/en-US/modelProvider.json
index a29c5ee50c9..2c2de4bdfaf 100644
--- a/locales/en-US/modelProvider.json
+++ b/locales/en-US/modelProvider.json
@@ -24,7 +24,14 @@
"bedrock.accessKeyId.desc": "Enter AWS Access Key Id",
"bedrock.accessKeyId.placeholder": "AWS Access Key Id",
"bedrock.accessKeyId.title": "AWS Access Key Id",
- "bedrock.checker.desc": "Test if AccessKeyId / SecretAccessKey are filled in correctly",
+ "bedrock.apiKey.desc": "Enter your Amazon Bedrock API key. Short-term API keys are recommended for production workloads.",
+ "bedrock.apiKey.placeholder": "Amazon Bedrock API Key",
+ "bedrock.apiKey.title": "API Key",
+ "bedrock.authMode.desc": "Choose how requests authenticate with Amazon Bedrock",
+ "bedrock.authMode.options.apiKey": "API Key",
+ "bedrock.authMode.options.awsCredentials": "AWS Credentials",
+ "bedrock.authMode.title": "Authentication",
+ "bedrock.checker.desc": "Test whether the Bedrock authentication details are correct",
"bedrock.region.desc": "Enter AWS Region",
"bedrock.region.placeholder": "AWS Region",
"bedrock.region.title": "AWS Region",
@@ -37,8 +44,8 @@
"bedrock.title": "Bedrock",
"bedrock.unlock.customRegion": "Custom Service Region",
"bedrock.unlock.customSessionToken": "Custom Session Token",
- "bedrock.unlock.description": "Enter your AWS AccessKeyId / SecretAccessKey to start the session. The app will not store your authentication configuration",
- "bedrock.unlock.imageGenerationDescription": "Enter your AWS AccessKeyId / SecretAccessKey to start generating. The application will not store your authentication credentials.",
+ "bedrock.unlock.description": "Enter your Amazon Bedrock API key or AWS credentials to start the session. The app will not store your authentication configuration",
+ "bedrock.unlock.imageGenerationDescription": "Enter your Amazon Bedrock API key or AWS credentials to start generating. The application will not store your authentication credentials.",
"bedrock.unlock.title": "Use Custom Bedrock Authentication Information",
"cloudflare.apiKey.desc": "Please enter Cloudflare API Key",
"cloudflare.apiKey.placeholder": "Cloudflare API Key",
diff --git a/locales/zh-CN/modelProvider.json b/locales/zh-CN/modelProvider.json
index e0b778ba2a9..a77a3b937c7 100644
--- a/locales/zh-CN/modelProvider.json
+++ b/locales/zh-CN/modelProvider.json
@@ -24,7 +24,14 @@
"bedrock.accessKeyId.desc": "填入 AWS Access Key Id",
"bedrock.accessKeyId.placeholder": "AWS Access Key Id",
"bedrock.accessKeyId.title": "AWS Access Key Id",
- "bedrock.checker.desc": "测试 AccessKeyId / SecretAccessKey 是否填写正确",
+ "bedrock.apiKey.desc": "输入 Amazon Bedrock API 密钥。生产环境建议使用短期 API 密钥。",
+ "bedrock.apiKey.placeholder": "Amazon Bedrock API 密钥",
+ "bedrock.apiKey.title": "API 密钥",
+ "bedrock.authMode.desc": "选择请求 Amazon Bedrock 时使用的鉴权方式",
+ "bedrock.authMode.options.apiKey": "API 密钥",
+ "bedrock.authMode.options.awsCredentials": "AWS 凭证",
+ "bedrock.authMode.title": "鉴权方式",
+ "bedrock.checker.desc": "测试 Bedrock 鉴权信息是否填写正确",
"bedrock.region.desc": "填入 AWS Region",
"bedrock.region.placeholder": "AWS Region",
"bedrock.region.title": "AWS Region",
@@ -37,8 +44,8 @@
"bedrock.title": "Bedrock",
"bedrock.unlock.customRegion": "自定义服务区域",
"bedrock.unlock.customSessionToken": "自定义 Session Token",
- "bedrock.unlock.description": "输入你的 AWS AccessKeyId / SecretAccessKey 即可开始会话。应用不会记录你的鉴权配置",
- "bedrock.unlock.imageGenerationDescription": "输入你的 AWS AccessKeyId / SecretAccessKey 即可开始生成。应用不会记录你的鉴权配置",
+ "bedrock.unlock.description": "输入你的 Amazon Bedrock API 密钥或 AWS 凭证即可开始会话。应用不会记录你的鉴权配置",
+ "bedrock.unlock.imageGenerationDescription": "输入你的 Amazon Bedrock API 密钥或 AWS 凭证即可开始生成。应用不会记录你的鉴权配置",
"bedrock.unlock.title": "使用自定义 Bedrock 鉴权信息",
"cloudflare.apiKey.desc": "请填写 Cloudflare API Key",
"cloudflare.apiKey.placeholder": "Cloudflare API Key",
diff --git a/packages/locales/src/default/modelProvider.ts b/packages/locales/src/default/modelProvider.ts
index 202f10e9e76..d46721c939d 100644
--- a/packages/locales/src/default/modelProvider.ts
+++ b/packages/locales/src/default/modelProvider.ts
@@ -27,10 +27,18 @@ export default {
'azureai.token.desc': 'Find the API key from the Azure AI project overview',
'azureai.token.placeholder': 'Azure Key',
'azureai.token.title': 'Key',
+ 'bedrock.apiKey.desc':
+ 'Enter your Amazon Bedrock API key. Short-term API keys are recommended for production workloads.',
+ 'bedrock.apiKey.placeholder': 'Amazon Bedrock API Key',
+ 'bedrock.apiKey.title': 'API Key',
'bedrock.accessKeyId.desc': 'Enter AWS Access Key Id',
'bedrock.accessKeyId.placeholder': 'AWS Access Key Id',
'bedrock.accessKeyId.title': 'AWS Access Key Id',
- 'bedrock.checker.desc': 'Test if AccessKeyId / SecretAccessKey are filled in correctly',
+ 'bedrock.authMode.desc': 'Choose how requests authenticate with Amazon Bedrock',
+ 'bedrock.authMode.options.apiKey': 'API Key',
+ 'bedrock.authMode.options.awsCredentials': 'AWS Credentials',
+ 'bedrock.authMode.title': 'Authentication',
+ 'bedrock.checker.desc': 'Test whether the Bedrock authentication details are correct',
'bedrock.region.desc': 'Enter AWS Region',
'bedrock.region.placeholder': 'AWS Region',
'bedrock.region.title': 'AWS Region',
@@ -44,9 +52,9 @@ export default {
'bedrock.unlock.customRegion': 'Custom Service Region',
'bedrock.unlock.customSessionToken': 'Custom Session Token',
'bedrock.unlock.description':
- 'Enter your AWS AccessKeyId / SecretAccessKey to start the session. The app will not store your authentication configuration',
+ 'Enter your Amazon Bedrock API key or AWS credentials to start the session. The app will not store your authentication configuration',
'bedrock.unlock.imageGenerationDescription':
- 'Enter your AWS AccessKeyId / SecretAccessKey to start generating. The application will not store your authentication credentials.',
+ 'Enter your Amazon Bedrock API key or AWS credentials to start generating. The application will not store your authentication credentials.',
'bedrock.unlock.title': 'Use Custom Bedrock Authentication Information',
'cloudflare.apiKey.desc': 'Please enter Cloudflare API Key',
'cloudflare.apiKey.placeholder': 'Cloudflare API Key',
diff --git a/packages/model-runtime/src/providers/bedrock/index.test.ts b/packages/model-runtime/src/providers/bedrock/index.test.ts
index 07e29de85d0..3c1f310147c 100644
--- a/packages/model-runtime/src/providers/bedrock/index.test.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.test.ts
@@ -75,6 +75,22 @@ describe('LobeBedrockAI', () => {
expect(instance).toBeInstanceOf(LobeBedrockAI);
});
+ it('should correctly initialize with API key authentication', async () => {
+ const instance = new LobeBedrockAI({
+ apiKey: 'test-bedrock-api-key',
+ region: 'us-west-2',
+ });
+
+ expect(instance).toBeInstanceOf(LobeBedrockAI);
+ expect(instance.region).toBe('us-west-2');
+ await expect(instance['client'].config.authSchemePreference()).resolves.toEqual([
+ 'httpBearerAuth',
+ ]);
+ await expect(instance['client'].config.token?.()).resolves.toEqual({
+ token: 'test-bedrock-api-key',
+ });
+ });
+
it('should throw InvalidBedrockCredentials if accessKeyId is missing', () => {
expect(() => {
new LobeBedrockAI({
diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.ts
index b39b9c825bf..806c1a3a07b 100644
--- a/packages/model-runtime/src/providers/bedrock/index.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.ts
@@ -75,6 +75,7 @@ export function experimental_buildLlama2Prompt(messages: { content: string; role
export interface LobeBedrockAIParams {
accessKeyId?: string;
accessKeySecret?: string;
+ apiKey?: string;
id?: string;
modelIdMapping?: Record<string, string>;
region?: string;
@@ -89,13 +90,32 @@ export class LobeBedrockAI implements LobeRuntimeAI {
region: string;
constructor(options: LobeBedrockAIParams = {}) {
- const { id, modelIdMapping = {}, region, accessKeyId, accessKeySecret, sessionToken } = options;
+ const {
+ id,
+ modelIdMapping = {},
+ region,
+ accessKeyId,
+ accessKeySecret,
+ apiKey,
+ sessionToken,
+ } = options;
- if (!(accessKeyId && accessKeySecret))
- throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidBedrockCredentials);
this.region = region ?? 'us-east-1';
this.id = id ?? ModelProvider.Bedrock;
this.modelIdMapping = modelIdMapping;
+
+ if (apiKey) {
+ this.client = new BedrockRuntimeClient({
+ authSchemePreference: ['httpBearerAuth'],
+ region: this.region,
+ token: { token: apiKey },
+ });
+ return;
+ }
+
+ if (!(accessKeyId && accessKeySecret))
+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidBedrockCredentials);
+
this.client = new BedrockRuntimeClient({
credentials: {
accessKeyId,
diff --git a/packages/types/src/auth.ts b/packages/types/src/auth.ts
index 45ae126830a..52d0e413564 100644
--- a/packages/types/src/auth.ts
+++ b/packages/types/src/auth.ts
@@ -1,9 +1,6 @@
export interface ClientSecretPayload {
/**
* Represents the user's API key
- *
- * If provider need multi keys like bedrock,
- * this will be used as the checker whether to use frontend key
*/
apiKey?: string;
/**
diff --git a/packages/types/src/user/settings/keyVaults.ts b/packages/types/src/user/settings/keyVaults.ts
index b691361e94a..efdd4ef4bbf 100644
--- a/packages/types/src/user/settings/keyVaults.ts
+++ b/packages/types/src/user/settings/keyVaults.ts
@@ -19,6 +19,7 @@ export interface AzureOpenAIKeyVault {
export interface AWSBedrockKeyVault {
accessKeyId?: string;
+ apiKey?: string;
region?: string;
secretAccessKey?: string;
sessionToken?: string;
diff --git a/packages/utils/src/client/apiKeyManager.test.ts b/packages/utils/src/client/apiKeyManager.test.ts
index e7d777c43fd..f6316811bcd 100644
--- a/packages/utils/src/client/apiKeyManager.test.ts
+++ b/packages/utils/src/client/apiKeyManager.test.ts
@@ -1,8 +1,25 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { ClientApiKeyManager } from './apiKeyManager';
+const mockCryptoValues = (...values: number[]) => {
+ const getRandomValues = vi.fn((array: Uint32Array) => {
+ array[0] = values.shift() ?? 0;
+
+ return array;
+ });
+
+ vi.stubGlobal('crypto', { getRandomValues });
+
+ return getRandomValues;
+};
+
describe('ClientApiKeyManager', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
it('should return empty string for empty input', () => {
const manager = new ClientApiKeyManager();
expect(manager.pick('')).toBeUndefined();
@@ -18,42 +35,34 @@ describe('ClientApiKeyManager', () => {
it('should pick random keys from comma-separated list', () => {
const manager = new ClientApiKeyManager();
const apiKeys = 'sk-key1,sk-key2,sk-key3';
-
- // Mock Math.random to return specific values
const mockRandom = vi.spyOn(Math, 'random');
+ mockCryptoValues(0, 1, 2);
+
// Test first key (index 0)
- mockRandom.mockReturnValueOnce(0);
expect(manager.pick(apiKeys)).toBe('sk-key1');
// Test second key (index 1)
- mockRandom.mockReturnValueOnce(0.4);
expect(manager.pick(apiKeys)).toBe('sk-key2');
// Test third key (index 2)
- mockRandom.mockReturnValueOnce(0.8);
expect(manager.pick(apiKeys)).toBe('sk-key3');
- mockRandom.mockRestore();
+ expect(mockRandom).not.toHaveBeenCalled();
});
it('should handle keys with spaces and filter empty keys', () => {
const manager = new ClientApiKeyManager();
const apiKeys = ' sk-key1 , sk-key2 , , sk-key3 ';
- const mockRandom = vi.spyOn(Math, 'random');
+ mockCryptoValues(0, 1, 2);
// Should only have 3 valid keys
- mockRandom.mockReturnValueOnce(0);
expect(manager.pick(apiKeys)).toBe('sk-key1');
- mockRandom.mockReturnValueOnce(0.4);
expect(manager.pick(apiKeys)).toBe('sk-key2');
- mockRandom.mockReturnValueOnce(0.8);
expect(manager.pick(apiKeys)).toBe('sk-key3');
-
- mockRandom.mockRestore();
});
it('should cache key stores for the same input', () => {
diff --git a/packages/utils/src/client/apiKeyManager.ts b/packages/utils/src/client/apiKeyManager.ts
index 384d64039a3..1349afd7224 100644
--- a/packages/utils/src/client/apiKeyManager.ts
+++ b/packages/utils/src/client/apiKeyManager.ts
@@ -4,6 +4,14 @@ interface KeyStore {
keys: string[];
}
+const getSecureRandomIndex = (max: number) => {
+ const values = new Uint32Array(1);
+
+ globalThis.crypto?.getRandomValues?.(values);
+
+ return values[0] % max;
+};
+
export class ClientApiKeyManager {
private _cache: Map<string, KeyStore> = new Map();
@@ -29,10 +37,12 @@ export class ClientApiKeyManager {
if (!apiKeys) return undefined;
const store = this.getKeyStore(apiKeys);
+ if (store.keyLen === 0) return undefined;
+
let index = 0;
if (this._mode === 'turn') index = store.index++ % store.keyLen;
- if (this._mode === 'random') index = Math.floor(Math.random() * store.keyLen);
+ if (this._mode === 'random') index = getSecureRandomIndex(store.keyLen);
return store.keys[index];
}
diff --git a/src/components/InvalidAPIKey/Bedrock.tsx b/src/components/InvalidAPIKey/Bedrock.tsx
index 4f26a335338..30f21a2a6c1 100644
--- a/src/components/InvalidAPIKey/Bedrock.tsx
+++ b/src/components/InvalidAPIKey/Bedrock.tsx
@@ -1,14 +1,20 @@
import { Aws } from '@lobehub/icons';
import { Button, Icon, InputPassword, Select } from '@lobehub/ui';
+import { Tabs, type TabsItem } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
import { Network, ShieldPlus } from 'lucide-react';
import { ModelProvider } from 'model-bank';
-import { memo, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FormAction } from '@/features/Conversation/Error/style';
import { usePermission } from '@/hooks/usePermission';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
+import {
+ BedrockAuthMode,
+ inferBedrockAuthMode,
+ normalizeBedrockKeyVaultsForAuthMode,
+} from '@/utils/bedrockAuthMode';
const BedrockForm = memo<{ description: string }>(({ description }) => {
const { t } = useTranslation('modelProvider');
@@ -18,7 +24,51 @@ const BedrockForm = memo<{ description: string }>(({ description }) => {
const config = useAiInfraStore(aiProviderSelectors.providerKeyVaults(ModelProvider.Bedrock));
const setConfig = useAiInfraStore((s) => s.updateAiProviderConfig);
- const { accessKeyId, secretAccessKey, sessionToken, region } = config || {};
+ const { accessKeyId, apiKey, secretAccessKey, sessionToken, region } = config || {};
+
+ const [authMode, setAuthMode] = useState(() => inferBedrockAuthMode(config));
+
+ useEffect(() => {
+ const hasAuthShape = !!(config?.accessKeyId || config?.apiKey || config?.secretAccessKey);
+
+ if (!hasAuthShape) return;
+
+ setAuthMode(inferBedrockAuthMode(config));
+ }, [config?.accessKeyId, config?.apiKey, config?.secretAccessKey]);
+
+ const authModeOptions = useMemo<TabsItem[]>(
+ () => [
+ { key: BedrockAuthMode.ApiKey, label: t('bedrock.authMode.options.apiKey') },
+ {
+ key: BedrockAuthMode.AwsCredentials,
+ label: t('bedrock.authMode.options.awsCredentials'),
+ },
+ ],
+ [t],
+ );
+
+ const updateKeyVaults = useCallback(
+ (params: Record<string, string | undefined>, nextMode = authMode) => {
+ if (!canManageProvider) return;
+
+ void setConfig(ModelProvider.Bedrock, {
+ keyVaults: normalizeBedrockKeyVaultsForAuthMode(nextMode, params),
+ });
+ },
+ [authMode, canManageProvider, setConfig],
+ );
+
+ const handleAuthModeChange = useCallback(
+ (mode: string) => {
+ if (!canManageProvider) return;
+
+ const nextMode = mode as BedrockAuthMode;
+
+ setAuthMode(nextMode);
+ updateKeyVaults({}, nextMode);
+ },
+ [canManageProvider, updateKeyVaults],
+ );
return (
<FormAction
@@ -26,62 +76,81 @@ const BedrockForm = memo<{ description: string }>(({ description }) => {
description={description}
title={t('bedrock.unlock.title')}
>
- <InputPassword
- autoComplete={'new-password'}
- disabled={!canManageProvider}
- placeholder={'Aws Access Key Id'}
- value={accessKeyId}
- variant={'filled'}
- onChange={(e) => {
- if (!canManageProvider) return;
-
- setConfig(ModelProvider.Bedrock, { keyVaults: { accessKeyId: e.target.value } });
- }}
- />
- <InputPassword
- autoComplete={'new-password'}
- disabled={!canManageProvider}
- placeholder={'Aws Secret Access Key'}
- value={secretAccessKey}
- variant={'filled'}
- onChange={(e) => {
- if (!canManageProvider) return;
-
- setConfig(ModelProvider.Bedrock, { keyVaults: { secretAccessKey: e.target.value } });
+ <Tabs
+ activeKey={authMode}
+ items={authModeOptions}
+ style={{ width: '100%' }}
+ styles={{
+ list: { display: 'flex', width: '100%' },
+ tab: { flex: 1 },
}}
+ onChange={handleAuthModeChange}
/>
- {showSessionToken ? (
+ {authMode === BedrockAuthMode.ApiKey ? (
<InputPassword
autoComplete={'new-password'}
disabled={!canManageProvider}
- placeholder={'Aws Session Token'}
- value={sessionToken}
+ placeholder={t('bedrock.apiKey.placeholder')}
+ value={apiKey}
variant={'filled'}
onChange={(e) => {
- if (!canManageProvider) return;
-
- setConfig(ModelProvider.Bedrock, { keyVaults: { sessionToken: e.target.value } });
+ updateKeyVaults({ apiKey: e.target.value });
}}
/>
) : (
- <Button
- block
- disabled={!canManageProvider}
- icon={ShieldPlus}
- type={'text'}
- onClick={() => {
- if (!canManageProvider) return;
+ <>
+ <InputPassword
+ autoComplete={'new-password'}
+ disabled={!canManageProvider}
+ placeholder={t('bedrock.accessKeyId.placeholder')}
+ value={accessKeyId}
+ variant={'filled'}
+ onChange={(e) => {
+ updateKeyVaults({ accessKeyId: e.target.value });
+ }}
+ />
+ <InputPassword
+ autoComplete={'new-password'}
+ disabled={!canManageProvider}
+ placeholder={t('bedrock.secretAccessKey.placeholder')}
+ value={secretAccessKey}
+ variant={'filled'}
+ onChange={(e) => {
+ updateKeyVaults({ secretAccessKey: e.target.value });
+ }}
+ />
+ {showSessionToken ? (
+ <InputPassword
+ autoComplete={'new-password'}
+ disabled={!canManageProvider}
+ placeholder={t('bedrock.sessionToken.placeholder')}
+ value={sessionToken}
+ variant={'filled'}
+ onChange={(e) => {
+ updateKeyVaults({ sessionToken: e.target.value });
+ }}
+ />
+ ) : (
+ <Button
+ block
+ disabled={!canManageProvider}
+ icon={ShieldPlus}
+ type={'text'}
+ onClick={() => {
+ if (!canManageProvider) return;
- setShowSessionToken(true);
- }}
- >
- {t('bedrock.unlock.customSessionToken')}
- </Button>
+ setShowSessionToken(true);
+ }}
+ >
+ {t('bedrock.unlock.customSessionToken')}
+ </Button>
+ )}
+ </>
)}
{showRegion ? (
<Select
disabled={!canManageProvider}
- placeholder={'https://api.openai.com/v1'}
+ placeholder={t('bedrock.region.placeholder')}
style={{ width: '100%' }}
value={region}
options={['us-east-1', 'us-west-2', 'ap-southeast-1', 'eu-central-1'].map((i) => ({
@@ -89,9 +158,7 @@ const BedrockForm = memo<{ description: string }>(({ description }) => {
value: i,
}))}
onChange={(region) => {
- if (!canManageProvider) return;
-
- setConfig('bedrock', { keyVaults: { region } });
+ updateKeyVaults({ region });
}}
/>
) : (
diff --git a/src/routes/(main)/settings/provider/detail/bedrock/index.tsx b/src/routes/(main)/settings/provider/detail/bedrock/index.tsx
index c0deb18f086..ba64fcd2a1d 100644
--- a/src/routes/(main)/settings/provider/detail/bedrock/index.tsx
+++ b/src/routes/(main)/settings/provider/detail/bedrock/index.tsx
@@ -1,13 +1,22 @@
'use client';
import { Select } from '@lobehub/ui';
+import { Tabs, type TabsItem } from '@lobehub/ui/base-ui';
import { BedrockProviderCard } from 'model-bank/modelProviders';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FormPassword } from '@/components/FormInput';
import { SkeletonInput } from '@/components/Skeleton';
+import { usePermission } from '@/hooks/usePermission';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { type GlobalLLMProviderKey } from '@/types/user/settings';
+import {
+ BedrockAuthMode,
+ inferBedrockAuthMode,
+ normalizeBedrockConfigValues,
+ normalizeBedrockKeyVaultsForAuthMode,
+} from '@/utils/bedrockAuthMode';
import { KeyVaultsConfigKey } from '../../const';
import { type ProviderItem } from '../../type';
@@ -51,51 +60,139 @@ const AWS_REGIONS: string[] = [
const useBedrockCard = (): ProviderItem => {
const { t } = useTranslation('modelProvider');
+ const { allowed: canManageProvider } = usePermission('manage_provider_key');
const isLoading = useAiInfraStore(aiProviderSelectors.isAiProviderConfigLoading(providerKey));
+ const keyVaults = useAiInfraStore(aiProviderSelectors.providerKeyVaults(providerKey));
+ const updateAiProviderConfig = useAiInfraStore((s) => s.updateAiProviderConfig);
- return {
- ...BedrockProviderCard,
- apiKeyItems: [
+ const [authMode, setAuthMode] = useState(() => inferBedrockAuthMode(keyVaults));
+
+ useEffect(() => {
+ if (isLoading) return;
+
+ const hasAuthShape = !!(
+ keyVaults?.accessKeyId ||
+ keyVaults?.apiKey ||
+ keyVaults?.secretAccessKey
+ );
+
+ if (!hasAuthShape) return;
+
+ setAuthMode(inferBedrockAuthMode(keyVaults));
+ }, [isLoading, keyVaults?.accessKeyId, keyVaults?.apiKey, keyVaults?.secretAccessKey]);
+
+ const authModeOptions = useMemo<TabsItem[]>(
+ () => [
{
- children: isLoading ? (
- <SkeletonInput />
- ) : (
- <FormPassword
- autoComplete={'new-password'}
- placeholder={t(`${providerKey}.accessKeyId.placeholder`)}
- />
- ),
- desc: t(`${providerKey}.accessKeyId.desc`),
- label: t(`${providerKey}.accessKeyId.title`),
- name: [KeyVaultsConfigKey, 'accessKeyId'],
+ disabled: !canManageProvider,
+ key: BedrockAuthMode.ApiKey,
+ label: t(`${providerKey}.authMode.options.apiKey`),
},
{
- children: isLoading ? (
- <SkeletonInput />
- ) : (
- <FormPassword
- autoComplete={'new-password'}
- placeholder={t(`${providerKey}.secretAccessKey.placeholder`)}
- />
- ),
- desc: t(`${providerKey}.secretAccessKey.desc`),
- label: t(`${providerKey}.secretAccessKey.title`),
- name: [KeyVaultsConfigKey, 'secretAccessKey'],
+ disabled: !canManageProvider,
+ key: BedrockAuthMode.AwsCredentials,
+ label: t(`${providerKey}.authMode.options.awsCredentials`),
},
+ ],
+ [canManageProvider, t],
+ );
+
+ const handleAuthModeChange = useCallback(
+ (mode: string) => {
+ if (!canManageProvider) return;
+
+ const nextMode = mode as BedrockAuthMode;
+
+ setAuthMode(nextMode);
+ void updateAiProviderConfig(providerKey, {
+ keyVaults: normalizeBedrockKeyVaultsForAuthMode(nextMode),
+ });
+ },
+ [canManageProvider, updateAiProviderConfig],
+ );
+
+ const apiKeyItem = {
+ children: isLoading ? (
+ <SkeletonInput />
+ ) : (
+ <FormPassword
+ autoComplete={'new-password'}
+ placeholder={t(`${providerKey}.apiKey.placeholder`)}
+ />
+ ),
+ desc: t(`${providerKey}.apiKey.desc`),
+ label: t(`${providerKey}.apiKey.title`),
+ name: [KeyVaultsConfigKey, 'apiKey'],
+ preserve: false,
+ };
+
+ const awsCredentialItems = [
+ {
+ children: isLoading ? (
+ <SkeletonInput />
+ ) : (
+ <FormPassword
+ autoComplete={'new-password'}
+ placeholder={t(`${providerKey}.accessKeyId.placeholder`)}
+ />
+ ),
+ desc: t(`${providerKey}.accessKeyId.desc`),
+ label: t(`${providerKey}.accessKeyId.title`),
+ name: [KeyVaultsConfigKey, 'accessKeyId'],
+ preserve: false,
+ },
+ {
+ children: isLoading ? (
+ <SkeletonInput />
+ ) : (
+ <FormPassword
+ autoComplete={'new-password'}
+ placeholder={t(`${providerKey}.secretAccessKey.placeholder`)}
+ />
+ ),
+ desc: t(`${providerKey}.secretAccessKey.desc`),
+ label: t(`${providerKey}.secretAccessKey.title`),
+ name: [KeyVaultsConfigKey, 'secretAccessKey'],
+ preserve: false,
+ },
+ {
+ children: isLoading ? (
+ <SkeletonInput />
+ ) : (
+ <FormPassword
+ autoComplete={'new-password'}
+ placeholder={t(`${providerKey}.sessionToken.placeholder`)}
+ />
+ ),
+ desc: t(`${providerKey}.sessionToken.desc`),
+ label: t(`${providerKey}.sessionToken.title`),
+ name: [KeyVaultsConfigKey, 'sessionToken'],
+ preserve: false,
+ },
+ ];
+
+ return {
+ ...BedrockProviderCard,
+ apiKeyItems: [
{
children: isLoading ? (
<SkeletonInput />
) : (
- <FormPassword
- autoComplete={'new-password'}
- placeholder={t(`${providerKey}.sessionToken.placeholder`)}
+ <Tabs
+ activeKey={authMode}
+ items={authModeOptions}
+ styles={{
+ list: { display: 'flex', width: '100%' },
+ tab: { flex: 1 },
+ }}
+ onChange={handleAuthModeChange}
/>
),
- desc: t(`${providerKey}.sessionToken.desc`),
- label: t(`${providerKey}.sessionToken.title`),
- name: [KeyVaultsConfigKey, 'sessionToken'],
+ desc: t(`${providerKey}.authMode.desc`),
+ label: t(`${providerKey}.authMode.title`),
},
+ ...(authMode === BedrockAuthMode.ApiKey ? [apiKeyItem] : awsCredentialItems),
{
children: isLoading ? (
<SkeletonInput />
@@ -114,6 +211,7 @@ const useBedrockCard = (): ProviderItem => {
name: [KeyVaultsConfigKey, 'region'],
},
],
+ normalizeConfigValues: normalizeBedrockConfigValues(authMode),
};
};
diff --git a/src/routes/(main)/settings/provider/features/ProviderConfig/index.tsx b/src/routes/(main)/settings/provider/features/ProviderConfig/index.tsx
index 87482d0e61d..a7a232ac538 100644
--- a/src/routes/(main)/settings/provider/features/ProviderConfig/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ProviderConfig/index.tsx
@@ -30,7 +30,11 @@ import { usePermission } from '@/hooks/usePermission';
import { lambdaQuery } from '@/libs/trpc/client';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { type AiProviderDetailItem, type AiProviderSourceType } from '@/types/aiProvider';
+import {
+ type AiProviderDetailItem,
+ type AiProviderSourceType,
+ type UpdateAiProviderConfigParams,
+} from '@/types/aiProvider';
import { AiProviderSourceEnum } from '@/types/aiProvider';
import { KeyVaultsConfigKey, LLMProviderApiTokenKey, LLMProviderBaseUrlKey } from '../../const';
@@ -114,6 +118,7 @@ export interface ProviderConfigProps extends Omit<AiProviderDetailItem, 'enabled
placeholder?: string;
showModelFetcher?: boolean;
};
+ normalizeConfigValues?: (values: UpdateAiProviderConfigParams) => UpdateAiProviderConfigParams;
showAceGcm?: boolean;
source?: AiProviderSourceType;
title?: ReactNode;
@@ -135,6 +140,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
source = AiProviderSourceEnum.Builtin,
apiKeyUrl,
title,
+ normalizeConfigValues,
}) => {
const {
authType,
@@ -249,6 +255,12 @@ const ProviderConfig = memo<ProviderConfigProps>(
},
[updateAiProviderConfig],
);
+
+ const normalizeValues = useCallback(
+ (values: UpdateAiProviderConfigParams) => normalizeConfigValues?.(values) ?? values,
+ [normalizeConfigValues],
+ );
+
const { run: debouncedHandleValueChange } = useDebounceFn(handleValueChange, {
wait: 500,
});
@@ -418,7 +430,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
// Set connection test state to prevent duplicate requests from onValuesChange
isCheckingConnection.current = true;
// Proactively save the latest form values to ensure fetchAiProviderRuntimeState retrieves up-to-date data
- await updateAiProviderConfig(id, form.getFieldsValue());
+ await updateAiProviderConfig(id, normalizeValues(form.getFieldsValue()));
}}
/>
),
@@ -512,7 +524,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
variant={'borderless'}
onValuesChange={(_, values) => {
if (!canManageProvider) return;
- debouncedHandleValueChange(id, values);
+ debouncedHandleValueChange(id, normalizeValues(values));
}}
{...FORM_STYLE}
/>
diff --git a/src/services/__tests__/_auth.test.ts b/src/services/__tests__/_auth.test.ts
index b8fd1793838..4d2a409f17d 100644
--- a/src/services/__tests__/_auth.test.ts
+++ b/src/services/__tests__/_auth.test.ts
@@ -1,6 +1,6 @@
import { act } from '@testing-library/react';
import { ModelProvider } from 'model-bank';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { useUserStore } from '@/store/user';
@@ -18,6 +18,16 @@ const mockTogetherAIAPIKey = 'togetherai-api-key';
// mock the traditional zustand
vi.mock('zustand/traditional');
+const mockCryptoValue = (value: number) => {
+ vi.stubGlobal('crypto', {
+ getRandomValues: vi.fn((array: Uint32Array) => {
+ array[0] = value;
+
+ return array;
+ }),
+ });
+};
+
const setModelProviderConfig = (provider: string, config: any) => {
useUserStore.setState({
settings: { keyVaults: { [provider]: config } },
@@ -25,6 +35,11 @@ const setModelProviderConfig = (provider: string, config: any) => {
};
describe('getProviderAuthPayload', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
it('should return correct payload for ZhiPu provider', () => {
const payload = getProviderAuthPayload(ModelProvider.ZhiPu, { apiKey: mockZhiPuAPIKey });
expect(payload).toEqual({ apiKey: mockZhiPuAPIKey });
@@ -71,7 +86,6 @@ describe('getProviderAuthPayload', () => {
});
it('should return correct payload for Bedrock provider', () => {
- // 假设的 Bedrock 配置
const mockBedrockConfig = {
accessKeyId: 'bedrock-access-key-id',
region: 'bedrock-region',
@@ -80,7 +94,7 @@ describe('getProviderAuthPayload', () => {
const payload = getProviderAuthPayload(ModelProvider.Bedrock, mockBedrockConfig);
expect(payload).toEqual({
- apiKey: mockBedrockConfig.secretAccessKey + mockBedrockConfig.accessKeyId,
+ apiKey: undefined,
awsAccessKeyId: mockBedrockConfig.accessKeyId,
awsRegion: mockBedrockConfig.region,
awsSecretAccessKey: mockBedrockConfig.secretAccessKey,
@@ -92,6 +106,37 @@ describe('getProviderAuthPayload', () => {
});
});
+ it('should return correct payload for Bedrock API key authentication', () => {
+ const payload = getProviderAuthPayload(ModelProvider.Bedrock, {
+ apiKey: 'bedrock-api-key',
+ region: 'us-east-1',
+ });
+
+ expect(payload).toEqual({
+ accessKeyId: undefined,
+ accessKeySecret: undefined,
+ apiKey: 'bedrock-api-key',
+ awsAccessKeyId: undefined,
+ awsRegion: 'us-east-1',
+ awsSecretAccessKey: undefined,
+ awsSessionToken: undefined,
+ region: 'us-east-1',
+ sessionToken: undefined,
+ });
+ });
+
+ it('should pick one Bedrock API key with client key selection', () => {
+ const apiKey = 'bedrock-api-key-a,bedrock-api-key-b';
+ mockCryptoValue(1);
+
+ const payload = getProviderAuthPayload(ModelProvider.Bedrock, {
+ apiKey,
+ region: 'us-east-1',
+ });
+
+ expect(payload.apiKey).toBe('bedrock-api-key-b');
+ });
+
it('should return correct payload for Azure provider', () => {
// 假设的 Azure 配置
const mockAzureConfig = {
diff --git a/src/services/_auth.ts b/src/services/_auth.ts
index bcd30e9adfe..3b0d10761e9 100644
--- a/src/services/_auth.ts
+++ b/src/services/_auth.ts
@@ -24,17 +24,15 @@ export const getProviderAuthPayload = (
) => {
switch (provider) {
case ModelProvider.Bedrock: {
- const { accessKeyId, region, secretAccessKey, sessionToken } = keyVaults;
+ const { accessKeyId, apiKey, region, secretAccessKey, sessionToken } = keyVaults;
const awsSecretAccessKey = secretAccessKey;
const awsAccessKeyId = accessKeyId;
- const apiKey = (awsSecretAccessKey || '') + (awsAccessKeyId || '');
-
return {
accessKeyId,
accessKeySecret: awsSecretAccessKey,
- apiKey,
+ apiKey: clientApiKeyManager.pick(apiKey),
/** @deprecated */
awsAccessKeyId,
/** @deprecated */
diff --git a/src/utils/bedrockAuthMode.test.ts b/src/utils/bedrockAuthMode.test.ts
new file mode 100644
index 00000000000..2fc3008c8ac
--- /dev/null
+++ b/src/utils/bedrockAuthMode.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ BedrockAuthMode,
+ inferBedrockAuthMode,
+ normalizeBedrockConfigValues,
+ normalizeBedrockKeyVaultsForAuthMode,
+} from './bedrockAuthMode';
+
+describe('Bedrock auth mode helpers', () => {
+ describe('inferBedrockAuthMode', () => {
+ it('should default to API key mode when keyVaults are empty', () => {
+ expect(inferBedrockAuthMode()).toBe(BedrockAuthMode.ApiKey);
+ expect(inferBedrockAuthMode({})).toBe(BedrockAuthMode.ApiKey);
+ });
+
+ it('should use API key mode when apiKey exists', () => {
+ expect(
+ inferBedrockAuthMode({
+ accessKeyId: 'aws-access-key',
+ apiKey: 'bedrock-api-key',
+ secretAccessKey: 'aws-secret-key',
+ }),
+ ).toBe(BedrockAuthMode.ApiKey);
+ });
+
+ it('should use AWS credentials mode for legacy credentials', () => {
+ expect(inferBedrockAuthMode({ accessKeyId: 'aws-access-key' })).toBe(
+ BedrockAuthMode.AwsCredentials,
+ );
+ expect(inferBedrockAuthMode({ secretAccessKey: 'aws-secret-key' })).toBe(
+ BedrockAuthMode.AwsCredentials,
+ );
+ });
+ });
+
+ describe('normalizeBedrockKeyVaultsForAuthMode', () => {
+ it('should clear AWS credential fields in API key mode', () => {
+ expect(
+ normalizeBedrockKeyVaultsForAuthMode(BedrockAuthMode.ApiKey, {
+ accessKeyId: 'aws-access-key',
+ apiKey: 'bedrock-api-key',
+ region: 'us-east-1',
+ secretAccessKey: 'aws-secret-key',
+ sessionToken: 'session-token',
+ }),
+ ).toEqual({
+ accessKeyId: '',
+ apiKey: 'bedrock-api-key',
+ region: 'us-east-1',
+ secretAccessKey: '',
+ sessionToken: '',
+ });
+ });
+
+ it('should clear API key in AWS credentials mode', () => {
+ expect(
+ normalizeBedrockKeyVaultsForAuthMode(BedrockAuthMode.AwsCredentials, {
+ accessKeyId: 'aws-access-key',
+ apiKey: 'bedrock-api-key',
+ region: 'us-east-1',
+ secretAccessKey: 'aws-secret-key',
+ }),
+ ).toEqual({
+ accessKeyId: 'aws-access-key',
+ apiKey: '',
+ region: 'us-east-1',
+ secretAccessKey: 'aws-secret-key',
+ });
+ });
+ });
+
+ it('should normalize full provider config values', () => {
+ expect(
+ normalizeBedrockConfigValues(BedrockAuthMode.ApiKey)({
+ fetchOnClient: true,
+ keyVaults: {
+ accessKeyId: 'aws-access-key',
+ apiKey: 'bedrock-api-key',
+ region: 'us-east-1',
+ secretAccessKey: 'aws-secret-key',
+ },
+ }),
+ ).toEqual({
+ fetchOnClient: true,
+ keyVaults: {
+ accessKeyId: '',
+ apiKey: 'bedrock-api-key',
+ region: 'us-east-1',
+ secretAccessKey: '',
+ sessionToken: '',
+ },
+ });
+ });
+});
diff --git a/src/utils/bedrockAuthMode.ts b/src/utils/bedrockAuthMode.ts
new file mode 100644
index 00000000000..544d35dfa4c
--- /dev/null
+++ b/src/utils/bedrockAuthMode.ts
@@ -0,0 +1,43 @@
+import { type AWSBedrockKeyVault } from '@lobechat/types';
+
+import { type UpdateAiProviderConfigParams } from '@/types/aiProvider';
+
+export enum BedrockAuthMode {
+ ApiKey = 'apiKey',
+ AwsCredentials = 'awsCredentials',
+}
+
+export const inferBedrockAuthMode = (
+ keyVaults?: Pick<AWSBedrockKeyVault, 'accessKeyId' | 'apiKey' | 'secretAccessKey'>,
+) => {
+ if (keyVaults?.apiKey) return BedrockAuthMode.ApiKey;
+ if (keyVaults?.accessKeyId || keyVaults?.secretAccessKey) return BedrockAuthMode.AwsCredentials;
+
+ return BedrockAuthMode.ApiKey;
+};
+
+export const normalizeBedrockKeyVaultsForAuthMode = (
+ authMode: BedrockAuthMode,
+ keyVaults: UpdateAiProviderConfigParams['keyVaults'] = {},
+): UpdateAiProviderConfigParams['keyVaults'] => {
+ if (authMode === BedrockAuthMode.ApiKey) {
+ return {
+ ...keyVaults,
+ accessKeyId: '',
+ secretAccessKey: '',
+ sessionToken: '',
+ };
+ }
+
+ return {
+ ...keyVaults,
+ apiKey: '',
+ };
+};
+
+export const normalizeBedrockConfigValues =
+ (authMode: BedrockAuthMode) =>
+ (values: UpdateAiProviderConfigParams): UpdateAiProviderConfigParams => ({
+ ...values,
+ keyVaults: normalizeBedrockKeyVaultsForAuthMode(authMode, values.keyVaults),
+ });