Skip to content

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

Do not show JWT shared secret as plaintext after it is saved (#71165)

Anderson1b26236cf1fa
diff --git a/e2e/test/scenarios/admin-2/sso/jwt.cy.spec.js b/e2e/test/scenarios/admin-2/sso/jwt.cy.spec.js
index 1d5d778f775..b0c0ceae892 100644
--- a/e2e/test/scenarios/admin-2/sso/jwt.cy.spec.js
+++ b/e2e/test/scenarios/admin-2/sso/jwt.cy.spec.js
@@ -22,7 +22,10 @@ describe("scenarios > admin > settings > SSO > JWT", () => {
/JWT Identity Provider URI/i,
"https://example.test",
);
- cy.button("Generate key").click();
+ cy.button("Set up key").click();
+ H.modal().within(() => {
+ cy.button("Done").click();
+ });
cy.button("Save and enable").click();
cy.wait("@updateSettings");
H.goToAuthOverviewPage();
@@ -73,13 +76,18 @@ describe("scenarios > admin > settings > SSO > JWT", () => {
enableJwtAuth();
cy.visit("/admin/settings/authentication/jwt");
+ cy.findByLabelText(/String used by the JWT signing key/i).should(
+ "have.value",
+ "**********00",
+ );
+
cy.button("Regenerate key").click();
H.modal().within(() => {
- cy.findByText("Regenerate JWT signing key?").should("exist");
+ cy.findByText("Set up secret key").should("exist");
cy.findByText(
"This will cause existing tokens to stop working until the identity provider is updated with the new key.",
).should("exist");
- cy.button("Yes").click();
+ cy.button("Done").click();
});
cy.button("Save changes").click();
cy.wait("@updateSettings");
diff --git a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
index c92942495a8..ce823b03667 100644
--- a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
@@ -1714,7 +1714,6 @@ describe("scenarios - embedding hub", () => {
expect(body["jwt-identity-provider-uri"]).to.equal(
"https://jwt.example.com/auth",
);
- expect(body["jwt-shared-secret"]).to.be.a("string");
expect(body["jwt-group-sync"]).to.equal(true);
});
@@ -1723,15 +1722,7 @@ describe("scenarios - embedding hub", () => {
.findByRole("listitem", { name: "Set up JWT authentication" })
.should("have.attr", "data-completed", "true");
- cy.log("valid signing key should be shown");
- H.main().within(() => {
- cy.findByLabelText(/JWT Signing Key/i)
- .should("be.visible")
- .should("have.attr", "value")
- .and("have.length.at.least", 32);
-
- cy.findByRole("button", { name: "Next" }).click();
- });
+ H.main().findByRole("button", { name: "Next" }).click();
cy.log("step 2 should be complete");
H.main()
diff --git a/enterprise/backend/src/metabase_enterprise/sso/settings.clj b/enterprise/backend/src/metabase_enterprise/sso/settings.clj
index c029818e4ec..7997aae5106 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/settings.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/settings.clj
@@ -220,6 +220,7 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e
(deferred-tru (str "String used to seed the private key used to validate JWT messages."
" "
"A hexadecimal-encoded 256-bit key (i.e., a 64-character string) is strongly recommended."))
+ :sensitive? true
:encryption :when-encryption-key-set
:type :string
:feature :sso-jwt
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx
index 8d703196870..502d6767022 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx
@@ -8,10 +8,7 @@ import {
import { AdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";
import { GroupMappingsWidget } from "metabase/admin/settings/components/widgets/GroupMappingsWidget";
import { getExtraFormFieldProps } from "metabase/admin/settings/utils";
-import {
- useGetAdminSettingsDetailsQuery,
- useGetSettingsQuery,
-} from "metabase/api";
+import { useGetAdminSettingsDetailsQuery } from "metabase/api";
import { useAdminSetting } from "metabase/api/utils";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import {
@@ -25,7 +22,10 @@ import {
} from "metabase/forms";
import { Flex, Stack } from "metabase/ui";
import { provisioningOptions } from "metabase-enterprise/auth/utils";
-import type { EnterpriseSettings } from "metabase-types/api";
+import type {
+ EnterpriseSettings,
+ SettingDefinitionMap,
+} from "metabase-types/api";
export type JWTFormValues = Pick<
EnterpriseSettings,
@@ -38,34 +38,48 @@ export type JWTFormValues = Pick<
>;
export const SettingsJWTForm = () => {
- const { data: settingDetails, isLoading: isLoadingDetails } =
- useGetAdminSettingsDetailsQuery();
- const { data: settingValues, isLoading: isLoadingValues } =
- useGetSettingsQuery();
+ const {
+ data: settingDetails,
+ isLoading: isLoadingDetails,
+ refetch: refetchSettingDetails,
+ } = useGetAdminSettingsDetailsQuery();
const { value: jwtEnabled, updateSettings } = useAdminSetting("jwt-enabled");
const handleSubmit = async (values: Partial<JWTFormValues>) => {
+ const { "jwt-shared-secret": jwtSecret, ...rest } = values;
+ const settingsToUpdate: Partial<JWTFormValues> = { ...rest };
+
+ // jwt-shared-secret may be initialized with the obfuscated value from /api/setting.
+ // Only send it to the backend if it's a newly generated plaintext value.
+ if (jwtSecret != null && !isObfuscatedValue(jwtSecret)) {
+ settingsToUpdate["jwt-shared-secret"] = jwtSecret;
+ }
+
const result = await updateSettings({
- ...values,
+ ...settingsToUpdate,
"jwt-enabled": true,
toast: false,
});
+ // Make sure the shared token obfuscated value is fetched from the backend.
+ refetchSettingDetails();
if (result.error) {
throw new Error(t`Error saving JWT Settings`);
}
};
- if (isLoadingDetails || isLoadingValues) {
+ if (isLoadingDetails) {
return <LoadingAndErrorWrapper loading />;
}
- if (!settingDetails || !settingValues) {
+ if (!settingDetails) {
return (
<LoadingAndErrorWrapper error={t`Error loading JWT configuration`} />
);
}
+ const usingTenants = settingDetails["use-tenants"]?.value;
+
return (
<SettingsPageWrapper title={t`JWT`}>
{jwtEnabled && (
@@ -80,7 +94,7 @@ export const SettingsJWTForm = () => {
)}
<SettingsSection>
<FormProvider
- initialValues={getFormValues(settingValues ?? {})}
+ initialValues={getFormValues(settingDetails)}
onSubmit={handleSubmit}
enableReinitialize
>
@@ -102,10 +116,6 @@ export const SettingsJWTForm = () => {
name="jwt-shared-secret"
label={t`String used by the JWT signing key`}
required
- confirmation={{
- header: t`Regenerate JWT signing key?`,
- dialog: t`This will cause existing tokens to stop working until the identity provider is updated with the new key.`,
- }}
{...getExtraFormFieldProps(
settingDetails?.["jwt-shared-secret"],
)}
@@ -145,7 +155,7 @@ export const SettingsJWTForm = () => {
settingDetails?.["jwt-attribute-groups"],
)}
/>
- {settingValues["use-tenants"] && (
+ {usingTenants && (
<FormTextInput
name="jwt-attribute-tenant"
label={t`Tenant assignment attribute`}
@@ -160,7 +170,6 @@ export const SettingsJWTForm = () => {
<GroupMappingsWidget
setting={{ key: "jwt-group-sync" }}
onChange={handleSubmit}
- settingValues={settingValues}
mappingSetting="jwt-group-mappings"
groupHeading={t`Group Name`}
groupPlaceholder={t`Group Name`}
@@ -182,10 +191,8 @@ export const SettingsJWTForm = () => {
);
};
-const getFormValues = (
- allSettings: Partial<EnterpriseSettings>,
-): JWTFormValues => {
- const jwtSettings = _.pick(allSettings, [
+const getFormValues = (settingDetails: SettingDefinitionMap): JWTFormValues => {
+ const jwtSettings = _.pick(settingDetails, [
"jwt-user-provisioning-enabled?",
"jwt-identity-provider-uri",
"jwt-shared-secret",
@@ -197,11 +204,17 @@ const getFormValues = (
"jwt-attribute-tenant",
]);
- if (jwtSettings["jwt-user-provisioning-enabled?"] == null) {
+ if (!jwtSettings["jwt-user-provisioning-enabled?"]?.value) {
// cast empty to false
- jwtSettings["jwt-user-provisioning-enabled?"] = false;
+ jwtSettings["jwt-user-provisioning-enabled?"] = {
+ ...jwtSettings["jwt-user-provisioning-enabled?"],
+ value: false,
+ };
}
// cast undefined to null
- return _.mapObject(jwtSettings, (val) => val ?? null) as JWTFormValues;
+ return _.mapObject(jwtSettings, (val) => val?.value ?? null) as JWTFormValues;
};
+
+const isObfuscatedValue = (value: string | null | undefined): boolean =>
+ !!value && value.startsWith("**");
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx
index ce1dcbf18f0..e3a94092031 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx
@@ -3,6 +3,7 @@ import fetchMock from "fetch-mock";
import {
findRequests,
+ setupGenerateRandomTokenEndpoint,
setupPropertiesEndpoints,
setupSettingsEndpoints,
setupUpdateSettingsEndpoint,
@@ -10,7 +11,7 @@ import {
import { renderWithProviders, screen, within } from "__support__/ui";
import { createMockGroup, createMockSettings } from "metabase-types/api/mocks";
-import { type JWTFormValues, SettingsJWTForm } from "./SettingsJWTForm";
+import { SettingsJWTForm } from "./SettingsJWTForm";
const GROUPS = [
createMockGroup(),
@@ -20,16 +21,25 @@ const GROUPS = [
createMockGroup({ id: 5, name: "flamingos" }),
];
-const setup = async (
- settingValues?: Partial<JWTFormValues> & {
- "jwt-enabled"?: boolean;
- "use-tenants"?: boolean;
- },
-) => {
- const settings = createMockSettings(settingValues);
- setupSettingsEndpoints([]);
- setupPropertiesEndpoints(settings);
+const setup = async ({
+ jwtEnabled,
+ useTenants,
+}: {
+ jwtEnabled?: boolean;
+ useTenants?: boolean;
+} = {}) => {
+ setupSettingsEndpoints([
+ { key: "use-tenants", value: useTenants ?? false },
+ { key: "jwt-enabled", value: jwtEnabled ?? false },
+ ]);
+ setupPropertiesEndpoints(
+ createMockSettings({
+ "use-tenants": useTenants,
+ "jwt-enabled": jwtEnabled,
+ }),
+ );
setupUpdateSettingsEndpoint();
+ setupGenerateRandomTokenEndpoint("1234abcd");
fetchMock.get("path:/api/permissions/group", GROUPS);
@@ -48,7 +58,6 @@ describe("SettingsJWTForm", () => {
"jwt-attribute-firstname": "John",
"jwt-attribute-lastname": "Doe",
"jwt-attribute-groups": "grouper",
- "jwt-attribute-tenant": null,
"jwt-enabled": true,
"jwt-group-sync": true,
};
@@ -60,10 +69,15 @@ describe("SettingsJWTForm", () => {
await screen.findByRole("textbox", { name: /JWT Identity Provider URI/ }),
ATTRS["jwt-identity-provider-uri"],
);
+ await userEvent.click(
+ await screen.findByRole("button", { name: /Set up key/ }),
+ );
+ await userEvent.clear(await screen.findByLabelText(/New secret key/));
await userEvent.type(
- await screen.findByLabelText(/String used by the JWT signing key/),
+ await screen.findByLabelText(/New secret key/),
ATTRS["jwt-shared-secret"],
);
+ await userEvent.click(await screen.findByRole("button", { name: /Done/ }));
await userEvent.type(
await screen.findByRole("textbox", { name: /Email attribute/ }),
ATTRS["jwt-attribute-email"],
@@ -104,16 +118,12 @@ describe("SettingsJWTForm", () => {
});
it("should show tenant attribute when tenanting is on", async () => {
- await setup({ "use-tenants": true });
+ await setup({ useTenants: true });
await userEvent.type(
await screen.findByRole("textbox", { name: /JWT Identity Provider URI/ }),
ATTRS["jwt-identity-provider-uri"],
);
- await userEvent.type(
- await screen.findByLabelText(/String used by the JWT signing key/),
- ATTRS["jwt-shared-secret"],
- );
await userEvent.type(
await screen.findByRole("textbox", {
@@ -133,7 +143,7 @@ describe("SettingsJWTForm", () => {
});
it("User provisioning should not appear if JWT has not been enabled", async () => {
- await setup({ "jwt-enabled": false });
+ await setup({ jwtEnabled: false });
const saveButton = await screen.findByRole("button", {
name: "Save and enable",
@@ -144,7 +154,7 @@ describe("SettingsJWTForm", () => {
});
it("User provisioning should appear if JWT has been enabled", async () => {
- await setup({ "jwt-enabled": true });
+ await setup({ jwtEnabled: true });
const saveButton = await screen.findByRole("button", {
name: "Save changes",
diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.unit.spec.tsx
index d7d22e5baf6..8760e711cfa 100644
--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/GuestEmbedsSettings/GuestEmbedsSettings.unit.spec.tsx
@@ -1,7 +1,6 @@
-import fetchMock from "fetch-mock";
-
import {
setupEmbeddableEntitiesEndpoints,
+ setupGenerateRandomTokenEndpoint,
setupPropertiesEndpoints,
setupSettingsEndpoints,
setupUpdateSettingEndpoint,
@@ -28,10 +27,7 @@ const setup = async ({ enabled }: { enabled: boolean }) => {
dashboards: [createMockDashboard({ name: "My cool dashboard" })],
cards: [createMockCard({ name: "My cool card" })],
});
-
- fetchMock.get("path:/api/util/random_token", {
- token: "fake-token",
- });
+ setupGenerateRandomTokenEndpoint("fake-token");
setupUserKeyValueEndpoints({
namespace: "user_acknowledgement",
key: "upsell-embedded-analytics-js",
diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.unit.spec.tsx
index 414181bbe15..58988ab67d0 100644
--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/SharedCombinedEmbeddingSettings/SharedCombinedEmbeddingSettings.unit.spec.tsx
@@ -1,9 +1,9 @@
import userEvent from "@testing-library/user-event";
-import fetchMock from "fetch-mock";
import {
findRequests,
setupEmbeddableEntitiesEndpoints,
+ setupGenerateRandomTokenEndpoint,
setupPropertiesEndpoints,
setupSettingsEndpoints,
setupUpdateSettingEndpoint,
@@ -32,10 +32,7 @@ const setup = async ({ enabled }: { enabled: boolean }) => {
dashboards: [createMockDashboard({ name: "My cool dashboard" })],
cards: [createMockCard({ name: "My cool card" })],
});
-
- fetchMock.get("path:/api/util/random_token", {
- token: "fake-token",
- });
+ setupGenerateRandomTokenEndpoint("fake-token");
setupUserKeyValueEndpoints({
namespace: "user_acknowledgement",
key: "upsell-embedded-analytics-js",
diff --git a/frontend/src/metabase/api/util.ts b/frontend/src/metabase/api/util.ts
new file mode 100644
index 00000000000..4f2d72fbc16
--- /dev/null
+++ b/frontend/src/metabase/api/util.ts
@@ -0,0 +1,14 @@
+import { Api } from "./api";
+
+export const utilApi = Api.injectEndpoints({
+ endpoints: (builder) => ({
+ generateRandomToken: builder.query<{ token: string }, void>({
+ query: () => ({
+ method: "GET",
+ url: "/api/util/random_token",
+ }),
+ }),
+ }),
+});
+
+export const { useLazyGenerateRandomTokenQuery } = utilApi;
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/AddEndpointStep.tsx b/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/AddEndpointStep.tsx
index a50939a2835..fd8ff5d816d 100644
--- a/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/AddEndpointStep.tsx
+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/AddEndpointStep.tsx
@@ -2,15 +2,12 @@
import { jt, t } from "ttag";
-import { CopyButton } from "metabase/common/components/CopyButton";
-import { useDocsUrl, useSetting } from "metabase/common/hooks";
-import { Anchor, Button, Group, Stack, Text, TextInput } from "metabase/ui";
+import { useDocsUrl } from "metabase/common/hooks";
+import { Anchor, Button, Group, Stack, Text } from "metabase/ui";
import S from "./SetupSsoPage.module.css";
export const AddEndpointStep = ({ onDone }: { onDone: () => void }) => {
- const jwtSharedSecret = useSetting("jwt-shared-secret");
-
// TODO(EMB-1337): replace this with standalone JWT backend docs page.
const { url: jwtDocsUrl } = useDocsUrl("embedding/authentication");
@@ -18,15 +15,6 @@ export const AddEndpointStep = ({ onDone }: { onDone: () => void }) => {
return (
<Stack gap="lg">
- <TextInput
- label={t`JWT Signing Key`}
- description={t`This secret is used to sign JWT tokens. Replace YOUR_SECRET_HERE in the below snippet with this value.`}
- value={jwtSharedSecret ?? ""}
- readOnly
- rightSection={<CopyButton value={jwtSharedSecret ?? ""} />}
- rightSectionWidth={40}
- />
-
<iframe
src={jwtDocsIframeUrl}
title={t`JWT Authentication Documentation`}
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/SetupSsoPage.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/SetupSsoPage.unit.spec.tsx
index 8ed91c102c3..7eeeac0f51f 100644
--- a/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/SetupSsoPage.unit.spec.tsx
+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/SetupSsoPage.unit.spec.tsx
@@ -106,8 +106,6 @@ describe("SetupSsoPage", () => {
);
await userEvent.click(enableJwtButton);
- expect(await screen.findByText("JWT Signing Key")).toBeVisible();
-
expect(
screen.getByRole("listitem", { name: "Set up JWT authentication" }),
).toHaveAttribute("data-completed", "true");
diff --git a/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.module.css b/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.module.css
new file mode 100644
index 00000000000..608d5ad9206
--- /dev/null
+++ b/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.module.css
@@ -0,0 +1,28 @@
+.inputWrapper {
+ display: flex;
+ gap: 0.5rem;
+
+ .input {
+ flex-grow: 1;
+
+ &.unset {
+ display: none;
+
+ & ~ .generateButton {
+ min-width: 10rem;
+ }
+ }
+ }
+
+ .generateButton {
+ flex-shrink: 0;
+ position: relative;
+ width: auto;
+ }
+}
+
+.rightSection {
+ justify-content: flex-start;
+ position: relative;
+ width: auto;
+}
diff --git a/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.tsx b/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.tsx
index 38274b1a3d7..2c372b64c8e 100644
--- a/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.tsx
+++ b/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.tsx
@@ -1,101 +1,75 @@
import { useDisclosure } from "@mantine/hooks";
+import cx from "classnames";
import { useField } from "formik";
-import type { ChangeEvent, FocusEvent, Ref } from "react";
-import { forwardRef, useCallback } from "react";
+import { type Ref, forwardRef } from "react";
import { t } from "ttag";
-import { ConfirmModal } from "metabase/common/components/ConfirmModal";
-import CS from "metabase/css/core/index.css";
-import { UtilApi } from "metabase/services";
-import type { PasswordInputProps } from "metabase/ui";
-import { Button, Flex, PasswordInput } from "metabase/ui";
+import {
+ Button,
+ Stack,
+ Text,
+ TextInput,
+ type TextInputProps,
+} from "metabase/ui";
+
+import S from "./FormSecretKey.module.css";
+import { SetupKeyModal } from "./SetupKeyModal";
export interface FormSecretKeyProps
- extends Omit<PasswordInputProps, "value" | "error"> {
+ extends Omit<TextInputProps, "value" | "error"> {
name: string;
nullable?: boolean;
- confirmation: {
- header: string;
- dialog: string;
- };
}
export const FormSecretKey = forwardRef(function FormSecretKey(
- {
- name,
- nullable,
- confirmation,
- onChange,
- onBlur,
- ...props
- }: FormSecretKeyProps,
+ { name, nullable, onChange, onBlur, ...props }: FormSecretKeyProps,
ref: Ref<HTMLInputElement>,
) {
- const [modalOpened, { open: openModal, close: closeModal }] = useDisclosure();
- const [{ value }, { error, touched }, { setValue, setTouched }] =
- useField(name);
-
- const handleChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const newValue = event.target.value;
- if (newValue === "") {
- setValue(nullable ? null : undefined);
- } else {
- setValue(newValue);
- }
- onChange?.(event);
- },
- [nullable, setValue, onChange],
- );
-
- const handleBlur = useCallback(
- (event: FocusEvent<HTMLInputElement>) => {
- setTouched(true);
- onBlur?.(event);
- },
- [setTouched, onBlur],
- );
- const generateToken = async () => {
- const result = await UtilApi.random_token();
- setValue(result.token);
- };
+ const [showModal, { open: openModal, close: closeModal }] = useDisclosure();
+ const [{ value }, { error }, { setValue }] = useField(name);
return (
<>
- <Flex align="end" gap="1rem">
- <PasswordInput
+ <Stack gap="sm">
+ <TextInput
{...props}
ref={ref}
name={name}
- value={value ?? ""}
- error={touched ? error : null}
- onChange={handleChange}
- onBlur={handleBlur}
+ readOnly
+ value={obfuscateValue(value)}
+ classNames={{
+ wrapper: S.inputWrapper,
+ input: cx(S.input, {
+ [S.unset]: !value, // Just show the 'Set up key' button when no key is set yet
+ }),
+ }}
+ rightSection={
+ <Button
+ className={S.generateButton}
+ miw={value ? undefined : "10rem"}
+ onClick={openModal}
+ variant="filled"
+ >
+ {value ? t`Regenerate key` : t`Set up key`}
+ </Button>
+ }
+ rightSectionProps={{ className: S.rightSection }}
+ />
+ {!!error && <Text c="error">{error}</Text>}
+ </Stack>
+ {showModal && (
+ <SetupKeyModal
+ onConfirm={(newValue) => {
+ setValue(newValue);
+ closeModal();
+ }}
+ onClose={closeModal}
+ currentValue={value}
/>
- {value ? (
- <Button
- variant="filled"
- onClick={openModal}
- className={CS.flexNoShrink}
- >{t`Regenerate key`}</Button>
- ) : (
- <Button
- className={CS.flexNoShrink}
- variant="filled"
- onClick={generateToken}
- >{t`Generate key`}</Button>
- )}
- </Flex>
- <ConfirmModal
- opened={modalOpened}
- title={t`Regenerate JWT signing key?`}
- content={t`This will cause existing tokens to stop working until the identity provider is updated with the new key.`}
- onConfirm={() => {
- generateToken();
- closeModal();
- }}
- onClose={closeModal}
- />
+ )}
</>
);
});
+
+const obfuscateValue = (value: string) =>
+ value ? "**********" + value.slice(-2) : "";
diff --git a/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.unit.spec.tsx b/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.unit.spec.tsx
new file mode 100644
index 00000000000..4b64a8ed5d2
--- /dev/null
+++ b/frontend/src/metabase/forms/components/FormSecretKey/FormSecretKey.unit.spec.tsx
@@ -0,0 +1,209 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupGenerateRandomTokenEndpoint } from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { Form, FormProvider, FormSubmitButton } from "metabase/forms";
+
+import { FormSecretKey } from "./FormSecretKey";
+
+interface FormValues {
+ secret: string | null | undefined;
+}
+
+interface SetupOpts {
+ initialValues?: FormValues;
+}
+
+const GENERATED_TOKEN = "newly-generated-token-xyz";
+const EXISTING_VALUE = "my-super-secret-token-abc123";
+// obfuscateValue shows "**********" + last 2 chars
+const OBFUSCATED_EXISTING = "**********23";
+const OBFUSCATED_GENERATED = "**********yz";
+
+const setup = ({ initialValues = { secret: undefined } }: SetupOpts = {}) => {
+ const onSubmit = jest.fn();
+
+ setupGenerateRandomTokenEndpoint(GENERATED_TOKEN);
+
+ renderWithProviders(
+ <FormProvider initialValues={initialValues} onSubmit={onSubmit}>
+ <Form>
+ <FormSecretKey name="secret" label="Signing Key" />
+ <FormSubmitButton />
+ </Form>
+ </FormProvider>,
+ );
+
+ return { onSubmit };
+};
+
+describe("FormSecretKey", () => {
+ afterEach(() => {
+ fetchMock.hardReset();
+ });
+
+ describe("when there is no value", () => {
+ it("shows a 'Set up key' button", () => {
+ setup({ initialValues: { secret: undefined } });
+
+ expect(
+ screen.getByRole("button", { name: "Set up key" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Regenerate key" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("opens the setup modal when 'Set up key' is clicked", async () => {
+ setup({ initialValues: { secret: undefined } });
+
+ await userEvent.click(screen.getByRole("button", { name: "Set up key" }));
+
+ expect(
+ await screen.findByRole("dialog", { name: "Set up secret key" }),
+ ).toBeInTheDocument();
+ });
+
+ it("auto-generates a token when the modal opens", async () => {
+ setup({ initialValues: { secret: undefined } });
+
+ expect(fetchMock.callHistory.calls("generate-random-token")).toHaveLength(
+ 0,
+ );
+
+ await userEvent.click(screen.getByRole("button", { name: "Set up key" }));
+
+ expect(fetchMock.callHistory.calls("generate-random-token")).toHaveLength(
+ 1,
+ );
+
+ // The modal's text input should contain the generated token
+ await waitFor(() => {
+ const modalInput = within(screen.getByRole("dialog")).getByRole(
+ "textbox",
+ { name: "New secret key" },
+ );
+ expect(modalInput).toHaveValue(GENERATED_TOKEN);
+ });
+ });
+
+ it("closes the modal and updates the form value after clicking 'Done'", async () => {
+ setup({ initialValues: { secret: undefined } });
+
+ await userEvent.click(screen.getByRole("button", { name: "Set up key" }));
+ await screen.findByRole("dialog", { name: "Set up secret key" });
+
+ await waitFor(() => {
+ expect(screen.getByRole("button", { name: "Done" })).toBeEnabled();
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: "Done" }));
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("dialog", { name: "Set up secret key" }),
+ ).not.toBeInTheDocument();
+ });
+
+ // The input shows the obfuscated generated value
+ await waitFor(() => {
+ expect(screen.getByLabelText("Signing Key")).toHaveValue(
+ OBFUSCATED_GENERATED,
+ );
+ });
+
+ // Button switches to "Regenerate key"
+ expect(
+ screen.getByRole("button", { name: "Regenerate key" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Set up key" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("closes the modal without updating the value after clicking 'Cancel'", async () => {
+ setup({ initialValues: { secret: undefined } });
+
+ await userEvent.click(screen.getByRole("button", { name: "Set up key" }));
+ await screen.findByRole("dialog", { name: "Set up secret key" });
+ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("dialog", { name: "Set up secret key" }),
+ ).not.toBeInTheDocument();
+ });
+
+ // Still shows "Set up key" — value was not changed
+ expect(
+ screen.getByRole("button", { name: "Set up key" }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("when there is an existing value", () => {
+ it("shows a read-only text input with the obfuscated value", () => {
+ setup({ initialValues: { secret: EXISTING_VALUE } });
+
+ const input = screen.getByLabelText("Signing Key");
+ expect(input).toHaveValue(OBFUSCATED_EXISTING);
+ expect(input).toHaveAttribute("readonly");
+ });
+
+ it("shows 'Regenerate key' button, not 'Set up key'", () => {
+ setup({ initialValues: { secret: EXISTING_VALUE } });
+
+ expect(
+ screen.getByRole("button", { name: "Regenerate key" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Set up key" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("opens the setup modal when 'Regenerate key' is clicked", async () => {
+ setup({ initialValues: { secret: EXISTING_VALUE } });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Regenerate key" }),
+ );
+
+ expect(
+ await screen.findByRole("dialog", { name: "Set up secret key" }),
+ ).toBeInTheDocument();
+ });
+
+ it("shows a warning about existing tokens being invalidated when regenerating", async () => {
+ setup({ initialValues: { secret: EXISTING_VALUE } });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Regenerate key" }),
+ );
+
+ expect(
+ await screen.findByText(
+ /This will cause existing tokens to stop working/,
+ ),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("token length validation", () => {
+ it("disables 'Done' button when the token is too short", async () => {
+ setup({ initialValues: { secret: undefined } });
+
+ await userEvent.click(screen.getByRole("button", { name: "Set up key" }));
+ const input = screen.getByRole("textbox", { name: "New secret key" });
+
+ await userEvent.clear(input);
+ await userEvent.type(input, "1234");
+ // Token is too short, so 'Done' button should be disabled
+ expect(screen.getByRole("button", { name: "Done" })).toBeDisabled();
+
+ await userEvent.clear(input);
+ await userEvent.type(input, "12345678");
+ expect(screen.getByRole("button", { name: "Done" })).toBeEnabled();
+ });
+ });
+});
diff --git a/frontend/src/metabase/forms/components/FormSecretKey/SetupKeyModal.tsx b/frontend/src/metabase/forms/components/FormSecretKey/SetupKeyModal.tsx
new file mode 100644
index 00000000000..ebfc95a1005
--- /dev/null
+++ b/frontend/src/metabase/forms/components/FormSecretKey/SetupKeyModal.tsx
@@ -0,0 +1,124 @@
+import { useCallback, useState } from "react";
+import { useMount } from "react-use";
+import { t } from "ttag";
+
+import { useLazyGenerateRandomTokenQuery } from "metabase/api/util";
+import { IconButtonWrapper } from "metabase/common/components/IconButtonWrapper";
+import CS from "metabase/css/core/index.css";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import {
+ Alert,
+ Button,
+ Flex,
+ Group,
+ Icon,
+ Loader,
+ Modal,
+ Stack,
+ Text,
+ TextInput,
+ Tooltip,
+} from "metabase/ui";
+
+type SetupKeyDialogProps = {
+ currentValue?: string;
+ onClose: () => void;
+ onConfirm: (secretKey: string) => void;
+};
+
+const MIN_SECRET_LENGTH = 8;
+
+export const SetupKeyModal = (props: SetupKeyDialogProps) => {
+ const { currentValue, onClose, onConfirm } = props;
+ const [secretValue, setSecretKey] = useState<string>("");
+ const { sendErrorToast, sendSuccessToast } = useMetadataToasts();
+ const [generateRandomToken, { isFetching: isGenerating }] =
+ useLazyGenerateRandomTokenQuery();
+
+ const generateToken = useCallback(async () => {
+ try {
+ const result = await generateRandomToken().unwrap();
+ setSecretKey(result.token);
+ } catch {
+ sendErrorToast(t`Error generating secret key.`);
+ }
+ }, [generateRandomToken, sendErrorToast]);
+
+ useMount(() => {
+ void generateToken();
+ });
+
+ return (
+ <Modal onClose={onClose} opened title={t`Set up secret key`}>
+ <Stack>
+ <Flex align="end" gap="1rem">
+ <TextInput
+ onChange={(event) => setSecretKey(event.target.value || "")}
+ value={secretValue}
+ disabled={isGenerating}
+ rightSection={
+ isGenerating ? (
+ <Loader size="xs" />
+ ) : (
+ <Tooltip label={t`Copy to clipboard`}>
+ <IconButtonWrapper
+ aria-label={t`Preview the query`}
+ onClick={async () => {
+ try {
+ await navigator.clipboard.writeText(secretValue);
+ sendSuccessToast(t`Secret key copied to clipboard`);
+ } catch {
+ sendErrorToast(
+ t`Error copying secret key to clipboard.`,
+ );
+ }
+ }}
+ >
+ <Icon name="copy" />
+ </IconButtonWrapper>
+ </Tooltip>
+ )
+ }
+ flex="1 0 auto"
+ aria-label={t`New secret key`}
+ />
+ <Button
+ className={CS.flexNoShrink}
+ variant="filled"
+ onClick={generateToken}
+ >
+ {t`Regenerate key`}
+ </Button>
+ </Flex>
+ <Stack gap="sm">
+ <Alert color="warning">
+ <Text component="span">
+ {t`Make sure you copy this key now and save it in a safe place.`}{" "}
+ </Text>
+ <Text fw="bold" component="strong" display="block">
+ {t`You won't be able to see it again.`}
+ </Text>
+ </Alert>
+ {!!currentValue && (
+ <Alert color="warning">
+ <Text mt="md" component="strong" fw="bold">
+ {t`This will cause existing tokens to stop working until the identity provider is updated with the new key.`}
+ </Text>
+ </Alert>
+ )}
+ </Stack>
+
+ <Group justify="flex-end" gap="sm" mt="sm">
+ <Button onClick={onClose} variant="subtle">{t`Cancel`}</Button>
+ <Button
+ disabled={secretValue.length < MIN_SECRET_LENGTH}
+ onClick={() => onConfirm(secretValue)}
+ variant="filled"
+ >
+ {t`Done`}
+ </Button>
+ </Group>
+ </Stack>
+ </Modal>
+ );
+};
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index f4c4de00396..f47c9d5ea64 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -352,6 +352,7 @@ export const UserApi = {
update_qbnewb: PUT("/api/user/:id/modal/qbnewb"),
};
+// TODO: move to all functions to RTK (metabase/api/util.ts)
export const UtilApi = {
password_check: POST("/api/session/password-check"),
random_token: GET("/api/util/random_token"),
diff --git a/frontend/test/__support__/server-mocks/settings.ts b/frontend/test/__support__/server-mocks/settings.ts
index 63e480d68f3..f4dd10e7e94 100644
--- a/frontend/test/__support__/server-mocks/settings.ts
+++ b/frontend/test/__support__/server-mocks/settings.ts
@@ -58,3 +58,11 @@ export function setupUpsellEndpoints() {
{ status: 204 },
);
}
+
+export function setupGenerateRandomTokenEndpoint(token: string) {
+ fetchMock.get(
+ "path:/api/util/random_token",
+ { token },
+ { name: "generate-random-token" },
+ );
+}