Skip to content

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

Redesign the LDAP settings page and its group mapping card (#82389)

Andrei Chernykh01f2c4b62408
diff --git a/e2e/test/scenarios/admin-2/sso/ldap.cy.spec.js b/e2e/test/scenarios/admin-2/sso/ldap.cy.spec.js
index d1d8332ce7e..e4860e672d5 100644
--- a/e2e/test/scenarios/admin-2/sso/ldap.cy.spec.js
+++ b/e2e/test/scenarios/admin-2/sso/ldap.cy.spec.js
@@ -1,10 +1,5 @@
const { H } = cy;
-import {
- checkGroupConsistencyAfterDeletingMappings,
- crudGroupMappingsWidget,
-} from "./shared/group-mappings-widget";
-
describe(
"scenarios > admin > settings > SSO > LDAP",
{ tags: "@external" },
@@ -12,7 +7,7 @@ describe(
beforeEach(() => {
H.restore();
cy.signInAsAdmin();
- cy.intercept("PUT", "/api/setting").as("updateSettings");
+ cy.intercept("PUT", /\/api\/setting$/).as("updateSettings");
cy.intercept("PUT", "/api/setting/*").as("updateSetting");
cy.intercept("PUT", "/api/ldap/settings").as("updateLdapSettings");
cy.intercept("POST", "/api/dataset").as("dataset");
@@ -144,24 +139,83 @@ describe(
});
});
- describe("Group Mappings Widget", () => {
+ describe("Group mapping", () => {
beforeEach(() => {
- cy.intercept("GET", "/api/setting").as("getSettings");
- cy.intercept("GET", "/api/session/properties").as(
- "getSessionProperties",
- );
cy.intercept("DELETE", "/api/permissions/group/*").as("deleteGroup");
cy.intercept("PUT", "/api/permissions/membership/*/clear").as(
"clearGroup",
);
+ H.setupLdap();
+ cy.visit("/admin/settings/authentication/ldap");
});
- it("should allow deleting mappings along with deleting, or clearing users of, mapped groups", () => {
- crudGroupMappingsWidget("ldap");
- });
+ it("should delete or clear mapped groups with their mappings and keep the remaining mappings consistent", () => {
+ turnGroupMappingOn();
+ addMapping("cn=People1", ["Administrators", "data", "nosql"]);
+ addMapping("cn=People2", ["data", "collection"]);
+ addMapping("cn=People3", ["collection", "readonly"]);
- it("should allow deleting mappings with groups, while keeping remaining mappings consistent with their undeleted groups", () => {
- checkGroupConsistencyAfterDeletingMappings("ldap");
+ 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("Deleted groups are no longer offered for new mappings");
+ newMappingButton().click();
+ groupsPicker().click();
+ cy.findByRole("listbox")
+ .should("contain", "readonly")
+ .and("not.contain", "data")
+ .and("not.contain", "collection");
+ cy.button("Cancel").click();
+
+ cy.log("The same mappings come back after a reload");
+ cy.reload();
+ mappingRow("cn=People1").should("contain", "Administrators, nosql");
+ mappingRow("cn=People3")
+ .should("contain", "readonly")
+ .and("not.contain", "collection");
+
+ cy.log(
+ "Clearing the last mappings empties their groups, skips Administrators and keeps group mapping on",
+ );
+ deleteMapping(
+ "cn=People3",
+ /remove all members/i,
+ "Remove mapping and members",
+ );
+ cy.wait("@clearGroup");
+ deleteMapping(
+ "cn=People1",
+ /remove all members/i,
+ "Remove mapping and members",
+ );
+ cy.wait("@clearGroup");
+ groupMappingSwitch().should("be.checked");
+ groupMappingSection()
+ .findByText("No mappings yet")
+ .should("be.visible");
+
+ 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(["nosql", "readonly"]);
+ expect(names).not.to.include("data");
+ expect(names).not.to.include("collection");
+ const memberCount = (name) =>
+ groups.find((group) => group.name === name).member_count;
+ expect(memberCount("nosql")).to.equal(0);
+ expect(memberCount("readonly")).to.equal(0);
+ });
});
});
},
@@ -182,9 +236,10 @@ describe(
H.setupLdap();
cy.visit("/admin/settings/authentication/ldap");
- cy.findByRole("switch", { name: "User provisioning" })
- .should("be.checked")
- .click({ force: true });
+ cy.findByRole("switch", { name: "User provisioning" }).should(
+ "be.checked",
+ );
+ cy.contains("label", "User provisioning").click();
H.undoToast().findByText("Changes saved").should("be.visible");
cy.findByRole("switch", { name: "User provisioning" }).should(
@@ -250,6 +305,54 @@ const getLdapCard = () => {
.parent();
};
+const groupMappingSection = () => cy.findByTestId("ldap-group-mapping-section");
+
+const groupMappingSwitch = () =>
+ cy.findByRole("switch", { name: "Group mapping" });
+
+const mappingRow = (name) =>
+ cy.contains('[data-testid="group-mapping-row"]', name);
+
+const newMappingButton = () =>
+ groupMappingSection().findByRole("button", { name: "New" });
+
+const groupsPicker = () => cy.findByLabelText("Metabase groups");
+
+// Mantine hides the switch input, so the click goes to the title label wired to it
+const clickGroupMappingSwitch = () =>
+ groupMappingSection().contains("label", "Group mapping").click();
+
+const turnGroupMappingOn = () => {
+ groupMappingSwitch().should("not.be.checked");
+ clickGroupMappingSwitch();
+ cy.wait("@updateSetting")
+ .its("request.body")
+ .should("deep.equal", { value: true });
+};
+
+const addMapping = (name, groups) => {
+ newMappingButton().click();
+ cy.findByLabelText("LDAP 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.findByRole("radio", { name: consequenceLabel }).click();
+ cy.button(confirmLabel).click();
+ });
+ cy.wait("@updateSettings");
+ mappingRow(name).should("not.exist");
+};
+
const enterLdapPort = (value) => {
H.typeAndBlurUsingLabel(/LDAP Port/i, value);
};
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/Ldap.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/Ldap.tsx
index 21e5d113899..cff1fdb7c15 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/Ldap.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/Ldap.tsx
@@ -1,15 +1,20 @@
import { t } from "ttag";
-import { getExtraFormFieldProps } from "metabase/admin/settings/utils";
+import {
+ getDefaultPlaceholder,
+ getExtraFormFieldProps,
+} from "metabase/admin/settings/utils";
import { FormTextInput } from "metabase/forms";
+import type { LdapUserProvisioningProps } from "metabase/plugins";
import { useAdminSetting } from "metabase/settings";
import { UserProvisioningSection } from "metabase-enterprise/auth/components/UserProvisioningSection";
-export function LdapUserProvisioning() {
+export function LdapUserProvisioning({ disabled }: LdapUserProvisioningProps) {
return (
<UserProvisioningSection
settingKey="ldap-user-provisioning-enabled?"
providerName="LDAP"
+ disabled={disabled}
/>
);
}
@@ -21,6 +26,7 @@ export function LdapGroupMembershipFilter() {
<FormTextInput
name="ldap-group-membership-filter"
label={t`Group membership filter`}
+ placeholder={getDefaultPlaceholder(settingDetails)}
nullable
{...getExtraFormFieldProps(settingDetails)}
/>
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.tsx
index 4eb0f0168c3..5b1b7e601e2 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.tsx
@@ -1,8 +1,11 @@
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { t } from "ttag";
+import {
+ useGroupLookup,
+ withMappingEntry,
+} from "metabase/admin/settings/auth/components/GroupMappings";
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";
@@ -11,14 +14,12 @@ 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";
+ useGroupMappingMode,
+} from "./use-group-mapping-mode";
+import { useGroupMappingSettings } from "./use-group-mapping-settings";
+import { useMappingDeletion } from "./use-mapping-deletion";
export function JWTGroupMappingSection({
isServerConfigured,
@@ -30,8 +31,7 @@ export function JWTGroupMappingSection({
lockedEnvNames?: string[];
}) {
const applicationName = useSelector(getApplicationName);
- const { data: groups = [] } = useListPermissionsGroupsQuery({});
- const groupLookup = useMemo(() => createGroupLookup(groups), [groups]);
+ const groupLookup = useGroupLookup();
const groupMapping = useGroupMappingSettings();
const deletion = useMappingDeletion({ groupMapping, groupLookup });
const modeSwitch = useGroupMappingMode(groupMapping);
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.tsx
index e22e42ade21..f34f31fbb62 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingRow.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingRow.tsx
@@ -1,11 +1,11 @@
import { t } from "ttag";
+import type { GroupLookup } from "metabase/admin/settings/auth/components/GroupMappings";
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,
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.ts
index 3b0f3490608..58e3feb022d 100644
--- 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.ts
@@ -2,7 +2,8 @@ import { useEffect, useState } from "react";
import { t } from "ttag";
import type { GroupMappingSettingsState } from "./use-group-mapping-settings";
-import type { JWTGroupSyncMode } from "./utils";
+
+export type JWTGroupSyncMode = "automatic" | "manual" | "off";
type GroupMappingModeState = {
mode: JWTGroupSyncMode;
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.ts
index 83684990650..a29fda35e85 100644
--- 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.ts
@@ -1,6 +1,10 @@
import { useState } from "react";
import { t } from "ttag";
+import {
+ type GroupLookup,
+ withoutMapping,
+} from "metabase/admin/settings/auth/components/GroupMappings";
import type {
DeleteMappingModalValueType,
GroupIds,
@@ -15,7 +19,6 @@ import type {
GroupMappingSettings,
GroupMappingSettingsState,
} from "./use-group-mapping-settings";
-import { type GroupLookup, withoutMapping } from "./utils";
type MappingCascade = {
value: Exclude<DeleteMappingModalValueType, "nothing">;
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index 528b38bb0f2..ab5d683f9ea 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -619,7 +619,7 @@ interface PublicSettings {
"ldap-group-sync": boolean;
"ldap-group-base": string | null;
"ldap-group-mappings": Record<string /*ldap group name */, GroupId[]> | null;
- "ldap-group-membership-filter"?: string;
+ "ldap-group-membership-filter"?: string | null;
"ldap-user-provisioning-enabled?": boolean;
"oidc-user-provisioning-enabled?": boolean;
"loading-message": LoadingMessage;
diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingList.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingList.tsx
new file mode 100644
index 00000000000..2c830d539bf
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingList.tsx
@@ -0,0 +1,100 @@
+import { t } from "ttag";
+
+import { DeleteGroupMappingModal } from "metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal";
+import { getGroupNameLocalized } from "metabase/common/utils/groups";
+import { Stack, Text } from "metabase/ui";
+
+import { MappingEditorRow } from "./MappingEditorRow";
+import { MappingRow } from "./MappingRow";
+import type { GroupMappingsState } from "./use-group-mappings";
+import type { MappingDeletionState } from "./use-mapping-deletion";
+import type { MappingEditorState } from "./use-mapping-editor";
+import type { GroupLookup } from "./utils";
+
+/** The mapping rows with the inline editor and the delete confirmation, driven by the caller's hooks */
+export function GroupMappingList({
+ groupMapping,
+ groupLookup,
+ editor,
+ deletion,
+ readOnly,
+ disabled,
+ nameLabel,
+ namePlaceholder,
+ emptyMessage,
+}: {
+ groupMapping: GroupMappingsState;
+ groupLookup: GroupLookup;
+ editor: MappingEditorState;
+ deletion: MappingDeletionState;
+ readOnly: boolean;
+ disabled: boolean;
+ nameLabel: string;
+ namePlaceholder: string;
+ emptyMessage: string;
+}) {
+ const { draft } = editor;
+ const hasMappings = Object.keys(groupMapping.mappings).length > 0;
+ const groupOptions = groupLookup.mappableGroups.map((group) => ({
+ value: String(group.id),
+ label: getGroupNameLocalized(group),
+ }));
+ const editorRowProps = {
+ groupOptions,
+ nameLabel,
+ namePlaceholder,
+ canSubmit: editor.canSave,
+ nameError: editor.nameError,
+ isSubmitting: disabled,
+ onChange: editor.change,
+ onCancel: editor.cancel,
+ onSubmit: editor.save,
+ };
+
+ return (
+ <>
+ <Stack gap="sm">
+ {!hasMappings && draft == null && !readOnly && (
+ <Text c="text-secondary">{emptyMessage}</Text>
+ )}
+ {Object.entries(groupMapping.mappings).map(([name, groupIds]) =>
+ draft?.originalName === name ? (
+ <MappingEditorRow
+ key={name}
+ draft={draft}
+ submitLabel={t`Save`}
+ {...editorRowProps}
+ />
+ ) : (
+ <MappingRow
+ key={name}
+ name={name}
+ groupIds={groupIds}
+ groupLookup={groupLookup}
+ readOnly={readOnly}
+ disabled={disabled}
+ onEdit={() => editor.startEdit(name, groupIds)}
+ onDelete={() => deletion.requestDelete(name)}
+ />
+ ),
+ )}
+ {draft != null && draft.originalName == null && (
+ <MappingEditorRow
+ draft={draft}
+ submitLabel={t`Add mapping`}
+ {...editorRowProps}
+ />
+ )}
+ </Stack>
+ {deletion.target != null && (
+ <DeleteGroupMappingModal
+ name={deletion.target}
+ groupIds={deletion.targetGroupIds}
+ hasAdminGroup={groupLookup.hasAdminGroup(deletion.targetGroupIds)}
+ onConfirm={deletion.confirmDelete}
+ onHide={deletion.cancelDelete}
+ />
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappings.module.css b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappings.module.css
new file mode 100644
index 00000000000..2e922971670
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappings.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/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingEditorRow.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingEditorRow.tsx
new file mode 100644
index 00000000000..a9e37fe5636
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingEditorRow.tsx
@@ -0,0 +1,138 @@
+import { useId } from "react";
+import { t } from "ttag";
+
+import { useSelector } from "metabase/redux";
+import { getApplicationName } from "metabase/selectors/whitelabel";
+import {
+ Box,
+ Button,
+ FixedSizeIcon,
+ Flex,
+ MultiSelect,
+ Stack,
+ Text,
+ TextInput,
+} from "metabase/ui";
+
+import S from "./GroupMappings.module.css";
+import type { MappingDraft } from "./use-mapping-editor";
+
+export function MappingEditorRow({
+ draft,
+ groupOptions,
+ nameLabel,
+ namePlaceholder,
+ submitLabel,
+ canSubmit,
+ nameError,
+ isSubmitting,
+ onChange,
+ onCancel,
+ onSubmit,
+}: {
+ draft: MappingDraft;
+ groupOptions: { value: string; label: string }[];
+ nameLabel: string;
+ namePlaceholder: string;
+ submitLabel: string;
+ canSubmit: boolean;
+ nameError: string | null;
+ isSubmitting: boolean;
+ onChange: (draft: MappingDraft) => void;
+ onCancel: () => void;
+ onSubmit: () => void;
+}) {
+ const applicationName = useSelector(getApplicationName);
+ const errorId = useId();
+
+ // 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 (
+ <Box
+ className={S.editorRow}
+ bd="1px solid var(--mb-color-border-neutral)"
+ bdrs="sm"
+ p="sm"
+ >
+ {/* the fields and their reason form one column, so the buttons follow the reason when they wrap */}
+ <Flex align="flex-start" gap="lg" wrap="wrap">
+ <Stack flex={1} gap="xs">
+ <Flex align="center" gap="lg" wrap="wrap">
+ <TextInput
+ flex={1}
+ miw="10rem"
+ aria-label={nameLabel}
+ // Mantine owns aria-describedby on its inputs, so the reason is linked as the error message instead
+ aria-errormessage={nameError == null ? undefined : errorId}
+ placeholder={namePlaceholder}
+ value={draft.name}
+ error={nameError != null}
+ onChange={(event) =>
+ onChange({ ...draft, name: event.target.value })
+ }
+ onKeyDown={handleNameKeyDown}
+ autoFocus
+ />
+ <FixedSizeIcon
+ aria-hidden
+ name="arrow_right"
+ c="text-secondary"
+ className={S.editorArrow}
+ />
+ <MultiSelect
+ flex={1}
+ miw="14rem"
+ classNames={{ inputField: S.groupsSearchField }}
+ aria-label={t`${applicationName} groups`}
+ placeholder={
+ draft.groupValues.length === 0
+ ? t`Pick ${applicationName} group...`
+ : undefined
+ }
+ data={groupOptions}
+ value={draft.groupValues}
+ onChange={(groupValues) => onChange({ ...draft, groupValues })}
+ onKeyDown={handleGroupsKeyDown}
+ searchable
+ />
+ </Flex>
+ {nameError != null && (
+ <Text id={errorId} role="alert" c="error" fz="sm">
+ {nameError}
+ </Text>
+ )}
+ </Stack>
+ <Flex align="center" gap="lg">
+ <Button variant="subtle" onClick={onCancel}>{t`Cancel`}</Button>
+ <Button
+ variant="filled"
+ disabled={!canSubmit}
+ loading={isSubmitting}
+ onClick={onSubmit}
+ >
+ {submitLabel}
+ </Button>
+ </Flex>
+ </Flex>
+ </Box>
+ );
+}
diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingRow.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingRow.tsx
new file mode 100644
index 00000000000..6d51a0f08a3
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingRow.tsx
@@ -0,0 +1,90 @@
+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 "./GroupMappings.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="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>
+ );
+ }
+ return (
+ <Text flex="1 1 auto" miw={0} className={S.wrappableText}>
+ {names.join(", ")}
+ </Text>
+ );
+}
diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/index.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/index.ts
new file mode 100644
index 00000000000..260b1326e12
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/index.ts
@@ -0,0 +1,6 @@
+export { GroupMappingList } from "./GroupMappingList";
+export { useGroupLookup } from "./use-group-lookup";
+export { useGroupMappings } from "./use-group-mappings";
+export { useMappingDeletion } from "./use-mapping-deletion";
+export { useMappingEditor } from "./use-mapping-editor";
+export { type GroupLookup, withMappingEntry, withoutMapping } from "./utils";
diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-group-lookup.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-group-lookup.ts
new file mode 100644
index 00000000000..70b69f24524
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-group-lookup.ts
@@ -0,0 +1,22 @@
+import { useMemo } from "react";
+
+import { useListPermissionsGroupsQuery } from "metabase/api";
+import type { GroupListQuery } from "metabase-types/api";
+
+import { type GroupLookup, createGroupLookup } from "./utils";
+
+const EMPTY_GROUPS: GroupListQuery[] = [];
+
+type UseGroupLookupOptions = {
+ // "internal" leaves tenant groups out, for providers whose users are never tenants
+ tenancy?: "internal" | "external";
+};
+
+export function useGroupLookup({
+ tenancy,
+}: UseGroupLookupOptions = {}): GroupLookup {
+ const { data: groups = EMPTY_GROUPS } = useListPermissionsGroupsQuery(
+ tenancy == null ? {} : { tenancy },
+ );
+ return useMemo(() => createGroupLookup(groups), [groups]);
+}
diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-group-mappings.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-group-mappings.ts
new file mode 100644
index 00000000000..fbf46ca3a9f
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-group-mappings.ts
@@ -0,0 +1,83 @@
+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";
+
+export type GroupMappingsSettingKey =
+ | "jwt-group-mappings"
+ | "ldap-group-mappings"
+ | "saml-group-mappings";
+
+export type GroupMappingsSaveResult =
+ | { ok: true }
+ | { ok: false; error: string };
+
+type SaveOptions = {
+ successMessage?: string;
+ showErrorToast?: boolean;
+};
+
+export type GroupMappingsState = {
+ mappings: MappingsType;
+ isSaving: boolean;
+ saveMappings: (
+ mappings: MappingsType,
+ options?: SaveOptions,
+ ) => Promise<GroupMappingsSaveResult>;
+};
+
+const EMPTY_MAPPINGS: MappingsType = {};
+
+export function useGroupMappings({
+ settingKey,
+}: {
+ settingKey: GroupMappingsSettingKey;
+}): GroupMappingsState {
+ const dispatch = useDispatch();
+ const [sendToast] = useToast();
+ const [updateSettings, { isLoading: isSaving }] = useUpdateSettingsMutation();
+ const mappings = useSetting(settingKey) ?? EMPTY_MAPPINGS;
+
+ const saveMappings = async (
+ nextMappings: MappingsType,
+ { successMessage, showErrorToast = true }: SaveOptions = {},
+ ): Promise<GroupMappingsSaveResult> => {
+ const response = await updateSettings({ [settingKey]: nextMappings });
+ if (response.error) {
+ const error = getErrorMessage(
+ response.error,
+ t`Error saving group mapping`,
+ );
+ if (showErrorToast) {
+ sendToast({
+ message: error,
+ icon: "warning",
+ toastColor: "feedback-negative",
+ });
+ }
+ return { ok: false, error };
+ }
+ dispatch(
+ settingsApi.util.updateQueryData(
+ "getSessionProperties",
+ undefined,
+ (draft) => {
+ draft[settingKey] = nextMappings;
+ },
+ ),
+ );
+ if (successMessage != null) {
+ sendToast({ message: successMessage, icon: "check_filled" });
+ }
+ return { ok: true };
+ };
+
+ return { mappings, isSaving, saveMappings };
+}
diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-mapping-deletion.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-mapping-deletion.ts
new file mode 100644
index 00000000000..3cd391058ab
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-mapping-deletion.ts
@@ -0,0 +1,122 @@
+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 { GroupMappingsState } from "./use-group-mappings";
+import { type GroupLookup, withoutMapping } from "./utils";
+
+type MappingCascade = {
+ value: Exclude<DeleteMappingModalValueType, "nothing">;
+ groupIds: GroupIds;
+};
+
+export type MappingDeletionState = {
+ target: string | null;
+ targetGroupIds: GroupIds;
+ isDeleting: boolean;
+ requestDelete: (name: string) => void;
+ cancelDelete: () => void;
+ confirmDelete: (
+ value: DeleteMappingModalValueType,
+ groupIds: GroupIds,
+ name: string,
+ ) => Promise<void>;
+};
+
+export function useMappingDeletion({
+ groupMapping,
+ groupLookup,
+}: {
+ groupMapping: GroupMappingsState;
+ 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] ?? []);
+
+ // "nothing, just remove the mapping" arrives as null and touches no group
+ const runCascade = async (cascade: MappingCascade | null) => {
+ if (cascade == null) {
+ return { failureCount: 0 };
+ }
+ 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 result = await groupMapping.saveMappings(nextMappings);
+ if (!result.ok) {
+ 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: 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,
+ isDeleting,
+ requestDelete: setTarget,
+ cancelDelete: () => setTarget(null),
+ confirmDelete,
+ };
+}
diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-mapping-editor.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-mapping-editor.ts
new file mode 100644
index 00000000000..80631d9ad43
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/use-mapping-editor.ts
@@ -0,0 +1,100 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import type { GroupId } from "metabase-types/api";
+
+import type { GroupMappingsState } from "./use-group-mappings";
+import { type GroupLookup, withMappingEntry } from "./utils";
+
+export type MappingDraft = {
+ name: string;
+ // MultiSelect values, so group ids as strings
+ groupValues: string[];
+ originalName: string | null;
+};
+
+export type MappingEditorState = {
+ draft: MappingDraft | null;
+ nameError: string | null;
+ canSave: boolean;
+ startNew: () => void;
+ startEdit: (name: string, groupIds: GroupId[]) => void;
+ change: (draft: MappingDraft) => void;
+ cancel: () => void;
+ save: () => Promise<void>;
+};
+
+/** Holds the mapping being added or edited and writes it into the mappings setting */
+export function useMappingEditor({
+ groupMapping,
+ groupLookup,
+}: {
+ groupMapping: GroupMappingsState;
+ groupLookup: GroupLookup;
+}): MappingEditorState {
+ const [draft, setDraft] = useState<MappingDraft | null>(null);
+ const [submitError, setSubmitError] = useState<string | null>(null);
+
+ const trimmedName = draft?.name.trim() ?? "";
+ const isDuplicateName =
+ draft != null &&
+ Object.hasOwn(groupMapping.mappings, trimmedName) &&
+ trimmedName !== draft.originalName;
+ const canSave =
+ draft != null &&
+ trimmedName !== "" &&
+ draft.groupValues.length > 0 &&
+ !isDuplicateName;
+ let nameError: string | null = null;
+ if (isDuplicateName) {
+ nameError = t`A mapping for this group already exists`;
+ } else if (submitError != null) {
+ nameError = submitError;
+ }
+
+ const replaceDraft = (nextDraft: MappingDraft | null) => {
+ setSubmitError(null);
+ setDraft(nextDraft);
+ };
+
+ const save = async () => {
+ if (draft == null || !canSave) {
+ return;
+ }
+ const isNewMapping = draft.originalName == null;
+ const result = await groupMapping.saveMappings(
+ withMappingEntry(
+ groupMapping.mappings,
+ draft.originalName,
+ trimmedName,
+ draft.groupValues.map(Number),
+ ),
+ {
+ successMessage: isNewMapping ? t`Mapping added` : t`Mapping updated`,
+ showErrorToast: false,
+ },
+ );
+ if (result.ok) {
+ replaceDraft(null);
+ } else {
+ setSubmitError(result.error);
+ }
+ };
+
+ return {
+ draft,
+ nameError,
+ canSave,
+ startNew: () =>
+ replaceDraft({ name: "", groupValues: [], originalName: null }),
+ startEdit: (name, groupIds) =>
+ replaceDraft({
+ name,
+ groupValues: groupLookup.existingIds(groupIds).map(String),
+ originalName: name,
+ }),
+ change: replaceDraft,
+ cancel: () => replaceDraft(null),
+ save,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.ts
similarity index 87%
rename from enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.ts
rename to frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.ts
index e65f7b4638c..d5f04bcad8c 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.ts
+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.ts
@@ -6,23 +6,19 @@ import {
} 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,
+ originalName: string | null,
+ name: string,
groupIds: GroupId[],
): MappingsType {
const entries = Object.entries(mappings).map(
([mappingName, ids]): [string, GroupId[]] =>
- mappingName === originalJwtGroupName
- ? [jwtGroupName, groupIds]
- : [mappingName, ids],
+ mappingName === originalName ? [name, groupIds] : [mappingName, ids],
);
- if (originalJwtGroupName == null) {
- entries.push([jwtGroupName, groupIds]);
+ if (originalName == null) {
+ entries.push([name, groupIds]);
}
// fromEntries defines own properties, so names like __proto__ stay plain keys
return Object.fromEntries(entries);
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.unit.spec.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.unit.spec.ts
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/utils.unit.spec.ts
rename to frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.unit.spec.ts
diff --git a/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.module.css b/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.module.css
new file mode 100644
index 00000000000..08c281b4f4e
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.module.css
@@ -0,0 +1,7 @@
+.titleLabel {
+ cursor: pointer;
+}
+
+.titleLabel.disabled {
+ cursor: default;
+}
diff --git a/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.tsx b/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.tsx
new file mode 100644
index 00000000000..b82b1cfc96b
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.tsx
@@ -0,0 +1,180 @@
+import cx from "classnames";
+import { useId } from "react";
+import { t } from "ttag";
+
+import {
+ GroupMappingList,
+ useGroupLookup,
+ useGroupMappings,
+ useMappingDeletion,
+ useMappingEditor,
+} from "metabase/admin/settings/auth/components/GroupMappings";
+import { useDispatch, useSelector } from "metabase/redux";
+import { getApplicationName } from "metabase/selectors/whitelabel";
+import { settingsApi, useAdminSetting } from "metabase/settings";
+import {
+ SETTINGS_CARD_DESCRIPTION_PROPS,
+ SETTINGS_CARD_STACK_PROPS,
+ SETTINGS_CARD_TITLE_PROPS,
+ SettingsSection,
+} from "metabase/settings-components";
+import {
+ Box,
+ type BoxProps,
+ Button,
+ Flex,
+ Icon,
+ Stack,
+ Switch,
+ Text,
+ Title,
+} from "metabase/ui";
+
+import S from "./LdapGroupMappingSection.module.css";
+
+// mapping names are group DNs, which the backend validates on write
+const LDAP_GROUP_DN_EXAMPLE = "cn=people,ou=groups,dc=example,dc=org";
+
+type LdapGroupMappingSectionProps = {
+ children: React.ReactNode;
+ disabled?: boolean;
+} & BoxProps;
+
+export function LdapGroupMappingSection({
+ children,
+ disabled = false,
+ ...boxProps
+}: LdapGroupMappingSectionProps) {
+ const inputId = useId();
+ const descriptionId = useId();
+ const dispatch = useDispatch();
+ const applicationName = useSelector(getApplicationName);
+ const {
+ value,
+ settingDetails,
+ updateSetting,
+ updateSettingResult,
+ isLoading,
+ } = useAdminSetting("ldap-group-sync");
+ const envName = settingDetails?.is_env_setting
+ ? settingDetails.env_name
+ : undefined;
+ // the env lock is only known once the settings list has loaded
+ const isDisabled =
+ disabled || envName != null || isLoading || updateSettingResult.isLoading;
+ const isChecked = value ?? false;
+
+ const handleChange = async (enabled: boolean) => {
+ const patch = dispatch(
+ settingsApi.util.updateQueryData(
+ "getSessionProperties",
+ undefined,
+ (draft) => {
+ draft["ldap-group-sync"] = enabled;
+ },
+ ),
+ );
+ const { error } = await updateSetting({
+ key: "ldap-group-sync",
+ value: enabled,
+ });
+ if (error) {
+ patch.undo();
+ }
+ };
+
+ // the card sits inside the page form, so Enter must not reach its submit button
+ const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ }
+ };
+
+ return (
+ <SettingsSection
+ stackProps={SETTINGS_CARD_STACK_PROPS}
+ disabled={disabled}
+ {...boxProps}
+ >
+ <Flex justify="space-between" align="flex-start" gap="lg">
+ <Box>
+ <Title {...SETTINGS_CARD_TITLE_PROPS}>
+ <Text
+ component="label"
+ htmlFor={inputId}
+ className={cx(S.titleLabel, isDisabled && S.disabled)}
+ inherit
+ >
+ {t`Group mapping`}
+ </Text>
+ </Title>
+ {/* the env line sits inside the description, so assistive tech hears why the switch is locked */}
+ <Box id={descriptionId}>
+ <Text c="text-secondary" {...SETTINGS_CARD_DESCRIPTION_PROPS}>
+ {t`Automatically assign people to ${applicationName} groups based on their LDAP group membership`}
+ </Text>
+ {envName != null && (
+ <Text c="text-secondary" mt="sm">{t`Using ${envName}`}</Text>
+ )}
+ </Box>
+ </Box>
+ <Switch
+ id={inputId}
+ aria-describedby={descriptionId}
+ checked={isChecked}
+ disabled={isDisabled}
+ onChange={(event) => handleChange(event.currentTarget.checked)}
+ onKeyDown={handleKeyDown}
+ />
+ </Flex>
+ {isChecked && !disabled && (
+ <Stack gap="lg">
+ <LdapGroupMappings />
+ {children}
+ </Stack>
+ )}
+ </SettingsSection>
+ );
+}
+
+function LdapGroupMappings() {
+ const { settingDetails } = useAdminSetting("ldap-group-mappings");
+ // LDAP users are never tenants, so tenant groups stay out of the picker
+ const groupLookup = useGroupLookup({ tenancy: "internal" });
+ const groupMapping = useGroupMappings({ settingKey: "ldap-group-mappings" });
+ const deletion = useMappingDeletion({ groupMapping, groupLookup });
+ const editor = useMappingEditor({ groupMapping, groupLookup });
+ const isBusy = groupMapping.isSaving || deletion.isDeleting;
+ const envName = settingDetails?.is_env_setting
+ ? settingDetails.env_name
+ : undefined;
+ const isLocked = envName != null;
+
+ return (
+ <Stack gap="sm">
+ <Flex justify="space-between" align="center" gap="lg">
+ <Text fw="bold">{t`Manual group mappings`}</Text>
+ {!isLocked && editor.draft == null && (
+ <Button
+ variant="subtle"
+ leftSection={<Icon name="add" aria-hidden />}
+ disabled={isBusy}
+ onClick={editor.startNew}
+ >{t`New`}</Button>
+ )}
+ </Flex>
+ {envName != null && <Text c="text-secondary">{t`Using ${envName}`}</Text>}
+ <GroupMappingList
+ groupMapping={groupMapping}
+ groupLookup={groupLookup}
+ editor={editor}
+ deletion={deletion}
+ readOnly={isLocked}
+ disabled={isBusy}
+ nameLabel={t`LDAP group name`}
+ namePlaceholder={LDAP_GROUP_DN_EXAMPLE}
+ emptyMessage={t`No mappings yet`}
+ />
+ </Stack>
+ );
+}
diff --git a/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/index.ts b/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/index.ts
new file mode 100644
index 00000000000..84cf8ccb734
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/index.ts
@@ -0,0 +1 @@
+export * from "./LdapGroupMappingSection";
diff --git a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.enterprise.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.enterprise.unit.spec.tsx
index 0d94acb0970..829874457b0 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.enterprise.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.enterprise.unit.spec.tsx
@@ -21,8 +21,7 @@ const setup = async (
settingValues?: Partial<EnterpriseSettings>,
{
settingDefinitions = [],
- detailsDelayMs,
- }: { settingDefinitions?: SettingDefinition[]; detailsDelayMs?: number } = {},
+ }: { settingDefinitions?: SettingDefinition[] } = {},
) => {
const settings = createMockSettings({
"token-features": createMockTokenFeatures({ sso_ldap: true }),
@@ -31,10 +30,8 @@ const setup = async (
// the auth plugin reads the token features from the global settings when it registers the LDAP cards
const settingsState = mockSettings(settings);
setupEnterpriseOnlyPlugin("auth");
- // the page renders before the admin list lands, so the list can be made to lag
fetchMock.get("path:/api/setting", settingDefinitions, {
name: "settings-list",
- delay: detailsDelayMs,
});
// the provisioning switch reads its value back after saving, so the properties mock has to remember writes
setupStatefulSettingsEndpoints(settings);
@@ -51,7 +48,7 @@ const setup = async (
describe("SettingsLdapForm (EE)", () => {
describe("user provisioning", () => {
- it("sits right below the server settings", async () => {
+ it("sits right above the attributes", async () => {
await setup();
const cardTitles = screen
@@ -59,24 +56,38 @@ describe("SettingsLdapForm (EE)", () => {
.map((heading) => heading.textContent);
expect(cardTitles).toEqual([
"Server settings",
- "User provisioning",
"User schema",
+ "User provisioning",
"Attributes",
"Group mapping",
]);
});
- it("stays editable before the LDAP host is saved", async () => {
- await setup({ "ldap-host": null });
+ it("stays disabled until LDAP is configured", async () => {
+ await setup({ "ldap-host": null, "ldap-configured?": false });
+
+ const toggle = screen.getByRole("switch", { name: "User provisioning" });
+ expect(toggle).toBeDisabled();
+ expect(
+ screen.getByRole("switch", { name: "Group mapping" }),
+ ).toBeDisabled();
+ });
+
+ it("comes alive once the host and user search base are saved", async () => {
+ await setup({
+ "ldap-host": "ldap.example.test",
+ "ldap-configured?": true,
+ });
const toggle = screen.getByRole("switch", { name: "User provisioning" });
await waitFor(() => expect(toggle).toBeEnabled());
});
- it("keeps the switch disabled until the settings list says whether an env var owns it", async () => {
+ it("locks the switch to the value set through an env var", async () => {
await setup(
{
"ldap-host": "ldap.example.test",
+ "ldap-configured?": true,
"ldap-user-provisioning-enabled?": true,
},
{
@@ -87,15 +98,10 @@ describe("SettingsLdapForm (EE)", () => {
env_name: "MB_LDAP_USER_PROVISIONING_ENABLED",
},
],
- detailsDelayMs: 300,
},
);
- const toggle = screen.getByRole("switch", { name: "User provisioning" });
- expect(toggle).toBeDisabled();
- expect(
- await screen.findByText("Using MB_LDAP_USER_PROVISIONING_ENABLED"),
- ).toBeInTheDocument();
+ const toggle = screen.getByRole("switch", { name: "User provisioning" });
expect(toggle).toBeDisabled();
expect(toggle).toBeChecked();
expect(toggle).toHaveAccessibleDescription(
@@ -107,6 +113,7 @@ describe("SettingsLdapForm (EE)", () => {
await setup({
"ldap-enabled": true,
"ldap-host": "ldap.example.test",
+ "ldap-configured?": true,
"ldap-user-provisioning-enabled?": true,
});
const toggle = screen.getByRole("switch", { name: "User provisioning" });
@@ -128,4 +135,82 @@ describe("SettingsLdapForm (EE)", () => {
).toBeDisabled();
});
});
+
+ describe("group membership filter", () => {
+ it("shows the default as the placeholder while group mapping is on", async () => {
+ await setup(
+ { "ldap-configured?": true, "ldap-group-sync": true },
+ {
+ settingDefinitions: [
+ { key: "ldap-group-membership-filter", default: "(member={dn})" },
+ ],
+ },
+ );
+
+ const filterInput = screen.getByRole("textbox", {
+ name: /Group membership filter/,
+ });
+ expect(filterInput).toHaveValue("");
+ expect(filterInput).toHaveAttribute("placeholder", "(member={dn})");
+ });
+
+ it("is saved with the page form", async () => {
+ // the required server fields have to be filled for the browser to let the form submit
+ await setup(
+ {
+ "ldap-enabled": true,
+ "ldap-configured?": true,
+ "ldap-group-sync": true,
+ },
+ {
+ settingDefinitions: [
+ { key: "ldap-host", value: "ldap.example.test" },
+ { key: "ldap-user-base", value: "ou=users,dc=example,dc=org" },
+ { key: "ldap-group-membership-filter", default: "(member={dn})" },
+ ],
+ },
+ );
+
+ const filterInput = screen.getByRole("textbox", {
+ name: /Group membership filter/,
+ });
+ await userEvent.type(filterInput, "(uniqueMember=user)");
+ expect(filterInput).toHaveValue("(uniqueMember=user)");
+ const saveButton = screen.getByRole("button", { name: "Save changes" });
+ expect(saveButton).toBeEnabled();
+ await userEvent.click(saveButton);
+
+ const [{ url, body }] = await findRequests("PUT");
+ expect(url).toMatch(/api\/ldap\/settings/);
+ expect(body["ldap-group-membership-filter"]).toBe("(uniqueMember=user)");
+ });
+
+ it("does not let a hidden filter with unbalanced parentheses block saving", async () => {
+ await setup(
+ { "ldap-enabled": true, "ldap-group-sync": false },
+ {
+ settingDefinitions: [
+ { key: "ldap-host", value: "ldap.example.test" },
+ { key: "ldap-user-base", value: "ou=users,dc=example,dc=org" },
+ { key: "ldap-group-membership-filter", value: "(member={dn}" },
+ ],
+ },
+ );
+
+ expect(
+ screen.queryByRole("textbox", { name: /Group membership filter/ }),
+ ).not.toBeInTheDocument();
+ await userEvent.type(
+ screen.getByRole("textbox", { name: /LDAP host/ }),
+ ".internal",
+ );
+ const saveButton = screen.getByRole("button", { name: "Save changes" });
+ expect(saveButton).toBeEnabled();
+ await userEvent.click(saveButton);
+
+ const [{ url, body }] = await findRequests("PUT");
+ expect(url).toMatch(/api\/ldap\/settings/);
+ expect(body["ldap-host"]).toBe("ldap.example.test.internal");
+ });
+ });
});
diff --git a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx
index a754745c356..7040f2aa16e 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx
@@ -1,11 +1,12 @@
-import { useCallback } from "react";
+import { useCallback, useMemo } from "react";
import { c, t } from "ttag";
-import _ from "underscore";
import type { TestConfig } from "yup";
import * as Yup from "yup";
-import { GroupMappingsWidget } from "metabase/admin/settings/components/widgets/GroupMappingsWidget";
-import { getExtraFormFieldProps } from "metabase/admin/settings/utils";
+import {
+ getDefaultPlaceholder,
+ getExtraFormFieldProps,
+} from "metabase/admin/settings/utils";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import {
Form,
@@ -16,21 +17,30 @@ import {
FormTextInput,
} from "metabase/forms";
import { PLUGIN_LDAP_FORM_FIELDS } from "metabase/plugins";
+import { useSelector } from "metabase/redux";
+import { getApplicationName } from "metabase/selectors/whitelabel";
import {
useGetAdminSettingsDetailsQuery,
useGetSettingsQuery,
} from "metabase/settings";
import {
+ CollapsibleSettingsSection,
SETTINGS_CARD_STACK_PROPS,
SETTINGS_CARD_TITLE_PROPS,
SettingsPageWrapper,
SettingsSection,
} from "metabase/settings-components";
-import { Box, Flex, Group, Radio, Stack } from "metabase/ui";
-import type { EnterpriseSettings, Settings } from "metabase-types/api";
+import { Box, Flex, Radio, Stack } from "metabase/ui";
+import type {
+ EnterpriseSettings,
+ SettingDefinition,
+ SettingDefinitionMap,
+} from "metabase-types/api";
import { useUpdateLdapMutation } from "../api/ldap";
+import { LdapGroupMappingSection } from "./LdapGroupMappingSection";
+
const testParentheses: TestConfig<string | null | undefined> = {
name: "test-parentheses",
message: "Check your parentheses",
@@ -38,15 +48,23 @@ const testParentheses: TestConfig<string | null | undefined> = {
(value?.match(/\(/g) || []).length === (value?.match(/\)/g) || []).length,
};
-const LDAP_SCHEMA = Yup.object({
- "ldap-port": Yup.number().integer().nullable(),
- "ldap-user-filter": Yup.string().nullable().test(testParentheses),
- "ldap-group-membership-filter": Yup.string().nullable().test(testParentheses),
-});
+// the membership filter is hidden while group mapping is off, so its check must not block the page then
+const getLdapSchema = (isGroupMappingOn: boolean) =>
+ Yup.object({
+ "ldap-port": Yup.number().integer().nullable(),
+ "ldap-user-filter": Yup.string().nullable().test(testParentheses),
+ "ldap-group-membership-filter": isGroupMappingOn
+ ? Yup.string().nullable().test(testParentheses)
+ : Yup.string().nullable(),
+ });
-export type LdapSettings = Pick<
+// an empty port means the default, so the form allows null where the setting does not
+export type LdapFormValues = Omit<LdapSettingValues, "ldap-port"> & {
+ "ldap-port": number | null;
+};
+
+type LdapSettingValues = Pick<
EnterpriseSettings,
- | "ldap-enabled"
| "ldap-host"
| "ldap-port"
| "ldap-security"
@@ -61,33 +79,80 @@ export type LdapSettings = Pick<
| "ldap-group-membership-filter"
>;
+type LdapTextKey = Exclude<keyof LdapFormValues, "ldap-port" | "ldap-security">;
+
+// the connection test needs a port spelled out, so an empty field falls back to the backend default
+const FALLBACK_LDAP_PORT = 389;
+
+const LDAP_ATTRIBUTE_KEYS = [
+ "ldap-attribute-email",
+ "ldap-attribute-firstname",
+ "ldap-attribute-lastname",
+] as const;
+
+// the backend copy for a few fields predates the design, so the page supplies its own description
+const withDescription = (
+ setting: SettingDefinition | undefined,
+ description: string,
+) => {
+ const fieldProps = getExtraFormFieldProps(setting);
+ return setting?.is_env_setting ? fieldProps : { ...fieldProps, description };
+};
+
+const getAttributeFieldProps = (setting: SettingDefinition | undefined) =>
+ setting?.is_env_setting
+ ? getExtraFormFieldProps(setting)
+ : { placeholder: getDefaultPlaceholder(setting) };
+
export const SettingsLdapForm = () => {
- const { data: settingDetails } = useGetAdminSettingsDetailsQuery();
- const { data: settingValues } = useGetSettingsQuery();
+ const { data: settingDetails, isLoading: isLoadingDetails } =
+ useGetAdminSettingsDetailsQuery();
+ const { data: settingValues, isLoading: isLoadingValues } =
+ useGetSettingsQuery();
const [updateLdapSettings] = useUpdateLdapMutation();
+ const applicationName = useSelector(getApplicationName);
const isEnabled = settingValues?.["ldap-enabled"];
+ const isConfigured = settingValues?.["ldap-configured?"] ?? false;
+ const isGroupMappingOn = settingValues?.["ldap-group-sync"] ?? false;
+ const schema = useMemo(
+ () => getLdapSchema(isGroupMappingOn),
+ [isGroupMappingOn],
+ );
+ const defaultPort =
+ settingDetails?.["ldap-port"]?.default ?? FALLBACK_LDAP_PORT;
const handleSubmit = useCallback(
- (values: Partial<LdapSettings>) => {
+ (values: LdapFormValues) => {
return updateLdapSettings({
...values,
- "ldap-port": Number(values["ldap-port"]),
+ "ldap-port": Number(values["ldap-port"] ?? defaultPort),
"ldap-enabled": true,
}).unwrap();
},
- [updateLdapSettings],
+ [updateLdapSettings, defaultPort],
);
- if (!settingValues) {
+ if (isLoadingDetails || isLoadingValues) {
return <LoadingAndErrorWrapper loading />;
}
+ if (!settingDetails || !settingValues) {
+ return (
+ <LoadingAndErrorWrapper error={t`Error loading LDAP configuration`} />
+ );
+ }
+
+ const hasCustomAttributes = LDAP_ATTRIBUTE_KEYS.some((key) => {
+ const setting = settingDetails[key];
+ return setting?.value != null || (setting?.is_env_setting ?? false);
+ });
+
return (
<SettingsPageWrapper title={t`LDAP`}>
<FormProvider
- initialValues={getFormValues(settingValues)}
+ initialValues={getFormValues(settingDetails, settingValues)}
onSubmit={handleSubmit}
- validationSchema={LDAP_SCHEMA}
+ validationSchema={schema}
enableReinitialize
>
{({ dirty }) => (
@@ -105,54 +170,48 @@ export const SettingsLdapForm = () => {
placeholder="ldap.yourdomain.org"
required
autoFocus
- {...getExtraFormFieldProps(settingDetails?.["ldap-host"])}
+ {...getExtraFormFieldProps(settingDetails["ldap-host"])}
/>
<FormTextInput
name="ldap-port"
label={t`LDAP port`}
- placeholder="389"
- required
+ placeholder={String(defaultPort)}
type="number"
- {...getExtraFormFieldProps(settingDetails?.["ldap-port"])}
+ nullable
+ {...getExtraFormFieldProps(settingDetails["ldap-port"])}
/>
<FormRadioGroup
name="ldap-security"
label={t`LDAP security`}
- {...getExtraFormFieldProps(
- settingDetails?.["ldap-security"],
- )}
+ {...getExtraFormFieldProps(settingDetails["ldap-security"])}
description={null}
>
- <Group mt={"xxs"}>
+ <Stack mt="xxs" gap="sm">
<Radio value="none" label={t`None`} />
<Radio
value="ssl"
label={c("short for 'Secure Sockets Layer'").t`SSL`}
/>
<Radio value="starttls" label={t`StartTLS`} />
- </Group>
+ </Stack>
</FormRadioGroup>
<FormTextInput
name="ldap-bind-dn"
label={t`Username or DN`}
+ placeholder="cn=admin,dc=company,dc=com"
nullable
- {...getExtraFormFieldProps(
- settingDetails?.["ldap-bind-dn"],
- )}
+ {...getExtraFormFieldProps(settingDetails["ldap-bind-dn"])}
/>
<FormTextInput
name="ldap-password"
label={t`Password`}
type="password"
+ placeholder={t`Shh...`}
nullable
- {...getExtraFormFieldProps(
- settingDetails?.["ldap-password"],
- )}
+ {...getExtraFormFieldProps(settingDetails["ldap-password"])}
/>
</Stack>
</SettingsSection>
- {/* the card saves on its own, so it stays out of the form's values */}
- <PLUGIN_LDAP_FORM_FIELDS.LdapUserProvisioning />
<SettingsSection
title={t`User schema`}
titleProps={SETTINGS_CARD_TITLE_PROPS}
@@ -161,83 +220,81 @@ export const SettingsLdapForm = () => {
<Stack gap="lg">
<FormTextInput
name="ldap-user-base"
- placeholder="ou=users,dc=example,dc=org"
label={t`User search base`}
+ placeholder="ou=users,dc=example,dc=org"
required
- {...getExtraFormFieldProps(
- settingDetails?.["ldap-user-base"],
+ {...withDescription(
+ settingDetails["ldap-user-base"],
+ t`The distinguished name (DN) of the entry in your LDAP server that ${applicationName} should use as the starting point when searching for users`,
)}
/>
<FormTextInput
name="ldap-user-filter"
label={t`User filter`}
+ placeholder={getDefaultPlaceholder(
+ settingDetails["ldap-user-filter"],
+ )}
nullable
{...getExtraFormFieldProps(
- settingDetails?.["ldap-user-filter"],
+ settingDetails["ldap-user-filter"],
)}
/>
</Stack>
</SettingsSection>
- <SettingsSection
+ {/* the card saves on its own, so it stays out of the form's values */}
+ <PLUGIN_LDAP_FORM_FIELDS.LdapUserProvisioning
+ disabled={!isConfigured}
+ />
+ <CollapsibleSettingsSection
title={t`Attributes`}
- titleProps={SETTINGS_CARD_TITLE_PROPS}
- stackProps={SETTINGS_CARD_STACK_PROPS}
+ description={t`Map LDAP attributes to the email, first name, and last name fields in ${applicationName}`}
+ defaultOpened={hasCustomAttributes}
+ disabled={!isConfigured}
>
<Stack gap="lg">
<FormTextInput
name="ldap-attribute-email"
- label={t`Email attribute`}
+ label={t`Email attribute key`}
nullable
- {...getExtraFormFieldProps(
- settingDetails?.["ldap-attribute-email"],
+ {...getAttributeFieldProps(
+ settingDetails["ldap-attribute-email"],
)}
/>
<FormTextInput
name="ldap-attribute-firstname"
- label={t`First name attribute`}
+ label={t`First name attribute key`}
nullable
- {...getExtraFormFieldProps(
- settingDetails?.["ldap-attribute-firstname"],
+ {...getAttributeFieldProps(
+ settingDetails["ldap-attribute-firstname"],
)}
/>
<FormTextInput
name="ldap-attribute-lastname"
- label={t`Last name attribute`}
+ label={t`Last name attribute key`}
nullable
- {...getExtraFormFieldProps(
- settingDetails?.["ldap-attribute-lastname"],
+ {...getAttributeFieldProps(
+ settingDetails["ldap-attribute-lastname"],
)}
/>
</Stack>
- </SettingsSection>
- <SettingsSection
- title={t`Group mapping`}
- titleProps={SETTINGS_CARD_TITLE_PROPS}
- stackProps={SETTINGS_CARD_STACK_PROPS}
+ </CollapsibleSettingsSection>
+ <LdapGroupMappingSection
+ data-testid="ldap-group-mapping-section"
+ disabled={!isConfigured}
>
- <Stack gap="lg">
- <GroupMappingsWidget
- isFormik
- setting={{ key: "ldap-group-sync" }}
- onChange={handleSubmit}
- settingValues={settingValues}
- mappingSetting="ldap-group-mappings"
- groupHeading={t`Group name`}
- groupPlaceholder={t`Group name`}
- />
- <FormTextInput
- name="ldap-group-base"
- label={t`Group search base`}
- placeholder="ou=groups,dc=example,dc=org"
- nullable
- {...getExtraFormFieldProps(
- settingDetails?.["ldap-group-base"],
- )}
- />
- <PLUGIN_LDAP_FORM_FIELDS.LdapGroupMembershipFilter />
- </Stack>
- </SettingsSection>
- <Flex justify="end" gap="1rem">
+ <FormTextInput
+ name="ldap-group-base"
+ label={t`Group search base`}
+ placeholder="ou=groups,dc=example,dc=org"
+ nullable
+ {...withDescription(
+ settingDetails["ldap-group-base"],
+ t`Not required for LDAP directories that provide a 'memberOf' overlay, such as Active Directory. It will be searched recursively.`,
+ )}
+ />
+ <PLUGIN_LDAP_FORM_FIELDS.LdapGroupMembershipFilter />
+ </LdapGroupMappingSection>
+ <Flex justify="end" gap="md">
<Box>
<FormErrorMessage />
</Box>
@@ -255,22 +312,40 @@ export const SettingsLdapForm = () => {
);
};
-export const getFormValues = (allSettings: Partial<Settings>) => {
- const ldapSettings = _.pick(allSettings, [
- "ldap-host",
- "ldap-port",
- "ldap-security",
- "ldap-bind-dn",
- "ldap-password",
- "ldap-user-base",
- "ldap-user-filter",
- "ldap-attribute-email",
- "ldap-attribute-firstname",
- "ldap-attribute-lastname",
- "ldap-group-sync",
- "ldap-group-base",
- "ldap-group-membership-filter",
- ]);
+export const getFormValues = (
+ settingDetails: SettingDefinitionMap,
+ settingValues: EnterpriseSettings,
+): LdapFormValues => {
+ // unset fields stay empty so the default shows as the placeholder; env-locked ones show the env value
+ const storedValue = (key: LdapTextKey): string | null => {
+ const setting = settingDetails[key];
+ if (setting?.is_env_setting) {
+ return settingValues[key] ?? null;
+ }
+ return setting?.value ?? null;
+ };
- return ldapSettings;
+ const portSetting = settingDetails["ldap-port"];
+ const values: LdapFormValues = {
+ "ldap-host": storedValue("ldap-host"),
+ "ldap-port": portSetting?.is_env_setting
+ ? settingValues["ldap-port"]
+ : (portSetting?.value ?? null),
+ "ldap-security": settingValues["ldap-security"] ?? "none",
+ "ldap-bind-dn": storedValue("ldap-bind-dn"),
+ "ldap-password": storedValue("ldap-password"),
+ "ldap-user-base": storedValue("ldap-user-base"),
+ "ldap-user-filter": storedValue("ldap-user-filter"),
+ "ldap-attribute-email": storedValue("ldap-attribute-email"),
+ "ldap-attribute-firstname": storedValue("ldap-attribute-firstname"),
+ "ldap-attribute-lastname": storedValue("ldap-attribute-lastname"),
+ "ldap-group-base": storedValue("ldap-group-base"),
+ };
+ // OSS builds have no membership filter setting, so the key stays out of the write
+ if (settingDetails["ldap-group-membership-filter"] != null) {
+ values["ldap-group-membership-filter"] = storedValue(
+ "ldap-group-membership-filter",
+ );
+ }
+ return values;
};
diff --git a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.unit.spec.tsx
index 4ca707d7b89..32986e40ae1 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.unit.spec.tsx
@@ -3,35 +3,132 @@ import fetchMock from "fetch-mock";
import {
findRequests,
- setupPropertiesEndpoints,
setupSettingsEndpoints,
+ setupStatefulSettingsEndpoints,
} from "__support__/server-mocks";
-import { renderWithProviders, screen } from "__support__/ui";
+import { createMockSettingsState, createMockState } from "__support__/state";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import type {
+ EnterpriseSettingKey,
+ EnterpriseSettings,
+ SettingDefinition,
+} from "metabase-types/api";
import { createMockGroup, createMockSettings } from "metabase-types/api/mocks";
-import type { LdapSettings } from "./SettingsLdapForm";
import { SettingsLdapForm } from "./SettingsLdapForm";
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 (settingValues?: Partial<LdapSettings>) => {
+const DEFAULT_USER_FILTER =
+ "(&(objectClass=inetOrgPerson)(|(uid={login})(mail={login})))";
+
+const DEFAULT_DEFINITIONS: SettingDefinition[] = [
+ { key: "ldap-user-filter", default: DEFAULT_USER_FILTER },
+ { key: "ldap-attribute-email", default: "mail" },
+ { key: "ldap-attribute-firstname", default: "givenName" },
+ { key: "ldap-attribute-lastname", default: "sn" },
+];
+
+const DEVS_DN = "cn=devs,ou=groups,dc=example,dc=org";
+const OPS_DN = "cn=ops,ou=groups,dc=example,dc=org";
+const RENAMED_DN = "cn=developers,ou=groups,dc=example,dc=org";
+const LDAP_GROUP_PLACEHOLDER = "cn=people,ou=groups,dc=example,dc=org";
+
+// the admin list only carries values that were set, so the test values stand in for those
+const toDefinitions = (
+ values: Partial<EnterpriseSettings>,
+): SettingDefinition[] =>
+ // Object.keys widens the keys of a typed record to string
+ (Object.keys(values) as EnterpriseSettingKey[]).map((key) => ({
+ key,
+ value: values[key],
+ }));
+
+const setup = async ({
+ settingValues = {},
+ settingDefinitions = [],
+ saveStatus,
+ saveMessage,
+}: {
+ settingValues?: Partial<EnterpriseSettings>;
+ // entries here win over the ones derived from settingValues
+ settingDefinitions?: SettingDefinition[];
+ saveStatus?: number;
+ saveMessage?: string;
+} = {}) => {
const settings = createMockSettings(settingValues);
delete settings["ldap-group-membership-filter"]; // not present in OSS
- setupSettingsEndpoints([]);
- setupPropertiesEndpoints(settings);
-
+ const listedKeys = new Set(
+ settingDefinitions.map((definition) => definition.key),
+ );
+ setupSettingsEndpoints([
+ ...settingDefinitions,
+ ...toDefinitions(settingValues).filter(({ key }) => !listedKeys.has(key)),
+ ]);
+ // the switch and the mappings read their values back after saving, so the properties mock has to remember writes
+ const settingsStore = setupStatefulSettingsEndpoints(settings);
+ if (saveStatus != null) {
+ // a rejected write comes back as a plain-text reason, the way the settings endpoint reports a 400
+ fetchMock.removeRoute("update-settings");
+ fetchMock.put(
+ "path:/api/setting",
+ {
+ status: saveStatus,
+ body: saveMessage,
+ headers: { "content-type": "text/plain" },
+ },
+ { name: "update-settings" },
+ );
+ }
fetchMock.get("path:/api/permissions/group", GROUPS);
+ fetchMock.put("express:/api/permissions/membership/:id/clear", 204);
+ fetchMock.delete("express:/api/permissions/group/:id", 204);
fetchMock.put("path:/api/ldap/settings", { status: 204 });
- renderWithProviders(<SettingsLdapForm />);
+ const { store } = renderWithProviders(<SettingsLdapForm />, {
+ withUndos: true,
+ storeInitialState: createMockState({
+ settings: createMockSettingsState(settings),
+ }),
+ });
await screen.findByText("Server settings");
+ return { store, settingsStore };
+};
+
+const setupConfigured = (options: Parameters<typeof setup>[0] = {}) =>
+ setup({
+ ...options,
+ settingValues: { "ldap-configured?": true, ...options.settingValues },
+ });
+
+const expandAttributes = async () => {
+ await userEvent.click(screen.getByRole("button", { name: "Attributes" }));
+};
+
+const groupMappingSwitch = () =>
+ screen.getByRole("switch", { name: "Group mapping" });
+
+const findMappingRow = (name: string) =>
+ screen
+ .queryAllByTestId("group-mapping-row")
+ .find((row) => within(row).queryByText(name) != null);
+
+const addMapping = async (name: string, groupName: string) => {
+ await userEvent.click(screen.getByRole("button", { name: "New" }));
+ await userEvent.type(
+ screen.getByPlaceholderText(LDAP_GROUP_PLACEHOLDER),
+ 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" }));
};
describe("SettingsLdapForm", () => {
@@ -47,12 +144,11 @@ describe("SettingsLdapForm", () => {
"ldap-attribute-firstname": "John",
"ldap-attribute-lastname": "Doe",
"ldap-enabled": true,
- "ldap-group-sync": true,
"ldap-group-base": "group-base",
- };
+ } satisfies Partial<EnterpriseSettings>;
it("should submit the correct payload", async () => {
- await setup();
+ await setupConfigured({ settingValues: { "ldap-group-sync": true } });
await userEvent.type(
await screen.findByLabelText(/LDAP host/),
@@ -79,19 +175,19 @@ describe("SettingsLdapForm", () => {
await screen.findByLabelText(/User filter/),
ATTRS["ldap-user-filter"],
);
+ await expandAttributes();
await userEvent.type(
- await screen.findByLabelText(/Email attribute/),
+ await screen.findByLabelText(/Email attribute key/),
ATTRS["ldap-attribute-email"],
);
await userEvent.type(
- await screen.findByLabelText(/First name attribute/),
+ await screen.findByLabelText(/First name attribute key/),
ATTRS["ldap-attribute-firstname"],
);
await userEvent.type(
- await screen.findByLabelText(/Last name attribute/),
+ await screen.findByLabelText(/Last name attribute key/),
ATTRS["ldap-attribute-lastname"],
);
- await userEvent.click(screen.getByTestId("group-sync-switch")); // checkbox for "ldap-group-sync"
await userEvent.type(
await screen.findByRole("textbox", { name: /Group search base/ }),
ATTRS["ldap-group-base"],
@@ -105,18 +201,23 @@ describe("SettingsLdapForm", () => {
expect(body).toEqual(ATTRS);
});
- it("should hide group membership fields on OSS", async () => {
- setup({ "ldap-enabled": true });
+ it("should hide the group membership filter on OSS", async () => {
+ await setupConfigured({ settingValues: { "ldap-group-sync": true } });
+
+ expect(
+ screen.getByRole("textbox", { name: /Group search base/ }),
+ ).toBeInTheDocument();
expect(
screen.queryByRole("textbox", { name: /Group membership filter/ }),
).not.toBeInTheDocument();
});
it("can remove a nullable field", async () => {
- // Unjustified type cast. FIXME
- setup(ATTRS as Partial<LdapSettings>);
+ await setup({ settingValues: ATTRS });
- await userEvent.clear(await screen.findByLabelText(/First name attribute/));
+ await userEvent.clear(
+ await screen.findByLabelText(/First name attribute key/),
+ );
await userEvent.click(await screen.findByRole("button", { name: /Save/ }));
const [{ body }] = await findRequests("PUT");
@@ -136,4 +237,501 @@ describe("SettingsLdapForm", () => {
screen.queryByRole("switch", { name: "User provisioning" }),
).not.toBeInTheDocument();
});
+
+ it("lays the cards out in the designed order", async () => {
+ await setup();
+
+ const cardTitles = screen
+ .getAllByRole("heading", { level: 2 })
+ .map((heading) => heading.textContent);
+ expect(cardTitles).toEqual([
+ "Server settings",
+ "User schema",
+ "Attributes",
+ "Group mapping",
+ ]);
+ });
+
+ describe("defaults", () => {
+ it("shows the defaults as placeholders and leaves unset fields empty", async () => {
+ await setupConfigured({ settingDefinitions: DEFAULT_DEFINITIONS });
+
+ const userFilter = screen.getByLabelText(/User filter/);
+ expect(userFilter).toHaveValue("");
+ expect(userFilter).toHaveAttribute("placeholder", DEFAULT_USER_FILTER);
+ const port = screen.getByLabelText(/LDAP port/);
+ expect(port).toHaveValue(null);
+ expect(port).toHaveAttribute("placeholder", "389");
+
+ await expandAttributes();
+
+ expect(screen.getByLabelText(/Email attribute key/)).toHaveValue("");
+ expect(screen.getByLabelText(/Email attribute key/)).toHaveAttribute(
+ "placeholder",
+ "mail",
+ );
+ expect(screen.getByLabelText(/First name attribute key/)).toHaveAttribute(
+ "placeholder",
+ "givenName",
+ );
+ expect(screen.getByLabelText(/Last name attribute key/)).toHaveAttribute(
+ "placeholder",
+ "sn",
+ );
+ });
+
+ it("sends the default port when the field is left empty", async () => {
+ await setup({ settingDefinitions: [{ key: "ldap-port", default: 636 }] });
+
+ const port = screen.getByLabelText(/LDAP port/);
+ expect(port).toHaveValue(null);
+ expect(port).toHaveAttribute("placeholder", "636");
+ await userEvent.type(screen.getByLabelText(/LDAP host/), "ldap.test");
+ await userEvent.type(
+ screen.getByLabelText(/User search base/),
+ "ou=users,dc=example,dc=org",
+ );
+ await userEvent.click(screen.getByRole("button", { name: /Save/ }));
+
+ const [{ body }] = await findRequests("PUT");
+ expect(body["ldap-port"]).toBe(636);
+ });
+
+ it("shows the value an env var gives a field, read-only", async () => {
+ await setup({
+ settingValues: { "ldap-host": "ldap.env.test" },
+ settingDefinitions: [
+ { key: "ldap-host", is_env_setting: true, env_name: "MB_LDAP_HOST" },
+ ],
+ });
+
+ const hostInput = screen.getByLabelText(/LDAP host/);
+ expect(hostInput).toHaveValue("ldap.env.test");
+ expect(hostInput).toHaveAttribute("readonly");
+ expect(screen.getByText("Using MB_LDAP_HOST")).toBeInTheDocument();
+ });
+
+ it("keeps the attributes card disabled until LDAP is configured", async () => {
+ await setup({ settingValues: { "ldap-attribute-email": "uid" } });
+
+ const attributesHeader = screen.getByRole("button", {
+ name: "Attributes",
+ });
+ expect(attributesHeader).toBeDisabled();
+ expect(attributesHeader).toHaveAttribute("aria-expanded", "false");
+ });
+
+ it("keeps the attributes card collapsed until an attribute is customized", async () => {
+ await setupConfigured({ settingDefinitions: DEFAULT_DEFINITIONS });
+
+ expect(
+ screen.getByRole("button", { name: "Attributes" }),
+ ).toHaveAttribute("aria-expanded", "false");
+ expect(screen.getByLabelText(/Email attribute key/)).not.toBeVisible();
+ });
+
+ it("opens the attributes card when an attribute is set", async () => {
+ await setupConfigured({
+ settingValues: { "ldap-attribute-email": "uid" },
+ });
+
+ expect(
+ screen.getByRole("button", { name: "Attributes" }),
+ ).toHaveAttribute("aria-expanded", "true");
+ expect(screen.getByLabelText(/Email attribute key/)).toHaveValue("uid");
+ });
+
+ it("opens the attributes card when an attribute comes from an env var", async () => {
+ await setupConfigured({
+ settingDefinitions: [
+ {
+ key: "ldap-attribute-lastname",
+ is_env_setting: true,
+ env_name: "MB_LDAP_ATTRIBUTE_LASTNAME",
+ },
+ ],
+ });
+
+ expect(
+ screen.getByRole("button", { name: "Attributes" }),
+ ).toHaveAttribute("aria-expanded", "true");
+ expect(
+ screen.getByText("Using MB_LDAP_ATTRIBUTE_LASTNAME"),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("group mapping", () => {
+ it("stays disabled until LDAP is configured", async () => {
+ await setup({ settingValues: { "ldap-group-sync": true } });
+
+ expect(groupMappingSwitch()).toBeDisabled();
+ expect(groupMappingSwitch()).toBeChecked();
+ expect(
+ screen.queryByText("Manual group mappings"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("textbox", { name: /Group search base/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("comes alive once the host and user search base are saved", async () => {
+ await setupConfigured();
+
+ expect(groupMappingSwitch()).toBeEnabled();
+ expect(groupMappingSwitch()).not.toBeChecked();
+ });
+
+ it("keeps the mappings and the group fields hidden while group mapping is off", async () => {
+ await setupConfigured();
+
+ expect(groupMappingSwitch()).not.toBeChecked();
+ expect(
+ screen.queryByText("Manual group mappings"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("textbox", { name: /Group search base/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("turns group mapping on right away and reveals the mappings and the group fields", async () => {
+ await setupConfigured();
+
+ await userEvent.click(groupMappingSwitch());
+
+ expect(groupMappingSwitch()).toBeChecked();
+ expect(screen.getByText("Manual group mappings")).toBeInTheDocument();
+ expect(screen.getByText("No mappings yet")).toBeInTheDocument();
+ expect(
+ screen.getByRole("textbox", { name: /Group search base/ }),
+ ).toBeInTheDocument();
+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();
+ const puts = await findRequests("PUT");
+ expect(puts).toHaveLength(1);
+ expect(puts[0].url).toMatch(/\/api\/setting\/ldap-group-sync$/);
+ expect(puts[0].body).toEqual({ value: true });
+ expect(screen.getByRole("button", { name: /Save/ })).toBeDisabled();
+ });
+
+ it("shows the new value and holds the switch while the write is in flight", async () => {
+ const { settingsStore } = await setupConfigured();
+ // the properties mock answers the write late, so the in-flight state can be seen
+ fetchMock.removeRoute("update-setting");
+ fetchMock.put(
+ new RegExp("/api/setting/(.+)"),
+ ({ url, options }) => {
+ const key = decodeURIComponent(url.split("/api/setting/")[1]);
+ settingsStore[key] = JSON.parse(String(options.body)).value;
+ return { status: 204 };
+ },
+ { name: "update-setting", delay: 200 },
+ );
+
+ await userEvent.click(groupMappingSwitch());
+
+ expect(groupMappingSwitch()).toBeChecked();
+ expect(groupMappingSwitch()).toBeDisabled();
+ expect(screen.getByText("Manual group mappings")).toBeInTheDocument();
+ await waitFor(() => expect(groupMappingSwitch()).toBeEnabled());
+ expect(groupMappingSwitch()).toBeChecked();
+ expect(await findRequests("PUT")).toHaveLength(1);
+ });
+
+ it("puts the old value back when the write fails", async () => {
+ await setupConfigured();
+ fetchMock.removeRoute("update-setting");
+ fetchMock.put(new RegExp("/api/setting/(.+)"), 500, {
+ name: "update-setting",
+ });
+
+ await userEvent.click(groupMappingSwitch());
+
+ expect(await screen.findByText(/Error saving/)).toBeInTheDocument();
+ expect(groupMappingSwitch()).not.toBeChecked();
+ expect(groupMappingSwitch()).toBeEnabled();
+ expect(
+ screen.queryByText("Manual group mappings"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("asks only for internal groups, since LDAP users are never tenants", async () => {
+ await setupConfigured({ settingValues: { "ldap-group-sync": true } });
+
+ await userEvent.click(screen.getByRole("button", { name: "New" }));
+ await userEvent.click(
+ screen.getByPlaceholderText("Pick Metabase group..."),
+ );
+ expect(
+ await screen.findByRole("option", { name: "bar" }),
+ ).toBeInTheDocument();
+ const groupRequests = (await findRequests("GET")).filter(({ url }) =>
+ url.includes("/api/permissions/group"),
+ );
+ expect(groupRequests.length).toBeGreaterThan(0);
+ expect(
+ groupRequests.every(({ url }) => url.includes("tenancy=internal")),
+ ).toBe(true);
+ });
+
+ it("adds a mapping and writes it without touching the page form", async () => {
+ await setupConfigured({ settingValues: { "ldap-group-sync": true } });
+
+ await userEvent.click(screen.getByRole("button", { name: "New" }));
+ expect(
+ screen.queryByRole("button", { name: "New" }),
+ ).not.toBeInTheDocument();
+ await userEvent.type(
+ screen.getByPlaceholderText(LDAP_GROUP_PLACEHOLDER),
+ DEVS_DN,
+ );
+ await userEvent.click(
+ screen.getByPlaceholderText("Pick Metabase group..."),
+ );
+ await userEvent.click(await screen.findByRole("option", { name: "bar" }));
+ await userEvent.click(
+ screen.getByRole("button", { name: "Add mapping" }),
+ );
+
+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();
+ const puts = await findRequests("PUT");
+ expect(puts).toHaveLength(1);
+ expect(puts[0].url).toMatch(/\/api\/setting$/);
+ expect(puts[0].body).toEqual({
+ "ldap-group-mappings": { [DEVS_DN]: [4] },
+ });
+ const row = findMappingRow(DEVS_DN);
+ expect(row).toBeDefined();
+ expect(within(row!).getByText("bar")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "New" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Save/ })).toBeDisabled();
+ });
+
+ it("keeps the row editor busy while the mapping write is in flight", async () => {
+ const { settingsStore } = await setupConfigured({
+ settingValues: { "ldap-group-sync": true },
+ });
+ // the properties mock answers the write late, so the busy state can be seen
+ fetchMock.removeRoute("update-settings");
+ fetchMock.put(
+ "path:/api/setting",
+ ({ options }) => {
+ Object.assign(settingsStore, JSON.parse(String(options.body)));
+ return { status: 204 };
+ },
+ { name: "update-settings", delay: 200 },
+ );
+
+ await addMapping(DEVS_DN, "bar");
+
+ const addButton = screen.getByRole("button", { name: "Add mapping" });
+ expect(addButton).toHaveAttribute("data-loading", "true");
+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();
+ expect(findMappingRow(DEVS_DN)).toBeDefined();
+ expect(screen.getByRole("button", { name: "New" })).toBeEnabled();
+ });
+
+ it("keeps group mapping on when the last mapping is deleted", async () => {
+ await setupConfigured({
+ settingValues: {
+ "ldap-group-sync": true,
+ "ldap-group-mappings": { [DEVS_DN]: [3] },
+ },
+ });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Delete mapping" }),
+ );
+ const modal = await screen.findByRole("dialog");
+ expect(
+ within(modal).queryByText(/group mapping will be turned off/),
+ ).not.toBeInTheDocument();
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Remove mapping" }),
+ );
+
+ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();
+ const [{ body }] = await findRequests("PUT");
+ expect(body).toEqual({ "ldap-group-mappings": {} });
+ expect(groupMappingSwitch()).toBeChecked();
+ expect(screen.getByText("No mappings yet")).toBeInTheDocument();
+ expect(findMappingRow(DEVS_DN)).toBeUndefined();
+ });
+
+ it("locks the mappings to the ones an env var sets", async () => {
+ await setupConfigured({
+ settingValues: {
+ "ldap-group-sync": true,
+ "ldap-group-mappings": { [DEVS_DN]: [3] },
+ },
+ settingDefinitions: [
+ {
+ key: "ldap-group-mappings",
+ is_env_setting: true,
+ env_name: "MB_LDAP_GROUP_MAPPINGS",
+ },
+ ],
+ });
+
+ expect(
+ screen.getByText("Using MB_LDAP_GROUP_MAPPINGS"),
+ ).toBeInTheDocument();
+ const row = findMappingRow(DEVS_DN);
+ expect(row).toBeDefined();
+ expect(await within(row!).findByText("foo")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "New" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Edit mapping" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Delete mapping" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("locks the switch to the value an env var sets", async () => {
+ await setupConfigured({
+ settingValues: { "ldap-group-sync": true },
+ settingDefinitions: [
+ {
+ key: "ldap-group-sync",
+ is_env_setting: true,
+ env_name: "MB_LDAP_GROUP_SYNC",
+ },
+ ],
+ });
+
+ expect(groupMappingSwitch()).toBeChecked();
+ expect(groupMappingSwitch()).toBeDisabled();
+ expect(groupMappingSwitch()).toHaveAccessibleDescription(
+ /Using MB_LDAP_GROUP_SYNC/,
+ );
+ expect(screen.getByText("Manual group mappings")).toBeInTheDocument();
+ });
+
+ it("keeps the editor open and shows the backend's reason under the name", async () => {
+ const reason = `qwf is not a valid DN. Example: ${LDAP_GROUP_PLACEHOLDER}`;
+ await setupConfigured({
+ settingValues: { "ldap-group-sync": true },
+ saveStatus: 400,
+ saveMessage: reason,
+ });
+
+ await addMapping("qwf", "bar");
+
+ const nameInput = screen.getByPlaceholderText(LDAP_GROUP_PLACEHOLDER);
+ expect(await screen.findByText(reason)).toBeInTheDocument();
+ // the reason sits under the field, not in a toast as well
+ expect(screen.getAllByText(reason)).toHaveLength(1);
+ expect(nameInput).toBeInvalid();
+ expect(nameInput).toHaveAccessibleErrorMessage(reason);
+ expect(screen.getByRole("alert")).toHaveTextContent(reason);
+ expect(nameInput).toHaveValue("qwf");
+ expect(screen.getByRole("button", { name: "Add mapping" })).toBeEnabled();
+ expect(screen.queryByTestId("group-mapping-row")).not.toBeInTheDocument();
+ expect(screen.queryByText("Mapping added")).not.toBeInTheDocument();
+
+ await userEvent.clear(nameInput);
+ expect(screen.queryByText(reason)).not.toBeInTheDocument();
+ expect(nameInput).not.toBeInvalid();
+ });
+
+ it("adds the mapping on Enter without submitting the page form", async () => {
+ await setupConfigured({ settingValues: { "ldap-group-sync": true } });
+
+ // a dirty page form has a live Save button, so Enter could submit it
+ await userEvent.type(screen.getByLabelText(/LDAP host/), "ldap.test");
+ expect(screen.getByRole("button", { name: /Save/ })).toBeEnabled();
+
+ await userEvent.click(screen.getByRole("button", { name: "New" }));
+ const nameInput = screen.getByPlaceholderText(LDAP_GROUP_PLACEHOLDER);
+ await userEvent.type(nameInput, DEVS_DN);
+ 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(findMappingRow(DEVS_DN)).toBeDefined();
+ });
+ const puts = await findRequests("PUT");
+ expect(puts).toHaveLength(1);
+ expect(puts[0].url).toMatch(/\/api\/setting$/);
+ });
+
+ it("edits an existing mapping in place", async () => {
+ await setupConfigured({
+ settingValues: {
+ "ldap-group-sync": true,
+ "ldap-group-mappings": { [DEVS_DN]: [3], [OPS_DN]: [4] },
+ },
+ });
+
+ await userEvent.click(
+ within(findMappingRow(DEVS_DN)!).getByRole("button", {
+ name: "Edit mapping",
+ }),
+ );
+ const nameInput = screen.getByLabelText("LDAP group name");
+ expect(nameInput).toHaveValue(DEVS_DN);
+ expect(screen.getByText("foo")).toBeInTheDocument();
+ await userEvent.clear(nameInput);
+ await userEvent.type(nameInput, RENAMED_DN);
+ await userEvent.click(screen.getByLabelText("Metabase groups"));
+ await userEvent.click(await screen.findByRole("option", { name: "bar" }));
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(await screen.findByText("Mapping updated")).toBeInTheDocument();
+ const [{ body }] = await findRequests("PUT");
+ expect(body).toEqual({
+ "ldap-group-mappings": { [RENAMED_DN]: [3, 4], [OPS_DN]: [4] },
+ });
+ const names = screen
+ .getAllByTestId("group-mapping-row")
+ .map((row) => within(row).getAllByText(/./)[0].textContent);
+ expect(names).toEqual([RENAMED_DN, OPS_DN]);
+ });
+
+ it("deletes a mapping and clears its groups after the mapping is gone", async () => {
+ await setupConfigured({
+ settingValues: {
+ "ldap-group-sync": true,
+ "ldap-group-mappings": { [DEVS_DN]: [4], [OPS_DN]: [3] },
+ },
+ });
+
+ await userEvent.click(
+ within(findMappingRow(DEVS_DN)!).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 mappingsWrite = puts.findIndex(({ url }) =>
+ /\/api\/setting$/.test(url),
+ );
+ const clearWrite = puts.findIndex(({ url }) =>
+ url.includes("/api/permissions/membership/4/clear"),
+ );
+ expect(puts[mappingsWrite].body).toEqual({
+ "ldap-group-mappings": { [OPS_DN]: [3] },
+ });
+ expect(clearWrite).toBeGreaterThan(mappingsWrite);
+ expect(
+ puts.some(({ url }) =>
+ url.includes("/api/permissions/membership/3/clear"),
+ ),
+ ).toBe(false);
+ await waitFor(() => expect(findMappingRow(DEVS_DN)).toBeUndefined());
+ });
+ });
});
diff --git a/frontend/src/metabase/admin/settings/utils.ts b/frontend/src/metabase/admin/settings/utils.ts
index e77980b4a9d..b826f0f55df 100644
--- a/frontend/src/metabase/admin/settings/utils.ts
+++ b/frontend/src/metabase/admin/settings/utils.ts
@@ -31,3 +31,13 @@ export const getExtraFormFieldProps = (setting?: SettingDefinition) => {
descriptionProps: SETTINGS_FIELD_DESCRIPTION_PROPS,
};
};
+
+// env-locked settings show the readOnly notice instead of a placeholder
+export const getDefaultPlaceholder = (
+ setting?: SettingDefinition,
+): string | undefined => {
+ if (setting?.is_env_setting || typeof setting?.default !== "string") {
+ return undefined;
+ }
+ return setting.default;
+};
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index d56b6c6df85..09495ddcd6b 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -10,6 +10,7 @@ export {
PLUGIN_ADMIN_USER_FORM_FIELDS,
type AuthSettingsPageProps,
type AuthSettingsPageTab,
+ type LdapUserProvisioningProps,
type SettingsJWTFormProps,
} from "./oss/auth";
export {
diff --git a/frontend/src/metabase/plugins/oss/auth.ts b/frontend/src/metabase/plugins/oss/auth.ts
index 70cc172d6d3..27f4e2cff64 100644
--- a/frontend/src/metabase/plugins/oss/auth.ts
+++ b/frontend/src/metabase/plugins/oss/auth.ts
@@ -38,8 +38,12 @@ export const PLUGIN_AUTH_PROVIDERS = definePluginSlot(
getDefaultPluginAuthProviders,
);
+export type LdapUserProvisioningProps = {
+ disabled?: boolean;
+};
+
const getDefaultPluginLdapFormFields = () => ({
- LdapUserProvisioning: PluginPlaceholder,
+ LdapUserProvisioning: PluginPlaceholder<LdapUserProvisioningProps>,
LdapGroupMembershipFilter: PluginPlaceholder,
});
diff --git a/src/metabase/sso/settings.clj b/src/metabase/sso/settings.clj
index 216462a2415..e033485bb6c 100644
--- a/src/metabase/sso/settings.clj
+++ b/src/metabase/sso/settings.clj
@@ -72,7 +72,8 @@
(defsetting ldap-attribute-firstname
(deferred-tru "Attribute to use for the user''s first name. (usually ''givenName'')")
- :default "givenName"
+ ;; kept in the getter's lower case, so an untouched value reads as the default it is
+ :default "givenname"
:getter (fn [] (u/lower-case-en (setting/get-value-of-type :string :ldap-attribute-firstname)))
:encryption :when-encryption-key-set
:audit :getter)
@@ -116,7 +117,10 @@
(doseq [k (keys new-value)]
(when-not (instance? DN k) ; handle DN-encoded keys like we get from the `:getter`
(when-not (DN/isValidDN (u/qualified-name k))
- (throw (IllegalArgumentException. (tru "{0} is not a valid DN." (u/qualified-name k)))))))
+ (throw (ex-info (tru "{0} is not a valid DN. Example: {1}"
+ (u/qualified-name k)
+ "cn=people,ou=groups,dc=example,dc=org")
+ {:status-code 400})))))
(setting/set-value-of-type! :json :ldap-group-mappings new-value)))))
(defsetting ldap-configured?
diff --git a/test/metabase/sso/settings_test.clj b/test/metabase/sso/settings_test.clj
index 2c3bf1d3d56..d4e41d7e933 100644
--- a/test/metabase/sso/settings_test.clj
+++ b/test/metabase/sso/settings_test.clj
@@ -1,6 +1,7 @@
(ns metabase.sso.settings-test
(:require
[clojure.test :refer :all]
+ [metabase.settings.core :as setting]
[metabase.sso.ldap :as ldap]
[metabase.sso.ldap-test-util :as ldap.test]
[metabase.sso.ldap.settings :as sso.ldap.settings]
@@ -24,3 +25,23 @@
(deftest ^:parallel send-new-sso-user-admin-email?-test
(is ((some-fn nil? boolean?) (sso.settings/send-new-sso-user-admin-email?))
"Make sure this Setting returns a boolean, not some other type of value. (It was returning a function before I fixed it.)"))
+
+(deftest ldap-group-mappings-invalid-dn-test
+ (testing "a mapping keyed by something other than a DN is a bad request that names the key and shows an example"
+ (let [before (sso.settings/ldap-group-mappings)]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"^qwf is not a valid DN\. Example: cn=people,ou=groups,dc=example,dc=org$"
+ (sso.settings/ldap-group-mappings! {"qwf" [1]})))
+ (is (= "qwf is not a valid DN. Example: cn=people,ou=groups,dc=example,dc=org"
+ (mt/user-http-request :crowberto :put 400 "setting" {:ldap-group-mappings {"qwf" [1]}})))
+ (testing "the rejected write left the stored mappings alone"
+ (is (= before (sso.settings/ldap-group-mappings)))))))
+
+(deftest ldap-attribute-defaults-read-as-unset-test
+ (testing "an attribute left at its default reports no value, even though its getter lower-cases it"
+ (mt/with-temporary-setting-values [ldap-attribute-email nil
+ ldap-attribute-firstname nil
+ ldap-attribute-lastname nil]
+ (doseq [k [:ldap-attribute-email :ldap-attribute-firstname :ldap-attribute-lastname]]
+ (testing k
+ (is (nil? (setting/user-facing-value k))))))))