The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
update UX for SCIM page (#74081)
Nick Fitzpatrickaefebb1badb2
diff --git a/e2e/test/scenarios/admin-2/authentication.cy.spec.ts b/e2e/test/scenarios/admin-2/authentication.cy.spec.tsindex 184f0c6b279..dfb580d626f 100644--- a/e2e/test/scenarios/admin-2/authentication.cy.spec.ts+++ b/e2e/test/scenarios/admin-2/authentication.cy.spec.ts@@ -159,40 +159,88 @@ describe("scenarios > admin > settings > user provisioning", () => {});it("should properly handle errors", () => {- cy.log("should show error when scim token fails to load");- cy.intercept("GET", "/api/ee/scim/api_key", { statusCode: 500 });+ cy.intercept("POST", "/api/ee/scim/api_key", {+ statusCode: 500,+ body: { message: "An error occurred" },+ });+cy.visit("/admin/settings/authentication/user-provisioning");++ // toggling SCIM on triggers the failing token-generation POST+ scimToggle().click();++ // no modal is opened on failure — error surfaces directly on the form+ H.modal().should("not.exist");+H.main().within(() => {- cy.findByText("Error fetching SCIM token");+ cy.findByText("Token failed to generate, Please try again.").should(+ "exist",+ );+ cy.findByRole("button", { name: /Retry/ }).should("exist");});+ });- cy.log(- "should show error when scim token fails to generate when scim is enabled",- );- // enable scim and stop mocking get scim api key request- cy.intercept("GET", "/api/ee/scim/api_key", (req) => {- req.continue();- });- cy.request("PUT", "api/setting/scim-enabled", { value: true });+ it("should close the regenerate modal and surface an error on the token field when regenerate fails", () => {+ // generate an initial token via the UIcy.visit("/admin/settings/authentication/user-provisioning");- H.main().within(() => {- cy.findByText("Token failed to generate, please regenerate one.");+ scimToggle().click();+ H.modal().within(() => {+ cy.findByRole("button", { name: /Done/ }).click();});- cy.log("should show error when scim token fails to regenerate");+ // now make subsequent regenerate calls failcy.intercept("POST", "/api/ee/scim/api_key", {statusCode: 500,body: { message: "An error occurred" },});- cy.findByRole("button", { name: /Regenerate/ }).click();+ cy.findByRole("button", { name: /Regenerate/ }).click();H.modal().within(() => {cy.findByText("Regenerate token?").should("exist");cy.findByRole("button", { name: /Regenerate now/ }).click();});+ // the post-confirm modal does not appear; error surfaces on the form+ H.modal().should("not.exist");+ H.main().within(() => {+ cy.findByText("Failed to regenerate token. Please try again.").should(+ "exist",+ );+ cy.findByText("An error occurred").should("not.exist");+ cy.findByRole("button", { name: /Regenerate/ }).should("exist");+ });+ });++ it("should show a warning when SCIM is enabled without a token", () => {+ // simulate enabling SCIM via config file / env var: enable it server-side, no token generated+ cy.intercept("GET", "/api/ee/scim/api_key", (req) => {+ req.continue();+ });+ cy.request("PUT", "api/setting/scim-enabled", { value: true });+ cy.visit("/admin/settings/authentication/user-provisioning");++ H.main().within(() => {+ cy.findByText(+ "Generate a SCIM token below to complete the setup.",+ ).should("exist");+ cy.findByRole("button", { name: /Generate/ }).should("exist");+ cy.findByText("Token failed to generate, Please try again.").should(+ "not.exist",+ );+ });++ cy.log("warning is removed once a token has been generated");+ cy.findByRole("button", { name: /Generate/ }).click();H.modal().within(() => {- cy.findByText("An error occurred");+ cy.findByText("Here's what you'll need to set SCIM up").should("exist");+ cy.findByRole("button", { name: /Done/ }).click();+ });++ H.main().within(() => {+ cy.findByText(+ "Generate a SCIM token below to complete the setup.",+ ).should("not.exist");+ cy.findByRole("button", { name: /Regenerate/ }).should("exist");});});});diff --git a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.tsx b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.tsxindex 79a1a8617cb..f5794e10b44 100644--- a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.tsx+++ b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.tsx@@ -9,6 +9,7 @@ import {import {AdminSettingInput,BasicAdminSettingInput,+ SetByEnvVar,} from "metabase/admin/settings/components/widgets/AdminSettingInput";import {useGetAdminSettingsDetailsQuery,@@ -18,7 +19,17 @@ import {import { NotFound } from "metabase/common/components/ErrorPages";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { useHasTokenFeature, useSetting } from "metabase/common/hooks";-import { Button, Divider, Flex, Stack, Text, TextInput } from "metabase/ui";+import {+ Alert,+ Box,+ Button,+ Divider,+ Flex,+ Icon,+ Stack,+ Text,+ TextInput,+} from "metabase/ui";import {useGetScimTokenQuery,useRegenerateScimTokenMutation,@@ -64,18 +75,26 @@ export const UserProvisioning = () => {const isScimEnabled = !!settingValues?.["scim-enabled"];const isScimInitialized = !!maskedTokenRequest.data;+ const scimEnabledSetting = fields?.["scim-enabled"];+ const isScimSetByEnv =+ !!scimEnabledSetting?.is_env_setting && !!scimEnabledSetting?.env_name;- // since the request to enable scim and create the first token are separate requests, it's possible- // that the token request failed or wasn't issued due to some interruption (network issue, instance down, etc.)- // we can detect this case by seeing the scim is enabled without any token after all requests for token have settled- // this is later used to show an error message based on this token not being found + encourage the user to go through- // the regenerate flow to get a new unmasked token- const isScimIncorrectlyIniailized = Boolean(+ // SCIM can be enabled without a token existing — e.g. via config file or env var, or if the+ // token-generation request failed during a previous UI-based enablement. In any of those cases+ // we expose the SCIM configuration section so the user can generate a token themselves.+ const isScimEnabledWithoutToken = Boolean(!isScimInitialized &&isScimEnabled &&!(isLoadingToken || maskedTokenRequest.isFetching),);+ // A token-generation attempt was made and failed (vs. "no attempt yet"). Used to surface the+ // failure on the token input — both when no token existed yet (Generate failed) and when a token+ // exists but regeneration failed.+ const hasTokenGenerationError = Boolean(+ regenerateTokenReq.error && !regenerateTokenReq.isLoading,+ );+const samlUserProvisioningEnabled = useSetting("saml-user-provisioning-enabled?" as any,);@@ -88,7 +107,16 @@ export const UserProvisioning = () => {});if (!result.error && enabled && !isScimInitialized) {- await regenerateToken();+ const regenerateResult = await regenerateToken();+ if (!regenerateResult.error) {+ openFirstEnabledModal();+ }+ }+ };++ const handleGenerateToken = async () => {+ const result = await regenerateToken();+ if (!result.error) {openFirstEnabledModal();}};@@ -138,15 +166,25 @@ export const UserProvisioning = () => {{t`When enabled, SAML user provisioning will be turned off in favor of SCIM.`}</ScimTextWarning>)}- <BasicAdminSettingInput- inputType="boolean"- name="scim-enabled"- value={!!settingValues?.["scim-enabled"]}- onChange={(newValue) => handleScimEnabledChange(!!newValue)}- />+ {isScimSetByEnv ? (+ <SetByEnvVar varName={scimEnabledSetting.env_name!} />+ ) : (+ <BasicAdminSettingInput+ inputType="boolean"+ name="scim-enabled"+ value={!!settingValues?.["scim-enabled"]}+ onChange={(newValue) => handleScimEnabledChange(!!newValue)}+ />+ )}+ {isScimEnabledWithoutToken && !hasTokenGenerationError && (+ <Alert+ color="warning"+ icon={<Icon name="warning" />}+ >{t`Generate a SCIM token below to complete the setup.`}</Alert>+ )}</Stack>- {(isScimInitialized || isScimIncorrectlyIniailized) && (+ {(isScimInitialized || isScimEnabledWithoutToken) && (<Stackgap="2rem"opacity={isScimEnabled ? 1 : 0.5}@@ -165,24 +203,39 @@ export const UserProvisioning = () => {disabledw="100%"error={- isScimIncorrectlyIniailized &&- t`Token failed to generate, please regenerate one.`+ hasTokenGenerationError &&+ (isScimInitialized+ ? t`Failed to regenerate token. Please try again.`+ : t`Token failed to generate, Please try again.`)}styles={getTextInputStyles({masked: true,disabled: true,})}+ inputContainer={(children) => (+ <Flex gap="sm">+ <Box style={{ flexGrow: 1 }}>{children}</Box>+ <Button+ disabled={isLoadingToken || !isScimEnabled}+ variant="filled"+ onClick={+ isScimInitialized+ ? openRegenerateModal+ : handleGenerateToken+ }+ style={{ flexShrink: 0 }}+ >+ {regenerateTokenReq.isLoading+ ? t`Generating...`+ : isScimInitialized+ ? t`Regenerate`+ : hasTokenGenerationError+ ? t`Retry`+ : t`Generate`}+ </Button>+ </Flex>+ )}/>- <Button- disabled={isLoadingToken || !isScimEnabled}- variant="filled"- onClick={openRegenerateModal}- style={{ flexShrink: 0 }}- >- {regenerateTokenReq.isLoading- ? t`Regenerating...`- : t`Regenerate`}- </Button></Flex></Stack>)}@@ -212,6 +265,8 @@ export const UserProvisioning = () => {<UserProvisioningRegenerateTokenModalopened={showRegenerateModal}onClose={closeRegenerateModal}+ regenerateToken={regenerateToken}+ regenerateTokenReq={regenerateTokenReq}/></SettingsSection></SettingsPageWrapper>diff --git a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.unit.spec.tsxindex 5de88794527..cb03f228439 100644--- a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioning.unit.spec.tsx@@ -1,9 +1,9 @@import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";import {findRequests,setupPropertiesEndpoints,- setupScimEndpoints,setupSettingsEndpoints,setupUpdateSettingEndpoint,} from "__support__/server-mocks";@@ -21,9 +21,32 @@ import {import { UserProvisioning } from "./UserProvisioning";+const MOCK_SCIM_TOKEN = {+ key_prefix: "mb_/1qM",+ key: "$2a$10$Mu6b.47KRz46Ko2eTJ8Os.3S2uKRwsjNxLZf3V1yVqiDnI3Ruv5C2",+ masked_key: "mb_/1qM****************************************",+ unmasked_key: "mb_/1qMpikachuoEbRrFa9XdAvRQfzyXcoiu1I0MfiEsmw=",+ updated_by_id: 1,+ name: "Metabase SCIM API Key - fc6a551f-d9ad-4d1a-9add-da3bedd12c87",+ scope: "scim" as const,+ creator_id: 1,+ updated_at: "2025-01-12T16:08:20.164094Z",+ created_at: "2025-01-12T16:08:20.164094Z",+ user_id: null,+ id: 626,+};+const setup = async ({settings: opts,-}: { settings?: Partial<EnterpriseSettings> } = {}) => {+ hasScimToken = true,+ tokenGenerationFails = false,+ settingDefinitions = [],+}: {+ settings?: Partial<EnterpriseSettings>;+ hasScimToken?: boolean;+ tokenGenerationFails?: boolean;+ settingDefinitions?: Parameters<typeof setupSettingsEndpoints>[0];+} = {}) => {const settings = createMockSettings({"token-features": createMockTokenFeatures({sso_jwt: true,@@ -32,21 +55,18 @@ const setup = async ({...opts,});setupPropertiesEndpoints(settings);- setupSettingsEndpoints([]);- setupScimEndpoints({- key_prefix: "mb_/1qM",- key: "$2a$10$Mu6b.47KRz46Ko2eTJ8Os.3S2uKRwsjNxLZf3V1yVqiDnI3Ruv5C2",- masked_key: "mb_/1qM****************************************",- unmasked_key: "mb_/1qMpikachuoEbRrFa9XdAvRQfzyXcoiu1I0MfiEsmw=",- updated_by_id: 1,- name: "Metabase SCIM API Key - fc6a551f-d9ad-4d1a-9add-da3bedd12c87",- scope: "scim",- creator_id: 1,- updated_at: "2025-01-12T16:08:20.164094Z",- created_at: "2025-01-12T16:08:20.164094Z",- user_id: null,- id: 626,- });+ setupSettingsEndpoints(settingDefinitions);+ if (hasScimToken) {+ fetchMock.get("path:/api/ee/scim/api_key", MOCK_SCIM_TOKEN);+ } else {+ fetchMock.get("path:/api/ee/scim/api_key", 404);+ }+ fetchMock.post(+ "path:/api/ee/scim/api_key",+ tokenGenerationFails+ ? { status: 500, body: { message: "An error occurred" } }+ : MOCK_SCIM_TOKEN,+ );setupUpdateSettingEndpoint();renderWithProviders(<UserProvisioning />, {@@ -163,4 +183,118 @@ describe("SCIM User Provisioning Settings", () => {const [{ url }] = posts;expect(url).toMatch(/\/api\/ee\/scim\/api_key/);});++ describe("SCIM enabled without a token (e.g. via config file)", () => {+ it("should show the warning and Generate button (and no error) when no token exists yet", async () => {+ await setup({+ settings: { "scim-enabled": true },+ hasScimToken: false,+ });++ expect(+ await screen.findByText(+ "Generate a SCIM token below to complete the setup.",+ ),+ ).toBeInTheDocument();+ expect(screen.getByText("Generate")).toBeInTheDocument();+ expect(screen.queryByText("Regenerate")).not.toBeInTheDocument();+ expect(+ screen.queryByText("Token failed to generate, Please try again."),+ ).not.toBeInTheDocument();+ });++ it("should generate a token when Generate is clicked", async () => {+ await setup({+ settings: { "scim-enabled": true },+ hasScimToken: false,+ });++ await userEvent.click(await screen.findByText("Generate"));++ // the first-enabled modal should appear with the new token+ await screen.findByText("Here's what you'll need to set SCIM up");++ const posts = await findRequests("POST");+ expect(posts).toHaveLength(1);+ const [{ url }] = posts;+ expect(url).toMatch(/\/api\/ee\/scim\/api_key/);+ });+ });++ describe("SCIM enabled with failed token generation", () => {+ it("should show the token-failed error and a Retry button after a failed generation", async () => {+ await setup({+ settings: { "scim-enabled": true },+ hasScimToken: false,+ tokenGenerationFails: true,+ });++ // click Generate to trigger the failed attempt+ await userEvent.click(await screen.findByText("Generate"));++ // the modal is not opened on failure; the form surfaces the error directly+ expect(+ await screen.findByText("Token failed to generate, Please try again."),+ ).toBeInTheDocument();+ expect(screen.getByText("Retry")).toBeInTheDocument();+ // the generic "needs a token" warning is suppressed in favor of the specific error+ expect(+ screen.queryByText(+ "Generate a SCIM token below to complete the setup.",+ ),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText("Here's what you'll need to set SCIM up"),+ ).not.toBeInTheDocument();+ });+ });++ describe("SCIM enabled with a token, regenerate fails", () => {+ it("should close the regenerate modal and surface the error on the SCIM token field", async () => {+ await setup({+ settings: { "scim-enabled": true },+ tokenGenerationFails: true,+ });++ await userEvent.click(await screen.findByText("Regenerate"));++ // confirm modal+ expect(await screen.findByText("Regenerate token?")).toBeInTheDocument();+ await userEvent.click(await screen.findByText("Regenerate now"));++ // the post-regenerate modal must NOT appear on failure+ expect(+ await screen.findByText(+ "Failed to regenerate token. Please try again.",+ ),+ ).toBeInTheDocument();+ expect(screen.queryByText("Regenerate token?")).not.toBeInTheDocument();+ expect(+ screen.queryByText("Copy and save the SCIM token"),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("An error occurred")).not.toBeInTheDocument();+ });+ });++ describe("SCIM enabled via environment variable", () => {+ it("should show the env-var message instead of the toggle when scim-enabled is set by env", async () => {+ await setup({+ settings: { "scim-enabled": true },+ settingDefinitions: [+ {+ key: "scim-enabled",+ is_env_setting: true,+ env_name: "MB_SCIM_ENABLED",+ value: true,+ },+ ],+ });++ expect(screen.getByTestId("setting-env-var-message")).toBeInTheDocument();+ expect(screen.getByText(/MB_SCIM_ENABLED/)).toBeInTheDocument();+ expect(+ screen.queryByRole("switch", { name: /scim/i }),+ ).not.toBeInTheDocument();+ });+ });});diff --git a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioningModals.tsx b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioningModals.tsxindex 2cfa8bd0d0a..748eff1fa38 100644--- a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioningModals.tsx+++ b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/UserProvisioningModals.tsx@@ -4,7 +4,7 @@ import { t } from "ttag";import { ConfirmModal } from "metabase/common/components/ConfirmModal";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { Button, Flex, Modal, type ModalProps, Stack, Text } from "metabase/ui";-import { useRegenerateScimTokenMutation } from "metabase-enterprise/api";+import type { useRegenerateScimTokenMutation } from "metabase-enterprise/api";import { CopyScimInput } from "./ScimInputs";import { ScimTextWarning } from "./ScimTextWarning";@@ -59,26 +59,35 @@ export const UserProvisioningFirstEnabledModal = ({);};-type UserProvisioningRegenerateTokenModalsProps = BaseUserProvisiongModalProps;+type RegenerateMutation = ReturnType<typeof useRegenerateScimTokenMutation>;++type UserProvisioningRegenerateTokenModalsProps =+ BaseUserProvisiongModalProps & {+ regenerateToken: RegenerateMutation[0];+ regenerateTokenReq: RegenerateMutation[1];+ };export const UserProvisioningRegenerateTokenModal = ({opened,onClose,+ regenerateToken,+ regenerateTokenReq,}: UserProvisioningRegenerateTokenModalsProps) => {const [confirmed, setConfirmed] = useState(false);- const [regenerateToken, regenerateTokenReq] =- useRegenerateScimTokenMutation();+ // Don't reset the mutation on close — the parent form needs the error to persist.useEffect(() => {if (!opened) {setConfirmed(false);- regenerateTokenReq.reset();}- }, [opened, regenerateTokenReq]);+ }, [opened]);const handleConfirmRegenerate = async () => {setConfirmed(true);- await regenerateToken();+ const result = await regenerateToken();+ if ("error" in result && result.error) {+ onClose();+ }};if (!confirmed) {