Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

fix: correctly handle invalid api key in settings (#73761)

Maksym Yakubych445c6359e3e2
diff --git a/frontend/src/metabase/admin/ai/MetabotSetup.tsx b/frontend/src/metabase/admin/ai/MetabotSetup.tsx
index 371e402ab4a..1b27fa966f7 100644
--- a/frontend/src/metabase/admin/ai/MetabotSetup.tsx
+++ b/frontend/src/metabase/admin/ai/MetabotSetup.tsx
@@ -16,6 +16,7 @@ import _ from "underscore";
import { SettingsSection } from "metabase/admin/components/SettingsSection";
import { SetByEnvVar } from "metabase/admin/settings/components/widgets/AdminSettingInput";
import {
+ skipToken,
useGetMetabotSettingsQuery,
useUpdateMetabotSettingsMutation,
useUpdateSettingsMutation,
@@ -137,6 +138,13 @@ export function MetabotSetup({ id }: { id?: string }) {
);
const isConfigured = !!useSetting("llm-metabot-configured?");
const connectedProvider = isConfigured ? config?.provider : undefined;
+ const connectedProviderSettingsQuery = useGetMetabotSettingsQuery(
+ connectedProvider && connectedProvider !== "metabase"
+ ? { provider: connectedProvider }
+ : skipToken,
+ );
+ const hasApiKeyError =
+ !!connectedProviderSettingsQuery.currentData?.["api-key-error"];
return (
<SettingsSection
@@ -144,13 +152,31 @@ export function MetabotSetup({ id }: { id?: string }) {
title={
<Flex justify="space-between" align="center">
<Group gap="xs" wrap="nowrap">
- {isConfigured ? (
- <Badge circle size="12" bg="success" mr="sm" />
- ) : null}
+ {connectedProvider && (
+ <Badge
+ circle
+ size="12"
+ bg={hasApiKeyError ? "error" : "success"}
+ mr="sm"
+ />
+ )}
<div>
- {connectedProvider
- ? t`Connected to ${getProviderOptions(offerMetabaseAiManaged)[connectedProvider]?.label}`
- : t`Connect to an AI provider`}
+ {match({ connectedProvider, hasApiKeyError })
+ .with(
+ { connectedProvider: P.nonNullable, hasApiKeyError: true },
+ ({ connectedProvider }) =>
+ t`Error connecting to ${getProviderOptions(offerMetabaseAiManaged)[connectedProvider]?.label}`,
+ )
+ .with(
+ { connectedProvider: P.nonNullable },
+ ({ connectedProvider }) =>
+ t`Connected to ${getProviderOptions(offerMetabaseAiManaged)[connectedProvider]?.label}`,
+ )
+ .with(
+ { connectedProvider: P.nullish },
+ () => t`Connect to an AI provider`,
+ )
+ .exhaustive()}
</div>
</Group>
</Flex>
@@ -489,6 +515,9 @@ const AIProviderSetup = ({
const selectedApiKeySetting =
providerApiKeyDetails[API_KEY_SETTING_BY_PROVIDER[selectedProvider]];
const selectedApiKeyValue = String(selectedApiKeySetting?.value ?? "");
+ const apiKeyEnvSettingName = selectedApiKeySetting?.is_env_setting
+ ? selectedApiKeySetting.env_name
+ : undefined;
const needsApiKey = !hasConfiguredSettingValue(selectedApiKeySetting);
const metabotSettingsQuery = useGetMetabotSettingsQuery(
@@ -507,6 +536,9 @@ const AIProviderSetup = ({
metabotSettingsQuery.error,
selectedProvider,
);
+ const apiKeyError = hasDirtyApiKey
+ ? undefined
+ : (metabotSettingsQuery.currentData?.["api-key-error"] ?? undefined);
const displayApiKeyValue = apiKeyLocalValue ?? selectedApiKeyValue;
@@ -557,16 +589,17 @@ const AIProviderSetup = ({
selectedProviderDetails.apiKey?.placeholder ?? t`Enter your API key`
}
value={displayApiKeyValue}
+ error={apiKeyError}
onChange={handleApiKeyChange}
- disabled={isLoading || isEnvSetting}
+ disabled={isLoading || isEnvSetting || !!apiKeyEnvSettingName}
w="100%"
/>
- {isEnvSetting && selectedApiKeySetting?.env_name ? (
- <SetByEnvVar varName={selectedApiKeySetting.env_name} />
+ {apiKeyEnvSettingName ? (
+ <SetByEnvVar varName={apiKeyEnvSettingName} />
) : null}
- {!needsApiKey && (
+ {!needsApiKey && !apiKeyError && (
<Select
label={t`Model`}
placeholder={
diff --git a/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx b/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx
index 8d93464d368..b39c998a3ad 100644
--- a/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx
+++ b/frontend/src/metabase/admin/ai/MetabotSetup.unit.spec.tsx
@@ -113,6 +113,8 @@ type SetupOptions = {
isConfigured?: boolean;
providerSettingIsEnv?: boolean;
providerSettingEnvName?: string;
+ apiKeySettingIsEnv?: boolean;
+ apiKeySettingEnvName?: string;
isStoreUser?: boolean;
anyStoreUserEmailAddress?: string;
metabasePricePerUnit?: number;
@@ -141,6 +143,8 @@ async function setup({
isConfigured = true,
providerSettingIsEnv = false,
providerSettingEnvName = "LLM_METABOT_PROVIDER",
+ apiKeySettingIsEnv = false,
+ apiKeySettingEnvName = "LLM_ANTHROPIC_API_KEY",
isStoreUser = isHosted,
anyStoreUserEmailAddress = "[email protected]",
metabasePricePerUnit = 3.75,
@@ -217,6 +221,8 @@ async function setup({
"llm-anthropic-api-key": createMockSettingDefinition({
key: "llm-anthropic-api-key",
value: mergedApiKeyValues.anthropic ?? undefined,
+ is_env_setting: apiKeySettingIsEnv,
+ env_name: apiKeySettingIsEnv ? apiKeySettingEnvName : undefined,
}),
"llm-openai-api-key": createMockSettingDefinition({
key: "llm-openai-api-key",
@@ -539,6 +545,84 @@ describe("MetabotSetup", () => {
});
});
+ it("shows a saved API key validation error without disconnecting", async () => {
+ await setup({
+ responses: {
+ anthropic: {
+ value: "anthropic/claude-haiku-4-5",
+ "api-key-error": "Anthropic API key expired or invalid",
+ models: [],
+ },
+ },
+ });
+
+ expect(await screen.findByLabelText("API key")).toHaveValue("**********45");
+ expect(
+ await screen.findByText("Anthropic API key expired or invalid"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("Error connecting to Anthropic"),
+ ).toBeInTheDocument();
+
+ expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Disconnect" }),
+ ).toBeInTheDocument();
+ expect(screen.queryByLabelText("Provider")).not.toBeInTheDocument();
+
+ const settingsRequest = fetchMock.callHistory.calls(
+ "path:/api/metabot/settings",
+ )[0];
+ expect(settingsRequest?.url).toContain("provider=anthropic");
+ expect(settingsRequest?.url).not.toContain("api-key");
+ });
+
+ it("disables an env-backed API key field with a saved key validation error", async () => {
+ await setup({
+ apiKeySettingIsEnv: true,
+ responses: {
+ anthropic: {
+ value: "anthropic/claude-haiku-4-5",
+ "api-key-error": "Anthropic API key expired or invalid",
+ models: [],
+ },
+ },
+ });
+
+ expect(await screen.findByLabelText("API key")).toBeDisabled();
+ expect(
+ await screen.findByText("Anthropic API key expired or invalid"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("setting-env-var-message")).toHaveTextContent(
+ "This has been set by the LLM_ANTHROPIC_API_KEY environment variable.",
+ );
+ expect(
+ screen.getByRole("button", { name: "Disconnect" }),
+ ).toBeInTheDocument();
+ });
+
+ it("clears the saved API key error and shows Connect when the key changes", async () => {
+ await setup({
+ responses: {
+ anthropic: {
+ value: "anthropic/claude-haiku-4-5",
+ "api-key-error": "Anthropic API key expired or invalid",
+ models: [],
+ },
+ },
+ });
+
+ await screen.findByText("Anthropic API key expired or invalid");
+
+ await userEvent.clear(screen.getByLabelText("API key"));
+ await userEvent.type(screen.getByLabelText("API key"), "sk-ant-rotated");
+
+ expect(
+ screen.queryByText("Anthropic API key expired or invalid"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Connect" })).toBeInTheDocument();
+ });
+
it("shows the disconnected title when not configured", async () => {
await setup({ savedProviderValue: null, isConfigured: false });
@@ -1210,20 +1294,17 @@ describe("MetabotSetup", () => {
);
await waitFor(() => {
- expect(fetchMock.callHistory.called("path:/api/setting")).toBe(true);
- });
-
- const [request] = fetchMock.callHistory.calls("path:/api/setting", {
- method: "PUT",
+ expect(
+ fetchMock.callHistory.called("path:/api/setting", {
+ method: "PUT",
+ body: {
+ "llm-metabot-provider": null,
+ "llm-anthropic-api-key": null,
+ },
+ }),
+ ).toBe(true);
});
- expect(request?.options?.body).toBe(
- JSON.stringify({
- "llm-metabot-provider": null,
- "llm-anthropic-api-key": null,
- }),
- );
-
expect(
await screen.findByText("Connect to an AI provider"),
).toBeInTheDocument();
@@ -1233,6 +1314,38 @@ describe("MetabotSetup", () => {
).not.toBeInTheDocument();
});
+ it("disconnects an env-backed API-key provider by clearing only the provider setting", async () => {
+ await setup({
+ apiKeySettingIsEnv: true,
+ responses: {
+ anthropic: {
+ value: "anthropic/claude-haiku-4-5",
+ "api-key-error": "Anthropic API key expired or invalid",
+ models: [],
+ },
+ },
+ });
+
+ await screen.findByText("Anthropic API key expired or invalid");
+
+ await confirmDisconnectProvider();
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.called("path:/api/setting", {
+ method: "PUT",
+ body: {
+ "llm-metabot-provider": null,
+ },
+ }),
+ ).toBe(true);
+ });
+
+ expect(
+ await screen.findByText("Connect to an AI provider"),
+ ).toBeInTheDocument();
+ });
+
it("disconnects the Metabase-managed provider by removing the add-on before clearing the provider setting", async () => {
await setup({
isHosted: true,