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
Redesign the JWT group mapping section (#81928)
Andrei Chernykh3d145ccb7361
diff --git a/e2e/test/scenarios/admin-2/sso/jwt.cy.spec.js b/e2e/test/scenarios/admin-2/sso/jwt.cy.spec.jsindex b0c0ceae892..5227e2ce63b 100644--- a/e2e/test/scenarios/admin-2/sso/jwt.cy.spec.js+++ b/e2e/test/scenarios/admin-2/sso/jwt.cy.spec.js@@ -1,11 +1,6 @@const { H } = cy;import { enableJwtAuth } from "e2e/support/helpers/e2e-jwt-helpers";-import {- checkGroupConsistencyAfterDeletingMappings,- crudGroupMappingsWidget,-} from "./shared/group-mappings-widget";-describe("scenarios > admin > settings > SSO > JWT", () => {beforeEach(() => {H.restore();@@ -97,22 +92,118 @@ describe("scenarios > admin > settings > SSO > JWT", () => {.should("exist");});- describe("Group Mappings Widget", () => {+ describe("Group mapping", () => {beforeEach(() => {- cy.intercept("GET", "/api/setting").as("getSettings");- cy.intercept("GET", "/api/session/properties").as("getSessionProperties");+ enableJwtAuth();cy.intercept("DELETE", "/api/permissions/group/*").as("deleteGroup");cy.intercept("PUT", "/api/permissions/membership/*/clear").as("clearGroup",);+ cy.visit("/admin/settings/authentication/jwt");});it("should allow deleting mappings along with deleting, or clearing users of, mapped groups", () => {- crudGroupMappingsWidget("jwt");+ cy.log("Every mapping is saved as soon as it is added");+ selectGroupMappingMode("Manual");+ addMapping("cn=People1", ["Administrators", "data", "nosql"]);+ addMapping("cn=People2", ["collection", "readonly"]);++ deleteMapping(+ "cn=People1",+ /delete the groups/i,+ "Remove mapping and delete groups",+ );+ cy.wait(["@deleteGroup", "@deleteGroup"]);++ cy.log("Deleted groups are no longer offered for new mappings");+ newMappingButton().click();+ groupsPicker().click();+ cy.findByRole("listbox")+ .should("contain", "collection")+ .and("not.contain", "data")+ .and("not.contain", "nosql");+ cy.button("Cancel").click();++ cy.log(+ "Deleting the last mapping clears its groups and turns group mapping off",+ );+ deleteMapping(+ "cn=People2",+ /remove all members/i,+ "Remove mapping and members",+ );+ cy.wait(["@clearGroup", "@clearGroup"]);+ groupMappingSection()+ .findByRole("radio", { name: "Off" })+ .should("be.checked");++ cy.log("Deleted groups are gone and cleared groups have no members");+ cy.request("GET", "/api/permissions/group").then(({ body: groups }) => {+ const names = groups.map((group) => group.name);+ expect(names).to.include.members(["collection", "readonly"]);+ expect(names).not.to.include("data");+ expect(names).not.to.include("nosql");+ const memberCount = (name) =>+ groups.find((group) => group.name === name).member_count;+ expect(memberCount("collection")).to.equal(0);+ expect(memberCount("readonly")).to.equal(0);+ });});- it("should allow deleting mappings with groups, while keeping remaining mappings consistent with their undeleted groups", () => {- checkGroupConsistencyAfterDeletingMappings("jwt");+ it("should drop deleted groups from the remaining mappings and clear all mappings when switching to automatic", () => {+ selectGroupMappingMode("Manual");+ addMapping("cn=People1", ["Administrators", "data", "nosql"]);+ addMapping("cn=People2", ["data", "collection"]);+ addMapping("cn=People3", ["collection", "readonly"]);++ cy.log(+ "Deleting a mapping's groups removes them from the other mappings too",+ );+ deleteMapping(+ "cn=People2",+ /delete the groups/i,+ "Remove mapping and delete groups",+ );+ cy.wait(["@deleteGroup", "@deleteGroup"]);+ mappingRow("cn=People1").should("contain", "Administrators, nosql");+ mappingRow("cn=People3")+ .should("contain", "readonly")+ .and("not.contain", "collection");++ cy.log("The same mappings come back after a reload");+ // the row assertions retry until the reloaded page has rendered, so there is nothing to wait on+ cy.reload();+ mappingRow("cn=People1").should("contain", "Administrators, nosql");+ mappingRow("cn=People3")+ .should("contain", "readonly")+ .and("not.contain", "collection");++ cy.log(+ "Switching to automatic asks for confirmation and deletes the mappings",+ );+ selectGroupMappingMode("Automatic");+ H.modal().within(() => {+ cy.findByText("Switch to automatic group mapping?").should(+ "be.visible",+ );+ cy.button("Delete mappings and switch").click();+ });+ cy.wait("@updateSettings").its("request.body").should("deep.equal", {+ "jwt-group-sync": true,+ "jwt-group-mappings": {},+ });+ groupMappingSection()+ .findByRole("radio", { name: "Automatic" })+ .should("be.checked");++ cy.reload();+ groupMappingSection()+ .findByRole("radio", { name: "Automatic" })+ .should("be.checked");+ selectGroupMappingMode("Manual");+ groupMappingSection()+ .findByText("Add at least one mapping to use manual group mapping")+ .should("be.visible");});});});@@ -124,3 +215,41 @@ const getJwtCard = () => {.parent().parent();};++const groupMappingSection = () => cy.findByTestId("jwt-group-schema");++const mappingRow = (name) =>+ cy.contains('[data-testid="jwt-group-mapping-row"]', name);++const newMappingButton = () => cy.button("New mapping");++const groupsPicker = () => cy.findByLabelText("Metabase groups");++// the segmented control keeps its radio inputs hidden, so the visible label takes the click+const selectGroupMappingMode = (mode) => {+ groupMappingSection().findByText(mode).click();+};++// adding a mapping saves it right away, so wait for that write before moving on+const addMapping = (name, groups) => {+ newMappingButton().click();+ cy.findByLabelText("JWT group name").type(name);+ groupsPicker().click();+ groups.forEach((group) => {+ cy.findByRole("option", { name: group }).click();+ });+ cy.button("Add mapping").click();+ cy.wait("@updateSettings");+ mappingRow(name).should("contain", groups.join(", "));+};++const deleteMapping = (name, consequenceLabel, confirmLabel) => {+ mappingRow(name).findByLabelText("Delete mapping").click();+ H.modal().within(() => {+ cy.findByText("Remove this group mapping?").should("be.visible");+ cy.findByText(consequenceLabel).click();+ cy.button(confirmLabel).click();+ });+ cy.wait("@updateSettings");+ mappingRow(name).should("not.exist");+};diff --git a/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js b/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.jsindex 583c3f35260..31d4aa960ce 100644--- a/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js+++ b/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js@@ -20,7 +20,7 @@ export function crudGroupMappingsWidget(authenticationMethod) {cy.findByTestId("admin-content-table").within(() => {cy.icon("close").click({ force: true });});- cy.findByText(/remove all group members/i).click();+ cy.findByText(/remove all members/i).click();cy.button("Remove mapping and members").click();cy.wait(["@clearGroup", "@clearGroup"]);diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.module.css b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.module.cssnew file mode 100644index 00000000000..2e922971670--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.module.css@@ -0,0 +1,46 @@+.mappingRow {+ border: 1px solid var(--mb-color-border-neutral);+ border-radius: var(--mantine-radius-sm);+ padding: var(--mantine-spacing-lg);+}++.mappingRow:hover {+ background-color: var(--mb-color-background_surface-hover);+}++.wrappableText {+ overflow-wrap: anywhere;+}++.rowActions {+ opacity: 0;+}++.mappingRow:hover .rowActions,+.mappingRow:focus-within .rowActions {+ opacity: 1;+}++/* no hover on touch devices, so the actions stay visible there */+@media (hover: none) {+ .rowActions {+ opacity: 1;+ }+}++/* Mantine reserves 100px for the search field, which pushes it under the first pill in a narrow picker */+.groupsSearchField {+ min-width: 3rem;+}++/* the editor row measures itself, so the arrow can go before the picker has to wrap under the name */+.editorRow {+ container-type: inline-size;+}++/* the name field, the arrow, the picker and their gaps need 27rem to share a line */+@container (max-width: 27rem) {+ .editorArrow {+ display: none;+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.tsxnew file mode 100644index 00000000000..4eb0f0168c3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.tsx@@ -0,0 +1,209 @@+import { useMemo, useState } from "react";+import { t } from "ttag";++import { DeleteGroupMappingModal } from "metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal";+import { useListPermissionsGroupsQuery } from "metabase/api";+import { ConfirmModal } from "metabase/common/components/ConfirmModal";+import { getGroupNameLocalized } from "metabase/common/utils/groups";+import { useSelector } from "metabase/redux";+import { getApplicationName } from "metabase/selectors/whitelabel";+import { Button, Flex, Icon, SegmentedControl, Stack, Text } from "metabase/ui";++import { type EditorState, MappingEditorRow } from "./MappingEditorRow";+import { MappingRow } from "./MappingRow";+import { useGroupMappingMode } from "./use-group-mapping-mode";+import { useGroupMappingSettings } from "./use-group-mapping-settings";+import { useMappingDeletion } from "./use-mapping-deletion";+import {+ type JWTGroupSyncMode,+ createGroupLookup,+ withMappingEntry,+} from "./utils";++export function JWTGroupMappingSection({+ isServerConfigured,+ lockedEnvNames = [],+}: {+ // until the server settings are saved, the section is read-only+ isServerConfigured: boolean;+ // env vars that configure the section, which then renders read-only+ lockedEnvNames?: string[];+}) {+ const applicationName = useSelector(getApplicationName);+ const { data: groups = [] } = useListPermissionsGroupsQuery({});+ const groupLookup = useMemo(() => createGroupLookup(groups), [groups]);+ const groupMapping = useGroupMappingSettings();+ const deletion = useMappingDeletion({ groupMapping, groupLookup });+ const modeSwitch = useGroupMappingMode(groupMapping);+ const isBusy = groupMapping.isSaving || deletion.isDeleting;+ const [editor, setEditor] = useState<EditorState | null>(null);++ const isLocked = lockedEnvNames.length > 0;+ const isReadOnly = isLocked || !isServerConfigured;++ const trimmedJwtGroupName = editor?.jwtGroupName.trim() ?? "";+ const isDuplicateName =+ editor != null &&+ Object.hasOwn(groupMapping.mappings, trimmedJwtGroupName) &&+ trimmedJwtGroupName !== editor.originalJwtGroupName;+ const canSaveMapping =+ editor != null &&+ trimmedJwtGroupName !== "" &&+ editor.groupValues.length > 0 &&+ !isDuplicateName;++ const saveMapping = async () => {+ if (editor == null || !canSaveMapping) {+ return;+ }+ const isNewMapping = editor.originalJwtGroupName == null;+ const saved = await groupMapping.saveSettings(+ {+ "jwt-group-sync": true,+ "jwt-group-mappings": withMappingEntry(+ groupMapping.mappings,+ editor.originalJwtGroupName,+ trimmedJwtGroupName,+ editor.groupValues.map(Number),+ ),+ },+ {+ successMessage: isNewMapping ? t`Mapping added` : t`Mapping updated`,+ },+ );+ if (saved) {+ setEditor(null);+ }+ };++ const groupOptions = groupLookup.mappableGroups.map((group) => ({+ value: String(group.id),+ label: getGroupNameLocalized(group),+ }));++ return (+ <Stack gap="lg">+ <Flex justify="space-between" align="center" wrap="wrap" gap="lg">+ <SegmentedControl<JWTGroupSyncMode>+ aria-label={t`Group mapping mode`}+ value={modeSwitch.mode}+ onChange={(nextMode) => {+ setEditor(null);+ modeSwitch.select(nextMode);+ }}+ disabled={isReadOnly || isBusy}+ data={[+ { label: t`Automatic`, value: "automatic" },+ { label: t`Manual`, value: "manual" },+ { label: t`Off`, value: "off" },+ ]}+ />+ {modeSwitch.mode === "manual" && !isReadOnly && (+ <Button+ variant="subtle"+ leftSection={<Icon name="add" aria-hidden />}+ disabled={isBusy}+ onClick={() =>+ setEditor({+ jwtGroupName: "",+ groupValues: [],+ originalJwtGroupName: null,+ })+ }+ >{t`New mapping`}</Button>+ )}+ </Flex>++ {isLocked &&+ lockedEnvNames.map((envName) => (+ <Text key={envName} c="text-secondary">{t`Using ${envName}`}</Text>+ ))}++ {modeSwitch.mode === "automatic" && (+ <Text c="text-secondary">+ {t`Users will be assigned to ${applicationName} groups based on their JWT group names`}+ </Text>+ )}++ {modeSwitch.mode === "manual" && (+ <Stack gap="sm">+ {!modeSwitch.hasMappings && editor == null && !isReadOnly && (+ <Text c="text-secondary">+ {t`Add at least one mapping to use manual group mapping`}+ </Text>+ )}+ {Object.entries(groupMapping.mappings).map(([name, groupIds]) =>+ editor?.originalJwtGroupName === name ? (+ <MappingEditorRow+ key={name}+ editor={editor}+ groupOptions={groupOptions}+ submitLabel={t`Save`}+ canSubmit={canSaveMapping}+ isDuplicateName={isDuplicateName}+ isSubmitting={isBusy}+ onChange={setEditor}+ onCancel={() => setEditor(null)}+ onSubmit={saveMapping}+ />+ ) : (+ <MappingRow+ key={name}+ name={name}+ groupIds={groupIds}+ groupLookup={groupLookup}+ readOnly={isReadOnly}+ disabled={isBusy}+ onEdit={() =>+ setEditor({+ jwtGroupName: name,+ groupValues: groupLookup.existingIds(groupIds).map(String),+ originalJwtGroupName: name,+ })+ }+ onDelete={() => deletion.requestDelete(name)}+ />+ ),+ )}+ {editor != null && editor.originalJwtGroupName == null && (+ <MappingEditorRow+ editor={editor}+ groupOptions={groupOptions}+ submitLabel={t`Add mapping`}+ canSubmit={canSaveMapping}+ isDuplicateName={isDuplicateName}+ isSubmitting={isBusy}+ onChange={setEditor}+ onCancel={() => setEditor(null)}+ onSubmit={saveMapping}+ />+ )}+ </Stack>+ )}++ {deletion.target != null && (+ <DeleteGroupMappingModal+ name={deletion.target}+ groupIds={deletion.targetGroupIds}+ hasAdminGroup={groupLookup.hasAdminGroup(deletion.targetGroupIds)}+ note={+ deletion.isDeletingLastMapping+ ? t`This is the last mapping, so group mapping will be turned off.`+ : undefined+ }+ onConfirm={deletion.confirmDelete}+ onHide={deletion.cancelDelete}+ />+ )}+ <ConfirmModal+ opened={modeSwitch.isClearConfirmOpen}+ title={t`Switch to automatic group mapping?`}+ message={t`Your existing group mappings will be deleted, and users will be assigned to ${applicationName} groups matching their JWT group names.`}+ confirmButtonText={t`Delete mappings and switch`}+ onClose={modeSwitch.cancelClear}+ // the modal's busy guard only engages on a returned promise, which also blocks double submits+ onConfirm={modeSwitch.confirmClear}+ />+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingEditorRow.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingEditorRow.tsxnew file mode 100644index 00000000000..76253fbe391--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingEditorRow.tsx@@ -0,0 +1,125 @@+import { t } from "ttag";++import { useSelector } from "metabase/redux";+import { getApplicationName } from "metabase/selectors/whitelabel";+import {+ Button,+ FixedSizeIcon,+ Flex,+ MultiSelect,+ TextInput,+} from "metabase/ui";++import S from "./JWTGroupMappingSection.module.css";++export type EditorState = {+ jwtGroupName: string;+ // MultiSelect values, so group ids as strings+ groupValues: string[];+ // set while an existing mapping is being edited+ originalJwtGroupName: string | null;+};++export function MappingEditorRow({+ editor,+ groupOptions,+ submitLabel,+ canSubmit,+ isDuplicateName,+ isSubmitting,+ onChange,+ onCancel,+ onSubmit,+}: {+ editor: EditorState;+ groupOptions: { value: string; label: string }[];+ submitLabel: string;+ canSubmit: boolean;+ isDuplicateName: boolean;+ isSubmitting: boolean;+ onChange: (editor: EditorState) => void;+ onCancel: () => void;+ onSubmit: () => void;+}) {+ const applicationName = useSelector(getApplicationName);++ // the editor is inside the page form, so Enter must not reach its submit button+ const handleNameKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key === "Enter") {+ event.preventDefault();+ if (canSubmit && !isSubmitting) {+ onSubmit();+ }+ }+ if (event.key === "Escape") {+ onCancel();+ }+ };++ const handleGroupsKeyDown = (+ event: React.KeyboardEvent<HTMLInputElement>,+ ) => {+ if (event.key === "Enter") {+ event.preventDefault();+ }+ };++ return (+ <Flex+ className={S.editorRow}+ bd="1px solid var(--mb-color-border-neutral)"+ bdrs="sm"+ p="sm"+ align="center"+ gap="lg"+ wrap="wrap"+ >+ <TextInput+ flex={1}+ miw="10rem"+ aria-label={t`JWT group name`}+ placeholder={t`Enter JWT group...`}+ value={editor.jwtGroupName}+ error={+ isDuplicateName ? t`A mapping for this group already exists` : null+ }+ onChange={(event) =>+ onChange({ ...editor, jwtGroupName: event.target.value })+ }+ onKeyDown={handleNameKeyDown}+ autoFocus+ />+ <FixedSizeIcon+ aria-hidden+ name="arrow_right"+ c="text-secondary"+ className={S.editorArrow}+ />+ <MultiSelect+ flex={2}+ miw="14rem"+ classNames={{ inputField: S.groupsSearchField }}+ aria-label={t`${applicationName} groups`}+ placeholder={+ editor.groupValues.length === 0+ ? t`Pick ${applicationName} group...`+ : undefined+ }+ data={groupOptions}+ value={editor.groupValues}+ onChange={(groupValues) => onChange({ ...editor, groupValues })}+ onKeyDown={handleGroupsKeyDown}+ searchable+ />+ <Button variant="subtle" onClick={onCancel}>{t`Cancel`}</Button>+ <Button+ variant="filled"+ disabled={!canSubmit}+ loading={isSubmitting}+ onClick={onSubmit}+ >+ {submitLabel}+ </Button>+ </Flex>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingRow.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingRow.tsxnew file mode 100644index 00000000000..e22e42ade21--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingRow.tsx@@ -0,0 +1,91 @@+import { t } from "ttag";++import { getGroupNameLocalized } from "metabase/common/utils/groups";+import { ActionIcon, FixedSizeIcon, Flex, Icon, Text } from "metabase/ui";+import type { GroupId } from "metabase-types/api";++import S from "./JWTGroupMappingSection.module.css";+import type { GroupLookup } from "./utils";++export function MappingRow({+ name,+ groupIds,+ groupLookup,+ readOnly,+ disabled,+ onEdit,+ onDelete,+}: {+ name: string;+ groupIds: GroupId[];+ groupLookup: GroupLookup;+ readOnly: boolean;+ disabled: boolean;+ onEdit: () => void;+ onDelete: () => void;+}) {+ return (+ <Flex+ className={S.mappingRow}+ align="center"+ gap="lg"+ data-testid="jwt-group-mapping-row"+ >+ <Flex flex={1} miw={0} align="center" gap="lg" wrap="wrap">+ <Text fw="bold" flex="0 0 auto" maw="100%" className={S.wrappableText}>+ {name}+ </Text>+ <FixedSizeIcon aria-hidden name="arrow_right" c="text-secondary" />+ <MappingRowGroups groupIds={groupIds} groupLookup={groupLookup} />+ </Flex>+ {!readOnly && (+ <Flex className={S.rowActions} gap="sm">+ <ActionIcon+ aria-label={t`Edit mapping`}+ disabled={disabled}+ onClick={onEdit}+ >+ <Icon name="pencil" />+ </ActionIcon>+ <ActionIcon+ aria-label={t`Delete mapping`}+ disabled={disabled}+ onClick={onDelete}+ >+ <Icon name="trash" />+ </ActionIcon>+ </Flex>+ )}+ </Flex>+ );+}++function MappingRowGroups({+ groupIds,+ groupLookup,+}: {+ groupIds: GroupId[];+ groupLookup: GroupLookup;+}) {+ const names = groupIds+ .map((groupId) => {+ const group = groupLookup.getGroup(groupId);+ return group ? getGroupNameLocalized(group) : null;+ })+ .filter((groupName) => groupName != null);++ // zero-group mappings can't be created here anymore, but exist in the wild+ if (names.length === 0) {+ return (+ <Text flex="1 1 auto" miw={0} c="text-secondary">+ {t`No groups`}+ </Text>+ );+ }+ // sized by content, so the names only drop under the mapping name when they don't fit+ return (+ <Text flex="1 1 auto" miw={0} className={S.wrappableText}>+ {names.join(", ")}+ </Text>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/index.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/index.tsnew file mode 100644index 00000000000..8c6f4dddffe--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/index.ts@@ -0,0 +1 @@+export { JWTGroupMappingSection } from "./JWTGroupMappingSection";diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-mode.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-mode.tsnew file mode 100644index 00000000000..3b0f3490608--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-mode.ts@@ -0,0 +1,103 @@+import { useEffect, useState } from "react";+import { t } from "ttag";++import type { GroupMappingSettingsState } from "./use-group-mapping-settings";+import type { JWTGroupSyncMode } from "./utils";++type GroupMappingModeState = {+ mode: JWTGroupSyncMode;+ hasMappings: boolean;+ isClearConfirmOpen: boolean;+ select: (nextMode: JWTGroupSyncMode) => Promise<void>;+ confirmClear: () => Promise<void>;+ cancelClear: () => void;+};++/** The backend stores no mode, so this derives it from the two settings and writes what each switch means */+export function useGroupMappingMode(+ groupMapping: GroupMappingSettingsState,+): GroupMappingModeState {+ // manual without mappings only exists on the client, until the first mapping is saved+ const [isManualPending, setIsManualPending] = useState(false);+ const [isClearConfirmOpen, setIsClearConfirmOpen] = useState(false);+ const hasMappings = Object.keys(groupMapping.mappings).length > 0;++ // pending manual ends once mappings exist, whether added here or brought in by a refetch+ useEffect(() => {+ if (hasMappings) {+ setIsManualPending(false);+ }+ }, [hasMappings]);++ let mode: JWTGroupSyncMode;+ if (isManualPending && !hasMappings) {+ mode = "manual";+ } else if (!groupMapping.syncEnabled) {+ mode = "off";+ } else if (hasMappings) {+ mode = "manual";+ } else {+ mode = "automatic";+ }++ const saveSyncEnabled = (enabled: boolean) =>+ groupMapping.saveSettings(+ { "jwt-group-sync": enabled },+ { successMessage: t`Changes saved` },+ );++ const switchOff = async () => {+ if (groupMapping.syncEnabled) {+ await saveSyncEnabled(false);+ }+ };++ // with mappings kept from before sync just turns back on, otherwise the first mapping does it+ const switchToManual = async () => {+ if (hasMappings) {+ await saveSyncEnabled(true);+ }+ };++ // automatic can't coexist with mappings, so those go through a confirmation first+ const switchToAutomatic = async () => {+ if (hasMappings) {+ setIsClearConfirmOpen(true);+ return;+ }+ if (!groupMapping.syncEnabled) {+ await saveSyncEnabled(true);+ }+ };++ const select = async (nextMode: JWTGroupSyncMode) => {+ // manual without mappings is the one switch that writes nothing yet+ setIsManualPending(nextMode === "manual" && !hasMappings);+ if (nextMode === "off") {+ await switchOff();+ } else if (nextMode === "manual") {+ await switchToManual();+ } else if (nextMode === "automatic") {+ await switchToAutomatic();+ }+ };++ const confirmClear = async () => {+ const saved = await groupMapping.saveSettings(+ { "jwt-group-sync": true, "jwt-group-mappings": {} },+ { successMessage: t`Changes saved` },+ );+ if (saved) {+ setIsClearConfirmOpen(false);+ }+ };++ return {+ mode,+ hasMappings,+ isClearConfirmOpen,+ select,+ confirmClear,+ cancelClear: () => setIsClearConfirmOpen(false),+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-settings.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-settings.tsnew file mode 100644index 00000000000..39d3bef482d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-settings.ts@@ -0,0 +1,77 @@+import { useState } from "react";+import { t } from "ttag";++import type { MappingsType } from "metabase/admin/types";+import { getErrorMessage } from "metabase/api/utils/errors";+import { useToast } from "metabase/common/hooks";+import { useDispatch } from "metabase/redux";+import {+ settingsApi,+ useSetting,+ useUpdateSettingsMutation,+} from "metabase/settings";+import type { EnterpriseSettings } from "metabase-types/api";++export type GroupMappingSettings = Partial<+ Pick<EnterpriseSettings, "jwt-group-sync" | "jwt-group-mappings">+>;++export type GroupMappingSettingsState = {+ syncEnabled: boolean;+ mappings: MappingsType;+ isSaving: boolean;+ saveSettings: (+ settings: GroupMappingSettings,+ options?: { successMessage?: string },+ ) => Promise<boolean>;+};++const EMPTY_MAPPINGS: MappingsType = {};++export function useGroupMappingSettings(): GroupMappingSettingsState {+ const dispatch = useDispatch();+ const [sendToast] = useToast();+ const [updateSettings] = useUpdateSettingsMutation();+ const syncEnabled = useSetting("jwt-group-sync") ?? false;+ const mappings = useSetting("jwt-group-mappings") ?? EMPTY_MAPPINGS;+ const [isSaving, setIsSaving] = useState(false);++ const saveSettings = async (+ settings: GroupMappingSettings,+ { successMessage }: { successMessage?: string } = {},+ ) => {+ setIsSaving(true);+ try {+ const response = await updateSettings(settings);+ if (response.error) {+ sendToast({+ message: getErrorMessage(+ response.error,+ t`Error saving group mapping`,+ ),+ icon: "warning",+ toastColor: "feedback-negative",+ });+ return false;+ }+ // show the saved state right away instead of waiting for the settings refetch+ dispatch(+ settingsApi.util.updateQueryData(+ "getSessionProperties",+ undefined,+ (draft) => {+ Object.assign(draft, settings);+ },+ ),+ );+ if (successMessage != null) {+ sendToast({ message: successMessage, icon: "check_filled" });+ }+ return true;+ } finally {+ setIsSaving(false);+ }+ };++ return { syncEnabled, mappings, isSaving, saveSettings };+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-mapping-deletion.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-mapping-deletion.tsnew file mode 100644index 00000000000..83684990650--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-mapping-deletion.ts@@ -0,0 +1,140 @@+import { useState } from "react";+import { t } from "ttag";++import type {+ DeleteMappingModalValueType,+ GroupIds,+} from "metabase/admin/types";+import {+ useClearGroupMembershipMutation,+ useDeletePermissionsGroupMutation,+} from "metabase/api";+import { useToast } from "metabase/common/hooks";++import type {+ GroupMappingSettings,+ GroupMappingSettingsState,+} from "./use-group-mapping-settings";+import { type GroupLookup, withoutMapping } from "./utils";++type MappingCascade = {+ value: Exclude<DeleteMappingModalValueType, "nothing">;+ groupIds: GroupIds;+};++type MappingDeletionState = {+ target: string | null;+ targetGroupIds: GroupIds;+ isDeletingLastMapping: boolean;+ isDeleting: boolean;+ requestDelete: (name: string) => void;+ cancelDelete: () => void;+ confirmDelete: (+ value: DeleteMappingModalValueType,+ groupIds: GroupIds,+ name: string,+ ) => Promise<void>;+};++export function useMappingDeletion({+ groupMapping,+ groupLookup,+}: {+ groupMapping: GroupMappingSettingsState;+ groupLookup: GroupLookup;+}): MappingDeletionState {+ const [sendToast] = useToast();+ const [clearGroupMembership] = useClearGroupMembershipMutation();+ const [deletePermissionsGroup] = useDeletePermissionsGroupMutation();+ const [target, setTarget] = useState<string | null>(null);+ const [isDeleting, setIsDeleting] = useState(false);++ const targetGroupIds =+ target == null+ ? []+ : groupLookup.existingIds(groupMapping.mappings[target] ?? []);+ const isDeletingLastMapping =+ target != null && Object.keys(groupMapping.mappings).length === 1;++ // "nothing, just remove the mapping" arrives as null and touches no group+ const runCascade = async (cascade: MappingCascade | null) => {+ if (cascade == null) {+ return { failureCount: 0 };+ }+ // the group calls are independent, so they run at once+ const results = await Promise.allSettled(+ cascade.groupIds.map((groupId) =>+ cascade.value === "clear"+ ? clearGroupMembership(groupId).unwrap()+ : deletePermissionsGroup(groupId).unwrap(),+ ),+ );+ const failures = results.filter((result) => result.status === "rejected");+ failures.forEach((failure) => console.error(failure.reason));+ return { failureCount: failures.length };+ };++ const deleteMapping = async (+ name: string,+ cascade: MappingCascade | null,+ ) => {+ const nextMappings = withoutMapping(+ groupMapping.mappings,+ name,+ cascade?.value === "delete" ? cascade.groupIds : [],+ );+ const isLastMapping = Object.keys(nextMappings).length === 0;+ // sync can't stay on without mappings, or the backend would silently fall back to name matching+ const settings: GroupMappingSettings = isLastMapping+ ? { "jwt-group-mappings": nextMappings, "jwt-group-sync": false }+ : { "jwt-group-mappings": nextMappings };+ const saved = await groupMapping.saveSettings(settings);+ if (!saved) {+ return;+ }+ const { failureCount } = await runCascade(cascade);+ if (failureCount > 0) {+ sendToast({+ message: t`Mapping deleted, but not all of its groups could be updated`,+ icon: "warning",+ toastColor: "feedback-negative",+ });+ return;+ }+ sendToast({+ message: isLastMapping+ ? t`Mapping deleted and group mapping turned off`+ : t`Mapping deleted`,+ icon: "check_filled",+ });+ };++ const confirmDelete = async (+ value: DeleteMappingModalValueType,+ groupIds: GroupIds,+ name: string,+ ) => {+ setTarget(null);+ const cascade =+ value === "nothing"+ ? null+ : { value, groupIds: groupLookup.actionableIds(groupIds) };+ // the write releases its own busy flag before the cascade, so this one covers the whole operation+ setIsDeleting(true);+ try {+ await deleteMapping(name, cascade);+ } finally {+ setIsDeleting(false);+ }+ };++ return {+ target,+ targetGroupIds,+ isDeletingLastMapping,+ isDeleting,+ requestDelete: setTarget,+ cancelDelete: () => setTarget(null),+ confirmDelete,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.tsnew file mode 100644index 00000000000..e65f7b4638c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.ts@@ -0,0 +1,71 @@+import type { MappingsType } from "metabase/admin/types";+import {+ isAdminGroup,+ isDefaultGroup,+ isDefaultTenantGroup,+} from "metabase/common/utils/groups";+import type { GroupId, GroupListQuery } from "metabase-types/api";++export type JWTGroupSyncMode = "automatic" | "manual" | "off";++/** Rebuilds in place so a renamed mapping keeps its position in the list */+export function withMappingEntry(+ mappings: MappingsType,+ originalJwtGroupName: string | null,+ jwtGroupName: string,+ groupIds: GroupId[],+): MappingsType {+ const entries = Object.entries(mappings).map(+ ([mappingName, ids]): [string, GroupId[]] =>+ mappingName === originalJwtGroupName+ ? [jwtGroupName, groupIds]+ : [mappingName, ids],+ );+ if (originalJwtGroupName == null) {+ entries.push([jwtGroupName, groupIds]);+ }+ // fromEntries defines own properties, so names like __proto__ stay plain keys+ return Object.fromEntries(entries);+}++/** Drops one mapping and scrubs deleted group ids from the rest, since the backend keeps their ids */+export function withoutMapping(+ mappings: MappingsType,+ name: string,+ deletedGroupIds: GroupId[] = [],+): MappingsType {+ const deleted = new Set(deletedGroupIds);+ return Object.fromEntries(+ Object.entries(mappings)+ .filter(([mappingName]) => mappingName !== name)+ .map(([mappingName, ids]): [string, GroupId[]] => [+ mappingName,+ ids.filter((groupId) => !deleted.has(groupId)),+ ]),+ );+}++export type GroupLookup = ReturnType<typeof createGroupLookup>;++export function createGroupLookup(groups: GroupListQuery[]) {+ const groupsById = new Map(groups.map((group) => [group.id, group]));+ const isAdminGroupId = (groupId: GroupId) => {+ const group = groupsById.get(groupId);+ return group != null && isAdminGroup(group);+ };+ return {+ // magic groups can't be mapped to+ mappableGroups: groups.filter(+ (group) => !isDefaultGroup(group) && !isDefaultTenantGroup(group),+ ),+ getGroup: (groupId: GroupId) => groupsById.get(groupId),+ existingIds: (groupIds: GroupId[]) =>+ groupIds.filter((groupId) => groupsById.has(groupId)),+ // cascades never touch the admin group, so it doesn't count as actionable+ actionableIds: (groupIds: GroupId[]) =>+ groupIds.filter(+ (groupId) => groupsById.has(groupId) && !isAdminGroupId(groupId),+ ),+ hasAdminGroup: (groupIds: GroupId[]) => groupIds.some(isAdminGroupId),+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.unit.spec.tsnew file mode 100644index 00000000000..28196d080ac--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.unit.spec.ts@@ -0,0 +1,74 @@+import { createMockGroup } from "metabase-types/api/mocks";++import { createGroupLookup, withMappingEntry, withoutMapping } from "./utils";++describe("withMappingEntry", () => {+ it("appends a new mapping", () => {+ expect(withMappingEntry({ first: [1] }, null, "second", [2])).toEqual({+ first: [1],+ second: [2],+ });+ });++ it("keeps a renamed mapping in place", () => {+ const result = withMappingEntry(+ { first: [1], second: [2], third: [3] },+ "second",+ "renamed",+ [4],+ );++ expect(Object.entries(result)).toEqual([+ ["first", [1]],+ ["renamed", [4]],+ ["third", [3]],+ ]);+ });++ it("stores prototype member names as plain keys", () => {+ const result = withMappingEntry({}, null, "__proto__", [1]);++ expect(Object.hasOwn(result, "__proto__")).toBe(true);+ expect(Object.getPrototypeOf(result)).toBe(Object.prototype);+ });+});++describe("withoutMapping", () => {+ it("drops the mapping and leaves the others alone", () => {+ expect(withoutMapping({ old: [4], devs: [4, 3] }, "old")).toEqual({+ devs: [4, 3],+ });+ });++ it("scrubs deleted group ids from the remaining mappings", () => {+ expect(withoutMapping({ old: [4], devs: [4, 3] }, "old", [4])).toEqual({+ devs: [3],+ });+ });+});++describe("createGroupLookup", () => {+ const groupLookup = createGroupLookup([+ createMockGroup(),+ createMockGroup({+ id: 2,+ name: "Administrators",+ magic_group_type: "admin",+ }),+ createMockGroup({ id: 3, name: "foo", magic_group_type: null }),+ ]);++ it("excludes magic groups from the mappable ones", () => {+ expect(groupLookup.mappableGroups.map((group) => group.id)).toEqual([2, 3]);+ });++ it("filters ids of groups that no longer exist", () => {+ expect(groupLookup.existingIds([3, 9])).toEqual([3]);+ });++ it("leaves the admin group out of cascades", () => {+ expect(groupLookup.actionableIds([2, 3, 9])).toEqual([3]);+ expect(groupLookup.hasAdminGroup([2, 3])).toBe(true);+ expect(groupLookup.hasAdminGroup([3])).toBe(false);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsxindex baf63acc273..292ba2bc2d5 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx@@ -10,8 +10,8 @@ import {SettingsSection,} from "metabase/admin/components/SettingsSection";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 { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { useToast } from "metabase/common/hooks";import {@@ -36,8 +36,12 @@ import type {SettingDefinitionMap,} from "metabase-types/api";-// Attribute-key fields show only a placeholder, no helper text. Env-locked-// fields swap the placeholder for the readOnly "Using MB_..." notice.+import { JWTGroupMappingSection } from "./JWTGroupMappingSection";++/**+ * Attribute-key fields show only a placeholder, no helper text.+ * Env-locked fields swap the placeholder for the readOnly "Using MB_..." notice.+ */const getAttributeFieldProps = (setting: SettingDefinition | undefined,placeholder?: string,@@ -55,6 +59,8 @@ export type JWTFormValues = Pick<| "jwt-attribute-email"| "jwt-attribute-firstname"| "jwt-attribute-lastname"+ | "jwt-attribute-groups"+ | "jwt-attribute-tenant">;export const SettingsJWTForm = () => {@@ -67,9 +73,23 @@ export const SettingsJWTForm = () => {const applicationName = useSelector(getApplicationName);const [sendToast] = useToast();- const handleSubmit = async (values: Partial<JWTFormValues>) => {+ // a paused JWT keeps its settings, so "configured" means an identity provider URI exists+ const uriSetting = settingDetails?.["jwt-identity-provider-uri"];+ const isServerConfigured =+ Boolean(uriSetting?.value) || (uriSetting?.is_env_setting ?? false);++ // either env var locks the whole group mapping section, since the two settings act as one feature+ const groupMappingEnvNames = [+ settingDetails?.["jwt-group-sync"],+ settingDetails?.["jwt-group-mappings"],+ ].flatMap((setting) =>+ setting?.is_env_setting && setting.env_name ? [setting.env_name] : [],+ );+ const isGroupMappingEnvConfigured = groupMappingEnvNames.length > 0;++ const saveSettings = async (values: JWTFormValues) => {const { "jwt-shared-secret": jwtSecret, ...rest } = values;- const settingsToUpdate: Partial<JWTFormValues> = { ...rest };+ const settingsToUpdate: Partial<EnterpriseSettings> = { ...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.@@ -77,13 +97,19 @@ export const SettingsJWTForm = () => {settingsToUpdate["jwt-shared-secret"] = jwtSecret;}+ // per the design, the first save turns automatic group mapping on; the section owns it from then on+ if (!isServerConfigured && !isGroupMappingEnvConfigured) {+ settingsToUpdate["jwt-group-sync"] = true;+ settingsToUpdate["jwt-group-mappings"] = {};+ }+const result = await updateSettings({...settingsToUpdate,"jwt-enabled": true,toast: false,});// Make sure the shared token obfuscated value is fetched from the backend.- refetchSettingDetails();+ await refetchSettingDetails();if (result.error) {throw new Error(t`Error saving JWT Settings`);@@ -110,8 +136,7 @@ export const SettingsJWTForm = () => {settingDetails["jwt-attribute-groups"],...(usingTenants ? [settingDetails["jwt-attribute-tenant"]] : []),].some(- // env-configured attributes come back with a nil value and only the- // is_env_setting flag, so value alone can't detect them+ // env-configured attributes come back as nil with only the is_env_setting flag set(setting) => Boolean(setting?.value) || (setting?.is_env_setting ?? false),);@@ -129,10 +154,10 @@ export const SettingsJWTForm = () => {)}<FormProviderinitialValues={getFormValues(settingDetails)}- onSubmit={handleSubmit}+ onSubmit={saveSettings}enableReinitialize>- {({ dirty }) => (+ {({ dirty, isSubmitting }) => (<Form><Stack gap="xl"><SettingsSection@@ -165,6 +190,7 @@ export const SettingsJWTForm = () => {title={t`User attribute configuration`}description={t`You can send additional user attributes to ${applicationName} by adding the attributes as key/value pairs to your JWT`}defaultOpened={hasUserAttributes}+ disabled={!isServerConfigured}><Stack gap="lg"><FormTextInput@@ -216,14 +242,13 @@ export const SettingsJWTForm = () => {description={t`Lets you assign users to custom ${applicationName} groups based on their JWT attributes`}descriptionProps={SETTINGS_CARD_DESCRIPTION_PROPS}stackProps={SETTINGS_CARD_STACK_PROPS}+ disabled={!isServerConfigured}>+ {/* the section saves on its own, so it stays out of the form's values */}<Box data-testid="jwt-group-schema">- <GroupMappingsWidget- setting={{ key: "jwt-group-sync" }}- onChange={handleSubmit}- mappingSetting="jwt-group-mappings"- groupHeading={t`Group Name`}- groupPlaceholder={t`Group Name`}+ <JWTGroupMappingSection+ isServerConfigured={isServerConfigured}+ lockedEnvNames={groupMappingEnvNames}/></Box></SettingsSection>@@ -236,6 +261,7 @@ export const SettingsJWTForm = () => {/></Flex></Stack>+ <LeaveRouteConfirmModal isEnabled={dirty && !isSubmitting} /></Form>)}</FormProvider>@@ -247,15 +273,13 @@ const getFormValues = (settingDetails: SettingDefinitionMap): JWTFormValues => {const jwtSettings = _.pick(settingDetails, ["jwt-identity-provider-uri","jwt-shared-secret",- "jwt-group-sync","jwt-attribute-email","jwt-attribute-firstname","jwt-attribute-lastname","jwt-attribute-groups","jwt-attribute-tenant",]);-- // cast undefined to null+ // mapObject widens the picked setting values (and casts undefined to null)return _.mapObject(jwtSettings, (val) => val?.value ?? null) as JWTFormValues;};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.tsxindex 05262a21fa8..75d8513e93c 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@@ -4,22 +4,31 @@ import fetchMock from "fetch-mock";import {findRequests,setupGenerateRandomTokenEndpoint,- setupPropertiesEndpoints,- setupSettingsEndpoints,- setupUpdateSettingEndpoint,- setupUpdateSettingsEndpoint,+ setupStatefulSettingsEndpoints,} from "__support__/server-mocks";-import { renderWithProviders, screen, within } from "__support__/ui";+import {+ act,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import {+ createMockSettingsState,+ createMockState,+} from "metabase/redux/store/mocks";+import { settingsApi } from "metabase/settings";+import type { SettingDefinition } from "metabase-types/api";import { createMockGroup, createMockSettings } from "metabase-types/api/mocks";import { SettingsJWTForm } from "./SettingsJWTForm";const GROUPS = [createMockGroup(),- createMockGroup({ id: 2, name: "Administrators" }),- createMockGroup({ id: 3, name: "foo" }),- createMockGroup({ id: 4, name: "bar" }),- createMockGroup({ id: 5, name: "flamingos" }),+ createMockGroup({ id: 2, name: "Administrators", magic_group_type: "admin" }),+ createMockGroup({ id: 3, name: "foo", magic_group_type: null }),+ createMockGroup({ id: 4, name: "bar", magic_group_type: null }),+ createMockGroup({ id: 5, name: "flamingos", magic_group_type: null }),];const setup = async ({@@ -29,6 +38,14 @@ const setup = async ({attributesConfigured,attributesEnvConfigured,tenantAttributeConfigured,+ groupSync,+ groupMappings,+ groupSyncEnvConfigured,+ groupMappingsEnvConfigured,+ saveStatus,+ saveDelayMs,+ cascadeStatus,+ cascadeDelayMs,}: {jwtEnabled?: boolean;useTenants?: boolean;@@ -36,10 +53,36 @@ const setup = async ({attributesConfigured?: boolean;attributesEnvConfigured?: boolean;tenantAttributeConfigured?: boolean;+ groupSync?: boolean;+ groupMappings?: Record<string, number[]>;+ groupSyncEnvConfigured?: boolean;+ groupMappingsEnvConfigured?: boolean;+ saveStatus?: number;+ saveDelayMs?: number;+ cascadeStatus?: number;+ cascadeDelayMs?: number;} = {}) => {- setupSettingsEndpoints([+ const settingDefinitions: SettingDefinition[] = [{ key: "use-tenants", value: useTenants ?? false },{ key: "jwt-enabled", value: jwtEnabled ?? false },+ ...(groupSyncEnvConfigured+ ? ([+ {+ key: "jwt-group-sync",+ is_env_setting: true,+ env_name: "MB_JWT_GROUP_SYNC",+ },+ ] as const)+ : ([{ key: "jwt-group-sync", value: groupSync ?? false }] as const)),+ ...(groupMappingsEnvConfigured+ ? ([+ {+ key: "jwt-group-mappings",+ is_env_setting: true,+ env_name: "MB_JWT_GROUP_MAPPINGS",+ },+ ] as const)+ : ([{ key: "jwt-group-mappings", value: groupMappings ?? {} }] as const)),...(configured? ([{ key: "jwt-identity-provider-uri", value: "http://example.com" },@@ -61,22 +104,77 @@ const setup = async ({...(tenantAttributeConfigured? ([{ key: "jwt-attribute-tenant", value: "tenant-key" }] as const): []),- ]);- setupPropertiesEndpoints(- createMockSettings({- "use-tenants": useTenants,- "jwt-enabled": jwtEnabled,- }),+ ];+ // session properties carry the effective values, and the stateful store reflects live writes on refetch, admin list included+ const sessionSettings = createMockSettings({+ "use-tenants": useTenants,+ "jwt-enabled": jwtEnabled,+ "jwt-group-sync": groupSync ?? false,+ "jwt-group-mappings": groupMappings ?? {},+ });+ const settingsStore = setupStatefulSettingsEndpoints(sessionSettings);+ // the shared helper keeps the admin list static, so serve it here with whatever the store has changed since setup+ const initialSettings = { ...settingsStore };+ fetchMock.get(+ "path:/api/setting",+ () => {+ const written = Object.fromEntries(+ Object.entries(settingsStore).filter(+ ([key, value]) => value !== initialSettings[key],+ ),+ );+ const listed = new Set<string>(+ settingDefinitions.map((definition) => definition.key),+ );+ return [+ ...settingDefinitions.map((definition) =>+ definition.key in written+ ? { ...definition, value: written[definition.key] }+ : definition,+ ),+ ...Object.entries(written)+ .filter(([key]) => !listed.has(key))+ .map(([key, value]) => ({ key, value })),+ ];+ },+ { name: "settings-list" },);- setupUpdateSettingsEndpoint();- setupUpdateSettingEndpoint();+ if (saveStatus != null || saveDelayMs != null) {+ // a failed write leaves the store alone, and a slow one lands in it once it resolves+ const status = saveStatus ?? 204;+ fetchMock.removeRoute("update-settings");+ fetchMock.put(+ "path:/api/setting",+ ({ options }) => {+ if (status < 300) {+ Object.assign(settingsStore, JSON.parse(String(options.body)));+ }+ return { status };+ },+ { name: "update-settings", delay: saveDelayMs },+ );+ }setupGenerateRandomTokenEndpoint("1234abcd");fetchMock.get("path:/api/permissions/group", GROUPS);+ fetchMock.put(+ "express:/api/permissions/membership/:id/clear",+ cascadeStatus ?? 204,+ { delay: cascadeDelayMs },+ );+ fetchMock.delete("express:/api/permissions/group/:id", cascadeStatus ?? 204, {+ delay: cascadeDelayMs,+ });- renderWithProviders(<SettingsJWTForm />, { withUndos: true });+ const { store } = renderWithProviders(<SettingsJWTForm />, {+ withUndos: true,+ storeInitialState: createMockState({+ settings: createMockSettingsState(sessionSettings),+ }),+ });await screen.findByText("Server settings");+ return { store, settingsStore };};const expandUserAttributeSection = async () => {@@ -85,6 +183,19 @@ const expandUserAttributeSection = async () => {);};+const addMapping = async (name: string, groupName: string) => {+ await userEvent.click(screen.getByRole("button", { name: "New mapping" }));+ await userEvent.type(screen.getByPlaceholderText("Enter JWT group..."), name);+ await userEvent.click(screen.getByPlaceholderText("Pick Metabase group..."));+ await userEvent.click(await screen.findByRole("option", { name: groupName }));+ await userEvent.click(screen.getByRole("button", { name: "Add mapping" }));+};++const findMappingRow = (name: string) =>+ screen+ .getAllByTestId("jwt-group-mapping-row")+ .find((row) => within(row).queryByText(name) != null);+describe("SettingsJWTForm", () => {const ATTRS = {"jwt-identity-provider-uri": "http://example.com",@@ -98,9 +209,7 @@ describe("SettingsJWTForm", () => {"jwt-group-sync": true,};- it("should submit the correct payload", async () => {- await setup();-+ const fillServerSettings = async () => {await userEvent.type(await screen.findByRole("textbox", { name: /JWT Identity Provider URI/ }),ATTRS["jwt-identity-provider-uri"],@@ -114,6 +223,44 @@ describe("SettingsJWTForm", () => {ATTRS["jwt-shared-secret"],);await userEvent.click(await screen.findByRole("button", { name: /Done/ }));+ };++ it("saves the server settings, turns automatic on and enables the other cards", async () => {+ await setup();+ const attributeHeader = screen.getByRole("button", {+ name: /User attribute configuration/,+ });+ expect(attributeHeader).toBeDisabled();++ await fillServerSettings();+ await userEvent.click(+ screen.getByRole("button", { name: /Save and enable/ }),+ );++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ const [{ url, body }] = puts;+ // it's strange that there's no special JWT endpoint when other SSO methods have endpoints with fancy validation 🤷♀️+ expect(url).toMatch(/\/api\/setting$/);+ // per the design, the first save turns automatic group mapping on+ expect(body).toEqual({+ "jwt-identity-provider-uri": ATTRS["jwt-identity-provider-uri"],+ "jwt-shared-secret": ATTRS["jwt-shared-secret"],+ "jwt-enabled": true,+ "jwt-group-sync": true,+ "jwt-group-mappings": {},+ });+ await waitFor(() => expect(attributeHeader).toBeEnabled());+ expect(screen.getByRole("radio", { name: "Automatic" })).toBeChecked();+ expect(screen.getByRole("radio", { name: "Automatic" })).toBeEnabled();+ expect(+ screen.getByText(/Users will be assigned to Metabase groups/),+ ).toBeInTheDocument();+ });++ it("saves the attribute keys once the server settings exist", async () => {+ await setup({ jwtEnabled: true, configured: true });+await expandUserAttributeSection();await userEvent.type(await screen.findByRole("textbox", { name: /Email attribute/ }),@@ -133,54 +280,23 @@ describe("SettingsJWTForm", () => {}),ATTRS["jwt-attribute-groups"],);- const groupSchema = await screen.findByTestId("jwt-group-schema");- await userEvent.click(within(groupSchema).getByRole("switch")); // checkbox for "jwt-group-sync"-- await userEvent.click(await screen.findByRole("button", { name: /Save/ }));-- const puts = await findRequests("PUT");- expect(puts).toHaveLength(1);- const [{ url, body }] = puts;- // it's strange that there's no special JWT endpoint when other SSO methods have endpoints with fancy validation 🤷♀️- expect(url).toMatch(/\/api\/setting$/);- expect(body).toEqual(ATTRS);- });- it("should only update the mappings setting when adding a group mapping", async () => {- await setup({ jwtEnabled: true, configured: true });-- await userEvent.click(- await screen.findByRole("button", { name: /New mapping/ }),- );- await userEvent.type(- await screen.findByLabelText("New group mapping name"),- "cn=People",- );- await userEvent.click(await screen.findByRole("button", { name: "Add" }));-- const puts = await findRequests("PUT");- expect(puts).toHaveLength(1);- const [{ url, body }] = puts;- expect(url).toMatch(/\/api\/setting\/jwt-group-mappings$/);- expect(body).toEqual({ value: { "cn=People": [] } });- });-- it("shows a toast after saving", async () => {- await setup({ jwtEnabled: true, configured: true });-- await userEvent.type(- await screen.findByRole("textbox", { name: /JWT Identity Provider URI/ }),- "/extra",- );- await userEvent.click(- await screen.findByRole("button", { name: "Save changes" }),- );+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));+ const [{ body }] = await findRequests("PUT");+ expect(body).toMatchObject({+ "jwt-attribute-email": ATTRS["jwt-attribute-email"],+ "jwt-attribute-firstname": ATTRS["jwt-attribute-firstname"],+ "jwt-attribute-lastname": ATTRS["jwt-attribute-lastname"],+ "jwt-attribute-groups": ATTRS["jwt-attribute-groups"],+ "jwt-enabled": true,+ });+ expect(body).not.toHaveProperty("jwt-group-sync");expect(await screen.findByText("Changes saved")).toBeInTheDocument();});it("collapses the user attribute section when no attribute is set", async () => {- await setup();+ await setup({ configured: true });expect(await screen.findByRole("button", {@@ -190,7 +306,7 @@ describe("SettingsJWTForm", () => {});it("expands the user attribute section when an attribute is set", async () => {- await setup({ attributesConfigured: true });+ await setup({ configured: true, attributesConfigured: true });expect(await screen.findByRole("button", {@@ -203,7 +319,7 @@ describe("SettingsJWTForm", () => {});it("expands the user attribute section when attributes are set via env vars", async () => {- await setup({ attributesEnvConfigured: true });+ await setup({ configured: true, attributesEnvConfigured: true });expect(await screen.findByRole("button", {@@ -212,8 +328,21 @@ describe("SettingsJWTForm", () => {).toHaveAttribute("aria-expanded", "true");});+ it("keeps the user attribute section collapsed while the server settings are missing, even with env-set attributes", async () => {+ await setup({ attributesEnvConfigured: true });++ const header = await screen.findByRole("button", {+ name: /User attribute configuration/,+ });+ expect(header).toBeDisabled();+ expect(header).toHaveAttribute("aria-expanded", "false");+ expect(+ screen.getByRole("textbox", { name: /Email attribute/, hidden: true }),+ ).not.toBeVisible();+ });+it("ignores a tenant attribute for the default-open check when tenants are off", async () => {- await setup({ tenantAttributeConfigured: true });+ await setup({ configured: true, tenantAttributeConfigured: true });expect(await screen.findByRole("button", {@@ -231,12 +360,7 @@ describe("SettingsJWTForm", () => {});it("should show tenant attribute when tenanting is on", async () => {- await setup({ useTenants: true });-- await userEvent.type(- await screen.findByRole("textbox", { name: /JWT Identity Provider URI/ }),- ATTRS["jwt-identity-provider-uri"],- );+ await setup({ useTenants: true, jwtEnabled: true, configured: true });await expandUserAttributeSection();await userEvent.type(@@ -246,7 +370,7 @@ describe("SettingsJWTForm", () => {"Cat",);- await userEvent.click(await screen.findByRole("button", { name: /Save/ }));+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));const puts = await findRequests("PUT");expect(puts).toHaveLength(1);@@ -277,4 +401,861 @@ describe("SettingsJWTForm", () => {expect(screen.getByText(/user provisioning/i)).toBeInTheDocument();});++ describe("group mapping", () => {+ it("keeps the attribute and group mapping cards disabled until the server settings are saved", async () => {+ await setup();++ expect(+ screen.getByRole("button", { name: /User attribute configuration/ }),+ ).toBeDisabled();+ expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();+ expect(screen.getByRole("radio", { name: "Off" })).toBeDisabled();+ expect(+ screen.queryByText(/Users will be assigned to Metabase groups/),+ ).not.toBeInTheDocument();+ });++ it("derives the stored mode when JWT is paused but already configured", async () => {+ await setup({+ jwtEnabled: false,+ configured: true,+ groupSync: true,+ groupMappings: { "group-a": [3] },+ });++ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();+ expect(screen.getByRole("radio", { name: "Manual" })).toBeEnabled();+ const row = screen.getByTestId("jwt-group-mapping-row");+ expect(within(row).getByText("group-a")).toBeInTheDocument();+ expect(await within(row).findByText("foo")).toBeInTheDocument();+ });++ it("derives off mode when group sync is disabled", async () => {+ await setup({ jwtEnabled: true, configured: true });++ expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();+ });++ it("writes a new mapping immediately without touching the page form", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ });++ await addMapping("devs", "bar");++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ const [{ body }] = puts;+ expect(body).toEqual({+ "jwt-group-sync": true,+ "jwt-group-mappings": { existing: [3], devs: [4] },+ });+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();+ expect(+ await screen.findAllByTestId("jwt-group-mapping-row"),+ ).toHaveLength(2);+ expect(+ screen.getByRole("button", { name: "Save changes" }),+ ).toBeDisabled();+ });++ it("turns off after the last mapping is deleted even if manual was pending before a refetch brought mappings in", async () => {+ const { store, settingsStore } = await setup({+ jwtEnabled: true,+ configured: true,+ });++ await userEvent.click(screen.getByRole("radio", { name: "Manual" }));+ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();++ // another admin set a mapping up meanwhile, and a refetch brings it in+ Object.assign(settingsStore, {+ "jwt-group-sync": true,+ "jwt-group-mappings": { other: [3] },+ });+ act(() => {+ store.dispatch(settingsApi.util.invalidateTags(["session-properties"]));+ });+ await waitFor(() => expect(findMappingRow("other")).toBeDefined());++ await userEvent.click(+ screen.getByRole("button", { name: "Delete mapping" }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Remove mapping" }),+ );++ expect(+ await screen.findByText("Mapping deleted and group mapping turned off"),+ ).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();+ expect(screen.getByRole("radio", { name: "Manual" })).not.toBeChecked();+ });++ it("keeps manual pending until the first mapping is added", async () => {+ await setup({ jwtEnabled: true, configured: true, groupSync: true });++ expect(screen.getByRole("radio", { name: "Automatic" })).toBeChecked();+ await userEvent.click(screen.getByRole("radio", { name: "Manual" }));++ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();+ expect(+ screen.getByText(+ "Add at least one mapping to use manual group mapping",+ ),+ ).toBeInTheDocument();+ expect(await findRequests("PUT")).toHaveLength(0);++ await addMapping("devs", "bar");++ const [{ body }] = await findRequests("PUT");+ expect(body).toEqual({+ "jwt-group-sync": true,+ "jwt-group-mappings": { devs: [4] },+ });+ });++ it("turns sync off and back on without touching the stored mappings", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ });++ await userEvent.click(screen.getByRole("radio", { name: "Off" }));++ await waitFor(() => {+ expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();+ });+ expect(await findRequests("PUT")).toHaveLength(1);+ expect(+ screen.queryByTestId("jwt-group-mapping-row"),+ ).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole("radio", { name: "Manual" }));++ await waitFor(() => {+ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();+ });+ expect(+ await screen.findByTestId("jwt-group-mapping-row"),+ ).toHaveTextContent("existing");+ const puts = await findRequests("PUT");+ expect(puts.map(({ body }) => body)).toEqual([+ { "jwt-group-sync": false },+ { "jwt-group-sync": true },+ ]);+ });++ it("deletes a mapping and clears its groups right away", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { admins: [4], devs: [3] },+ });++ await userEvent.click(+ within(findMappingRow("admins")!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /Also remove all members/ }),+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Remove mapping and members" }),+ );++ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();+ const puts = await findRequests("PUT");+ const settingsIndex = puts.findIndex(({ url }) =>+ /\/api\/setting$/.test(url),+ );+ const clearIndex = puts.findIndex(({ url }) =>+ url.includes("/api/permissions/membership/4/clear"),+ );+ expect(puts[settingsIndex].body).toEqual({+ "jwt-group-mappings": { devs: [3] },+ });+ // the cascade runs only after the mapping was removed+ expect(clearIndex).toBeGreaterThan(settingsIndex);+ expect(+ puts.some(({ url }) =>+ url.includes("/api/permissions/membership/3/clear"),+ ),+ ).toBe(false);+ await waitFor(() => {+ expect(findMappingRow("admins")).toBeUndefined();+ });+ });++ it("reports a failed cascade once and skips the success toast", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { old: [4, 5], devs: [3] },+ cascadeStatus: 500,+ });++ await userEvent.click(+ within(findMappingRow("old")!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /Also delete the groups/ }),+ );+ await userEvent.click(+ screen.getByRole("button", {+ name: "Remove mapping and delete groups",+ }),+ );++ expect(+ await screen.findAllByText(+ "Mapping deleted, but not all of its groups could be updated",+ ),+ ).toHaveLength(1);+ expect(screen.queryByText("Mapping deleted")).not.toBeInTheDocument();+ const deletes = await findRequests("DELETE");+ expect(deletes).toHaveLength(2);+ await waitFor(() => {+ expect(findMappingRow("old")).toBeUndefined();+ });+ });++ it("keeps the editor open and reports the error when the write fails", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ saveStatus: 500,+ });++ await addMapping("devs", "bar");++ expect(+ await screen.findByText("Error saving group mapping"),+ ).toBeInTheDocument();+ expect(screen.getByPlaceholderText("Enter JWT group...")).toHaveValue(+ "devs",+ );+ expect(screen.getByRole("button", { name: "Add mapping" })).toBeEnabled();+ expect(screen.getAllByTestId("jwt-group-mapping-row")).toHaveLength(1);+ expect(screen.queryByText("Mapping added")).not.toBeInTheDocument();+ });++ it("keeps the mapping and skips the cascade when the delete write fails", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { old: [4], devs: [3] },+ saveStatus: 500,+ });++ await userEvent.click(+ within(findMappingRow("old")!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /Also delete the group/ }),+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Remove mapping and delete group" }),+ );++ expect(+ await screen.findByText("Error saving group mapping"),+ ).toBeInTheDocument();+ expect(findMappingRow("old")).toBeDefined();+ expect(await findRequests("DELETE")).toHaveLength(0);+ expect(screen.queryByText(/Mapping deleted/)).not.toBeInTheDocument();+ });++ it("keeps the stored mode when switching it fails", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ saveStatus: 500,+ });++ await userEvent.click(screen.getByRole("radio", { name: "Off" }));++ expect(+ await screen.findByText("Error saving group mapping"),+ ).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();+ expect(screen.getByRole("radio", { name: "Manual" })).toBeEnabled();+ expect(findMappingRow("existing")).toBeDefined();+ });++ it("disables the new mapping button while a save is in flight", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ saveDelayMs: 300,+ });++ await addMapping("devs", "bar");++ expect(+ screen.getByRole("button", { name: "New mapping" }),+ ).toBeDisabled();+ expect(+ await screen.findByText("Mapping added", {}, { timeout: 3000 }),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "New mapping" })).toBeEnabled();+ });++ it("keeps the controls disabled until the cascade finishes", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { old: [4], devs: [3] },+ cascadeDelayMs: 300,+ });++ await userEvent.click(+ within(findMappingRow("old")!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /Also delete the group/ }),+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Remove mapping and delete group" }),+ );++ // the mapping write is done once the row is gone, while the group delete is still in flight+ await waitFor(() => expect(findMappingRow("old")).toBeUndefined());+ expect(+ within(findMappingRow("devs")!).getByRole("button", {+ name: "Delete mapping",+ }),+ ).toBeDisabled();+ expect(screen.getByRole("radio", { name: "Off" })).toBeDisabled();++ expect(+ await screen.findByText("Mapping deleted", {}, { timeout: 3000 }),+ ).toBeInTheDocument();+ expect(+ within(findMappingRow("devs")!).getByRole("button", {+ name: "Delete mapping",+ }),+ ).toBeEnabled();+ expect(screen.getByRole("radio", { name: "Off" })).toBeEnabled();+ });++ it("deletes a mapping's groups and drops them from the other mappings in the same write", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { old: [4], devs: [4, 3] },+ });++ await userEvent.click(+ within(findMappingRow("old")!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /Also delete the group/ }),+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Remove mapping and delete group" }),+ );++ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();+ const puts = await findRequests("PUT");+ const settingsPut = puts.find(({ url }) => /\/api\/setting$/.test(url));+ expect(settingsPut?.body).toEqual({+ "jwt-group-mappings": { devs: [3] },+ });+ const deletes = await findRequests("DELETE");+ expect(deletes.map(({ url }) => url)).toEqual([+ "http://localhost/api/permissions/group/4",+ ]);+ });++ it("edits a mapping without the ids of groups that no longer exist", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { devs: [9, 3] },+ });++ await userEvent.click(+ screen.getByRole("button", { name: "Edit mapping" }),+ );++ expect(screen.getByText("foo")).toBeInTheDocument();+ expect(screen.queryByText("9")).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Save" }));++ const [{ body }] = await findRequests("PUT");+ expect(body["jwt-group-mappings"]).toEqual({ devs: [3] });+ });++ it("turns group mapping off when the last mapping is deleted", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { only: [3] },+ });++ await userEvent.click(+ screen.getByRole("button", { name: "Delete mapping" }),+ );+ expect(+ await screen.findByText(+ "This is the last mapping, so group mapping will be turned off.",+ ),+ ).toBeInTheDocument();+ await userEvent.click(+ screen.getByRole("button", { name: "Remove mapping" }),+ );++ expect(+ await screen.findByText("Mapping deleted and group mapping turned off"),+ ).toBeInTheDocument();+ const [{ body }] = await findRequests("PUT");+ expect(body).toEqual({+ "jwt-group-mappings": {},+ "jwt-group-sync": false,+ });+ await waitFor(() => {+ expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();+ });+ });++ it("keeps a renamed mapping in place and rejects duplicate names", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { first: [3], second: [4] },+ });++ await userEvent.click(+ within(findMappingRow("second")!).getByRole("button", {+ name: "Edit mapping",+ }),+ );+ const nameInput = screen.getByLabelText("JWT group name");+ await userEvent.clear(nameInput);+ await userEvent.type(nameInput, "first");++ expect(+ screen.getByText("A mapping for this group already exists"),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();++ await userEvent.clear(nameInput);+ await userEvent.type(nameInput, "second-renamed");+ await userEvent.click(screen.getByRole("button", { name: "Save" }));++ expect(await screen.findByText("Mapping updated")).toBeInTheDocument();+ const [{ body }] = await findRequests("PUT");+ expect(body["jwt-group-mappings"]).toEqual({+ first: [3],+ "second-renamed": [4],+ });+ const names = screen+ .getAllByTestId("jwt-group-mapping-row")+ .map((row) => within(row).getAllByText(/./)[0].textContent);+ expect(names).toEqual(["first", "second-renamed"]);+ });++ it("allows mapping names that collide with object prototype members", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ });++ await userEvent.click(+ screen.getByRole("button", { name: "New mapping" }),+ );+ await userEvent.type(+ screen.getByPlaceholderText("Enter JWT group..."),+ "constructor",+ );+ await userEvent.click(+ screen.getByPlaceholderText("Pick Metabase group..."),+ );+ await userEvent.click(await screen.findByRole("option", { name: "bar" }));++ expect(+ screen.queryByText("A mapping for this group already exists"),+ ).not.toBeInTheDocument();+ await userEvent.click(+ screen.getByRole("button", { name: "Add mapping" }),+ );++ expect(+ await screen.findAllByTestId("jwt-group-mapping-row"),+ ).toHaveLength(2);+ });++ it("commits the row editor on Enter instead of submitting the page", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ });++ // a dirty page form has a live Save button, so Enter could submit it+ await userEvent.type(+ screen.getByRole("textbox", { name: /JWT Identity Provider URI/ }),+ "/v2",+ );+ expect(+ screen.getByRole("button", { name: "Save changes" }),+ ).toBeEnabled();++ await userEvent.click(+ screen.getByRole("button", { name: "New mapping" }),+ );+ const nameInput = screen.getByPlaceholderText("Enter JWT group...");+ await userEvent.type(nameInput, "devs");+ await userEvent.click(+ screen.getByPlaceholderText("Pick Metabase group..."),+ );+ await userEvent.click(await screen.findByRole("option", { name: "bar" }));+ await userEvent.click(nameInput);+ await userEvent.keyboard("{Enter}");++ await waitFor(() => {+ expect(+ screen.queryByPlaceholderText("Enter JWT group..."),+ ).not.toBeInTheDocument();+ });+ expect(screen.getAllByTestId("jwt-group-mapping-row")).toHaveLength(2);+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ expect(puts[0].body).not.toHaveProperty("jwt-identity-provider-uri");+ });++ it("cancels the row editor on Escape", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ });++ await userEvent.click(+ screen.getByRole("button", { name: "New mapping" }),+ );+ await userEvent.type(+ screen.getByPlaceholderText("Enter JWT group..."),+ "temp{Escape}",+ );++ expect(+ screen.queryByPlaceholderText("Enter JWT group..."),+ ).not.toBeInTheDocument();+ expect(screen.getAllByTestId("jwt-group-mapping-row")).toHaveLength(1);+ expect(await findRequests("PUT")).toHaveLength(0);+ });++ it("confirms admin-only and zero-group deletions without offering cascades", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { admins: [2], legacy: [], devs: [3] },+ });++ await userEvent.click(+ within(findMappingRow("admins")!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ const adminsModal = await screen.findByRole("dialog");+ expect(+ within(adminsModal).getByText("Remove this group mapping?"),+ ).toBeInTheDocument();+ expect(+ within(adminsModal).getByText(+ "The Administrators group is not affected.",+ ),+ ).toBeInTheDocument();+ expect(within(adminsModal).queryByRole("radio")).not.toBeInTheDocument();+ await userEvent.click(+ within(adminsModal).getByRole("button", { name: "Remove mapping" }),+ );+ await waitFor(() => {+ expect(findMappingRow("admins")).toBeUndefined();+ });++ await userEvent.click(+ within(findMappingRow("legacy")!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ const legacyModal = await screen.findByRole("dialog");+ expect(+ within(legacyModal).getByText(+ "This mapping isn't linked to any group.",+ ),+ ).toBeInTheDocument();+ expect(within(legacyModal).queryByRole("radio")).not.toBeInTheDocument();+ await userEvent.click(+ within(legacyModal).getByRole("button", { name: "Remove mapping" }),+ );+ await waitFor(() => {+ expect(findMappingRow("legacy")).toBeUndefined();+ });++ await userEvent.click(+ within(findMappingRow("devs")!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ const devsModal = await screen.findByRole("dialog");+ expect(within(devsModal).getAllByRole("radio")).toHaveLength(3);+ const puts = await findRequests("PUT");+ expect(puts.map(({ body }) => body["jwt-group-mappings"])).toEqual([+ { legacy: [], devs: [3] },+ { devs: [3] },+ ]);+ });++ it("names the mode control and the editor inputs for assistive tech", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ });++ expect(+ screen.getByRole("radiogroup", { name: "Group mapping mode" }),+ ).toBeInTheDocument();++ await userEvent.click(+ screen.getByRole("button", { name: "New mapping" }),+ );++ expect(screen.getByLabelText("JWT group name")).toBeInTheDocument();+ expect(screen.getByLabelText("Metabase groups")).toBeInTheDocument();+ });++ it("asks for confirmation before switching to automatic and stays manual on cancel", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { "group-a": [3] },+ });++ await userEvent.click(screen.getByRole("radio", { name: "Automatic" }));++ expect(+ await screen.findByText("Switch to automatic group mapping?"),+ ).toBeInTheDocument();+ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));++ expect(+ screen.queryByText("Switch to automatic group mapping?"),+ ).not.toBeInTheDocument();+ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();+ expect(await findRequests("PUT")).toHaveLength(0);+ });++ it("switches to automatic and deletes the stored mappings on confirmation", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { "group-a": [3] },+ });++ await userEvent.click(screen.getByRole("radio", { name: "Automatic" }));+ await userEvent.click(+ await screen.findByRole("button", {+ name: "Delete mappings and switch",+ }),+ );++ await waitFor(() => {+ expect(screen.getByRole("radio", { name: "Automatic" })).toBeChecked();+ });+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ expect(puts[0].body).toEqual({+ "jwt-group-sync": true,+ "jwt-group-mappings": {},+ });+ expect(+ screen.queryByTestId("jwt-group-mapping-row"),+ ).not.toBeInTheDocument();+ });++ it("keeps the confirmation busy until the automatic switch is saved", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { "group-a": [3] },+ saveDelayMs: 300,+ });++ await userEvent.click(screen.getByRole("radio", { name: "Automatic" }));+ const confirmButton = await screen.findByRole("button", {+ name: "Delete mappings and switch",+ });+ await userEvent.dblClick(confirmButton);++ expect(confirmButton).toBeDisabled();+ expect(+ screen.getByText("Switch to automatic group mapping?"),+ ).toBeInTheDocument();++ await waitFor(+ () => {+ expect(+ screen.queryByText("Switch to automatic group mapping?"),+ ).not.toBeInTheDocument();+ },+ { timeout: 3000 },+ );+ expect(await findRequests("PUT")).toHaveLength(1);+ });++ it("keeps the confirmation open when the automatic switch fails to save", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { "group-a": [3] },+ saveStatus: 500,+ });++ await userEvent.click(screen.getByRole("radio", { name: "Automatic" }));+ const confirmButton = await screen.findByRole("button", {+ name: "Delete mappings and switch",+ });+ await userEvent.click(confirmButton);++ expect(+ await screen.findByText("Error saving group mapping"),+ ).toBeInTheDocument();+ expect(await findRequests("PUT")).toHaveLength(1);+ expect(+ screen.getByText("Switch to automatic group mapping?"),+ ).toBeInTheDocument();+ expect(confirmButton).toBeEnabled();+ expect(findMappingRow("group-a")).toBeDefined();+ });++ it("locks the section to the values configured through env vars", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { "env-group": [3] },+ groupSyncEnvConfigured: true,+ groupMappingsEnvConfigured: true,+ });++ expect(screen.getByText("Using MB_JWT_GROUP_SYNC")).toBeInTheDocument();+ expect(+ screen.getByText("Using MB_JWT_GROUP_MAPPINGS"),+ ).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();+ expect(screen.getByRole("radio", { name: "Manual" })).toBeDisabled();+ expect(screen.getByTestId("jwt-group-mapping-row")).toHaveTextContent(+ "env-group",+ );+ expect(+ screen.queryByRole("button", { name: "New mapping" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Delete mapping" }),+ ).not.toBeInTheDocument();+ });++ it("locks the section when only the sync flag comes from an env var", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { "stored-group": [3] },+ groupSyncEnvConfigured: true,+ });++ expect(screen.getByText("Using MB_JWT_GROUP_SYNC")).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();+ expect(screen.getByTestId("jwt-group-mapping-row")).toHaveTextContent(+ "stored-group",+ );+ expect(+ screen.queryByRole("button", { name: "Edit mapping" }),+ ).not.toBeInTheDocument();+ });++ it("does not turn sync on with the first save when it is env-configured", async () => {+ await setup({ groupSyncEnvConfigured: true });++ await userEvent.type(+ await screen.findByRole("textbox", {+ name: /JWT Identity Provider URI/,+ }),+ ATTRS["jwt-identity-provider-uri"],+ );+ await userEvent.click(+ await screen.findByRole("button", { name: /Save/ }),+ );++ const [{ body }] = await findRequests("PUT");+ expect(body).not.toHaveProperty("jwt-group-sync");+ expect(body).not.toHaveProperty("jwt-group-mappings");+ });++ it("leaves the group settings alone when saving other fields of a configured setup", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ });++ await userEvent.type(+ screen.getByRole("textbox", { name: /JWT Identity Provider URI/ }),+ "/sso",+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Save changes" }),+ );++ const [{ body }] = await findRequests("PUT");+ expect(body["jwt-identity-provider-uri"]).toBe("http://example.com/sso");+ expect(body).not.toHaveProperty("jwt-group-sync");+ expect(body).not.toHaveProperty("jwt-group-mappings");+ });+ });});diff --git a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.module.css b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.module.cssindex c30919c19d3..f38b2bde096 100644--- a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.module.css+++ b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.module.css@@ -86,3 +86,19 @@line-height: inherit;word-break: normal;}++/* disabled cards fade as a whole, the way the mocks show them before setup */+.DisabledSection {+ opacity: 0.5;+}++/* the card fades as a whole, so the disabled control must not fade a second time */+.CollapsibleAccordion .CollapsibleControl:disabled {+ opacity: 1;+}++/* a disabled card is a preview rather than a blocked action, so its header shows a plain cursor */+.CollapsibleAccordion .CollapsibleControl:disabled,+.CollapsibleAccordion .CollapsibleControl:disabled::after {+ cursor: default;+}diff --git a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsxindex 1bb0096cdf3..5aab64f1b7e 100644--- a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx+++ b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx@@ -1,5 +1,6 @@import cx from "classnames";import type React from "react";+import { useState } from "react";import {Accordion,@@ -33,6 +34,8 @@ export function SettingsSection({children,id,stackProps,+ disabled = false,+ className,...boxProps}: {title?: React.ReactNode;@@ -42,10 +45,16 @@ export function SettingsSection({children?: React.ReactNode;id?: string;stackProps?: StackProps;+ // greys the whole card out; the caller still disables the controls inside+ disabled?: boolean;} & BoxProps) {const { className: stackClassName, ...restStackProps } = stackProps ?? {};return (- <Box id={id} {...boxProps}>+ <Box+ id={id}+ className={cx(disabled && S.DisabledSection, className)}+ {...boxProps}+ >{children && (<Stackgap="xl"@@ -79,6 +88,7 @@ export function CollapsibleSettingsSection({title,description,defaultOpened = false,+ disabled = false,children,className,...boxProps@@ -86,11 +96,19 @@ export function CollapsibleSettingsSection({title: React.ReactNode;description?: React.ReactNode;defaultOpened?: boolean;+ // greys the card out, keeps it closed and keeps it from toggling+ disabled?: boolean;children?: React.ReactNode;} & BoxProps) {+ // a card that defaults open while disabled opens once it is enabled+ const [isOpened, setIsOpened] = useState(defaultOpened);return (<Accordion- className={cx(S.CollapsibleAccordion, className)}+ className={cx(+ S.CollapsibleAccordion,+ disabled && S.DisabledSection,+ className,+ )}classNames={{item: S.CollapsibleItem,control: S.CollapsibleControl,@@ -101,7 +119,8 @@ export function CollapsibleSettingsSection({}}chevron={<Icon aria-hidden name="chevrondown" />}order={2}- defaultValue={defaultOpened ? COLLAPSIBLE_SECTION_VALUE : null}+ value={isOpened && !disabled ? COLLAPSIBLE_SECTION_VALUE : null}+ onChange={(value) => setIsOpened(value != null)}{...boxProps}><Accordion.Item value={COLLAPSIBLE_SECTION_VALUE}>@@ -109,7 +128,7 @@ export function CollapsibleSettingsSection({the whole header row toggles while the description stays outsidethe control button and out of its accessible name */}<Box className={S.CollapsibleHeader}>- <Accordion.Control>{title}</Accordion.Control>+ <Accordion.Control disabled={disabled}>{title}</Accordion.Control>{description && (<Text c="text-secondary" {...SETTINGS_CARD_DESCRIPTION_PROPS}>{description}diff --git a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.unit.spec.tsx b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.unit.spec.tsxindex 073cfe82e52..005fccc88e0 100644--- a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.unit.spec.tsx+++ b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.unit.spec.tsx@@ -4,17 +4,21 @@ import { renderWithProviders, screen, waitFor } from "__support__/ui";import { CollapsibleSettingsSection } from "./SettingsSection";-const setup = ({ defaultOpened }: { defaultOpened?: boolean } = {}) => {- renderWithProviders(- <CollapsibleSettingsSection- title="Section title"- description="Section description"- defaultOpened={defaultOpened}- >- <div>Section content</div>- </CollapsibleSettingsSection>,- );-};+type SetupOptions = { defaultOpened?: boolean; disabled?: boolean };++const getSection = ({ defaultOpened, disabled }: SetupOptions = {}) => (+ <CollapsibleSettingsSection+ title="Section title"+ description="Section description"+ defaultOpened={defaultOpened}+ disabled={disabled}+ >+ <div>Section content</div>+ </CollapsibleSettingsSection>+);++const setup = (options: SetupOptions = {}) =>+ renderWithProviders(getSection(options));describe("CollapsibleSettingsSection", () => {it("shows the title and description while collapsed", () => {@@ -60,4 +64,21 @@ describe("CollapsibleSettingsSection", () => {expect(screen.getByText("Section content")).toBeVisible();});++ it("stays collapsed while disabled and opens once enabled when defaultOpened", async () => {+ const { rerender } = setup({ defaultOpened: true, disabled: true });+ const header = screen.getByRole("button", { name: /Section title/ });++ expect(header).toBeDisabled();+ expect(header).toHaveAttribute("aria-expanded", "false");+ expect(screen.getByText("Section content")).not.toBeVisible();++ rerender(getSection({ defaultOpened: true, disabled: false }));++ expect(header).toBeEnabled();+ expect(header).toHaveAttribute("aria-expanded", "true");+ await waitFor(() =>+ expect(screen.getByText("Section content")).toBeVisible(),+ );+ });});diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsxindex ada16974905..a84a97da4ab 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx@@ -5,11 +5,17 @@ import type {DeleteMappingModalValueType,GroupIds,} from "metabase/admin/types";+import { useSelector } from "metabase/redux";+import { getApplicationName } from "metabase/selectors/whitelabel";import { Box, Button, Group, Modal, Radio, Stack, Text } from "metabase/ui";export type DeleteGroupMappingModalProps = {name: string;groupIds: GroupIds;+ // the Administrators group is never cleared or deleted, so the copy says so when it is mapped+ hasAdminGroup?: boolean;+ // an extra consequence the caller wants spelled out, shown under the lead text+ note?: string;onConfirm: (value: DeleteMappingModalValueType,groupIds: GroupIds,@@ -21,10 +27,16 @@ export type DeleteGroupMappingModalProps = {export const DeleteGroupMappingModal = ({name,groupIds,+ hasAdminGroup = false,+ note,onConfirm,onHide,}: DeleteGroupMappingModalProps) => {const [value, setValue] = useState<DeleteMappingModalValueType>("nothing");+ const applicationName = useSelector(getApplicationName);+ const isPlural = groupIds.length > 1;+ // with only the Administrators group, or no group at all, there is nothing a cascade could touch+ const canCascade = groupIds.length > (hasAdminGroup ? 1 : 0);const handleChange = (newValue: DeleteMappingModalValueType) => {setValue(newValue);@@ -37,56 +49,77 @@ export const DeleteGroupMappingModal = ({const submitButtonLabels: Record<DeleteMappingModalValueType, string> = {nothing: t`Remove mapping`,clear: t`Remove mapping and members`,- delete:- groupIds.length > 1- ? t`Remove mapping and delete groups`- : t`Remove mapping and delete group`,+ delete: isPlural+ ? t`Remove mapping and delete groups`+ : t`Remove mapping and delete group`,};- const subtitle =- groupIds.length > 1- ? t`These groups' user memberships will no longer be synced with the directory server.`- : t`This group's user membership will no longer be synced with the directory server.`;+ const adminNote = hasAdminGroup+ ? t`The Administrators group is not affected.`+ : null;- const whatShouldHappenText =- groupIds.length > 1- ? t`What should happen with the groups themselves in Metabase?`- : t`What should happen with the group itself in Metabase?`;+ let lead: string;+ if (groupIds.length === 0) {+ lead = t`This mapping isn't linked to any group.`;+ } else if (isPlural) {+ lead = t`Membership of these groups will no longer be synced when users log in.`;+ } else {+ lead = t`Membership of this group will no longer be synced when users log in.`;+ }return (<Modal opened onClose={onHide} title={t`Remove this group mapping?`}><Stack gap="xl" mt="sm">- <Text>{subtitle}</Text>+ <Text>{lead}</Text>+ {note && <Text>{note}</Text>}+ {!canCascade && adminNote && <Text>{adminNote}</Text>}- <Box>- <Text mb="lg">{whatShouldHappenText}</Text>- <Radio.Group- value={value}- onChange={(newValue) =>- // Unjustified type cast. FIXME- handleChange(newValue as DeleteMappingModalValueType)- }- >- <Stack gap="sm">- <Radio- value="nothing"- label={t`Nothing, just remove the mapping`}- />- <Radio- value="clear"- label={t`Also remove all group members (except from Admin)`}- />- <Radio- value="delete"- label={- groupIds.length > 1- ? t`Also delete the groups (except Admin)`- : t`Also delete the group`- }- />- </Stack>- </Radio.Group>- </Box>+ {canCascade && (+ <Box>+ <Text mb="lg">+ {isPlural+ ? t`What should happen with the groups themselves in ${applicationName}?`+ : t`What should happen with the group itself in ${applicationName}?`}+ </Text>+ <Radio.Group+ value={value}+ onChange={(newValue) =>+ // Unjustified type cast. FIXME+ handleChange(newValue as DeleteMappingModalValueType)+ }+ >+ <Stack gap="sm">+ <Radio+ value="nothing"+ label={t`Nothing, just remove the mapping`}+ />+ <Radio+ value="clear"+ label={+ isPlural+ ? t`Also remove all members from these groups`+ : t`Also remove all members from this group`+ }+ description={+ <>+ {t`Members keep their ${applicationName} accounts.`}{" "}+ {adminNote}+ </>+ }+ />+ <Radio+ value="delete"+ label={+ isPlural+ ? t`Also delete the groups`+ : t`Also delete the group`+ }+ description={adminNote}+ />+ </Stack>+ </Radio.Group>+ </Box>+ )}<Group justify="flex-end"><Button onClick={onHide}>{t`Cancel`}</Button>diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsxindex 666dec8cfeb..7e382299094 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx@@ -1,6 +1,6 @@import userEvent from "@testing-library/user-event";-import { render, screen } from "__support__/ui";+import { renderWithProviders, screen } from "__support__/ui";import {DeleteGroupMappingModal,@@ -17,7 +17,9 @@ const DEFAULT_PROPS = {};const setup = (props?: SetupOpts) => {- render(<DeleteGroupMappingModal {...DEFAULT_PROPS} {...props} />);+ renderWithProviders(+ <DeleteGroupMappingModal {...DEFAULT_PROPS} {...props} />,+ );};describe("DeleteGroupMappingModal", () => {@@ -28,30 +30,70 @@ describe("DeleteGroupMappingModal", () => {it("shows options for when mapping is linked to just one group", () => {setup();+ expect(+ screen.getByText(+ "Membership of this group will no longer be synced when users log in.",+ ),+ ).toBeInTheDocument();expect(screen.getByText("Nothing, just remove the mapping"),).toBeInTheDocument();-expect(- screen.getByText("Also remove all group members (except from Admin)"),+ screen.getByText("Also remove all members from this group"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("Members keep their Metabase accounts."),).toBeInTheDocument();-expect(screen.getByText("Also delete the group")).toBeInTheDocument();+ expect(screen.queryByText(/Administrators group/)).not.toBeInTheDocument();});it("shows options for when mapping is linked to more than one group", () => {setup({ groupIds: [1, 2] });+ expect(+ screen.getByText(+ "Membership of these groups will no longer be synced when users log in.",+ ),+ ).toBeInTheDocument();expect(screen.getByText("Nothing, just remove the mapping"),).toBeInTheDocument();+ expect(+ screen.getByText("Also remove all members from these groups"),+ ).toBeInTheDocument();+ expect(screen.getByText("Also delete the groups")).toBeInTheDocument();+ });+ it("notes that the Administrators group is left alone when it is mapped", () => {+ setup({ groupIds: [1, 2], hasAdminGroup: true });++ expect(+ screen.getAllByText(/The Administrators group is not affected/),+ ).toHaveLength(2);+ });++ it("offers no group options when only the Administrators group is mapped", () => {+ setup({ groupIds: [1], hasAdminGroup: true });++ expect(+ screen.getByText("The Administrators group is not affected."),+ ).toBeInTheDocument();+ expect(screen.queryByRole("radio")).not.toBeInTheDocument();expect(- screen.getByText("Also remove all group members (except from Admin)"),+ screen.getByRole("button", { name: "Remove mapping" }),).toBeInTheDocument();+ });++ it("offers no group options when no group is mapped", () => {+ setup({ groupIds: [] });expect(- screen.getByText("Also delete the groups (except Admin)"),+ screen.getByText("This mapping isn't linked to any group."),+ ).toBeInTheDocument();+ expect(screen.queryByRole("radio")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Remove mapping" }),).toBeInTheDocument();});@@ -67,9 +109,7 @@ describe("DeleteGroupMappingModal", () => {setup();await userEvent.click(- screen.getByLabelText(- "Also remove all group members (except from Admin)",- ),+ screen.getByLabelText("Also remove all members from this group"),);await userEvent.click(diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsxindex a3b56171d48..774dafc8e61 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx@@ -62,20 +62,7 @@ const setup = ({describe("GroupMappingsWidgetView", () => {describe("tooltip text", () => {- it("shows JWT-specific tooltip text when mappingSetting is jwt-group-mappings", async () => {- setup({ mappingSetting: "jwt-group-mappings" });-- const aboutMappingsElement = await screen.findByText("About mappings");- await userEvent.hover(aboutMappingsElement);-- expect(- await screen.findByText(- /If no mappings are defined, groups will automatically be assigned based on exactly matching names/,- ),- ).toBeInTheDocument();- });-- it("shows default tooltip text when mappingSetting is not jwt-group-mappings", async () => {+ it("shows the tooltip text", async () => {setup({ mappingSetting: "ldap-group-mappings" });const aboutMappingsElement = await screen.findByText("About mappings");@@ -90,25 +77,10 @@ describe("GroupMappingsWidgetView", () => {});describe("no mappings message", () => {- it("shows JWT-specific message when mappingSetting is jwt-group-mappings and sync is enabled", async () => {- setup({- mappingSetting: "jwt-group-mappings",- mappings: {},- setting: { key: "jwt-group-sync", value: true },- });-- expect(- await screen.findByText(- "No mappings yet, groups will be automatically assigned by exactly matching names",- ),- ).toBeInTheDocument();- });-- it("shows default message when mappingSetting is jwt-group-mappings but sync is disabled", async () => {+ it("shows the sync-off message when group sync is disabled", async () => {setup({- mappingSetting: "jwt-group-mappings",mappings: {},- setting: { key: "jwt-group-sync", value: false },+ setting: { key: "ldap-group-sync", value: false },});expect(@@ -116,11 +88,8 @@ describe("GroupMappingsWidgetView", () => {).toBeInTheDocument();});- it("shows default message when mappingSetting is not jwt-group-mappings", async () => {- setup({- mappingSetting: "ldap-group-mappings",- mappings: {},- });+ it("shows the no mappings message", async () => {+ setup({ mappings: {} });expect(await screen.findByText("No mappings yet")).toBeInTheDocument();});@@ -246,9 +215,7 @@ describe("GroupMappingsWidgetView", () => {// Click on button to delete mappingawait userEvent.click(await screen.findByLabelText("close icon"));- await userEvent.click(- screen.getByLabelText(/Also remove all group members/i),- );+ await userEvent.click(screen.getByLabelText(/Also remove all members/i));await userEvent.click(await screen.findByRole("button", {name: "Remove mapping and members",diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsxindex 153860870e8..5b713c60a50 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx@@ -32,23 +32,15 @@ const groupIsMappable = (group: GroupInfo) => !isDefaultGroup(group);export type MappingSettingKey =| "ldap-group-mappings"| "saml-group-mappings"- | "jwt-group-mappings"| "oidc-group-mappings";-const helpText = (mappingSetting: string) => {- if (mappingSetting === "jwt-group-mappings") {- return t`Mappings allow Metabase to automatically add and remove users from groups based on the membership information provided by the directory server. If no mappings are defined, groups will automatically be assigned based on exactly matching names.`;- }- return t`Mappings allow Metabase to automatically add and remove users from groups based on the membership information provided by the directory server. If a group isn‘t mapped, its membership won‘t be synced.`;-};+const helpText = () =>+ t`Mappings allow Metabase to automatically add and remove users from groups based on the membership information provided by the directory server. If a group isn‘t mapped, its membership won‘t be synced.`;-const noMappingText = (mappingSetting: string, syncSwitchValue: boolean) => {+const noMappingText = (syncSwitchValue: boolean) => {if (!syncSwitchValue) {return t`No mappings yet, group sync is not on`;}- if (mappingSetting === "jwt-group-mappings") {- return t`No mappings yet, groups will be automatically assigned by exactly matching names`;- }return t`No mappings yet`;};@@ -189,7 +181,7 @@ export function GroupMappingsWidgetView({{t`New mapping`}</Button>)}- <Tooltip label={helpText(mappingSetting)} position="top" maw="20rem">+ <Tooltip label={helpText()} position="top" maw="20rem"><Flex align="center" gap="sm" c="text-secondary" ml="auto"><Icon name="info" /><span>{t`About mappings`}</span>@@ -230,7 +222,7 @@ export function GroupMappingsWidgetView({<Box pb="lg"><EmptyStateillustrationElement={<img src={NoResults} alt="" />}- message={noMappingText(mappingSetting, groupSyncSwitchValue)}+ message={noMappingText(groupSyncSwitchValue)}spacing="sm"/></Box>diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsxindex 0f1b1c21621..cafeb640055 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx@@ -126,6 +126,10 @@ export const MappingRow = ({selectedGroupIdsFromGroupsThatExist.length > 0 &&!isMappingLinkedOnlyToAdminGroup;+ const hasAdminGroup = groups.some(+ (group) => isAdminGroup(group) && selectedGroupIds.includes(group.id),+ );+return (<><tr>@@ -162,6 +166,7 @@ export const MappingRow = ({<DeleteGroupMappingModalname={name}groupIds={selectedGroupIds}+ hasAdminGroup={hasAdminGroup}onHide={closeDeleteGroupMappingModal}onConfirm={handleConfirmDeleteMapping}/>