The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Redesigned the SAML and OIDC settings pages (#82449)
Andrei Chernykhe4055bbfe4c4
diff --git a/e2e/support/config.js b/e2e/support/config.jsindex eefc280967c..c629f1f6ee7 100644--- a/e2e/support/config.js+++ b/e2e/support/config.js@@ -40,6 +40,10 @@ import {startMockLlmServer,stopMockLlmServer,} from "./helpers/e2e-mock-llm-tasks";+import {+ startMockOidcServer,+ stopMockOidcServer,+} from "./helpers/e2e-mock-oidc-tasks";const createBundler = require("@bahmutov/cypress-esbuild-preprocessor"); // This function is called when a project is opened or re-opened (e.g. due to the project's config changing)const coverageTask = require("@cypress/code-coverage/task");@@ -302,6 +306,8 @@ const defaultConfig = {requestAsAdmin,startMockLlmServer,stopMockLlmServer,+ startMockOidcServer,+ stopMockOidcServer,startCustomVizDevServer,stopCustomVizDevServer,buildDataApp,diff --git a/e2e/support/helpers/e2e-mock-oidc-tasks.ts b/e2e/support/helpers/e2e-mock-oidc-tasks.tsnew file mode 100644index 00000000000..ea5a068fda0--- /dev/null+++ b/e2e/support/helpers/e2e-mock-oidc-tasks.ts@@ -0,0 +1,67 @@+import http from "node:http";++let server: http.Server | null = null;++type MockOidcServerOptions = {+ port: number;+};++/** Start a mock OIDC identity provider that answers the backend's connection check. */+export function startMockOidcServer({+ port,+}: MockOidcServerOptions): Promise<null> {+ return new Promise((resolve, reject) => {+ if (server) {+ server.close();+ server = null;+ }++ const issuer = `http://localhost:${port}`;++ server = http.createServer((req, res) => {+ if (+ req.method === "GET" &&+ req.url === "/.well-known/openid-configuration"+ ) {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(+ JSON.stringify({+ issuer,+ authorization_endpoint: `${issuer}/authorize`,+ token_endpoint: `${issuer}/token`,+ jwks_uri: `${issuer}/jwks`,+ }),+ );+ return;+ }++ if (req.method === "POST" && req.url === "/token") {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(+ JSON.stringify({+ access_token: "mock-access-token",+ token_type: "Bearer",+ }),+ );+ return;+ }++ res.writeHead(404);+ res.end();+ });++ server.on("error", reject);+ server.listen(port, () => resolve(null));+ });+}++export function stopMockOidcServer(): Promise<null> {+ return new Promise((resolve) => {+ if (server) {+ server.close(() => resolve(null));+ server = null;+ } else {+ resolve(null);+ }+ });+}diff --git a/e2e/test/scenarios/admin/authentication.cy.spec.ts b/e2e/test/scenarios/admin/authentication.cy.spec.tsindex dfb580d626f..206df1bbe7c 100644--- a/e2e/test/scenarios/admin/authentication.cy.spec.ts+++ b/e2e/test/scenarios/admin/authentication.cy.spec.ts@@ -1,6 +1,6 @@const { H } = cy;-import { setupSaml } from "./sso/shared/helpers.js";+import { setupSaml } from "./sso/shared/helpers";describe("scenarios > admin > settings > user provisioning", () => {beforeEach(() => {diff --git a/e2e/test/scenarios/admin/sso/jwt.cy.spec.js b/e2e/test/scenarios/admin/sso/jwt.cy.spec.tssimilarity index 80%rename from e2e/test/scenarios/admin/sso/jwt.cy.spec.jsrename to e2e/test/scenarios/admin/sso/jwt.cy.spec.tsindex 3e42ce16957..4c1dcff849d 100644--- a/e2e/test/scenarios/admin/sso/jwt.cy.spec.js+++ b/e2e/test/scenarios/admin/sso/jwt.cy.spec.ts@@ -1,5 +1,24 @@const { H } = cy;+import { USER_GROUPS } from "e2e/support/cypress_data";import { enableJwtAuth } from "e2e/support/helpers/e2e-jwt-helpers";+import type { GroupListQuery } from "metabase-types/api";++import { groupMappingCardHelpers } from "./shared/group-mapping-card";++const { ADMIN_GROUP, NOSQL_GROUP, READONLY_GROUP } = USER_GROUPS;++const {+ groupMappingSection,+ mappingRow,+ newMappingButton,+ groupsPicker,+ addMapping,+ deleteMapping,+} = groupMappingCardHelpers({+ sectionTestId: "jwt-group-schema",+ nameLabel: "JWT group name",+ newMappingLabel: "New mapping",+});describe("scenarios > admin > settings > SSO > JWT", () => {beforeEach(() => {@@ -118,6 +137,12 @@ describe("scenarios > admin > settings > SSO > JWT", () => {"Remove mapping and delete groups",);cy.wait(["@deleteGroup", "@deleteGroup"]);+ cy.wait("@updateSettings")+ .its("request.body.jwt-group-mappings")+ .should("deep.equal", {+ "cn=People1": [ADMIN_GROUP, NOSQL_GROUP],+ "cn=People3": [READONLY_GROUP],+ });mappingRow("cn=People1").should("contain", "Administrators, nosql");mappingRow("cn=People3").should("contain", "readonly")@@ -160,16 +185,18 @@ describe("scenarios > admin > settings > SSO > JWT", () => {.should("be.checked");cy.log("Deleted groups are gone and cleared groups have no members");- cy.request("GET", "/api/permissions/group").then(({ body: groups }) => {- const names = groups.map((group) => group.name);- expect(names).to.include.members(["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);- });+ cy.request<GroupListQuery[]>("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: string) =>+ groups.find((group) => group.name === name)?.member_count;+ expect(memberCount("nosql")).to.equal(0);+ expect(memberCount("readonly")).to.equal(0);+ },+ );cy.log("Switching to automatic asks for confirmation and deletes the mappings",@@ -211,40 +238,11 @@ const getJwtCard = () => {.parent();};-const groupMappingSection = () => cy.findByTestId("jwt-group-schema");--const mappingRow = (name) =>- cy.contains('[data-testid="jwt-group-mapping-row"]', name);--const newMappingButton = () => cy.button("New mapping");--const groupsPicker = () => cy.findByLabelText("Metabase groups");-// the segmented control keeps its radio inputs hidden, so the visible label takes the click-const selectGroupMappingMode = (mode) => {- groupMappingSection().findByText(mode).click();-};--// adding a mapping saves it right away, so wait for that write before moving on-const addMapping = (name, groups) => {- newMappingButton().click();- cy.findByLabelText("JWT group name").type(name);- groupsPicker().click();- groups.forEach((group) => {- cy.findByRole("option", { name: group }).click();- });- cy.button("Add mapping").click();- cy.wait("@updateSettings");- mappingRow(name).should("contain", groups.join(", "));-};--const deleteMapping = (name, consequenceLabel, confirmLabel) => {- mappingRow(name).findByLabelText("Delete mapping").click();- H.modal().within(() => {- cy.findByText("Remove this group mapping?").should("be.visible");- cy.findByText(consequenceLabel).click();- cy.button(confirmLabel).click();- });- cy.wait("@updateSettings");- mappingRow(name).should("not.exist");+const selectGroupMappingMode = (mode: string) => {+ // a click during a write is ignored, so wait for the control to be free first+ groupMappingSection()+ .contains("label", mode)+ .should("not.have.attr", "data-read-only");+ groupMappingSection().contains("label", mode).click();};diff --git a/e2e/test/scenarios/admin/sso/ldap.cy.spec.js b/e2e/test/scenarios/admin/sso/ldap.cy.spec.tssimilarity index 76%rename from e2e/test/scenarios/admin/sso/ldap.cy.spec.jsrename to e2e/test/scenarios/admin/sso/ldap.cy.spec.tsindex ce477cd8aef..44d1d7b088a 100644--- a/e2e/test/scenarios/admin/sso/ldap.cy.spec.js+++ b/e2e/test/scenarios/admin/sso/ldap.cy.spec.ts@@ -1,5 +1,26 @@const { H } = cy;+import { USER_GROUPS } from "e2e/support/cypress_data";+import type { GroupListQuery } from "metabase-types/api";++import { groupMappingCardHelpers } from "./shared/group-mapping-card";++const { ADMIN_GROUP, NOSQL_GROUP, READONLY_GROUP } = USER_GROUPS;++const {+ groupMappingSection,+ groupMappingSwitch,+ mappingRow,+ newMappingButton,+ groupsPicker,+ toggleGroupMapping,+ addMapping,+ deleteMapping,+} = groupMappingCardHelpers({+ sectionTestId: "ldap-group-mapping-section",+ nameLabel: "LDAP group name",+});+describe("scenarios > admin > settings > SSO > LDAP",{ tags: "@external" },@@ -55,7 +76,7 @@ describe(getLdapCard().findByText("Set up").should("exist");});- it("should validate the port, not reset previously populated fields when schema or connection validation fails, and setup ldap once the port is valid (metabase#13313, metabase#16173, metabase#16226)", () => {+ it("should validate the port, not reset previously populated fields when connection validation fails, and setup ldap once the port is valid (metabase#13313, metabase#16173, metabase#16226)", () => {cy.visit("/admin/settings/authentication/ldap");cy.findByLabelText(/LDAP Port/i)@@ -71,21 +92,12 @@ describe(enterLdapPort("21.3");cy.get("@portSection")- .findByText("ldap-port must be an integer")+ .findByText("Port must be a whole number between 1 and 65535").should("be.visible");- cy.log("Schema validation error (metabase#16226)");- enterLdapPort("0");- cy.button("Save and enable").click();- cy.wait("@updateLdapSettings");-- cy.findAllByText("nullable integer greater than 0").should("exist");- cy.findByDisplayValue("localhost").should("exist");-cy.log("Connection validation error (metabase#16226)");enterLdapPort("1");- // the submit button reads "Failed" for 5s after a rejected save- cy.button(/Save and enable|Failed/).click();+ cy.button("Save and enable").click();cy.wait("@updateLdapSettings");cy.findAllByText("Wrong host or port").should("exist");@@ -96,7 +108,7 @@ describe();enterLdapPort("389 ");cy.get("@portSection")- .findByText("That's not a valid port number")+ .findByText("Port must be a whole number between 1 and 65535").should("not.exist");// the submit button can still read "Failed" from the rejected save above@@ -132,7 +144,7 @@ describe(});it("should delete or clear mapped groups with their mappings and keep the remaining mappings consistent", () => {- turnGroupMappingOn();+ toggleGroupMapping(true);addMapping("cn=People1", ["Administrators", "data", "nosql"]);addMapping("cn=People2", ["data", "collection"]);addMapping("cn=People3", ["collection", "readonly"]);@@ -146,6 +158,12 @@ describe("Remove mapping and delete groups",);cy.wait(["@deleteGroup", "@deleteGroup"]);+ cy.wait("@updateSettings")+ .its("request.body.ldap-group-mappings")+ .should("deep.equal", {+ "cn=People1": [ADMIN_GROUP, NOSQL_GROUP],+ "cn=People3": [READONLY_GROUP],+ });mappingRow("cn=People1").should("contain", "Administrators, nosql");mappingRow("cn=People3").should("contain", "readonly")@@ -188,16 +206,18 @@ describe(.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);- });+ cy.request<GroupListQuery[]>("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: string) =>+ groups.find((group) => group.name === name)?.member_count;+ expect(memberCount("nosql")).to.equal(0);+ expect(memberCount("readonly")).to.equal(0);+ },+ );});});},@@ -287,55 +307,7 @@ 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) => {+const enterLdapPort = (value: string) => {H.typeAndBlurUsingLabel(/LDAP Port/i, value);};diff --git a/e2e/test/scenarios/admin/sso/oidc.cy.spec.ts b/e2e/test/scenarios/admin/sso/oidc.cy.spec.tsnew file mode 100644index 00000000000..4bbdad4fb42--- /dev/null+++ b/e2e/test/scenarios/admin/sso/oidc.cy.spec.ts@@ -0,0 +1,111 @@+const { H } = cy;++import { groupMappingCardHelpers } from "./shared/group-mapping-card";++const MOCK_IDP_PORT = 6130;+const ISSUER_URI = `http://localhost:${MOCK_IDP_PORT}`;++const {+ groupMappingSwitch,+ mappingRow,+ toggleGroupMapping,+ addMapping,+ deleteMapping,+} = groupMappingCardHelpers({+ sectionTestId: "oidc-group-mapping-section",+ nameLabel: "OIDC group name",+ switchRequestAlias: "updateProvider",+ switchValuePath: "group-sync.enabled",+ mappingsRequestAlias: "updateProvider",+});++describe("scenarios > admin > settings > SSO > OIDC", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("pro-self-hosted");+ cy.task("startMockOidcServer", { port: MOCK_IDP_PORT });+ cy.intercept("POST", "/api/ee/sso/oidc/check").as("checkConnection");+ cy.intercept("POST", "/api/ee/sso/oidc").as("createProvider");+ cy.intercept("PUT", "/api/ee/sso/oidc/*").as("updateProvider");+ });++ afterEach(() => {+ cy.task("stopMockOidcServer");+ });++ it("should check the connection, then save and enable a provider", () => {+ cy.visit("/admin/settings/authentication/oidc");+ enterProviderSettings();++ cy.log("The check runs on its own against the identity provider");+ cy.button("Check connection").click();+ cy.wait("@checkConnection");+ H.undoToast().findByText("OIDC connection is valid").should("be.visible");++ cy.log("Saving checks again and creates the provider with group sync off");+ cy.button("Save and enable").click();+ cy.wait("@checkConnection");+ cy.wait("@createProvider").its("request.body.key").should("equal", "okta");++ cy.log("The page switches to its configured state");+ cy.button("Success").should("be.visible");+ cy.findByLabelText(/^Key/).should("be.disabled");+ groupMappingSwitch().should("be.enabled").and("not.be.checked");+ });++ describe("Group mapping", () => {+ beforeEach(() => {+ cy.intercept("DELETE", "/api/permissions/group/*").as("deleteGroup");+ setupOidcProvider();+ cy.visit("/admin/settings/authentication/oidc");+ });++ it("should save the switch and the mappings through the provider and keep them after a reload", () => {+ toggleGroupMapping(true);+ addMapping("engineering", ["data", "nosql"]);++ cy.log("Everything comes back after a reload");+ cy.reload();+ groupMappingSwitch().should("be.checked");+ mappingRow("engineering").should("contain", "data, nosql");++ cy.log("Deleting a mapping takes its groups with it");+ deleteMapping(+ "engineering",+ /delete the groups/i,+ "Remove mapping and delete groups",+ );+ cy.wait(["@deleteGroup", "@deleteGroup"]);++ cy.log("Turning group mapping off sticks");+ toggleGroupMapping(false);+ cy.reload();+ groupMappingSwitch().should("not.be.checked");+ });+ });+});++const setupOidcProvider = () => {+ cy.request("PUT", "/api/setting/oidc-providers", {+ value: [+ {+ key: "okta",+ "login-prompt": "Sign in with Okta",+ "issuer-uri": ISSUER_URI,+ "client-id": "metabase-client-id",+ "client-secret": "metabase-client-secret",+ enabled: true,+ scopes: ["openid", "email", "profile"],+ },+ ],+ });+};++const enterProviderSettings = () => {+ H.typeAndBlurUsingLabel(/^Key/, "okta");+ H.typeAndBlurUsingLabel(/^Login prompt/, "Sign in with Okta");+ H.typeAndBlurUsingLabel(/^Issuer URI/, ISSUER_URI);+ H.typeAndBlurUsingLabel(/^Client ID/, "metabase-client-id");+ H.typeAndBlurUsingLabel(/^Client secret/, "metabase-client-secret");+};diff --git a/e2e/test/scenarios/admin/sso/saml.cy.spec.js b/e2e/test/scenarios/admin/sso/saml.cy.spec.tssimilarity index 67%rename from e2e/test/scenarios/admin/sso/saml.cy.spec.jsrename to e2e/test/scenarios/admin/sso/saml.cy.spec.tsindex c00d0193528..d41112a3a52 100644--- a/e2e/test/scenarios/admin/sso/saml.cy.spec.js+++ b/e2e/test/scenarios/admin/sso/saml.cy.spec.ts@@ -1,8 +1,19 @@const { H } = cy;-import { checkGroupMappingsWidget } from "./shared/group-mappings-widget";+import { groupMappingCardHelpers } from "./shared/group-mapping-card";import { getSamlCertificate, setupSaml } from "./shared/helpers";+const {+ groupMappingSwitch,+ mappingRow,+ toggleGroupMapping,+ addMapping,+ deleteMapping,+} = groupMappingCardHelpers({+ sectionTestId: "saml-group-mapping-section",+ nameLabel: "SAML group name",+});+describe("scenarios > admin > settings > SSO > SAML", () => {beforeEach(() => {H.restore();@@ -69,9 +80,8 @@ describe("scenarios > admin > settings > SSO > SAML", () => {setupSaml();cy.visit("/admin/settings/authentication/saml");- 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();cy.wait("@updateSetting");H.undoToast().findByText("Changes saved").should("exist");cy.findByRole("switch", { name: "User provisioning" }).should(@@ -79,18 +89,43 @@ describe("scenarios > admin > settings > SSO > SAML", () => {);});- 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",- );+ setupSaml();+ cy.visit("/admin/settings/authentication/saml");});- it("should allow deleting mappings along with deleting, or clearing users of, mapped groups, while keeping remaining mappings consistent", () => {- checkGroupMappingsWidget("saml");+ it("should save the switch and the mappings on their own and the group attribute with the form", () => {+ toggleGroupMapping(true);+ addMapping("engineering", ["data", "nosql"]);++ cy.log("The group attribute saves with the page form");+ cy.findByLabelText(/Group attribute name/).type("memberOf");+ cy.button("Save changes").click();+ cy.wait("@updateSamlSettings");++ cy.log("Everything comes back after a reload");+ cy.reload();+ groupMappingSwitch().should("be.checked");+ mappingRow("engineering").should("contain", "data, nosql");+ cy.findByLabelText(/Group attribute name/).should(+ "have.value",+ "memberOf",+ );++ cy.log("Deleting a mapping takes its groups with it");+ deleteMapping(+ "engineering",+ /delete the groups/i,+ "Remove mapping and delete groups",+ );+ cy.wait(["@deleteGroup", "@deleteGroup"]);++ cy.log("Turning group mapping off sticks");+ toggleGroupMapping(false);+ cy.reload();+ groupMappingSwitch().should("not.be.checked");});});});diff --git a/e2e/test/scenarios/admin/sso/shared/group-mapping-card.ts b/e2e/test/scenarios/admin/sso/shared/group-mapping-card.tsnew file mode 100644index 00000000000..56a0146c603--- /dev/null+++ b/e2e/test/scenarios/admin/sso/shared/group-mapping-card.ts@@ -0,0 +1,81 @@+const { H } = cy;++type GroupMappingCardOptions = {+ sectionTestId: string;+ nameLabel: string;+ newMappingLabel?: string;+ switchRequestAlias?: string;+ switchValuePath?: string;+ mappingsRequestAlias?: string;+};++/** The calling spec must alias the intercepts these helpers wait on. */+export const groupMappingCardHelpers = ({+ sectionTestId,+ nameLabel,+ newMappingLabel = "New",+ switchRequestAlias = "updateSetting",+ switchValuePath = "value",+ mappingsRequestAlias = "updateSettings",+}: GroupMappingCardOptions) => {+ const groupMappingSection = () => cy.findByTestId(sectionTestId);++ const groupMappingSwitch = () =>+ cy.findByRole("switch", { name: "Group mapping" });++ const mappingRow = (name: string) =>+ cy.contains('[data-testid="group-mapping-row"]', name);++ const newMappingButton = () =>+ groupMappingSection().findByRole("button", { name: newMappingLabel });++ const groupsPicker = () => cy.findByLabelText("Metabase groups");++ const toggleGroupMapping = (enabled: boolean) => {+ groupMappingSwitch().should(enabled ? "not.be.checked" : "be.checked");+ // a click during a write is ignored, so wait for the switch to be free first+ groupMappingSwitch().should("not.have.attr", "aria-disabled");+ groupMappingSection().contains("label", "Group mapping").click();+ cy.wait(`@${switchRequestAlias}`)+ .its(`request.body.${switchValuePath}`)+ .should("equal", enabled);+ };++ const addMapping = (name: string, groups: string[]) => {+ newMappingButton().click();+ cy.findByLabelText(nameLabel).type(name);+ groupsPicker().click();+ groups.forEach((group) => {+ cy.findByRole("option", { name: group }).click();+ });+ cy.button("Add mapping").click();+ cy.wait(`@${mappingsRequestAlias}`);+ mappingRow(name).should("contain", groups.join(", "));+ };++ const deleteMapping = (+ name: string,+ consequenceLabel: string | RegExp,+ confirmLabel: string,+ ) => {+ 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(`@${mappingsRequestAlias}`);+ mappingRow(name).should("not.exist");+ };++ return {+ groupMappingSection,+ groupMappingSwitch,+ mappingRow,+ newMappingButton,+ groupsPicker,+ toggleGroupMapping,+ addMapping,+ deleteMapping,+ };+};diff --git a/e2e/test/scenarios/admin/sso/shared/group-mappings-widget.js b/e2e/test/scenarios/admin/sso/shared/group-mappings-widget.jsdeleted file mode 100644index 9a945777322..00000000000--- a/e2e/test/scenarios/admin/sso/shared/group-mappings-widget.js+++ /dev/null@@ -1,134 +0,0 @@-export function checkGroupMappingsWidget(authenticationMethod) {- cy.visit("/admin/settings/authentication/" + authenticationMethod);- cy.wait("@getSettings");- cy.wait("@getSessionProperties");-- createMapping("cn=People1");- addGroupsToMapping("cn=People1", ["Administrators", "data", "nosql"]);-- createMapping("cn=People2");- // Administrators is never deleted along with a mapping's groups, so- // cn=People1 keeps it below- addGroupsToMapping("cn=People2", ["Administrators", "data", "collection"]);-- createMapping("cn=People3");- addGroupsToMapping("cn=People3", ["collection", "readonly"]);-- cy.log(- "Deleting a mapping with its groups keeps the remaining mappings consistent",- );- deleteMapping(- "cn=People2",- /delete the groups/i,- "Remove mapping and delete groups",- );- cy.wait(["@deleteGroup", "@deleteGroup"]);-- // Scope to the table: the group dropdown is portaled, so a group name can- // also show up as an option outside the table.- cy.findByTestId("admin-content-table").within(() => {- // cn=People1 will have Admin and nosql as groups- cy.findByText("1 other group");- // cn=People3 will have readonly as group- cy.findByText("readonly");- });-- cy.log("Deleted groups are no longer offered for mappings");- mappingRow("cn=People3").findByText("readonly").click();- cy.findByRole("option", { name: "readonly" }).should("exist");- cy.findByRole("option", { name: "data" }).should("not.exist");- cy.findByRole("option", { name: "collection" }).should("not.exist");- cy.realPress("{esc}");-- cy.log("Mappings are as expected after a page reload");- cy.visit("/admin/settings/authentication/" + authenticationMethod);- cy.findByTestId("admin-content-table").within(() => {- cy.findByText("1 other group");- cy.findByText("readonly");- });-- cy.log(- "Deleting mappings while clearing their groups empties the groups, skipping Administrators",- );- 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");-- cy.visit("/admin/people/groups");- cy.findByText("data").should("not.exist");- cy.findByText("collection").should("not.exist");-- checkThatGroupHasNoMembers("nosql");- checkThatGroupHasNoMembers("readonly");-}--const mappingRow = (mappingName) => cy.findByText(mappingName).closest("tr");--const deleteMapping = (mappingName, consequenceLabel, confirmLabel) => {- mappingRow(mappingName).within(() => {- cy.icon("close").click({ force: true });- });-- cy.findByText(consequenceLabel).click();- cy.button(confirmLabel).click();-- // Removing the mapping PUTs the setting and invalidates session properties,- // triggering a refetch. Wait for both to settle so this trailing refetch- // can't land mid-flight during a later mapping's edits and revert its state- // (same last-write-wins hazard guarded against in addGroupsToMapping).- cy.wait("@updateSetting");- cy.wait("@getSessionProperties");-};--const createMapping = (name) => {- cy.button("New mapping").click();- cy.findByLabelText("New group mapping name").type(name);- cy.button("Add").click();-- // Adding the mapping PUTs the setting and triggers a session-properties- // refetch. Wait for both so the widget's mappings state is fully settled- // from a completed round-trip before we start adding groups to it.- cy.wait("@updateSetting");- cy.wait("@getSessionProperties");-};--const addGroupsToMapping = (mappingName, groups) => {- mappingRow(mappingName).within(() => {- cy.findByText("Default").click();- });-- groups.forEach((group) => {- cy.findByRole("option", { name: group }).click();-- // Each selection PUTs the mapping (built from the widget's current mappings- // cache) and invalidates session properties, triggering a refetch. If the- // next selection fires before this round-trip settles, a trailing stale- // refetch can revert the just-added group in the cache and the next PUT is- // then built from that stale set, dropping the group server-side- // (last-write-wins). Fewer groups then remain than the test deletes, so- // fewer deleteGroup requests fire and cy.wait times out. Wait for the PUT- // and the trailing refetch to settle before picking the next group.- cy.wait("@updateSetting");- cy.wait("@getSessionProperties");- cy.findByRole("option", { name: group })- .find("input[type=checkbox]")- .should("be.checked");- });-- cy.realPress("{esc}");-};--const checkThatGroupHasNoMembers = (name) => {- cy.findByText(name)- .closest("tr")- .within(() => cy.findByText("0"));-};diff --git a/e2e/test/scenarios/admin/sso/shared/helpers.js b/e2e/test/scenarios/admin/sso/shared/helpers.tssimilarity index 100%rename from e2e/test/scenarios/admin/sso/shared/helpers.jsrename to e2e/test/scenarios/admin/sso/shared/helpers.tsdiff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.cljindex 24d80e84181..790e4d65e90 100644--- a/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj@@ -7,6 +7,7 @@[metabase.auth-identity.core :as auth-identity][metabase.premium-features.core :as premium-features][metabase.sso.core :as sso]+ [metabase.util :as u][metabase.util.i18n :refer [tru]][methodical.core :as methodical]))@@ -24,15 +25,14 @@(when (and (:client-id provider-config)(:client-secret provider-config)(:issuer-uri provider-config))- (let [attribute-map (:attribute-map provider-config)]+ ;; the stored setting decodes with keyword keys, and a blank claim falls back to the default+ (let [attribute-map (update-vals (update-keys (:attribute-map provider-config) name) u/not-blank)]+ ;; the email picks the account, and email_verified only covers the standard claim, so it is never remapped(cond-> {:client-id (:client-id provider-config):client-secret (:client-secret provider-config):issuer-uri (:issuer-uri provider-config):scopes (or (:scopes provider-config) ["openid" "email" "profile"]):redirect-uri (:redirect-uri request)}- (get attribute-map "email")- (assoc :attribute-email (get attribute-map "email"))-(get attribute-map "first_name")(assoc :attribute-firstname (get attribute-map "first_name"))@@ -103,9 +103,7 @@(get claims group-attribute)))](when (and user-groups group-mappings (:user result))(let [groups-to-sync (if (sequential? user-groups) user-groups [user-groups])]- (if (empty? group-mappings)- (sso/sync-group-memberships! (:user result) (sso-utils/group-names->ids groups-to-sync group-mappings))- (sso/sync-group-memberships! (:user result)- (sso-utils/group-names->ids groups-to-sync group-mappings)- (sso-utils/all-mapped-group-ids group-mappings))))))))))+ (sso/sync-group-memberships! (:user result)+ (sso-utils/group-names->ids groups-to-sync group-mappings)+ (sso-utils/all-mapped-group-ids group-mappings)))))))))result)diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.cljindex e8158a0a08b..f6cd8093438 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj@@ -1,11 +1,16 @@(ns metabase-enterprise.sso.integrations.oidc-test(:require+ [clj-http.client :as http][clojure.string :as str][clojure.test :refer :all][metabase-enterprise.sso.integrations.oidc :as oidc-integration]+ [metabase-enterprise.sso.providers.oidc :as oidc.provider]+ [metabase-enterprise.sso.settings :as sso-settings][metabase-enterprise.sso.test-setup :as sso.test-setup][metabase.auth-identity.core :as auth-identity]+ [metabase.sso.oidc.discovery :as oidc.discovery][metabase.sso.oidc.state :as oidc.state]+ [metabase.sso.oidc.tokens :as oidc.tokens][metabase.sso.test-helpers :as sso.test-helpers][metabase.test :as mt][metabase.test.fixtures :as fixtures]@@ -306,6 +311,24 @@;; All Users group (id=1) is the only group(is (= #{1} (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (:id user)))))))))))+(deftest oidc-group-sync-empty-mappings-keep-memberships-test+ (testing "Empty mappings leave a returning user's memberships alone, since only mapped groups are synced"+ (let [email (str "oidc-keep-" (random-uuid) "@example.com")]+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name (str "OIDC Unmapped Group " (random-uuid))}+ :model/User {user-id :id} {:email email}+ :model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}]+ (let [provider-config (assoc test-provider+ :group-sync {:enabled true+ :group-attribute "groups"+ :group-mappings {}})]+ (do-with-group-sync-login!+ provider-config {:groups ["test-group"]} email+ (fn [result]+ (is (true? (:success? result)) (str "login result: " (pr-str result)))+ (testing "the unmapped group membership survives the login and nothing else is added"+ (is (= #{1 group-id}+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id)))))))))))+(deftest oidc-group-sync-single-string-value-test(testing "Single group value (string instead of array) should still work"(mt/with-temp [:model/PermissionsGroup {group-id :id} {:name (str "OIDC String Group " (random-uuid))}]@@ -356,6 +379,52 @@(is (contains? group-ids group-a-id))(is (not (contains? group-ids group-b-id)))))))))))+(deftest authenticate-ignores-custom-email-claim-test+ (testing "login takes the email from the standard claim that email_verified covers, whatever the provider maps"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values+ [oidc-providers [(assoc test-provider :attribute-map {"email" "mail"+ "first_name" "gn"})]]+ (mt/with-dynamic-fn-redefs [oidc.discovery/discover-oidc-configuration+ (fn [_issuer]+ {:authorization_endpoint "https://test.idp.example.com/authorize"+ :token_endpoint "https://test.idp.example.com/token"+ :jwks_uri "https://test.idp.example.com/jwks"})+ http/post+ (fn [_url _opts]+ {:status 200+ :body {:id_token "valid-token"+ :access_token "access-token"}})+ oidc.tokens/validate-id-token+ (fn [_token _config _nonce]+ {:valid? true+ :claims {:sub "sam-rivera"+ :email "[email protected]"+ :email_verified true+ :mail "[email protected]"+ :gn "Sam"}})]+ (let [result (auth-identity/authenticate :provider/custom-oidc+ {:oidc-provider-key "test-idp"+ :code "auth-code"+ :state "state-token"+ :redirect-uri "http://localhost/auth/sso/test-idp/callback"})]+ (is (true? (:success? result)) (str "authenticate result: " (pr-str (dissoc result :claims))))+ (is (= "[email protected]" (get-in result [:user-data :email])))+ (testing "the name claims still follow the mapping"+ (is (= "Sam" (get-in result [:user-data :first_name]))))))))))++(deftest build-oidc-config-attribute-map-test+ (testing "a blank claim name counts as unset, and the email claim is never remapped"+ (mt/with-additional-premium-features #{:sso-oidc}+ (mt/with-temporary-setting-values+ [oidc-providers [(assoc test-provider :attribute-map {"email" "mail"+ "first_name" " "+ "last_name" "sn"})]]+ (let [stored (sso-settings/get-oidc-provider "test-idp")+ config (#'oidc.provider/build-oidc-config stored {:redirect-uri "http://localhost/callback"})]+ (is (= {:attribute-lastname "sn"}+ (select-keys config [:attribute-email :attribute-firstname :attribute-lastname]))))))))+(deftest oidc-group-sync-custom-attribute-test(testing "Non-default group attribute — using a custom claim name"(mt/with-temp [:model/PermissionsGroup {group-id :id} {:name (str "OIDC Custom Attr Group " (random-uuid))}]diff --git a/enterprise/frontend/src/metabase-enterprise/api/oidc.ts b/enterprise/frontend/src/metabase-enterprise/api/oidc.tsindex c859bf297f0..9dea932cc9c 100644--- a/enterprise/frontend/src/metabase-enterprise/api/oidc.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/oidc.ts@@ -1,4 +1,5 @@import { invalidateTags, tag } from "metabase/api/tags";+import type { GroupMappings } from "metabase-types/api";import { EnterpriseApi } from "./api";@@ -35,7 +36,7 @@ export interface CustomOidcConfig {"group-sync"?: {enabled?: boolean;"group-attribute"?: string;- "group-mappings"?: Record<string, number[]>;+ "group-mappings"?: GroupMappings;};}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/Ldap.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/Ldap.tsxindex cff1fdb7c15..f511801bafd 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/Ldap.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/Ldap.tsx@@ -5,16 +5,14 @@ import {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({ disabled }: LdapUserProvisioningProps) {+export function LdapUserProvisioning() {return (<UserProvisioningSectionsettingKey="ldap-user-provisioning-enabled?"providerName="LDAP"- disabled={disabled}/>);}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.module.css b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.module.cssdeleted file mode 100644index 2e922971670..00000000000--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.module.css+++ /dev/null@@ -1,46 +0,0 @@-.mappingRow {- border: 1px solid var(--mb-color-border-neutral);- border-radius: var(--mantine-radius-sm);- padding: var(--mantine-spacing-lg);-}--.mappingRow:hover {- background-color: var(--mb-color-background_surface-hover);-}--.wrappableText {- overflow-wrap: anywhere;-}--.rowActions {- opacity: 0;-}--.mappingRow:hover .rowActions,-.mappingRow:focus-within .rowActions {- opacity: 1;-}--/* no hover on touch devices, so the actions stay visible there */-@media (hover: none) {- .rowActions {- opacity: 1;- }-}--/* Mantine reserves 100px for the search field, which pushes it under the first pill in a narrow picker */-.groupsSearchField {- min-width: 3rem;-}--/* the editor row measures itself, so the arrow can go before the picker has to wrap under the name */-.editorRow {- container-type: inline-size;-}--/* the name field, the arrow, the picker and their gaps need 27rem to share a line */-@container (max-width: 27rem) {- .editorArrow {- display: none;- }-}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/JWTGroupMappingSection.tsxindex 5b1b7e601e2..614e04f3c5c 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,204 +1,148 @@-import { useState } from "react";import { t } from "ttag";import {+ GroupMappingList,useGroupLookup,- withMappingEntry,+ useMappingDeletion,+ useMappingEditor,} from "metabase/admin/settings/auth/components/GroupMappings";-import { DeleteGroupMappingModal } from "metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal";import { ConfirmModal } from "metabase/common/components/ConfirmModal";-import { getGroupNameLocalized } from "metabase/common/utils/groups";import { useSelector } from "metabase/redux";import { getApplicationName } from "metabase/selectors/whitelabel";import { Button, Flex, Icon, SegmentedControl, Stack, Text } from "metabase/ui";-import { type EditorState, MappingEditorRow } from "./MappingEditorRow";-import { MappingRow } from "./MappingRow";import {type JWTGroupSyncMode,useGroupMappingMode,} from "./use-group-mapping-mode";import { useGroupMappingSettings } from "./use-group-mapping-settings";-import { useMappingDeletion } from "./use-mapping-deletion";-export function JWTGroupMappingSection({- isServerConfigured,- lockedEnvNames = [],-}: {+type JWTGroupMappingSectionProps = {// until the server settings are saved, the section is read-onlyisServerConfigured: boolean;// env vars that configure the section, which then renders read-onlylockedEnvNames?: string[];-}) {+};++export function JWTGroupMappingSection({+ isServerConfigured,+ lockedEnvNames = [],+}: JWTGroupMappingSectionProps) {const applicationName = useSelector(getApplicationName);const groupLookup = useGroupLookup();const groupMapping = useGroupMappingSettings();- const deletion = useMappingDeletion({ groupMapping, groupLookup });const modeSwitch = useGroupMappingMode(groupMapping);- const isBusy = groupMapping.isSaving || deletion.isDeleting;- const [editor, setEditor] = useState<EditorState | null>(null);++ const editor = useMappingEditor({+ mappings: groupMapping.mappings,+ saveMappings: (mappings, options) =>+ groupMapping.saveSettings(+ { "jwt-group-sync": true, "jwt-group-mappings": mappings },+ options,+ ),+ groupLookup,+ });+ const deletion = useMappingDeletion({+ mappings: groupMapping.mappings,+ // deleting the last mapping turns sync off, otherwise the backend falls back to matching by name+ saveMappings: (mappings, options) =>+ groupMapping.saveSettings(+ Object.keys(mappings).length === 0+ ? { "jwt-group-mappings": mappings, "jwt-group-sync": false }+ : { "jwt-group-mappings": mappings },+ options,+ ),+ groupLookup,+ });+ // a settings refetch still in flight could overwrite a new write, so the section waits for it too+ const isBusy =+ groupMapping.isSaving ||+ groupMapping.isAdminSettingsFetching ||+ deletion.isDeleting;+ const isListHeld = isBusy || !groupLookup.isLoaded;const isLocked = lockedEnvNames.length > 0;const isReadOnly = isLocked || !isServerConfigured;-- const trimmedJwtGroupName = editor?.jwtGroupName.trim() ?? "";- const isDuplicateName =- editor != null &&- Object.hasOwn(groupMapping.mappings, trimmedJwtGroupName) &&- trimmedJwtGroupName !== editor.originalJwtGroupName;- const canSaveMapping =- editor != null &&- trimmedJwtGroupName !== "" &&- editor.groupValues.length > 0 &&- !isDuplicateName;-- const saveMapping = async () => {- if (editor == null || !canSaveMapping) {- return;- }- const isNewMapping = editor.originalJwtGroupName == null;- const saved = await groupMapping.saveSettings(- {- "jwt-group-sync": true,- "jwt-group-mappings": withMappingEntry(- groupMapping.mappings,- editor.originalJwtGroupName,- trimmedJwtGroupName,- editor.groupValues.map(Number),- ),- },- {- successMessage: isNewMapping ? t`Mapping added` : t`Mapping updated`,- },- );- if (saved) {- setEditor(null);- }- };-- const groupOptions = groupLookup.mappableGroups.map((group) => ({- value: String(group.id),- label: getGroupNameLocalized(group),- }));+ const isLockedUntilSave = !isServerConfigured && !isLocked;+ const isLastMapping = Object.keys(groupMapping.mappings).length === 1;+ const isNewMappingShown =+ modeSwitch.mode === "manual" && !isReadOnly && editor.draft == null;return (<Stack gap="lg">+ {isLockedUntilSave && (+ <Text c="text-secondary">+ {t`Save the settings above to set up group mapping.`}+ </Text>+ )}<Flex justify="space-between" align="center" wrap="wrap" gap="lg"><SegmentedControl<JWTGroupSyncMode>aria-label={t`Group mapping mode`}value={modeSwitch.mode}- onChange={(nextMode) => {- setEditor(null);- modeSwitch.select(nextMode);+ onChange={modeSwitch.select}+ // Enter must not submit the surrounding page form+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ }}}- disabled={isReadOnly || isBusy}+ disabled={isReadOnly}+ // read-only, not disabled, so keyboard focus survives a write+ readOnly={isBusy}data={[{ label: t`Automatic`, value: "automatic" },{ label: t`Manual`, value: "manual" },{ label: t`Off`, value: "off" },]}/>- {modeSwitch.mode === "manual" && !isReadOnly && (+ {isNewMappingShown && (<Buttonvariant="subtle"+ flex="0 0 auto"leftSection={<Icon name="add" aria-hidden />}- disabled={isBusy}- onClick={() =>- setEditor({- jwtGroupName: "",- groupValues: [],- originalJwtGroupName: null,- })- }+ disabled={isListHeld}+ onClick={editor.startNew}>{t`New mapping`}</Button>)}</Flex>- {isLocked &&- lockedEnvNames.map((envName) => (- <Text key={envName} c="text-secondary">{t`Using ${envName}`}</Text>- ))}+ {lockedEnvNames.map((envName) => (+ <Text key={envName} c="text-secondary">{t`Using ${envName}`}</Text>+ ))}{modeSwitch.mode === "automatic" && (<Text c="text-secondary">- {t`Users will be assigned to ${applicationName} groups based on their JWT group names`}+ {t`At each sign-in, people are added to the ${applicationName} groups named in their JWT and removed from all other groups, including Administrators.`}</Text>)}- {modeSwitch.mode === "manual" && (- <Stack gap="sm">- {!modeSwitch.hasMappings && editor == null && !isReadOnly && (- <Text c="text-secondary">- {t`Add at least one mapping to use manual group mapping`}- </Text>- )}- {Object.entries(groupMapping.mappings).map(([name, groupIds]) =>- editor?.originalJwtGroupName === name ? (- <MappingEditorRow- key={name}- editor={editor}- groupOptions={groupOptions}- submitLabel={t`Save`}- canSubmit={canSaveMapping}- isDuplicateName={isDuplicateName}- isSubmitting={isBusy}- onChange={setEditor}- onCancel={() => setEditor(null)}- onSubmit={saveMapping}- />- ) : (- <MappingRow- key={name}- name={name}- groupIds={groupIds}- groupLookup={groupLookup}- readOnly={isReadOnly}- disabled={isBusy}- onEdit={() =>- setEditor({- jwtGroupName: name,- groupValues: groupLookup.existingIds(groupIds).map(String),- originalJwtGroupName: name,- })- }- onDelete={() => deletion.requestDelete(name)}- />- ),- )}- {editor != null && editor.originalJwtGroupName == null && (- <MappingEditorRow- editor={editor}- groupOptions={groupOptions}- submitLabel={t`Add mapping`}- canSubmit={canSaveMapping}- isDuplicateName={isDuplicateName}- isSubmitting={isBusy}- onChange={setEditor}- onCancel={() => setEditor(null)}- onSubmit={saveMapping}- />- )}- </Stack>+ {modeSwitch.mode === "manual" && groupLookup.loadFailed && (+ <Text c="error">{t`Groups could not be loaded`}</Text>)}- {deletion.target != null && (- <DeleteGroupMappingModal- name={deletion.target}- groupIds={deletion.targetGroupIds}- hasAdminGroup={groupLookup.hasAdminGroup(deletion.targetGroupIds)}- note={- deletion.isDeletingLastMapping+ {modeSwitch.mode === "manual" && (+ <GroupMappingList+ mappings={groupMapping.mappings}+ groupLookup={groupLookup}+ editor={editor}+ deletion={deletion}+ readOnly={isReadOnly}+ disabled={isListHeld}+ nameLabel={t`JWT group name`}+ namePlaceholder={t`Enter JWT group...`}+ emptyMessage={t`Add at least one mapping to use manual group mapping`}+ deleteNote={+ isLastMapping? t`This is the last mapping, so group mapping will be turned off.`: undefined}- onConfirm={deletion.confirmDelete}- onHide={deletion.cancelDelete}/>)}+<ConfirmModalopened={modeSwitch.isClearConfirmOpen}title={t`Switch to automatic group mapping?`}- message={t`Your existing group mappings will be deleted, and users will be assigned to ${applicationName} groups matching their JWT group names.`}+ message={t`Your existing group mappings will be deleted. From then on, at each sign-in, people are added to the ${applicationName} groups named in their JWT and removed from all other groups, including Administrators.`}confirmButtonText={t`Delete mappings and switch`}onClose={modeSwitch.cancelClear}// the modal's busy guard only engages on a returned promise, which also blocks double submitsdiff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingEditorRow.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingEditorRow.tsxdeleted file mode 100644index 66277415d48..00000000000--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingEditorRow.tsx+++ /dev/null@@ -1,129 +0,0 @@-import { t } from "ttag";--import { useSelector } from "metabase/redux";-import { getApplicationName } from "metabase/selectors/whitelabel";-import {- Button,- FixedSizeIcon,- Flex,- MultiSelect,- TextInput,-} from "metabase/ui";--import S from "./JWTGroupMappingSection.module.css";--export type EditorState = {- jwtGroupName: string;- // MultiSelect values, so group ids as strings- groupValues: string[];- // set while an existing mapping is being edited- originalJwtGroupName: string | null;-};--export function MappingEditorRow({- editor,- groupOptions,- submitLabel,- canSubmit,- isDuplicateName,- isSubmitting,- onChange,- onCancel,- onSubmit,-}: {- editor: EditorState;- groupOptions: { value: string; label: string }[];- submitLabel: string;- canSubmit: boolean;- isDuplicateName: boolean;- isSubmitting: boolean;- onChange: (editor: EditorState) => void;- onCancel: () => void;- onSubmit: () => void;-}) {- const applicationName = useSelector(getApplicationName);-- // the editor is inside the page form, so Enter must not reach its submit button- const handleNameKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {- if (event.key === "Enter") {- event.preventDefault();- if (canSubmit && !isSubmitting) {- onSubmit();- }- }- if (event.key === "Escape") {- onCancel();- }- };-- const handleGroupsKeyDown = (- event: React.KeyboardEvent<HTMLInputElement>,- ) => {- if (event.key === "Enter") {- event.preventDefault();- }- };-- return (- <Flex- className={S.editorRow}- bd="1px solid var(--mb-color-border-neutral)"- bdrs="sm"- p="sm"- align="center"- gap="lg"- wrap="wrap"- >- <TextInput- flex={1}- miw="10rem"- aria-label={t`JWT group name`}- placeholder={t`Enter JWT group...`}- value={editor.jwtGroupName}- error={- isDuplicateName ? t`A mapping for this group already exists` : null- }- onChange={(event) =>- onChange({ ...editor, jwtGroupName: event.target.value })- }- onKeyDown={handleNameKeyDown}- autoFocus- />- <FixedSizeIcon- aria-hidden- name="arrow_right"- c="text-secondary"- className={S.editorArrow}- />- <MultiSelect- flex={2}- miw="14rem"- classNames={{ inputField: S.groupsSearchField }}- aria-label={t`${applicationName} groups`}- placeholder={- editor.groupValues.length === 0- ? t`Pick ${applicationName} group...`- : undefined- }- data={groupOptions}- value={editor.groupValues}- onChange={(groupValues) => onChange({ ...editor, groupValues })}- onKeyDown={handleGroupsKeyDown}- searchable- />- <Button- variant="subtle"- color="neutral"- onClick={onCancel}- >{t`Cancel`}</Button>- <Button- variant="filled"- disabled={!canSubmit}- loading={isSubmitting}- onClick={onSubmit}- >- {submitLabel}- </Button>- </Flex>- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingRow.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingRow.tsxdeleted file mode 100644index f34f31fbb62..00000000000--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/MappingRow.tsx+++ /dev/null@@ -1,91 +0,0 @@-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";--export function MappingRow({- name,- groupIds,- groupLookup,- readOnly,- disabled,- onEdit,- onDelete,-}: {- name: string;- groupIds: GroupId[];- groupLookup: GroupLookup;- readOnly: boolean;- disabled: boolean;- onEdit: () => void;- onDelete: () => void;-}) {- return (- <Flex- className={S.mappingRow}- align="center"- gap="lg"- data-testid="jwt-group-mapping-row"- >- <Flex flex={1} miw={0} align="center" gap="lg" wrap="wrap">- <Text fw="bold" flex="0 0 auto" maw="100%" className={S.wrappableText}>- {name}- </Text>- <FixedSizeIcon aria-hidden name="arrow_right" c="text-secondary" />- <MappingRowGroups groupIds={groupIds} groupLookup={groupLookup} />- </Flex>- {!readOnly && (- <Flex className={S.rowActions} gap="sm">- <ActionIcon- aria-label={t`Edit mapping`}- disabled={disabled}- onClick={onEdit}- >- <Icon name="pencil" />- </ActionIcon>- <ActionIcon- aria-label={t`Delete mapping`}- disabled={disabled}- onClick={onDelete}- >- <Icon name="trash" />- </ActionIcon>- </Flex>- )}- </Flex>- );-}--function MappingRowGroups({- groupIds,- groupLookup,-}: {- groupIds: GroupId[];- groupLookup: GroupLookup;-}) {- const names = groupIds- .map((groupId) => {- const group = groupLookup.getGroup(groupId);- return group ? getGroupNameLocalized(group) : null;- })- .filter((groupName) => groupName != null);-- // zero-group mappings can't be created here anymore, but exist in the wild- if (names.length === 0) {- return (- <Text flex="1 1 auto" miw={0} c="text-secondary">- {t`No groups`}- </Text>- );- }- // sized by content, so the names only drop under the mapping name when they don't fit- return (- <Text flex="1 1 auto" miw={0} className={S.wrappableText}>- {names.join(", ")}- </Text>- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-mode.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-mode.tsindex 58e3feb022d..3414653b42c 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@@ -7,7 +7,6 @@ export type JWTGroupSyncMode = "automatic" | "manual" | "off";type GroupMappingModeState = {mode: JWTGroupSyncMode;- hasMappings: boolean;isClearConfirmOpen: boolean;select: (nextMode: JWTGroupSyncMode) => Promise<void>;confirmClear: () => Promise<void>;@@ -84,18 +83,17 @@ export function useGroupMappingMode(};const confirmClear = async () => {- const saved = await groupMapping.saveSettings(+ const result = await groupMapping.saveSettings({ "jwt-group-sync": true, "jwt-group-mappings": {} },{ successMessage: t`Changes saved` },);- if (saved) {+ if (result.ok) {setIsClearConfirmOpen(false);}};return {mode,- hasMappings,isClearConfirmOpen,select,confirmClear,diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-settings.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-settings.tsindex 39d3bef482d..9c1c0515f6a 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-settings.ts+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-group-mapping-settings.ts@@ -1,58 +1,66 @@import { useState } from "react";import { t } from "ttag";-import type { MappingsType } from "metabase/admin/types";+import {+ EMPTY_MAPPINGS,+ type GroupMappingsSaveResult,+ type SaveOptions,+} from "metabase/admin/settings/auth/components/GroupMappings";import { getErrorMessage } from "metabase/api/utils/errors";import { useToast } from "metabase/common/hooks";import { useDispatch } from "metabase/redux";import {settingsApi,+ useGetSettingsQuery,useSetting,useUpdateSettingsMutation,} from "metabase/settings";-import type { EnterpriseSettings } from "metabase-types/api";+import type { EnterpriseSettings, GroupMappings } from "metabase-types/api";-export type GroupMappingSettings = Partial<+type GroupMappingSettings = Partial<Pick<EnterpriseSettings, "jwt-group-sync" | "jwt-group-mappings">>;export type GroupMappingSettingsState = {syncEnabled: boolean;- mappings: MappingsType;+ mappings: GroupMappings;isSaving: boolean;+ isAdminSettingsFetching: boolean;saveSettings: (settings: GroupMappingSettings,- options?: { successMessage?: string },- ) => Promise<boolean>;+ options?: SaveOptions,+ ) => Promise<GroupMappingsSaveResult>;};-const EMPTY_MAPPINGS: MappingsType = {};-export function useGroupMappingSettings(): GroupMappingSettingsState {const dispatch = useDispatch();const [sendToast] = useToast();const [updateSettings] = useUpdateSettingsMutation();const syncEnabled = useSetting("jwt-group-sync") ?? false;const mappings = useSetting("jwt-group-mappings") ?? EMPTY_MAPPINGS;+ const { isFetching: isAdminSettingsFetching } = useGetSettingsQuery();const [isSaving, setIsSaving] = useState(false);const saveSettings = async (settings: GroupMappingSettings,- { successMessage }: { successMessage?: string } = {},- ) => {+ { successMessage, showErrorToast = true }: SaveOptions = {},+ ): Promise<GroupMappingsSaveResult> => {setIsSaving(true);try {const response = await updateSettings(settings);if (response.error) {- sendToast({- message: getErrorMessage(- response.error,- t`Error saving group mapping`,- ),- icon: "warning",- toastColor: "feedback-negative",- });- return false;+ const error = getErrorMessage(+ response.error,+ t`Error saving group mapping`,+ );+ if (showErrorToast) {+ sendToast({+ message: error,+ icon: "warning",+ toastColor: "feedback-negative",+ });+ }+ return { ok: false, error };}// show the saved state right away instead of waiting for the settings refetchdispatch(@@ -67,11 +75,17 @@ export function useGroupMappingSettings(): GroupMappingSettingsState {if (successMessage != null) {sendToast({ message: successMessage, icon: "check_filled" });}- return true;+ return { ok: true };} finally {setIsSaving(false);}};- return { syncEnabled, mappings, isSaving, saveSettings };+ return {+ syncEnabled,+ mappings,+ isSaving,+ isAdminSettingsFetching,+ saveSettings,+ };}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-mapping-deletion.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-mapping-deletion.tsdeleted file mode 100644index a29fda35e85..00000000000--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/JWTGroupMappingSection/use-mapping-deletion.ts+++ /dev/null@@ -1,143 +0,0 @@-import { useState } from "react";-import { t } from "ttag";--import {- type GroupLookup,- withoutMapping,-} from "metabase/admin/settings/auth/components/GroupMappings";-import type {- DeleteMappingModalValueType,- GroupIds,-} from "metabase/admin/types";-import {- useClearGroupMembershipMutation,- useDeletePermissionsGroupMutation,-} from "metabase/api";-import { useToast } from "metabase/common/hooks";--import type {- GroupMappingSettings,- GroupMappingSettingsState,-} from "./use-group-mapping-settings";--type MappingCascade = {- value: Exclude<DeleteMappingModalValueType, "nothing">;- groupIds: GroupIds;-};--type MappingDeletionState = {- target: string | null;- targetGroupIds: GroupIds;- isDeletingLastMapping: boolean;- isDeleting: boolean;- requestDelete: (name: string) => void;- cancelDelete: () => void;- confirmDelete: (- value: DeleteMappingModalValueType,- groupIds: GroupIds,- name: string,- ) => Promise<void>;-};--export function useMappingDeletion({- groupMapping,- groupLookup,-}: {- groupMapping: GroupMappingSettingsState;- groupLookup: GroupLookup;-}): MappingDeletionState {- const [sendToast] = useToast();- const [clearGroupMembership] = useClearGroupMembershipMutation();- const [deletePermissionsGroup] = useDeletePermissionsGroupMutation();- const [target, setTarget] = useState<string | null>(null);- const [isDeleting, setIsDeleting] = useState(false);-- const targetGroupIds =- target == null- ? []- : groupLookup.existingIds(groupMapping.mappings[target] ?? []);- const isDeletingLastMapping =- target != null && Object.keys(groupMapping.mappings).length === 1;-- // "nothing, just remove the mapping" arrives as null and touches no group- const runCascade = async (cascade: MappingCascade | null) => {- if (cascade == null) {- return { failureCount: 0 };- }- // the group calls are independent, so they run at once- const results = await Promise.allSettled(- cascade.groupIds.map((groupId) =>- cascade.value === "clear"- ? clearGroupMembership(groupId).unwrap()- : deletePermissionsGroup(groupId).unwrap(),- ),- );- const failures = results.filter((result) => result.status === "rejected");- failures.forEach((failure) => console.error(failure.reason));- return { failureCount: failures.length };- };-- const deleteMapping = async (- name: string,- cascade: MappingCascade | null,- ) => {- const nextMappings = withoutMapping(- groupMapping.mappings,- name,- cascade?.value === "delete" ? cascade.groupIds : [],- );- const isLastMapping = Object.keys(nextMappings).length === 0;- // sync can't stay on without mappings, or the backend would silently fall back to name matching- const settings: GroupMappingSettings = isLastMapping- ? { "jwt-group-mappings": nextMappings, "jwt-group-sync": false }- : { "jwt-group-mappings": nextMappings };- const saved = await groupMapping.saveSettings(settings);- if (!saved) {- return;- }- const { failureCount } = await runCascade(cascade);- if (failureCount > 0) {- sendToast({- message: t`Mapping deleted, but not all of its groups could be updated`,- icon: "warning",- toastColor: "feedback-negative",- });- return;- }- sendToast({- message: isLastMapping- ? t`Mapping deleted and group mapping turned off`- : t`Mapping deleted`,- icon: "check_filled",- });- };-- const confirmDelete = async (- value: DeleteMappingModalValueType,- groupIds: GroupIds,- name: string,- ) => {- setTarget(null);- const cascade =- value === "nothing"- ? null- : { value, groupIds: groupLookup.actionableIds(groupIds) };- // the write releases its own busy flag before the cascade, so this one covers the whole operation- setIsDeleting(true);- try {- await deleteMapping(name, cascade);- } finally {- setIsDeleting(false);- }- };-- return {- target,- targetGroupIds,- isDeletingLastMapping,- isDeleting,- requestDelete: setTarget,- cancelDelete: () => setTarget(null),- confirmDelete,- };-}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsxindex a2e85860739..843ae79d641 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx@@ -1,7 +1,12 @@import { t } from "ttag";import _ from "underscore";+import * as Yup from "yup";-import { getExtraFormFieldProps } from "metabase/admin/settings/utils";+import {+ getDefaultPlaceholder,+ getExtraFormFieldProps,+ getStoredFieldValue,+} from "metabase/admin/settings/utils";import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { useToast } from "metabase/common/hooks";@@ -18,6 +23,7 @@ import { getApplicationName } from "metabase/selectors/whitelabel";import {useAdminSetting,useGetAdminSettingsDetailsQuery,+ useGetSettingsQuery,} from "metabase/settings";import {CollapsibleSettingsSection,@@ -38,18 +44,13 @@ import type {import { JWTGroupMappingSection } from "./JWTGroupMappingSection";/**- * Attribute-key fields show only a placeholder, no helper text.+ * Attribute-key fields show the backend default as a placeholder, no helper text.* Env-locked fields swap the placeholder for the readOnly "Using MB_..." notice.*/-const getAttributeFieldProps = (- setting: SettingDefinition | undefined,- placeholder?: string,-) => {- if (setting?.is_env_setting) {- return getExtraFormFieldProps(setting);- }- return { placeholder };-};+const getAttributeFieldProps = (setting: SettingDefinition | undefined) =>+ setting?.is_env_setting+ ? getExtraFormFieldProps(setting)+ : { placeholder: getDefaultPlaceholder(setting) };export type JWTFormValues = Pick<EnterpriseSettings,@@ -62,20 +63,37 @@ export type JWTFormValues = Pick<| "jwt-attribute-tenant">;+type JWTTextKey = Exclude<keyof JWTFormValues, "jwt-shared-secret">;++const JWT_TEXT_KEYS = [+ "jwt-identity-provider-uri",+ "jwt-attribute-email",+ "jwt-attribute-firstname",+ "jwt-attribute-lastname",+ "jwt-attribute-groups",+ "jwt-attribute-tenant",+] satisfies JWTTextKey[];+export const SettingsJWTForm = () => {const {data: settingDetails,isLoading: isLoadingDetails,refetch: refetchSettingDetails,} = useGetAdminSettingsDetailsQuery();+ const { data: settingValues, isLoading: isLoadingValues } =+ useGetSettingsQuery();const { value: jwtEnabled, updateSettings } = useAdminSetting("jwt-enabled");const applicationName = useSelector(getApplicationName);const [sendToast] = useToast();- // a paused JWT keeps its settings, so "configured" means an identity provider URI exists+ const isServerConfigured = settingValues?.["jwt-configured"] ?? false;+ // a saved URI or mapping means the setup is not new, even if the shared secret went missing sinceconst uriSetting = settingDetails?.["jwt-identity-provider-uri"];- const isServerConfigured =+ const hasSavedUri =Boolean(uriSetting?.value) || (uriSetting?.is_env_setting ?? false);+ const hasMappings =+ Object.keys(settingValues?.["jwt-group-mappings"] ?? {}).length > 0;+ const isNewSetup = !hasSavedUri && !hasMappings;// either env var locks the whole group mapping section, since the two settings act as one featureconst groupMappingEnvNames = [@@ -85,10 +103,17 @@ export const SettingsJWTForm = () => {setting?.is_env_setting && setting.env_name ? [setting.env_name] : [],);const isGroupMappingEnvConfigured = groupMappingEnvNames.length > 0;+ const turnsOnGroupMapping = isNewSetup && !isGroupMappingEnvConfigured;const saveSettings = async (values: JWTFormValues) => {const { "jwt-shared-secret": jwtSecret, ...rest } = values;- const settingsToUpdate: Partial<EnterpriseSettings> = { ...rest };+ const envLockedKeys = JWT_TEXT_KEYS.filter(+ (key) => settingDetails?.[key]?.is_env_setting,+ );+ const settingsToUpdate: Partial<EnterpriseSettings> = _.omit(+ rest,+ envLockedKeys,+ );// jwt-shared-secret may be initialized with the obfuscated value from /api/setting.// Only send it to the backend if it's a newly generated plaintext value.@@ -96,8 +121,7 @@ export const SettingsJWTForm = () => {settingsToUpdate["jwt-shared-secret"] = jwtSecret;}- // per the design, the first save turns automatic group mapping on; the section owns it from then on- if (!isServerConfigured && !isGroupMappingEnvConfigured) {+ if (turnsOnGroupMapping) {settingsToUpdate["jwt-group-sync"] = true;settingsToUpdate["jwt-group-mappings"] = {};}@@ -114,19 +138,35 @@ export const SettingsJWTForm = () => {throw new Error(t`Error saving JWT Settings`);}- sendToast({ message: t`Changes saved`, icon: "check_filled" });+ sendToast({+ message: turnsOnGroupMapping+ ? t`Changes saved. Group mapping is set to Automatic.`+ : t`Changes saved`,+ icon: "check_filled",+ });};- if (isLoadingDetails) {+ if (isLoadingDetails || isLoadingValues) {return <LoadingAndErrorWrapper loading />;}- if (!settingDetails) {+ if (!settingDetails || !settingValues) {return (<LoadingAndErrorWrapper error={t`Error loading JWT configuration`} />);}+ const isSigningKeyEnvSet =+ settingDetails["jwt-shared-secret"]?.is_env_setting ?? false;+ const validationSchema = Yup.object({+ "jwt-shared-secret": Yup.string()+ .nullable()+ .when("jwt-identity-provider-uri", {+ is: (uri: string | null) => Boolean(uri) && !isSigningKeyEnvSet,+ then: (schema) =>+ schema.required(t`Set up a signing key before saving`),+ }),+ });const usingTenants = settingDetails["use-tenants"]?.value;const hasUserAttributes = [settingDetails["jwt-attribute-email"],@@ -142,13 +182,19 @@ export const SettingsJWTForm = () => {return (<SettingsPageWrapper title={t`JWT`}><FormProvider- initialValues={getFormValues(settingDetails)}+ initialValues={getFormValues(settingDetails, settingValues)}onSubmit={saveSettings}+ validationSchema={validationSchema}enableReinitialize>{({ dirty, isSubmitting }) => (<Form><Stack gap="xl">+ <UserProvisioningSection+ settingKey="jwt-user-provisioning-enabled?"+ providerName="JWT"+ reactivatesAccounts+ /><SettingsSectiontitle={t`Server settings`}titleProps={SETTINGS_CARD_TITLE_PROPS}@@ -175,12 +221,6 @@ export const SettingsJWTForm = () => {/></Stack></SettingsSection>- {/* the card saves on its own, so it stays out of the form's values */}- <UserProvisioningSection- settingKey="jwt-user-provisioning-enabled?"- providerName="JWT"- disabled={!isServerConfigured}- /><CollapsibleSettingsSectiontitle={t`User attribute configuration`}description={t`You can send additional user attributes to ${applicationName} by adding the attributes as key/value pairs to your JWT`}@@ -193,7 +233,6 @@ export const SettingsJWTForm = () => {label={t`Email attribute key`}{...getAttributeFieldProps(settingDetails?.["jwt-attribute-email"],- "email-key",)}/><FormTextInput@@ -201,7 +240,6 @@ export const SettingsJWTForm = () => {label={t`First name attribute key`}{...getAttributeFieldProps(settingDetails?.["jwt-attribute-firstname"],- "first-name-key",)}/><FormTextInput@@ -209,7 +247,6 @@ export const SettingsJWTForm = () => {label={t`Last name attribute key`}{...getAttributeFieldProps(settingDetails?.["jwt-attribute-lastname"],- "last-name-key",)}/><FormTextInput@@ -217,7 +254,6 @@ export const SettingsJWTForm = () => {label={t`Group assignment attribute key`}{...getAttributeFieldProps(settingDetails?.["jwt-attribute-groups"],- "group-assignment-key",)}/>{usingTenants && (@@ -264,18 +300,23 @@ export const SettingsJWTForm = () => {);};-const getFormValues = (settingDetails: SettingDefinitionMap): JWTFormValues => {- const jwtSettings = _.pick(settingDetails, [- "jwt-identity-provider-uri",- "jwt-shared-secret",- "jwt-attribute-email",- "jwt-attribute-firstname",- "jwt-attribute-lastname",- "jwt-attribute-groups",- "jwt-attribute-tenant",- ]);- // mapObject widens the picked setting values (and casts undefined to null)- return _.mapObject(jwtSettings, (val) => val?.value ?? null) as JWTFormValues;+const getFormValues = (+ settingDetails: SettingDefinitionMap,+ settingValues: EnterpriseSettings,+): JWTFormValues => {+ const storedValue = (key: JWTTextKey): string | null =>+ getStoredFieldValue(settingDetails[key], settingValues[key]);++ return {+ "jwt-identity-provider-uri": storedValue("jwt-identity-provider-uri"),+ // sensitive, so only the admin settings list carries it, obfuscated+ "jwt-shared-secret": settingDetails["jwt-shared-secret"]?.value ?? null,+ "jwt-attribute-email": storedValue("jwt-attribute-email"),+ "jwt-attribute-firstname": storedValue("jwt-attribute-firstname"),+ "jwt-attribute-lastname": storedValue("jwt-attribute-lastname"),+ "jwt-attribute-groups": storedValue("jwt-attribute-groups"),+ "jwt-attribute-tenant": storedValue("jwt-attribute-tenant"),+ };};const isObfuscatedValue = (value: string | null | undefined): boolean =>diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsxindex 18d194efee9..14b26b9a3bc 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx@@ -15,7 +15,7 @@ import {within,} from "__support__/ui";import { settingsApi } from "metabase/settings";-import { PROVISIONING_WRITE_DEBOUNCE_MS } from "metabase-enterprise/auth/components/UserProvisioningSection";+import { defer } from "metabase/utils/promise";import type { SettingDefinition } from "metabase-types/api";import { createMockGroup, createMockSettings } from "metabase-types/api/mocks";@@ -27,12 +27,19 @@ const GROUPS = [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 }),+ createMockGroup({+ id: 6,+ name: "Data Analysts",+ magic_group_type: "data-analyst",+ }),];const setup = async ({jwtEnabled,useTenants,configured,+ uriOnly,+ sharedSecretEnvConfigured,attributesConfigured,attributesEnvConfigured,tenantAttributeConfigured,@@ -43,15 +50,19 @@ const setup = async ({userProvisioning,userProvisioningEnvConfigured,saveStatus,- saveDelayMs,+ saveGate,provisioningSaveStatus,- provisioningSaveDelayMs,+ provisioningSaveGate,cascadeStatus,- cascadeDelayMs,+ deleteGroupStatuses,+ cascadeGate,+ groupsGate,}: {jwtEnabled?: boolean;useTenants?: boolean;configured?: boolean;+ uriOnly?: boolean;+ sharedSecretEnvConfigured?: boolean;attributesConfigured?: boolean;attributesEnvConfigured?: boolean;tenantAttributeConfigured?: boolean;@@ -62,11 +73,13 @@ const setup = async ({userProvisioning?: boolean;userProvisioningEnvConfigured?: boolean;saveStatus?: number;- saveDelayMs?: number;+ saveGate?: Promise<void>;provisioningSaveStatus?: number;- provisioningSaveDelayMs?: number;+ provisioningSaveGate?: Promise<void>;cascadeStatus?: number;- cascadeDelayMs?: number;+ deleteGroupStatuses?: Record<number, number>;+ cascadeGate?: Promise<void>;+ groupsGate?: Promise<void>;} = {}) => {const settingDefinitions: SettingDefinition[] = [{ key: "use-tenants", value: useTenants ?? false },@@ -109,29 +122,50 @@ const setup = async ({{ key: "jwt-shared-secret", value: "590ab155f412d477b8ab9c8b0e7b" },] as const): []),- ...(attributesConfigured- ? ([{ key: "jwt-attribute-email", value: "email-key" }] as const)+ ...(uriOnly+ ? ([+ { key: "jwt-identity-provider-uri", value: "http://example.com" },+ ] as const): []),- ...(attributesEnvConfigured+ ...(sharedSecretEnvConfigured? ([{- key: "jwt-attribute-email",+ key: "jwt-shared-secret",is_env_setting: true,- env_name: "MB_JWT_ATTRIBUTE_EMAIL",+ env_name: "MB_JWT_SHARED_SECRET",},] as const): []),- ...(tenantAttributeConfigured- ? ([{ key: "jwt-attribute-tenant", value: "tenant-key" }] as const)- : []),+ {+ key: "jwt-attribute-email",+ default: "email",+ ...(attributesConfigured && { value: "email-key" }),+ ...(attributesEnvConfigured && {+ is_env_setting: true,+ env_name: "MB_JWT_ATTRIBUTE_EMAIL",+ }),+ },+ { key: "jwt-attribute-firstname", default: "first_name" },+ { key: "jwt-attribute-lastname", default: "last_name" },+ { key: "jwt-attribute-groups", default: "groups" },+ {+ key: "jwt-attribute-tenant",+ default: "@tenant",+ ...(tenantAttributeConfigured && { value: "tenant-key" }),+ },];// session properties carry the effective values, and the stateful store reflects live writes on refetch, admin list includedconst sessionSettings = createMockSettings({"use-tenants": useTenants,"jwt-enabled": jwtEnabled,+ "jwt-configured": configured ?? false,+ "jwt-identity-provider-uri":+ configured || uriOnly ? "http://example.com" : null,+ "jwt-shared-secret": configured ? "590ab155f412d477b8ab9c8b0e7b" : null,"jwt-user-provisioning-enabled?": userProvisioning ?? true,"jwt-group-sync": groupSync ?? false,"jwt-group-mappings": groupMappings ?? {},+ ...(attributesEnvConfigured && { "jwt-attribute-email": "mail" }),});const settingsStore = setupStatefulSettingsEndpoints(sessionSettings);// the shared helper keeps the admin list static, so serve it here with whatever the store has changed since setup@@ -160,50 +194,56 @@ const setup = async ({},{ name: "settings-list" },);- if (saveStatus != null || saveDelayMs != null) {- // a failed write leaves the store alone, and a slow one lands in it once it resolves- const status = saveStatus ?? 204;- fetchMock.removeRoute("update-settings");- fetchMock.put(- "path:/api/setting",- ({ options }) => {- if (status < 300) {- Object.assign(settingsStore, JSON.parse(String(options.body)));- }- return { status };- },- { name: "update-settings", delay: saveDelayMs },- );- }- if (provisioningSaveStatus != null || provisioningSaveDelayMs != null) {+ const status = saveStatus ?? 204;+ fetchMock.removeRoute("update-settings");+ fetchMock.put(+ "path:/api/setting",+ async ({ options }) => {+ await saveGate;+ if (status < 300) {+ Object.assign(settingsStore, JSON.parse(String(options.body)));+ settingsStore["jwt-configured"] =+ Boolean(settingsStore["jwt-identity-provider-uri"]) &&+ Boolean(settingsStore["jwt-shared-secret"]);+ }+ return { status };+ },+ { name: "update-settings" },+ );+ if (provisioningSaveStatus != null || provisioningSaveGate != null) {// the single-key write behaves the same way for the provisioning switchconst status = provisioningSaveStatus ?? 204;fetchMock.removeRoute("update-setting");fetchMock.put(new RegExp("/api/setting/(.+)"),- ({ url, options }) => {+ async ({ url, options }) => {+ await provisioningSaveGate;if (status < 300) {const key = decodeURIComponent(url.split("/api/setting/")[1]);settingsStore[key] = JSON.parse(String(options.body)).value;}return { status };},- { name: "update-setting", delay: provisioningSaveDelayMs },+ { name: "update-setting" },);}setupGenerateRandomTokenEndpoint("1234abcd");- fetchMock.get("path:/api/permissions/group", GROUPS);- fetchMock.put(- "express:/api/permissions/membership/:id/clear",- cascadeStatus ?? 204,- { delay: cascadeDelayMs },- );- fetchMock.delete("express:/api/permissions/group/:id", cascadeStatus ?? 204, {- delay: cascadeDelayMs,+ fetchMock.get("path:/api/permissions/group", async () => {+ await groupsGate;+ return GROUPS;+ });+ fetchMock.delete("express:/api/permissions/group/:id", async ({ url }) => {+ await cascadeGate;+ return {+ status:+ deleteGroupStatuses?.[Number(url.split("/").pop())] ??+ cascadeStatus ??+ 204,+ };});- const { store, unmount } = renderWithProviders(<SettingsJWTForm />, {+ const { store } = renderWithProviders(<SettingsJWTForm />, {withUndos: true,storeInitialState: createMockState({settings: createMockSettingsState(sessionSettings),@@ -211,7 +251,26 @@ const setup = async ({});await screen.findByText("Server settings");- return { store, settingsStore, unmount };+ return { store, settingsStore };+};++const holdSettingsReads = (settingsStore: Record<string, unknown>) => {+ const gate = defer<void>();+ fetchMock.removeRoute("get-session-properties");+ fetchMock.get(+ "path:/api/session/properties",+ async () => {+ await gate.promise;+ return { ...settingsStore };+ },+ { name: "get-session-properties" },+ );+ return () => gate.resolve();+};++const clickWhenEnabled = async (element: HTMLElement) => {+ await waitFor(() => expect(element).toBeEnabled());+ await userEvent.click(element);};const expandUserAttributeSection = async () => {@@ -221,7 +280,7 @@ const expandUserAttributeSection = async () => {};const addMapping = async (name: string, groupName: string) => {- await userEvent.click(screen.getByRole("button", { name: "New mapping" }));+ await clickWhenEnabled(screen.getByRole("button", { name: "New mapping" }));await userEvent.type(screen.getByPlaceholderText("Enter JWT group..."), name);await userEvent.click(screen.getByPlaceholderText("Pick Metabase group..."));await userEvent.click(await screen.findByRole("option", { name: groupName }));@@ -230,9 +289,28 @@ const addMapping = async (name: string, groupName: string) => {const findMappingRow = (name: string) =>screen- .getAllByTestId("jwt-group-mapping-row")+ .getAllByTestId("group-mapping-row").find((row) => within(row).queryByText(name) != null);+const deleteMappingWithGroups = async (name: string, submitLabel: string) => {+ await clickWhenEnabled(+ within(findMappingRow(name)!).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /Also delete the group/ }),+ );+ await userEvent.click(screen.getByRole("button", { name: submitLabel }));+};++// Mantine marks a read-only option on its label, not on its input+const modeLabel = (name: string) => {+ const [label] =+ screen.getByRole<HTMLInputElement>("radio", { name }).labels ?? [];+ return label;+};+describe("SettingsJWTForm", () => {const ATTRS = {"jwt-identity-provider-uri": "http://example.com",@@ -267,11 +345,7 @@ describe("SettingsJWTForm", () => {const attributeHeader = screen.getByRole("button", {name: /User attribute configuration/,});- const provisioningToggle = screen.getByRole("switch", {- name: "User provisioning",- });expect(attributeHeader).toBeDisabled();- expect(provisioningToggle).toBeDisabled();await fillServerSettings();await userEvent.click(@@ -287,17 +361,70 @@ describe("SettingsJWTForm", () => {expect(body).toEqual({"jwt-identity-provider-uri": ATTRS["jwt-identity-provider-uri"],"jwt-shared-secret": ATTRS["jwt-shared-secret"],+ "jwt-attribute-email": null,+ "jwt-attribute-firstname": null,+ "jwt-attribute-lastname": null,+ "jwt-attribute-groups": null,+ "jwt-attribute-tenant": null,"jwt-enabled": true,"jwt-group-sync": true,"jwt-group-mappings": {},});await waitFor(() => expect(attributeHeader).toBeEnabled());- expect(provisioningToggle).toBeEnabled();expect(screen.getByRole("radio", { name: "Automatic" })).toBeChecked();expect(screen.getByRole("radio", { name: "Automatic" })).toBeEnabled();expect(- screen.getByText(/Users will be assigned to Metabase groups/),+ screen.getByText(+ "At each sign-in, people are added to the Metabase groups named in their JWT and removed from all other groups, including Administrators.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByText("Changes saved. Group mapping is set to Automatic."),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("Save the settings above to set up group mapping."),+ ).not.toBeInTheDocument();+ });++ it("keeps Save and enable disabled until a signing key is set up", async () => {+ await setup();+ const saveButton = screen.getByRole("button", { name: /Save and enable/ });+ expect(+ screen.queryByText("Set up a signing key before saving"),+ ).not.toBeInTheDocument();++ await userEvent.type(+ screen.getByRole("textbox", { name: /JWT Identity Provider URI/ }),+ ATTRS["jwt-identity-provider-uri"],+ );++ expect(+ await screen.findByText("Set up a signing key before saving"),).toBeInTheDocument();+ expect(saveButton).toBeDisabled();++ await userEvent.click(screen.getByRole("button", { name: /Set up key/ }));+ await userEvent.click(await screen.findByRole("button", { name: /Done/ }));++ await waitFor(() => expect(saveButton).toBeEnabled());+ });++ it("saves without a key when the key comes from an env var", async () => {+ await setup({ sharedSecretEnvConfigured: true });++ await userEvent.type(+ screen.getByRole("textbox", { name: /JWT Identity Provider URI/ }),+ ATTRS["jwt-identity-provider-uri"],+ );+ await userEvent.click(+ screen.getByRole("button", { name: /Save and enable/ }),+ );++ const [{ body }] = await findRequests("PUT");+ expect(body["jwt-identity-provider-uri"]).toBe(+ ATTRS["jwt-identity-provider-uri"],+ );+ expect(body).not.toHaveProperty("jwt-shared-secret");});it("saves the attribute keys once the server settings exist", async () => {@@ -370,6 +497,50 @@ describe("SettingsJWTForm", () => {).toHaveAttribute("aria-expanded", "true");});+ it("shows the backend defaults as placeholders in the attribute fields", async () => {+ await setup({ configured: true, useTenants: true });+ await expandUserAttributeSection();++ const placeholders = [+ ["Email attribute key", "email"],+ ["First name attribute key", "first_name"],+ ["Last name attribute key", "last_name"],+ ["Group assignment attribute key", "groups"],+ ["Tenant assignment attribute key", "@tenant"],+ ];+ placeholders.forEach(([label, placeholder]) => {+ const input = screen.getByLabelText(label);+ expect(input).toHaveValue("");+ expect(input).toHaveAttribute("placeholder", placeholder);+ });+ });++ it("shows an env-set attribute key read-only and leaves it out of a save", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ attributesEnvConfigured: true,+ });++ const emailInput = screen.getByLabelText("Email attribute key");+ expect(emailInput).toHaveValue("mail");+ expect(emailInput).toHaveAttribute("readonly");+ expect(+ screen.getByText("Using MB_JWT_ATTRIBUTE_EMAIL"),+ ).toBeInTheDocument();++ await userEvent.type(+ screen.getByLabelText("First name attribute key"),+ "given_name",+ );+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));++ expect(await screen.findByText("Changes saved")).toBeInTheDocument();+ const [{ body }] = await findRequests("PUT");+ expect(body).toHaveProperty("jwt-attribute-firstname", "given_name");+ expect(body).not.toHaveProperty("jwt-attribute-email");+ });+it("keeps the user attribute section collapsed while the server settings are missing, even with env-set attributes", async () => {await setup({ attributesEnvConfigured: true });@@ -423,30 +594,88 @@ describe("SettingsJWTForm", () => {});describe("user provisioning", () => {- afterEach(() => {- jest.useRealTimers();- });-- it("sits right below the server settings", async () => {+ it("sits at the top of the page", async () => {await setup();const cardTitles = screen.getAllByRole("heading", { level: 2 }).map((heading) => heading.textContent);expect(cardTitles).toEqual([- "Server settings","User provisioning",+ "Server settings","User attribute configuration","Group mapping",]);});+ it("says that JWT sign-in also reactivates deactivated accounts", async () => {+ await setup({ configured: true });++ expect(+ screen.getByRole("switch", { name: "User provisioning" }),+ ).toHaveAccessibleDescription(/reactivate deactivated accounts/);+ });+it("stays editable while JWT is paused but configured", async () => {await setup({ jwtEnabled: false, configured: true });+ const toggle = screen.getByRole("switch", { name: "User provisioning" });+ expect(toggle).toBeEnabled();+ expect(toggle).not.toHaveAttribute("aria-disabled");+ });++ it("stays editable before the server settings are saved", async () => {+ await setup();++ const toggle = screen.getByRole("switch", { name: "User provisioning" });+ expect(toggle).toBeEnabled();+ expect(toggle).not.toHaveAttribute("aria-disabled");+ });++ it("keeps existing mappings on the first save", async () => {+ await setup({ groupSync: true, groupMappings: { devs: [3] } });++ await fillServerSettings();+ await userEvent.click(+ screen.getByRole("button", { name: /Save and enable/ }),+ );++ const [{ body }] = await findRequests("PUT");+ expect(body).not.toHaveProperty("jwt-group-mappings");+ expect(body).not.toHaveProperty("jwt-group-sync");+ });++ it("keeps group mapping off when the shared secret is saved later", async () => {+ await setup({ uriOnly: true });++ await userEvent.click(+ await screen.findByRole("button", { name: /Set up key/ }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: /Done/ }),+ );+ await userEvent.click(+ screen.getByRole("button", { name: /Save and enable/ }),+ );++ const [{ body }] = await findRequests("PUT");+ expect(body).not.toHaveProperty("jwt-group-sync");+ expect(body).not.toHaveProperty("jwt-group-mappings");+ });++ it("stays editable while only the identity provider URI is saved", async () => {+ await setup({ uriOnly: true });+expect(- screen.getByRole("switch", { name: "User provisioning" }),- ).toBeEnabled();+ screen.getByText("Set up a signing key before saving"),+ ).toBeInTheDocument();++ const toggle = screen.getByRole("switch", { name: "User provisioning" });+ expect(toggle).toBeEnabled();+ expect(toggle).not.toHaveAttribute("aria-disabled");+ expect(+ screen.getByRole("button", { name: /User attribute configuration/ }),+ ).toBeDisabled();});it("saves right away without touching the page form", async () => {@@ -472,153 +701,51 @@ describe("SettingsJWTForm", () => {).toBeDisabled();});- it("reverts the switch and reports the error when the save fails", async () => {+ it("ignores clicks while the write is in flight and reverts the switch when it fails", async () => {+ const provisioningSaveGate = defer<void>();await setup({jwtEnabled: true,configured: true,provisioningSaveStatus: 500,- provisioningSaveDelayMs: 100,+ provisioningSaveGate: provisioningSaveGate.promise,});const toggle = screen.getByRole("switch", { name: "User provisioning" });+ await userEvent.click(toggle);+ await userEvent.click(toggle);await userEvent.click(toggle);- // the switch flips right away and only comes back once the write fails- expect(toggle).not.toBeChecked();+ try {+ expect(toggle).not.toBeChecked();+ expect(toggle).toHaveAttribute("aria-disabled", "true");+ } finally {+ provisioningSaveGate.resolve();+ }expect(await screen.findByText(/error saving/i)).toBeInTheDocument();expect(toggle).toBeChecked();- expect(toggle).toBeEnabled();- });-- it("keeps Enter on the switch from submitting the page form", async () => {- jest.useFakeTimers();- const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });- await setup({ jwtEnabled: true, configured: true });- await user.type(- screen.getByRole("textbox", { name: /JWT Identity Provider URI/ }),- "-edited",- );- const submitButton = screen.getByRole("button", { name: "Save changes" });- expect(submitButton).toBeEnabled();- const toggle = screen.getByRole("switch", { name: "User provisioning" });-- toggle.focus();- await user.keyboard("{Enter}");-- // give a submission time to reach the network before ruling it out- await act(() => jest.advanceTimersByTimeAsync(1000));- expect(await findRequests("PUT")).toHaveLength(0);- expect(toggle).toBeChecked();- expect(submitButton).toBeEnabled();- });-- it("sends one write for a burst of clicks", async () => {- jest.useFakeTimers();- const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });- await setup({ jwtEnabled: true, configured: true });- const toggle = screen.getByRole("switch", { name: "User provisioning" });-- await user.click(toggle);- await user.click(toggle);- await user.click(toggle);-- expect(toggle).not.toBeChecked();- await act(() =>- jest.advanceTimersByTimeAsync(PROVISIONING_WRITE_DEBOUNCE_MS),- );- expect(await screen.findByText("Changes saved")).toBeInTheDocument();- const puts = await findRequests("PUT");- expect(puts).toHaveLength(1);- expect(puts[0].body).toEqual({ value: false });- });-- it("writes a pending toggle when the page is left before the debounce fires", async () => {- jest.useFakeTimers();- const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });- const { unmount } = await setup({ jwtEnabled: true, configured: true });- const toggle = screen.getByRole("switch", { name: "User provisioning" });-- await user.click(toggle);- unmount();-- await waitFor(async () => {- expect(await findRequests("PUT")).toHaveLength(1);- });- const puts = await findRequests("PUT");- expect(puts[0].body).toEqual({ value: false });- });-- it("keeps the switch focused and enabled while the write is in flight", async () => {- await setup({- jwtEnabled: true,- configured: true,- provisioningSaveDelayMs: 100,- });- const toggle = screen.getByRole("switch", { name: "User provisioning" });-- toggle.focus();- await userEvent.keyboard(" ");-- expect(toggle).not.toBeChecked();- expect(toggle).toBeEnabled();- expect(toggle).toHaveFocus();- expect(await screen.findByText("Changes saved")).toBeInTheDocument();- expect(toggle).toHaveFocus();+ expect(toggle).not.toHaveAttribute("aria-disabled");+ expect(await findRequests("PUT")).toHaveLength(1);});- it("keeps the written value while an older properties refetch lands", async () => {- jest.useFakeTimers();- const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });- const { store, settingsStore } = await setup({+ it("holds the switch until the settings refetch after the write lands", async () => {+ const { settingsStore } = await setup({jwtEnabled: true,configured: true,});const toggle = screen.getByRole("switch", { name: "User provisioning" });- const loadRequests = fetchMock.callHistory.calls(- "get-session-properties",- ).length;- // a refetch that started before the click answers after the write has gone out- const staleSnapshot = { ...settingsStore };- fetchMock.removeRoute("get-session-properties");- fetchMock.get("path:/api/session/properties", staleSnapshot, {- name: "stale-session-properties",- delay: PROVISIONING_WRITE_DEBOUNCE_MS + 100,- repeat: 1,- });- fetchMock.get(- "path:/api/session/properties",- () => ({ ...settingsStore }),- { name: "get-session-properties", delay: 200 },- );- act(() => {- store.dispatch(settingsApi.util.invalidateTags(["session-properties"]));- });- await waitFor(() =>- expect(- fetchMock.callHistory.calls("stale-session-properties"),- ).toHaveLength(1),- );- // a click in the same millisecond would look like it came after the refetch- act(() => {- jest.advanceTimersByTime(5);- });+ await waitFor(() => expect(toggle).not.toHaveAttribute("aria-disabled"));+ const releaseReads = holdSettingsReads(settingsStore);- await user.click(toggle);+ await userEvent.click(toggle);- expect(toggle).not.toBeChecked();- // the write goes out, then the stale answer lands while the write's own refetch is still pending- await act(() =>- jest.advanceTimersByTimeAsync(PROVISIONING_WRITE_DEBOUNCE_MS + 100),- );- expect(await screen.findByText("Changes saved")).toBeInTheDocument();- expect(toggle).not.toBeChecked();- // the refetch after the write is the only one left to land- await waitFor(() =>- expect(- fetchMock.callHistory.calls("get-session-properties"),- ).toHaveLength(loadRequests + 1),- );- await act(() => jest.advanceTimersByTimeAsync(200));+ try {+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();+ expect(toggle).not.toBeChecked();+ expect(toggle).toHaveAttribute("aria-disabled", "true");+ } finally {+ releaseReads();+ }+ await waitFor(() => expect(toggle).not.toHaveAttribute("aria-disabled"));expect(toggle).not.toBeChecked();});@@ -632,7 +759,7 @@ describe("SettingsJWTForm", () => {// the effective value comes from the session properties, the admin list nils itconst toggle = screen.getByRole("switch", { name: "User provisioning" });- expect(toggle).toBeDisabled();+ expect(toggle).toHaveAttribute("aria-disabled", "true");expect(toggle).toBeChecked();expect(toggle).toHaveAccessibleDescription(/Using MB_JWT_USER_PROVISIONING_ENABLED/,@@ -647,11 +774,17 @@ describe("SettingsJWTForm", () => {expect(screen.getByRole("button", { name: /User attribute configuration/ }),).toBeDisabled();+ expect(+ screen.getByRole("radiogroup", { name: "Group mapping mode" }),+ ).toBeInTheDocument();expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();expect(screen.getByRole("radio", { name: "Off" })).toBeDisabled();expect(- screen.queryByText(/Users will be assigned to Metabase groups/),+ screen.queryByText(/people are added to the Metabase groups/),).not.toBeInTheDocument();+ expect(+ screen.getByText("Save the settings above to set up group mapping."),+ ).toBeInTheDocument();});it("derives the stored mode when JWT is paused but already configured", async () => {@@ -664,7 +797,7 @@ describe("SettingsJWTForm", () => {expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();expect(screen.getByRole("radio", { name: "Manual" })).toBeEnabled();- const row = screen.getByTestId("jwt-group-mapping-row");+ const row = screen.getByTestId("group-mapping-row");expect(within(row).getByText("group-a")).toBeInTheDocument();expect(await within(row).findByText("foo")).toBeInTheDocument();});@@ -675,6 +808,36 @@ describe("SettingsJWTForm", () => {expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();});+ it("holds the mode control until the settings refetch after the write lands", async () => {+ const { settingsStore } = await setup({+ jwtEnabled: true,+ configured: true,+ });+ const automatic = () => screen.getByRole("radio", { name: "Automatic" });+ const manual = () => screen.getByRole("radio", { name: "Manual" });+ await waitFor(() =>+ expect(modeLabel("Manual")).not.toHaveAttribute("data-read-only"),+ );+ const releaseReads = holdSettingsReads(settingsStore);++ await userEvent.click(automatic());++ try {+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();+ expect(automatic()).toBeChecked();+ expect(automatic()).toBeEnabled();+ expect(automatic()).toHaveFocus();+ expect(modeLabel("Manual")).toHaveAttribute("data-read-only");+ await userEvent.click(manual());+ expect(automatic()).toBeChecked();+ } finally {+ releaseReads();+ }+ await waitFor(() =>+ expect(modeLabel("Manual")).not.toHaveAttribute("data-read-only"),+ );+ });+it("writes a new mapping immediately without touching the page form", async () => {await setup({jwtEnabled: true,@@ -693,9 +856,7 @@ describe("SettingsJWTForm", () => {"jwt-group-mappings": { existing: [3], devs: [4] },});expect(await screen.findByText("Mapping added")).toBeInTheDocument();- expect(- await screen.findAllByTestId("jwt-group-mapping-row"),- ).toHaveLength(2);+ expect(await screen.findAllByTestId("group-mapping-row")).toHaveLength(2);expect(screen.getByRole("button", { name: "Save changes" }),).toBeDisabled();@@ -720,16 +881,14 @@ describe("SettingsJWTForm", () => {});await waitFor(() => expect(findMappingRow("other")).toBeDefined());- await userEvent.click(+ await clickWhenEnabled(screen.getByRole("button", { name: "Delete mapping" }),);await userEvent.click(await screen.findByRole("button", { name: "Remove mapping" }),);- expect(- await screen.findByText("Mapping deleted and group mapping turned off"),- ).toBeInTheDocument();+ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();expect(screen.getByRole("radio", { name: "Manual" })).not.toBeChecked();});@@ -771,18 +930,16 @@ describe("SettingsJWTForm", () => {expect(screen.getByRole("radio", { name: "Off" })).toBeChecked();});expect(await findRequests("PUT")).toHaveLength(1);- expect(- screen.queryByTestId("jwt-group-mapping-row"),- ).not.toBeInTheDocument();+ expect(screen.queryByTestId("group-mapping-row")).not.toBeInTheDocument();await userEvent.click(screen.getByRole("radio", { name: "Manual" }));await waitFor(() => {expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();});- expect(- await screen.findByTestId("jwt-group-mapping-row"),- ).toHaveTextContent("existing");+ expect(await screen.findByTestId("group-mapping-row")).toHaveTextContent(+ "existing",+ );const puts = await findRequests("PUT");expect(puts.map(({ body }) => body)).toEqual([{ "jwt-group-sync": false },@@ -790,92 +947,37 @@ describe("SettingsJWTForm", () => {]);});- it("deletes a mapping and clears its groups right away", async () => {+ it("reports a failed cascade once and skips the success toast", async () => {await setup({jwtEnabled: true,configured: true,groupSync: true,- groupMappings: { admins: [4], devs: [3] },+ groupMappings: { old: [4, 5], devs: [3] },+ cascadeStatus: 500,});- await userEvent.click(- within(findMappingRow("admins")!).getByRole("button", {- name: "Delete mapping",- }),- );- await userEvent.click(- await screen.findByRole("radio", { name: /Also remove all members/ }),- );- await userEvent.click(- screen.getByRole("button", { name: "Remove mapping and members" }),- );+ await deleteMappingWithGroups("old", "Remove mapping and delete groups");- expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();- const puts = await findRequests("PUT");- const settingsIndex = puts.findIndex(({ url }) =>- /\/api\/setting$/.test(url),- );- const clearIndex = puts.findIndex(({ url }) =>- url.includes("/api/permissions/membership/4/clear"),- );- expect(puts[settingsIndex].body).toEqual({- "jwt-group-mappings": { devs: [3] },- });- // the cascade runs only after the mapping was removed- expect(clearIndex).toBeGreaterThan(settingsIndex);expect(- puts.some(({ url }) =>- url.includes("/api/permissions/membership/3/clear"),+ await screen.findAllByText(+ "Mapping deleted, but not all of its groups could be updated",),- ).toBe(false);+ ).toHaveLength(1);+ expect(screen.queryByText("Mapping deleted")).not.toBeInTheDocument();+ const deletes = await findRequests("DELETE");+ expect(deletes).toHaveLength(2);await waitFor(() => {- expect(findMappingRow("admins")).toBeUndefined();+ expect(findMappingRow("old")).toBeUndefined();});});- it("reports a failed cascade once and skips the success toast", async () => {+ it("keeps the editor open and reports the error when the write fails", async () => {await setup({jwtEnabled: true,configured: true,groupSync: true,- groupMappings: { old: [4, 5], devs: [3] },- cascadeStatus: 500,- });-- await userEvent.click(- within(findMappingRow("old")!).getByRole("button", {- name: "Delete mapping",- }),- );- await userEvent.click(- await screen.findByRole("radio", { name: /Also delete the groups/ }),- );- await userEvent.click(- screen.getByRole("button", {- name: "Remove mapping and delete groups",- }),- );-- expect(- await screen.findAllByText(- "Mapping deleted, but not all of its groups could be updated",- ),- ).toHaveLength(1);- expect(screen.queryByText("Mapping deleted")).not.toBeInTheDocument();- const deletes = await findRequests("DELETE");- expect(deletes).toHaveLength(2);- await waitFor(() => {- expect(findMappingRow("old")).toBeUndefined();- });- });-- it("keeps the editor open and reports the error when the write fails", async () => {- await setup({- jwtEnabled: true,- configured: true,- groupSync: true,- groupMappings: { existing: [3] },- saveStatus: 500,+ groupMappings: { existing: [3] },+ saveStatus: 500,});await addMapping("devs", "bar");@@ -887,7 +989,7 @@ describe("SettingsJWTForm", () => {"devs",);expect(screen.getByRole("button", { name: "Add mapping" })).toBeEnabled();- expect(screen.getAllByTestId("jwt-group-mapping-row")).toHaveLength(1);+ expect(screen.getAllByTestId("group-mapping-row")).toHaveLength(1);expect(screen.queryByText("Mapping added")).not.toBeInTheDocument();});@@ -900,17 +1002,7 @@ describe("SettingsJWTForm", () => {saveStatus: 500,});- await userEvent.click(- within(findMappingRow("old")!).getByRole("button", {- name: "Delete mapping",- }),- );- await userEvent.click(- await screen.findByRole("radio", { name: /Also delete the group/ }),- );- await userEvent.click(- screen.getByRole("button", { name: "Remove mapping and delete group" }),- );+ await deleteMappingWithGroups("old", "Remove mapping and delete group");expect(await screen.findByText("Error saving group mapping"),@@ -939,82 +1031,225 @@ describe("SettingsJWTForm", () => {expect(findMappingRow("existing")).toBeDefined();});- it("disables the new mapping button while a save is in flight", async () => {+ it("keeps Enter on the mode control from submitting the page form and lets the other keys switch it", async () => {+ await setup({ configured: true, groupSync: true });+ await userEvent.type(+ screen.getByRole("textbox", { name: /JWT Identity Provider URI/ }),+ "/sso",+ );+ const saveButton = screen.getByRole("button", {+ name: "Save and enable",+ });+ expect(saveButton).toBeEnabled();+ const offRadio = screen.getByRole("radio", { name: "Off" });++ act(() => offRadio.focus());+ await userEvent.keyboard("{Enter}");++ expect(await findRequests("PUT")).toHaveLength(0);+ expect(saveButton).toBeEnabled();++ await userEvent.keyboard(" ");++ await waitFor(() => expect(offRadio).toBeChecked());+ const [{ body }] = await findRequests("PUT");+ expect(body).toEqual({ "jwt-group-sync": false });+ });++ it("keeps an open draft when a mode switch is cancelled or fails", async () => {await setup({jwtEnabled: true,configured: true,groupSync: true,- groupMappings: { existing: [3] },- saveDelayMs: 300,+ groupMappings: { devs: [3] },+ saveStatus: 500,});- await addMapping("devs", "bar");+ await clickWhenEnabled(+ within(findMappingRow("devs")!).getByRole("button", {+ name: "Edit mapping",+ }),+ );+ await userEvent.type(+ screen.getByPlaceholderText("Enter JWT group..."),+ "-team",+ );+ await userEvent.click(screen.getByRole("radio", { name: "Automatic" }));+ await userEvent.click(+ within(await screen.findByRole("dialog")).getByRole("button", {+ name: "Cancel",+ }),+ );+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );+ await userEvent.click(screen.getByRole("radio", { name: "Off" }));expect(- screen.getByRole("button", { name: "New mapping" }),- ).toBeDisabled();- expect(- await screen.findByText("Mapping added", {}, { timeout: 3000 }),+ await screen.findByText("Error saving group mapping"),).toBeInTheDocument();- expect(screen.getByRole("button", { name: "New mapping" })).toBeEnabled();+ expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();+ expect(screen.getByPlaceholderText("Enter JWT group...")).toHaveValue(+ "devs-team",+ );});- it("keeps the controls disabled until the cascade finishes", async () => {+ it("hides the new mapping button while a draft is open", async () => {await setup({jwtEnabled: true,configured: true,groupSync: true,- groupMappings: { old: [4], devs: [3] },- cascadeDelayMs: 300,+ groupMappings: { devs: [3] },});+ const newButton = () =>+ screen.queryByRole("button", { name: "New mapping" });- await userEvent.click(- within(findMappingRow("old")!).getByRole("button", {- name: "Delete mapping",+ await clickWhenEnabled(+ within(findMappingRow("devs")!).getByRole("button", {+ name: "Edit mapping",}),);- await userEvent.click(- await screen.findByRole("radio", { name: /Also delete the group/ }),- );- await userEvent.click(- screen.getByRole("button", { name: "Remove mapping and delete group" }),+ expect(newButton()).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(newButton()).toBeInTheDocument();+ });++ it("holds the mapping rows while a save is in flight", async () => {+ const saveGate = defer<void>();+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { existing: [3] },+ saveGate: saveGate.promise,+ });+ const deleteButton = within(findMappingRow("existing")!).getByRole(+ "button",+ { name: "Delete mapping" },);- // the mapping write is done once the row is gone, while the group delete is still in flight- await waitFor(() => expect(findMappingRow("old")).toBeUndefined());- expect(+ await addMapping("devs", "bar");++ try {+ expect(deleteButton).toBeDisabled();+ } finally {+ saveGate.resolve();+ }+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();+ await waitFor(() => expect(deleteButton).toBeEnabled());+ });++ it("holds the mapping controls until the groups have loaded", async () => {+ const groupsGate = defer<void>();+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { devs: [3] },+ groupsGate: groupsGate.promise,+ });+ const newButton = () =>+ screen.getByRole("button", { name: "New mapping" });+ const deleteButton = () =>within(findMappingRow("devs")!).getByRole("button", {name: "Delete mapping",- }),- ).toBeDisabled();- expect(screen.getByRole("radio", { name: "Off" })).toBeDisabled();+ });++ try {+ expect(newButton()).toBeDisabled();+ expect(deleteButton()).toBeDisabled();+ expect(screen.getByRole("radio", { name: "Off" })).toBeEnabled();+ await waitFor(() =>+ expect(modeLabel("Off")).not.toHaveAttribute("data-read-only"),+ );+ expect(newButton()).toBeDisabled();+ } finally {+ groupsGate.resolve();+ }+ await waitFor(() => expect(newButton()).toBeEnabled());+ expect(deleteButton()).toBeEnabled();+ });++ it("holds the controls until the cascade finishes", async () => {+ const cascadeGate = defer<void>();+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { old: [4], devs: [3] },+ cascadeGate: cascadeGate.promise,+ });++ await deleteMappingWithGroups("old", "Remove mapping and delete group");++ try {+ await waitFor(() => expect(findMappingRow("old")).toBeUndefined());+ expect(+ within(findMappingRow("devs")!).getByRole("button", {+ name: "Delete mapping",+ }),+ ).toBeDisabled();+ expect(screen.getByRole("radio", { name: "Off" })).toBeEnabled();+ expect(modeLabel("Off")).toHaveAttribute("data-read-only");+ } finally {+ cascadeGate.resolve();+ }+ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();+ await waitFor(() =>+ expect(+ within(findMappingRow("devs")!).getByRole("button", {+ name: "Delete mapping",+ }),+ ).toBeEnabled(),+ );+ expect(modeLabel("Off")).not.toHaveAttribute("data-read-only");+ });++ it("keeps a group in the other mappings when its deletion is refused", async () => {+ await setup({+ jwtEnabled: true,+ configured: true,+ groupSync: true,+ groupMappings: { old: [4, 3], devs: [3] },+ deleteGroupStatuses: { 3: 400 },+ });++ await deleteMappingWithGroups("old", "Remove mapping and delete groups");expect(- await screen.findByText("Mapping deleted", {}, { timeout: 3000 }),+ await screen.findByText(+ "Mapping deleted, but not all of its groups could be updated",+ ),).toBeInTheDocument();- expect(- within(findMappingRow("devs")!).getByRole("button", {- name: "Delete mapping",- }),- ).toBeEnabled();- expect(screen.getByRole("radio", { name: "Off" })).toBeEnabled();+ const puts = await findRequests("PUT");+ expect(puts.map(({ body }) => body)).toEqual([+ { "jwt-group-mappings": { devs: [3] } },+ ]);+ expect(findMappingRow("devs")).toHaveTextContent("foo");});- it("deletes a mapping's groups and drops them from the other mappings in the same write", async () => {+ it("deletes only a mapping's deletable groups and drops them from the other mappings once they are gone", async () => {await setup({jwtEnabled: true,configured: true,groupSync: true,- groupMappings: { old: [4], devs: [4, 3] },+ groupMappings: { old: [4, 6], devs: [4, 3] },});- await userEvent.click(+ await clickWhenEnabled(within(findMappingRow("old")!).getByRole("button", {name: "Delete mapping",}),);+ expect(+ await screen.findByText(/The Data Analysts group is not affected/),+ ).toBeInTheDocument();+ const dialog = within(screen.getByRole("dialog"));+ expect(dialog.getByText("old")).toBeInTheDocument();+ expect(dialog.getByText("bar")).toBeInTheDocument();await userEvent.click(- await screen.findByRole("radio", { name: /Also delete the group/ }),+ screen.getByRole("radio", { name: "Also delete the group" }),);await userEvent.click(screen.getByRole("button", { name: "Remove mapping and delete group" }),@@ -1022,10 +1257,10 @@ describe("SettingsJWTForm", () => {expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();const puts = await findRequests("PUT");- const settingsPut = puts.find(({ url }) => /\/api\/setting$/.test(url));- expect(settingsPut?.body).toEqual({- "jwt-group-mappings": { devs: [3] },- });+ expect(puts.map(({ body }) => body)).toEqual([+ { "jwt-group-mappings": { devs: [4, 3] } },+ { "jwt-group-mappings": { devs: [3] } },+ ]);const deletes = await findRequests("DELETE");expect(deletes.map(({ url }) => url)).toEqual(["http://localhost/api/permissions/group/4",@@ -1040,7 +1275,7 @@ describe("SettingsJWTForm", () => {groupMappings: { devs: [9, 3] },});- await userEvent.click(+ await clickWhenEnabled(screen.getByRole("button", { name: "Edit mapping" }),);@@ -1061,7 +1296,7 @@ describe("SettingsJWTForm", () => {groupMappings: { only: [3] },});- await userEvent.click(+ await clickWhenEnabled(screen.getByRole("button", { name: "Delete mapping" }),);expect(@@ -1073,9 +1308,7 @@ describe("SettingsJWTForm", () => {screen.getByRole("button", { name: "Remove mapping" }),);- expect(- await screen.findByText("Mapping deleted and group mapping turned off"),- ).toBeInTheDocument();+ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();const [{ body }] = await findRequests("PUT");expect(body).toEqual({"jwt-group-mappings": {},@@ -1086,44 +1319,6 @@ describe("SettingsJWTForm", () => {});});- it("keeps a renamed mapping in place and rejects duplicate names", async () => {- await setup({- jwtEnabled: true,- configured: true,- groupSync: true,- groupMappings: { first: [3], second: [4] },- });-- await userEvent.click(- within(findMappingRow("second")!).getByRole("button", {- name: "Edit mapping",- }),- );- const nameInput = screen.getByLabelText("JWT group name");- await userEvent.clear(nameInput);- await userEvent.type(nameInput, "first");-- expect(- screen.getByText("A mapping for this group already exists"),- ).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();-- await userEvent.clear(nameInput);- await userEvent.type(nameInput, "second-renamed");- await userEvent.click(screen.getByRole("button", { name: "Save" }));-- expect(await screen.findByText("Mapping updated")).toBeInTheDocument();- const [{ body }] = await findRequests("PUT");- expect(body["jwt-group-mappings"]).toEqual({- first: [3],- "second-renamed": [4],- });- const names = screen- .getAllByTestId("jwt-group-mapping-row")- .map((row) => within(row).getAllByText(/./)[0].textContent);- expect(names).toEqual(["first", "second-renamed"]);- });-it("allows mapping names that collide with object prototype members", async () => {await setup({jwtEnabled: true,@@ -1132,7 +1327,7 @@ describe("SettingsJWTForm", () => {groupMappings: { existing: [3] },});- await userEvent.click(+ await clickWhenEnabled(screen.getByRole("button", { name: "New mapping" }),);await userEvent.type(@@ -1151,49 +1346,7 @@ describe("SettingsJWTForm", () => {screen.getByRole("button", { name: "Add mapping" }),);- expect(- await screen.findAllByTestId("jwt-group-mapping-row"),- ).toHaveLength(2);- });-- it("commits the row editor on Enter instead of submitting the page", async () => {- await setup({- jwtEnabled: true,- configured: true,- groupSync: true,- groupMappings: { existing: [3] },- });-- // a dirty page form has a live Save button, so Enter could submit it- await userEvent.type(- screen.getByRole("textbox", { name: /JWT Identity Provider URI/ }),- "/v2",- );- expect(- screen.getByRole("button", { name: "Save changes" }),- ).toBeEnabled();-- await userEvent.click(- screen.getByRole("button", { name: "New mapping" }),- );- const nameInput = screen.getByPlaceholderText("Enter JWT group...");- await userEvent.type(nameInput, "devs");- await userEvent.click(- screen.getByPlaceholderText("Pick Metabase group..."),- );- await userEvent.click(await screen.findByRole("option", { name: "bar" }));- await userEvent.click(nameInput);- await userEvent.keyboard("{Enter}");-- await waitFor(() => {- expect(- screen.queryByPlaceholderText("Enter JWT group..."),- ).not.toBeInTheDocument();- });- expect(screen.getAllByTestId("jwt-group-mapping-row")).toHaveLength(2);- const puts = await findRequests("PUT");- expect(puts).toHaveLength(1);- expect(puts[0].body).not.toHaveProperty("jwt-identity-provider-uri");+ expect(await screen.findAllByTestId("group-mapping-row")).toHaveLength(2);});it("cancels the row editor on Escape", async () => {@@ -1204,7 +1357,7 @@ describe("SettingsJWTForm", () => {groupMappings: { existing: [3] },});- await userEvent.click(+ await clickWhenEnabled(screen.getByRole("button", { name: "New mapping" }),);await userEvent.type(@@ -1215,93 +1368,10 @@ describe("SettingsJWTForm", () => {expect(screen.queryByPlaceholderText("Enter JWT group..."),).not.toBeInTheDocument();- expect(screen.getAllByTestId("jwt-group-mapping-row")).toHaveLength(1);+ expect(screen.getAllByTestId("group-mapping-row")).toHaveLength(1);expect(await findRequests("PUT")).toHaveLength(0);});- it("confirms admin-only and zero-group deletions without offering cascades", async () => {- await setup({- jwtEnabled: true,- configured: true,- groupSync: true,- groupMappings: { admins: [2], legacy: [], devs: [3] },- });-- await userEvent.click(- within(findMappingRow("admins")!).getByRole("button", {- name: "Delete mapping",- }),- );- const adminsModal = await screen.findByRole("dialog");- expect(- within(adminsModal).getByText("Remove this group mapping?"),- ).toBeInTheDocument();- expect(- within(adminsModal).getByText(- "The Administrators group is not affected.",- ),- ).toBeInTheDocument();- expect(within(adminsModal).queryByRole("radio")).not.toBeInTheDocument();- await userEvent.click(- within(adminsModal).getByRole("button", { name: "Remove mapping" }),- );- await waitFor(() => {- expect(findMappingRow("admins")).toBeUndefined();- });-- await userEvent.click(- within(findMappingRow("legacy")!).getByRole("button", {- name: "Delete mapping",- }),- );- const legacyModal = await screen.findByRole("dialog");- expect(- within(legacyModal).getByText(- "This mapping isn't linked to any group.",- ),- ).toBeInTheDocument();- expect(within(legacyModal).queryByRole("radio")).not.toBeInTheDocument();- await userEvent.click(- within(legacyModal).getByRole("button", { name: "Remove mapping" }),- );- await waitFor(() => {- expect(findMappingRow("legacy")).toBeUndefined();- });-- await userEvent.click(- within(findMappingRow("devs")!).getByRole("button", {- name: "Delete mapping",- }),- );- const devsModal = await screen.findByRole("dialog");- expect(within(devsModal).getAllByRole("radio")).toHaveLength(3);- const puts = await findRequests("PUT");- expect(puts.map(({ body }) => body["jwt-group-mappings"])).toEqual([- { legacy: [], devs: [3] },- { devs: [3] },- ]);- });-- it("names the mode control and the editor inputs for assistive tech", async () => {- await setup({- jwtEnabled: true,- configured: true,- groupSync: true,- groupMappings: { existing: [3] },- });-- expect(- screen.getByRole("radiogroup", { name: "Group mapping mode" }),- ).toBeInTheDocument();-- await userEvent.click(- screen.getByRole("button", { name: "New mapping" }),- );-- expect(screen.getByLabelText("JWT group name")).toBeInTheDocument();- expect(screen.getByLabelText("Metabase groups")).toBeInTheDocument();- });-it("asks for confirmation before switching to automatic and stays manual on cancel", async () => {await setup({jwtEnabled: true,@@ -1315,6 +1385,11 @@ describe("SettingsJWTForm", () => {expect(await screen.findByText("Switch to automatic group mapping?"),).toBeInTheDocument();+ expect(+ screen.getByText(+ "Your existing group mappings will be deleted. From then on, at each sign-in, people are added to the Metabase groups named in their JWT and removed from all other groups, including Administrators.",+ ),+ ).toBeInTheDocument();await userEvent.click(screen.getByRole("button", { name: "Cancel" }));expect(@@ -1348,18 +1423,17 @@ describe("SettingsJWTForm", () => {"jwt-group-sync": true,"jwt-group-mappings": {},});- expect(- screen.queryByTestId("jwt-group-mapping-row"),- ).not.toBeInTheDocument();+ expect(screen.queryByTestId("group-mapping-row")).not.toBeInTheDocument();});it("keeps the confirmation busy until the automatic switch is saved", async () => {+ const saveGate = defer<void>();await setup({jwtEnabled: true,configured: true,groupSync: true,groupMappings: { "group-a": [3] },- saveDelayMs: 300,+ saveGate: saveGate.promise,});await userEvent.click(screen.getByRole("radio", { name: "Automatic" }));@@ -1368,18 +1442,18 @@ describe("SettingsJWTForm", () => {});await userEvent.dblClick(confirmButton);- expect(confirmButton).toBeDisabled();- expect(- screen.getByText("Switch to automatic group mapping?"),- ).toBeInTheDocument();-- await waitFor(- () => {- expect(- screen.queryByText("Switch to automatic group mapping?"),- ).not.toBeInTheDocument();- },- { timeout: 3000 },+ try {+ expect(confirmButton).toBeDisabled();+ expect(+ screen.getByText("Switch to automatic group mapping?"),+ ).toBeInTheDocument();+ } finally {+ saveGate.resolve();+ }+ await waitFor(() =>+ expect(+ screen.queryByText("Switch to automatic group mapping?"),+ ).not.toBeInTheDocument(),);expect(await findRequests("PUT")).toHaveLength(1);});@@ -1426,7 +1500,7 @@ describe("SettingsJWTForm", () => {).toBeInTheDocument();expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();expect(screen.getByRole("radio", { name: "Manual" })).toBeDisabled();- expect(screen.getByTestId("jwt-group-mapping-row")).toHaveTextContent(+ expect(screen.getByTestId("group-mapping-row")).toHaveTextContent("env-group",);expect(@@ -1448,7 +1522,7 @@ describe("SettingsJWTForm", () => {expect(screen.getByText("Using MB_JWT_GROUP_SYNC")).toBeInTheDocument();expect(screen.getByRole("radio", { name: "Manual" })).toBeChecked();- expect(screen.getByTestId("jwt-group-mapping-row")).toHaveTextContent(+ expect(screen.getByTestId("group-mapping-row")).toHaveTextContent("stored-group",);expect(@@ -1456,15 +1530,15 @@ describe("SettingsJWTForm", () => {).not.toBeInTheDocument();});- it("does not turn sync on with the first save when it is env-configured", async () => {+ it("leaves the save hint out and sync alone on the first save while an env var sets group mapping", async () => {await setup({ groupSyncEnvConfigured: true });- await userEvent.type(- await screen.findByRole("textbox", {- name: /JWT Identity Provider URI/,- }),- ATTRS["jwt-identity-provider-uri"],- );+ expect(screen.getByText("Using MB_JWT_GROUP_SYNC")).toBeInTheDocument();+ expect(+ screen.queryByText("Save the settings above to set up group mapping."),+ ).not.toBeInTheDocument();++ await fillServerSettings();await userEvent.click(await screen.findByRole("button", { name: /Save/ }),);diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/OidcGroupMappingSection/OidcGroupMappingSection.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/OidcGroupMappingSection/OidcGroupMappingSection.tsxnew file mode 100644index 00000000000..fecdc924998--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/OidcGroupMappingSection/OidcGroupMappingSection.tsx@@ -0,0 +1,160 @@+import { useEffect, useState } from "react";+import { t } from "ttag";++import {+ EMPTY_MAPPINGS,+ GroupMappingsPanel,+ type GroupMappingsSaveResult,+ type SaveOptions,+ useGroupLookup,+} from "metabase/admin/settings/auth/components/GroupMappings";+import { getErrorMessage } from "metabase/api/utils/errors";+import { useToast } from "metabase/common/hooks";+import { useDispatch, useSelector } from "metabase/redux";+import { getApplicationName } from "metabase/selectors/whitelabel";+import { SwitchSettingsSection } from "metabase/settings-components";+import type { BoxProps } from "metabase/ui";+import {+ type CustomOidcConfig,+ customOidcApi,+ useGetCustomOidcProvidersQuery,+ useUpdateCustomOidcMutation,+} from "metabase-enterprise/api";++import { type OidcGroupSync, toGroupSync } from "../group-sync";++type OidcGroupMappingSectionProps = {+ provider: CustomOidcConfig | null;+ onSavingChange?: (isSaving: boolean) => void;+ children: React.ReactNode;+ lockedEnvName?: string;+ isPageSaving?: boolean;+ disabled?: boolean;+ onToggle?: (enabled: boolean) => void;+} & BoxProps;++/** OIDC group mapping card whose switch and mappings save apart from the page form */+export function OidcGroupMappingSection({+ provider,+ onSavingChange,+ children,+ lockedEnvName,+ isPageSaving = false,+ disabled = false,+ onToggle,+ ...boxProps+}: OidcGroupMappingSectionProps) {+ const applicationName = useSelector(getApplicationName);+ const dispatch = useDispatch();+ const [sendToast] = useToast();+ const groupLookup = useGroupLookup({ tenancy: "internal" });+ const { isFetching: isProvidersFetching } = useGetCustomOidcProvidersQuery();+ const [updateProvider, { isLoading: isUpdating }] =+ useUpdateCustomOidcMutation();+ const [isDeleting, setIsDeleting] = useState(false);+ // a deletion makes several writes, and nothing else may write the provider between them+ const isSaving = isUpdating || isDeleting;+ useEffect(() => {+ onSavingChange?.(isSaving);+ }, [isSaving, onSavingChange]);+ // a refetch still in flight could answer with the value from before the write+ const isWriting = isSaving || isProvidersFetching || isPageSaving;+ const isLocked = lockedEnvName != null;+ const isUnconfigured = disabled || provider == null;+ const isLockedUntilSave = isUnconfigured && !isLocked;++ const patchCachedProvider = (shown: CustomOidcConfig) =>+ dispatch(+ customOidcApi.util.updateQueryData(+ "getCustomOidcProviders",+ undefined,+ (draft) => {+ const index = draft.findIndex((entry) => entry.key === shown.key);+ if (index !== -1) {+ draft[index] = shown;+ }+ },+ ),+ );++ const saveGroupSync = async (+ current: CustomOidcConfig,+ changes: Partial<OidcGroupSync>,+ { successMessage, showErrorToast = true }: SaveOptions = {},+ ): Promise<GroupMappingsSaveResult> => {+ const { data: savedProvider, error: writeError } = await updateProvider({+ key: current.key,+ provider: { "group-sync": toGroupSync(current["group-sync"], changes) },+ });+ if (writeError != null || savedProvider == null) {+ const error = getErrorMessage(writeError, t`Error saving group mapping`);+ if (showErrorToast) {+ sendToast({+ message: error,+ icon: "warning",+ toastColor: "feedback-negative",+ });+ }+ return { ok: false, error };+ }+ patchCachedProvider(savedProvider);+ if (successMessage != null) {+ sendToast({ message: successMessage, icon: "check_filled" });+ }+ return { ok: true };+ };++ const handleChange = async (enabled: boolean) => {+ if (provider == null) {+ return;+ }+ const patch = patchCachedProvider({+ ...provider,+ "group-sync": toGroupSync(provider["group-sync"], { enabled }),+ });+ const result = await saveGroupSync(+ provider,+ { enabled },+ { successMessage: t`Changes saved` },+ );+ if (result.ok) {+ onToggle?.(enabled);+ } else {+ patch.undo();+ }+ };++ return (+ <SwitchSettingsSection+ title={t`Group mapping`}+ description={t`Automatically assign people to ${applicationName} groups based on groups from your OIDC provider`}+ note={+ isLockedUntilSave && t`Save the settings above to set up group mapping.`+ }+ checked={provider?.["group-sync"]?.enabled ?? false}+ disabled={isUnconfigured}+ switchDisabled={isWriting}+ lockedEnvName={lockedEnvName}+ onChange={handleChange}+ {...boxProps}+ >+ {provider != null && (+ <GroupMappingsPanel+ mappings={+ provider["group-sync"]?.["group-mappings"] ?? EMPTY_MAPPINGS+ }+ saveMappings={(mappings, options) =>+ saveGroupSync(provider, { "group-mappings": mappings }, options)+ }+ onDeletingChange={setIsDeleting}+ groupLookup={groupLookup}+ disabled={isWriting}+ readOnly={isLocked}+ nameLabel={t`OIDC group name`}+ namePlaceholder={t`Enter OIDC group...`}+ />+ )}+ {children}+ </SwitchSettingsSection>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/OidcGroupMappingSection/index.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/OidcGroupMappingSection/index.tsnew file mode 100644index 00000000000..0df37f859ff--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/OidcGroupMappingSection/index.ts@@ -0,0 +1 @@+export * from "./OidcGroupMappingSection";diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsxindex 955d9fe7842..7293e55ac27 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx@@ -1,18 +1,16 @@-import { useDisclosure } from "@mantine/hooks";-import { useCallback, useEffect, useMemo, useRef } from "react";+import type { FormikHelpers } from "formik";+import { useCallback, useMemo, useState } from "react";import { t } from "ttag";import * as Yup from "yup";-import { GroupMappingsWidgetView } from "metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView";-import { SETTINGS_FIELD_DESCRIPTION_PROPS } from "metabase/admin/settings/utils";import {- useClearGroupMembershipMutation,- useDeletePermissionsGroupMutation,- useListPermissionsGroupsQuery,-} from "metabase/api";+ SETTINGS_FIELD_DESCRIPTION_PROPS,+ resetFieldsToInitial,+} from "metabase/admin/settings/utils";import { getErrorMessage } from "metabase/api/utils/errors";-import { ConfirmModal } from "metabase/common/components/ConfirmModal";+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { SetByEnvVar } from "metabase/common/components/SetByEnvVar";import { useToast } from "metabase/common/hooks";import {Form,@@ -23,10 +21,13 @@ import {} from "metabase/forms";import { useSelector } from "metabase/redux";import { getApplicationName } from "metabase/selectors/whitelabel";-import { useSetting } from "metabase/settings";+import {+ useGetAdminSettingsDetailsQuery,+ useGetSettingsQuery,+ useSetting,+} from "metabase/settings";import {CollapsibleSettingsSection,- SETTINGS_CARD_DESCRIPTION_PROPS,SETTINGS_CARD_STACK_PROPS,SETTINGS_CARD_TITLE_PROPS,SettingsPageWrapper,@@ -38,19 +39,24 @@ import {type OidcCheckRequest,useCheckOidcConnectionMutation,useCreateCustomOidcMutation,- useDeleteCustomOidcMutation,useGetCustomOidcProvidersQuery,useUpdateCustomOidcMutation,} from "metabase-enterprise/api";import { UserProvisioningSection } from "metabase-enterprise/auth/components/UserProvisioningSection";-import type { Group, GroupId } from "metabase-types/api";++import { OidcGroupMappingSection } from "./OidcGroupMappingSection";+import {+ DEFAULT_GROUP_ATTRIBUTE,+ type OidcGroupSync,+ toGroupSync,+} from "./group-sync";const DEFAULT_SCOPES = ["openid", "email", "profile"];-const DEFAULT_EMAIL_ATTRIBUTE = "email";const DEFAULT_FIRST_NAME_ATTRIBUTE = "given_name";const DEFAULT_LAST_NAME_ATTRIBUTE = "family_name";-function getOidcFormSchema() {+// the API keeps an existing provider's secret when none is sent, but a new provider needs one+function getOidcFormSchema({ isExisting }: { isExisting: boolean }) {return Yup.object({"login-prompt": Yup.string().required(t`Login prompt is required`),key: Yup.string()@@ -61,17 +67,13 @@ function getOidcFormSchema() {),"issuer-uri": Yup.string().required(t`Issuer URI is required`),"client-id": Yup.string().required(t`Client ID is required`),- "client-secret": Yup.string().nullable().default(null),- scopes: Yup.string().nullable().default(DEFAULT_SCOPES.join(", ")),- "attribute-email": Yup.string().nullable().default(DEFAULT_EMAIL_ATTRIBUTE),- "attribute-firstname": Yup.string()- .nullable()- .default(DEFAULT_FIRST_NAME_ATTRIBUTE),- "attribute-lastname": Yup.string()- .nullable()- .default(DEFAULT_LAST_NAME_ATTRIBUTE),- "group-sync-enabled": Yup.boolean().default(false),- "group-attribute": Yup.string().nullable().default("groups"),+ "client-secret": isExisting+ ? Yup.string().nullable().default(null)+ : Yup.string().required(t`Client secret is required`),+ scopes: Yup.string().nullable().default(null),+ "attribute-firstname": Yup.string().nullable().default(null),+ "attribute-lastname": Yup.string().nullable().default(null),+ "group-attribute": Yup.string().nullable().default(null),});}@@ -82,13 +84,16 @@ interface OIDCFormValues {"client-id": string;"client-secret": string | null;scopes: string | null;- "attribute-email": string | null;"attribute-firstname": string | null;"attribute-lastname": string | null;- "group-sync-enabled": boolean;"group-attribute": string | null;}+const withoutDefault = (+ value: string | undefined,+ defaultValue: string,+): string | null => (value == null || value === defaultValue ? null : value);+function providerToFormValues(provider: CustomOidcConfig | null,): OIDCFormValues {@@ -99,17 +104,14 @@ function providerToFormValues("issuer-uri": "","client-id": "","client-secret": null,- scopes: DEFAULT_SCOPES.join(", "),- "attribute-email": DEFAULT_EMAIL_ATTRIBUTE,- "attribute-firstname": DEFAULT_FIRST_NAME_ATTRIBUTE,- "attribute-lastname": DEFAULT_LAST_NAME_ATTRIBUTE,- "group-sync-enabled": false,- "group-attribute": "groups",+ scopes: null,+ "attribute-firstname": null,+ "attribute-lastname": null,+ "group-attribute": null,};}const attributeMap = provider["attribute-map"] ?? {};- const groupSync = provider["group-sync"] ?? {};return {"login-prompt": provider["login-prompt"] ?? "",@@ -117,20 +119,28 @@ function providerToFormValues("issuer-uri": provider["issuer-uri"] ?? "","client-id": provider["client-id"] ?? "","client-secret": null,- scopes: (provider.scopes ?? DEFAULT_SCOPES).join(", "),- "attribute-email": attributeMap["email"] ?? DEFAULT_EMAIL_ATTRIBUTE,- "attribute-firstname":- attributeMap["first_name"] ?? DEFAULT_FIRST_NAME_ATTRIBUTE,- "attribute-lastname":- attributeMap["last_name"] ?? DEFAULT_LAST_NAME_ATTRIBUTE,- "group-sync-enabled": groupSync.enabled ?? false,- "group-attribute": groupSync["group-attribute"] ?? "groups",+ scopes: withoutDefault(+ provider.scopes?.join(", "),+ DEFAULT_SCOPES.join(", "),+ ),+ "attribute-firstname": withoutDefault(+ attributeMap["first_name"],+ DEFAULT_FIRST_NAME_ATTRIBUTE,+ ),+ "attribute-lastname": withoutDefault(+ attributeMap["last_name"],+ DEFAULT_LAST_NAME_ATTRIBUTE,+ ),+ "group-attribute": withoutDefault(+ provider["group-sync"]?.["group-attribute"],+ DEFAULT_GROUP_ATTRIBUTE,+ ),};}function formValuesToProvider(values: OIDCFormValues,- groupMappings: Record<string, number[]>,+ groupSync: Partial<OidcGroupSync> | undefined,): Partial<CustomOidcConfig> {const scopes = values.scopes? values.scopes@@ -140,9 +150,6 @@ function formValuesToProvider(: DEFAULT_SCOPES;const attributeMap: Record<string, string> = {};- if (values["attribute-email"]) {- attributeMap["email"] = values["attribute-email"];- }if (values["attribute-firstname"]) {attributeMap["first_name"] = values["attribute-firstname"];}@@ -158,11 +165,9 @@ function formValuesToProvider(scopes,enabled: true,"attribute-map": attributeMap,- "group-sync": {- enabled: values["group-sync-enabled"],- "group-attribute": values["group-attribute"] ?? undefined,- "group-mappings": groupMappings,- },+ "group-sync": toGroupSync(groupSync, {+ "group-attribute": values["group-attribute"] ?? DEFAULT_GROUP_ATTRIBUTE,+ }),};if (values["client-secret"]) {@@ -175,33 +180,43 @@ function formValuesToProvider(export function SettingsOIDCForm() {const applicationName = useSelector(getApplicationName);const siteUrl = useSetting("site-url");- const { data: providers, isLoading } = useGetCustomOidcProvidersQuery();+ const { data: settingDetails, isLoading: isLoadingDetails } =+ useGetAdminSettingsDetailsQuery();+ const { data: settingValues, isLoading: isLoadingValues } =+ useGetSettingsQuery();+ const { data: providers, isLoading: isLoadingProviders } =+ useGetCustomOidcProvidersQuery();const [createProvider] = useCreateCustomOidcMutation();const [updateProvider] = useUpdateCustomOidcMutation();- const [deleteProvider] = useDeleteCustomOidcMutation();const [checkConnection, { isLoading: isChecking }] =useCheckOidcConnectionMutation();const [sendToast] = useToast();+ const [isGroupMappingSaving, setIsGroupMappingSaving] = useState(false);const existingProvider =providers && providers.length > 0 ? providers[0] : null;- const isExisting = existingProvider !== null;+ const isExisting = existingProvider != null;+ const isConfigured = settingValues?.["oidc-configured"] ?? false;+ const providersSetting = settingDetails?.["oidc-providers"];+ const lockedEnvName = providersSetting?.is_env_setting+ ? providersSetting.env_name+ : undefined;+ const isLocked = lockedEnvName != null;const isEnabled = existingProvider?.enabled ?? false;- const providerMappings = useMemo(- () => existingProvider?.["group-sync"]?.["group-mappings"] ?? {},- [existingProvider],- );- const groupMappingsRef = useRef<Record<string, number[]>>(providerMappings);-- useEffect(() => {- groupMappingsRef.current = providerMappings;- }, [providerMappings]);-const initialValues = useMemo(() => providerToFormValues(existingProvider),[existingProvider],);+ const validationSchema = useMemo(+ () => getOidcFormSchema({ isExisting }),+ [isExisting],+ );+ const hasCustomAttributes = [+ initialValues["attribute-firstname"],+ initialValues["attribute-lastname"],+ ].some((value) => value != null);+const runCheck = useCallback(async (values: OIDCFormValues) => {const req: OidcCheckRequest = {@@ -210,12 +225,12 @@ export function SettingsOIDCForm() {};if (values["client-secret"]) {req["client-secret"] = values["client-secret"];- } else if (isExisting && existingProvider) {+ } else if (existingProvider) {req.key = existingProvider.key;}return await checkConnection(req).unwrap();},- [checkConnection, isExisting, existingProvider],+ [checkConnection, existingProvider],);const handleCheckConnection = useCallback(@@ -244,16 +259,16 @@ export function SettingsOIDCForm() {);const handleSubmit = useCallback(- async (values: OIDCFormValues) => {- // Run the connection check before saving — will throw on failure+ async (values: OIDCFormValues, helpers: FormikHelpers<OIDCFormValues>) => {await runCheck(values);+ // the card and the save button hold each other, so no card write can be in flight hereconst providerData = formValuesToProvider(values,- groupMappingsRef.current,+ existingProvider?.["group-sync"],);- if (isExisting && existingProvider) {+ if (existingProvider) {const { key: _key, ...updateData } = providerData;await updateProvider({key: existingProvider.key,@@ -263,118 +278,40 @@ export function SettingsOIDCForm() {// Unjustified type cast. FIXMEawait createProvider(providerData as CustomOidcConfig).unwrap();}+ // the saved values become the baseline, so the form is clean before the refetch lands+ helpers.resetForm({ values });},- [- isExisting,- existingProvider,- createProvider,- updateProvider,- runCheck,- groupMappingsRef,- ],- );-- const { data: allGroupsData } = useListPermissionsGroupsQuery(undefined);- // Unjustified type cast. FIXME- const allGroups = (allGroupsData ?? []) as Group[];- const [deleteGroupMutation] = useDeletePermissionsGroupMutation();- const [clearGroupMembershipMutation] = useClearGroupMembershipMutation();-- const handleDeleteGroup = useCallback(- async ({ id }: { id: number }) => {- await deleteGroupMutation(id).unwrap();- },- [deleteGroupMutation],- );-- const handleClearGroupMember = useCallback(- async ({ id }: { id: number }) => {- await clearGroupMembershipMutation(id).unwrap();- },- [clearGroupMembershipMutation],- );-- const handleUpdateGroupMappings = useCallback(- async ({ value }: { key: string; value: Record<string, GroupId[]> }) => {- if (!existingProvider) {- return;- }- groupMappingsRef.current = value;- const existingGroupSync = existingProvider["group-sync"] ?? {};- await updateProvider({- key: existingProvider.key,- provider: {- "group-sync": {- enabled: existingGroupSync.enabled ?? false,- "group-attribute": existingGroupSync["group-attribute"],- "group-mappings": value,- },- },- }).unwrap();- },- [existingProvider, updateProvider],+ [existingProvider, createProvider, updateProvider, runCheck],);- const handleToggleEnabled = useCallback(async () => {- if (!existingProvider) {- return;- }- try {- await updateProvider({- key: existingProvider.key,- provider: { enabled: !isEnabled },- }).unwrap();- sendToast({- message: isEnabled- ? t`OIDC provider disabled`- : t`OIDC provider enabled`,- icon: "check",- });- } catch {- sendToast({- message: t`Failed to update OIDC provider`,- icon: "warning",- });- }- }, [existingProvider, isEnabled, updateProvider, sendToast]);-- const [isDeleteModalOpen, deleteModal] = useDisclosure(false);-- const handleDelete = useCallback(async () => {- if (!existingProvider) {- return;- }- try {- await deleteProvider(existingProvider.key).unwrap();- sendToast({- message: t`OIDC provider deleted`,- icon: "check",- });- } catch (error) {- sendToast({- message: t`Failed to delete OIDC provider`,- icon: "warning",- });- } finally {- deleteModal.close();- }- }, [existingProvider, deleteProvider, sendToast, deleteModal]);-- if (isLoading) {+ if (isLoadingDetails || isLoadingValues || isLoadingProviders) {return <LoadingAndErrorWrapper loading />;}+ if (settingDetails == null || settingValues == null || providers == null) {+ return (+ <LoadingAndErrorWrapper error={t`Error loading OIDC configuration`} />+ );+ }+return (<SettingsPageWrapper title={t`OpenID Connect`}><FormProviderinitialValues={initialValues}onSubmit={handleSubmit}- validationSchema={getOidcFormSchema()}+ validationSchema={validationSchema}enableReinitialize>- {({ dirty, values }) => (+ {({ dirty, values, initialValues, isSubmitting, setFieldValue }) => (<Form><Stack gap="xl">+ <UserProvisioningSection+ settingKey="oidc-user-provisioning-enabled?"+ providerName="OIDC"+ />+ {/* provisioning is its own setting, so the banner heads the cards it locks */}+ {lockedEnvName != null && <SetByEnvVar varName={lockedEnvName} />}+<SettingsSectiontitle={t`Server settings`}titleProps={SETTINGS_CARD_TITLE_PROPS}@@ -386,166 +323,132 @@ export function SettingsOIDCForm() {label={t`Key`}description={t`Provider identifier. Your OIDC redirect URI will be "${siteUrl}/auth/sso/${values.key || "{key}"}/callback"`}descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}- placeholder={t`e.g. okta`}+ placeholder="okta"requireddisabled={isExisting}+ readOnly={isLocked}/><FormTextInputname="login-prompt"label={t`Login prompt`}description={t`Button text on the ${applicationName} sign-in screen`}descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}- placeholder={t`e.g. Sign in with Okta`}+ placeholder={t`Sign in with Okta`}required+ readOnly={isLocked}/><FormTextInputname="issuer-uri"label={t`Issuer URI`}- description={t`The OIDC issuer URI. The discovery endpoint "${(values["issuer-uri"] || "{url}").replace(/\/+$/, "")}/.well-known/openid-configuration" should be accessible.`}+ description={t`The discovery endpoint "${(values["issuer-uri"] || "{url}").replace(/\/+$/, "")}/.well-known/openid-configuration" should be accessible`}descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}placeholder="https://your-idp.example.com"required+ readOnly={isLocked}/><FormTextInputname="client-id"label={t`Client ID`}- description={t`The Client ID configured for ${applicationName} in your OIDC provider.`}+ description={t`This is configured for ${applicationName} in your OIDC provider`}descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}+ placeholder="metabase-client-id"required+ readOnly={isLocked}/><FormTextInputname="client-secret"- label={t`Client Secret`}- description={t`The Client secret configured in your OIDC provider.`}+ label={t`Client secret`}+ description={t`This is configured in your OIDC provider`}descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}type="password"+ required={!isExisting}placeholder={- isExisting ? t`Leave blank to keep current value` : ""+ existingProvider+ ? t`Leave blank to keep current value`+ : "your-client-secret"}+ readOnly={isLocked}/>- </Stack>- </SettingsSection>-- {/* the card saves on its own, so it stays out of the form's values */}- <UserProvisioningSection- settingKey="oidc-user-provisioning-enabled?"- providerName="OIDC"- />-- {isExisting && (- <SettingsSection- title={t`Group mapping`}- titleProps={SETTINGS_CARD_TITLE_PROPS}- description={t`To enable this, you'll need to create mappings to tell ${applicationName} which group(s) your users should be added to based on the SSO group they're in.`}- descriptionProps={SETTINGS_CARD_DESCRIPTION_PROPS}- stackProps={SETTINGS_CARD_STACK_PROPS}- >- <Stack gap="lg">- <GroupMappingsWidgetView- setting={{ key: "group-sync-enabled" }}- mappings={- existingProvider?.["group-sync"]?.["group-mappings"] ??- {}- }- updateSetting={handleUpdateGroupMappings}- allGroups={allGroups}- deleteGroup={handleDeleteGroup}- clearGroupMember={handleClearGroupMember}- mappingSetting="oidc-group-mappings"- groupHeading={t`Group name`}- groupPlaceholder={t`Group name`}- />- <FormTextInput- name="group-attribute"- label={t`Group attribute name`}- description={t`The OIDC claim that contains group membership information.`}- descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}- nullable- />- </Stack>- </SettingsSection>- )}-- <CollapsibleSettingsSection title={t`Optional settings`}>- <Stack gap="lg"><FormTextInputname="scopes"label={t`Scopes`}- description={t`Comma-separated list of OIDC scopes to request.`}+ description={t`Comma-separated list of OIDC scopes to request`}descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}+ placeholder={DEFAULT_SCOPES.join(", ")}nullable+ readOnly={isLocked}/></Stack>- </CollapsibleSettingsSection>+ </SettingsSection><CollapsibleSettingsSection- title={t`Attribute mapping`}- description={t`Map OIDC claims to user attributes. Use standard OIDC claim names or your provider's custom claims.`}+ title={t`Attributes`}+ description={t`Map OIDC claims to the first name and last name fields in ${applicationName}. The email always comes from the standard email claim.`}+ defaultOpened={hasCustomAttributes}><Stack gap="lg">- <FormTextInput- name="attribute-email"- label={t`Email attribute`}- nullable- /><FormTextInputname="attribute-firstname"- label={t`First name attribute`}+ label={t`First name attribute key`}+ placeholder={DEFAULT_FIRST_NAME_ATTRIBUTE}nullable+ readOnly={isLocked}/><FormTextInputname="attribute-lastname"- label={t`Last name attribute`}+ label={t`Last name attribute key`}+ placeholder={DEFAULT_LAST_NAME_ATTRIBUTE}nullable+ readOnly={isLocked}/></Stack></CollapsibleSettingsSection>+ <OidcGroupMappingSection+ provider={existingProvider}+ onSavingChange={setIsGroupMappingSaving}+ disabled={!isConfigured}+ lockedEnvName={lockedEnvName}+ isPageSaving={isSubmitting}+ data-testid="oidc-group-mapping-section"+ onToggle={(enabled) => {+ if (!enabled) {+ resetFieldsToInitial(setFieldValue, initialValues, [+ "group-attribute",+ ]);+ }+ }}+ >+ <FormTextInput+ name="group-attribute"+ label={t`Group attribute name`}+ description={t`The OIDC claim that contains group membership information.`}+ descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}+ placeholder={DEFAULT_GROUP_ATTRIBUTE}+ nullable+ readOnly={isLocked}+ />+ </OidcGroupMappingSection>+<FormErrorMessage />- <Flex gap="lg" wrap="wrap" justify="space-between">- {isExisting && (- <>- <Flex gap="lg" wrap="wrap">- <Button onClick={handleToggleEnabled}>- {isEnabled ? t`Disable` : t`Enable`}- </Button>- <Button- variant="filled"- color="negative"- onClick={deleteModal.open}- >- {t`Delete configuration`}- </Button>- </Flex>- <ConfirmModal- opened={isDeleteModalOpen}- title={t`Delete this OIDC provider?`}- message={t`Users will no longer be able to sign in with this provider. This can't be undone.`}- onClose={deleteModal.close}- onConfirm={handleDelete}- />- </>- )}- <Flex gap="lg" wrap="wrap" ml={isExisting ? undefined : "auto"}>- <Button- loading={isChecking}- disabled={!values["issuer-uri"] || !values["client-id"]}- onClick={() => handleCheckConnection(values)}- >- {t`Check connection`}- </Button>+ <Flex gap="lg" wrap="wrap" justify="end">+ <Button+ loading={isChecking}+ disabled={!values["issuer-uri"] || !values["client-id"]}+ onClick={() => handleCheckConnection(values)}+ >+ {t`Check connection`}+ </Button>+ {!isLocked && (<FormSubmitButton- disabled={!dirty}- label={- isExisting && isEnabled- ? t`Save changes`- : t`Save and enable`- }+ disabled={!dirty || isGroupMappingSaving}+ label={isEnabled ? t`Save changes` : t`Save and enable`}variant="filled"/>- </Flex>+ )}</Flex></Stack>+ <LeaveRouteConfirmModal isEnabled={dirty && !isSubmitting} /></Form>)}</FormProvider>diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsxindex 08eaa857516..ee46c34a674 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx@@ -6,9 +6,21 @@ import {setupSettingsEndpoints,setupStatefulSettingsEndpoints,} from "__support__/server-mocks";-import { renderWithProviders, screen, waitFor } from "__support__/ui";+import {+ act,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { defer, delay } from "metabase/utils/promise";+import { checkNotNull } from "metabase/utils/types";import type { CustomOidcConfig } from "metabase-enterprise/api";-import { createMockGroup, createMockSettings } from "metabase-types/api/mocks";+import {+ createMockGroup,+ createMockSettingDefinition,+ createMockSettings,+} from "metabase-types/api/mocks";import { SettingsOIDCForm } from "./SettingsOIDCForm";@@ -18,13 +30,9 @@ const GROUPS = [name: "All Users",magic_group_type: "all-internal-users",}),- createMockGroup({- id: 2,- name: "Administrators",- magic_group_type: "admin",- }),- createMockGroup({ id: 3, name: "Engineering" }),- createMockGroup({ id: 4, name: "Marketing" }),+ createMockGroup({ id: 2, name: "Administrators", magic_group_type: "admin" }),+ createMockGroup({ id: 3, name: "Engineering", magic_group_type: null }),+ createMockGroup({ id: 4, name: "Marketing", magic_group_type: null }),];const EXISTING_PROVIDER: CustomOidcConfig = {@@ -41,295 +49,789 @@ const EXISTING_PROVIDER: CustomOidcConfig = {},};-function setupEndpoints({+const MAPPED_PROVIDER: CustomOidcConfig = {+ ...EXISTING_PROVIDER,+ "group-sync": {+ enabled: true,+ "group-attribute": "groups",+ "group-mappings": { admins: [2] },+ },+};++const OIDC_GROUP_PLACEHOLDER = "Enter OIDC group...";++const setup = async ({providers = [],+ configured = providers.length > 0,+ providersEnvName,+ groupDeleteGate,+ writeDelay,+ readDelay,+ readStatus,+ writeStatus,+ writeMessage,+ writeGate,}: {providers?: CustomOidcConfig[];-} = {}) {- const settings = createMockSettings();- setupSettingsEndpoints([]);- // the provisioning switch reads its value back after saving, so the properties mock has to remember writes- setupStatefulSettingsEndpoints(settings);-+ configured?: boolean;+ providersEnvName?: string;+ groupDeleteGate?: Promise<void>;+ writeDelay?: number;+ readDelay?: number;+ readStatus?: number;+ writeStatus?: number;+ writeMessage?: string;+ writeGate?: Promise<void>;+} = {}) => {+ setupSettingsEndpoints(+ providersEnvName == null+ ? []+ : [+ createMockSettingDefinition({+ key: "oidc-providers",+ is_env_setting: true,+ env_name: providersEnvName,+ }),+ ],+ );+ setupStatefulSettingsEndpoints(+ createMockSettings({ "oidc-configured": configured }),+ );fetchMock.get("path:/api/permissions/group", GROUPS);- fetchMock.get("path:/api/ee/sso/oidc", providers, {- name: "oidc-providers",+ fetchMock.delete("express:/api/permissions/group/:id", async () => {+ await groupDeleteGate;+ return 204;});- fetchMock.post("path:/api/ee/sso/oidc", 200);- fetchMock.put("path:/api/ee/sso/oidc/okta", 200);+ const stored = providers.map((provider) => ({ ...provider }));+ fetchMock.get(+ "path:/api/ee/sso/oidc",+ () =>+ readStatus != null+ ? { status: readStatus }+ : stored.map((provider) => ({ ...provider })),+ { delay: readDelay },+ );+ fetchMock.post("path:/api/ee/sso/oidc", ({ options }) => {+ const provider = JSON.parse(String(options.body));+ stored.push(provider);+ return provider;+ });+ fetchMock.put(+ "express:/api/ee/sso/oidc/:key",+ async ({ url, options }) => {+ await writeGate;+ if (writeStatus != null) {+ return { status: writeStatus, body: writeMessage };+ }+ const key = url.split("/api/ee/sso/oidc/")[1];+ const index = stored.findIndex((provider) => provider.key === key);+ stored[index] = {+ ...stored[index],+ ...JSON.parse(String(options.body)),+ };+ return stored[index];+ },+ { delay: writeDelay },+ );fetchMock.post("path:/api/ee/sso/oidc/check", {ok: true,discovery: { step: "discovery", success: true },credentials: { step: "credentials", success: true, verified: true },});-}++ renderWithProviders(<SettingsOIDCForm />, { withUndos: true });++ if (readStatus == null) {+ await screen.findByText("OpenID Connect");+ }+};async function getOidcPutCalls() {const puts = await findRequests("PUT");return puts.filter(({ url }) => url.includes("/api/ee/sso/oidc/okta"));}-const setup = async (options?: { providers?: CustomOidcConfig[] }) => {- setupEndpoints(options);+const groupMappingSwitch = () =>+ screen.getByRole("switch", { name: "Group mapping" });- renderWithProviders(<SettingsOIDCForm />, { withUndos: true });+const queryMappingRow = (name: string) =>+ screen+ .queryAllByTestId("group-mapping-row")+ .find((row) => within(row).queryByText(name) != null);++const getMappingRow = (name: string) => checkNotNull(queryMappingRow(name));- await screen.findByText("OpenID Connect");+const expandAttributes = async () => {+ await userEvent.click(screen.getByRole("button", { name: "Attributes" }));};-describe("SettingsOIDCForm - collapsible sections", () => {- it("starts both optional sections collapsed for a new provider", async () => {- await setup({ providers: [] });+const fillRequiredFields = async () => {+ await userEvent.type(screen.getByLabelText(/^Key/), "okta");+ await userEvent.type(screen.getByLabelText(/^Login prompt/), "Sign in");+ await userEvent.type(+ screen.getByLabelText(/^Issuer URI/),+ "https://idp.example.test",+ );+ await userEvent.type(screen.getByLabelText(/^Client ID/), "client-123");+ await userEvent.type(+ screen.getByLabelText(/^Client secret/),+ "client-secret-123",+ );+};- expect(- screen.getByRole("button", { name: "Optional settings" }),- ).toHaveAttribute("aria-expanded", "false");- expect(- screen.getByRole("button", { name: "Attribute mapping" }),- ).toHaveAttribute("aria-expanded", "false");- });+const clickWhenEnabled = async (element: HTMLElement) => {+ await waitFor(() => expect(element).toBeEnabled());+ await userEvent.click(element);+};++const addMapping = async (name: string, groupName: string) => {+ await clickWhenEnabled(screen.getByRole("button", { name: "New" }));+ await userEvent.type(+ screen.getByPlaceholderText(OIDC_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" }));+};- it("starts both optional sections collapsed when the provider only has default values", async () => {- await setup({ providers: [EXISTING_PROVIDER] });+describe("SettingsOIDCForm", () => {+ describe("loading", () => {+ it("shows an error instead of an empty form when the providers fail to load", async () => {+ await setup({ readStatus: 500 });- expect(- screen.getByRole("button", { name: "Optional settings" }),- ).toHaveAttribute("aria-expanded", "false");- expect(- screen.getByRole("button", { name: "Attribute mapping" }),- ).toHaveAttribute("aria-expanded", "false");+ expect(+ await screen.findByText("Error loading OIDC configuration"),+ ).toBeInTheDocument();+ expect(screen.queryByText("OpenID Connect")).not.toBeInTheDocument();+ });});- it("starts both optional sections collapsed even when the provider has custom values", async () => {- await setup({- providers: [- {- ...EXISTING_PROVIDER,- scopes: ["openid", "email"],- "attribute-map": {- ...EXISTING_PROVIDER["attribute-map"],- email: "mail",- },- },- ],+ describe("environment variable", () => {+ it("locks the whole page when the providers come from an environment variable", async () => {+ await setup({+ providers: [MAPPED_PROVIDER],+ providersEnvName: "MB_OIDC_PROVIDERS",+ });++ expect(screen.getByTestId("setting-env-var-message")).toHaveTextContent(+ "This has been set by the MB_OIDC_PROVIDERS environment variable.",+ );+ expect(screen.getByLabelText(/^Issuer URI/)).toHaveAttribute("readonly");+ expect(screen.getByLabelText("Group attribute name")).toHaveAttribute(+ "readonly",+ );+ expect(+ screen.queryByRole("button", { name: "Save changes" }),+ ).not.toBeInTheDocument();+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true");+ expect(groupMappingSwitch()).toHaveAccessibleDescription(+ /Using MB_OIDC_PROVIDERS/,+ );+ const banner = screen.getByTestId("setting-env-var-message");+ const bannerAfterProvisioning = screen+ .getByRole("switch", { name: "User provisioning" })+ .compareDocumentPosition(banner);+ const serverSettingsAfterBanner = banner.compareDocumentPosition(+ screen.getByRole("heading", { name: "Server settings" }),+ );+ expect(bannerAfterProvisioning & Node.DOCUMENT_POSITION_FOLLOWING).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(serverSettingsAfterBanner & Node.DOCUMENT_POSITION_FOLLOWING).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(queryMappingRow("admins")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "New" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByLabelText("Delete mapping")).not.toBeInTheDocument();+ expect(+ screen.getByRole("switch", { name: "User provisioning" }),+ ).not.toHaveAttribute("aria-disabled");});- expect(- screen.getByRole("button", { name: "Optional settings" }),- ).toHaveAttribute("aria-expanded", "false");- expect(- screen.getByRole("button", { name: "Attribute mapping" }),- ).toHaveAttribute("aria-expanded", "false");+ it("locks an empty page too, since a new provider would be ignored as well", async () => {+ await setup({ providersEnvName: "MB_OIDC_PROVIDERS" });++ expect(screen.getByTestId("setting-env-var-message")).toBeInTheDocument();+ expect(screen.getByLabelText(/^Key/)).toHaveAttribute("readonly");+ expect(+ screen.queryByRole("button", { name: "Save and enable" }),+ ).not.toBeInTheDocument();+ expect(groupMappingSwitch()).not.toHaveAccessibleDescription(+ /Save the settings above to set up group mapping/,+ );+ });});-});-describe("SettingsOIDCForm - Group Sync", () => {- it("does not show group sync section for new providers", async () => {- await setup({ providers: [] });+ describe("client secret", () => {+ it("is required for a new provider", async () => {+ await setup();+ await fillRequiredFields();+ const saveButton = screen.getByRole("button", {+ name: "Save and enable",+ });+ await waitFor(() => expect(saveButton).toBeEnabled());- expect(screen.queryByText("Group mapping")).not.toBeInTheDocument();- });+ await userEvent.clear(screen.getByLabelText(/^Client secret/));- it("shows the group sync UI for existing providers", async () => {- await setup({ providers: [EXISTING_PROVIDER] });+ expect(screen.getByLabelText(/^Client secret/)).toBeRequired();+ await waitFor(() => expect(saveButton).toBeDisabled());+ });++ it("stays optional for an existing provider", async () => {+ await setup({ providers: [EXISTING_PROVIDER] });- expect(screen.getByText("Group mapping")).toBeInTheDocument();- expect(screen.getByTestId("group-sync-switch")).toBeInTheDocument();- expect(screen.getByLabelText("Group attribute name")).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "New mapping" }),- ).toBeInTheDocument();+ expect(screen.getByLabelText(/^Client secret/)).not.toBeRequired();+ });});- it("populates group sync fields and mappings from existing provider config", async () => {- await setup({- providers: [- {- ...EXISTING_PROVIDER,- "group-sync": {- enabled: true,- "group-attribute": "groups",- "group-mappings": { admins: [2], devs: [3] },- },- },- ],+ describe("layout", () => {+ it("lays the cards out in the designed order", async () => {+ await setup({ providers: [EXISTING_PROVIDER] });++ const cardTitles = screen+ .getAllByRole("heading", { level: 2 })+ .map((heading) => heading.textContent);+ expect(cardTitles).toEqual([+ "User provisioning",+ "Server settings",+ "Attributes",+ "Group mapping",+ ]);});- expect(screen.getByLabelText("Group attribute name")).toHaveValue("groups");- expect(screen.getByText("admins")).toBeInTheDocument();- expect(screen.getByText("devs")).toBeInTheDocument();+ it("keeps the group mapping card disabled until the provider is saved", async () => {+ await setup();++ const provisioningSwitch = screen.getByRole("switch", {+ name: "User provisioning",+ });+ expect(provisioningSwitch).toBeEnabled();+ expect(provisioningSwitch).not.toHaveAttribute("aria-disabled");+ expect(screen.getByRole("button", { name: "Attributes" })).toBeEnabled();+ expect(groupMappingSwitch()).toBeDisabled();+ expect(groupMappingSwitch()).not.toBeChecked();+ expect(groupMappingSwitch()).toHaveAccessibleDescription(+ /Save the settings above to set up group mapping/,+ );+ expect(+ screen.queryByRole("textbox", { name: /Group attribute name/ }),+ ).not.toBeInTheDocument();+ });++ it("locks the group mapping card on the backend's configured flag rather than the provider list", async () => {+ await setup({ providers: [EXISTING_PROVIDER], configured: false });++ expect(groupMappingSwitch()).toBeDisabled();+ });});- it("includes group sync in form submission", async () => {- await setup({ providers: [EXISTING_PROVIDER] });+ describe("defaults", () => {+ it("shows the defaults as placeholders and leaves the fields empty for a new provider", async () => {+ await setup();++ const key = screen.getByLabelText(/^Key/);+ expect(key).toHaveValue("");+ expect(key).toHaveAttribute("placeholder", "okta");+ const loginPrompt = screen.getByLabelText(/^Login prompt/);+ expect(loginPrompt).toHaveValue("");+ expect(loginPrompt).toHaveAttribute("placeholder", "Sign in with Okta");+ const clientId = screen.getByLabelText(/^Client ID/);+ expect(clientId).toHaveValue("");+ expect(clientId).toHaveAttribute("placeholder", "metabase-client-id");+ const clientSecret = screen.getByLabelText(/^Client secret/);+ expect(clientSecret).toHaveValue("");+ expect(clientSecret).toHaveAttribute("placeholder", "your-client-secret");+ const scopes = screen.getByLabelText(/^Scopes/);+ expect(scopes).toBeVisible();+ expect(scopes).toHaveValue("");+ expect(scopes).toHaveAttribute("placeholder", "openid, email, profile");+ });- // Change group attribute to make the form dirty- const groupAttrInput = screen.getByLabelText("Group attribute name");- await userEvent.clear(groupAttrInput);- await userEvent.type(groupAttrInput, "roles");+ it("keeps the attributes card collapsed and shows the stored defaults as placeholders", async () => {+ await setup({ providers: [MAPPED_PROVIDER] });++ expect(+ screen.getByRole("button", { name: "Attributes" }),+ ).toHaveAttribute("aria-expanded", "false");+ expect(screen.getByLabelText(/^Scopes/)).toHaveValue("");+ expect(screen.getByLabelText(/^Client secret/)).toHaveAttribute(+ "placeholder",+ "Leave blank to keep current value",+ );+ const attributeInput = screen.getByRole("textbox", {+ name: /Group attribute name/,+ });+ expect(attributeInput).toHaveValue("");+ expect(attributeInput).toHaveAttribute("placeholder", "groups");++ await expandAttributes();++ const firstName = screen.getByLabelText("First name attribute key");+ expect(firstName).toHaveValue("");+ expect(firstName).toHaveAttribute("placeholder", "given_name");+ const lastName = screen.getByLabelText("Last name attribute key");+ expect(lastName).toHaveValue("");+ expect(lastName).toHaveAttribute("placeholder", "family_name");+ expect(+ screen.queryByLabelText("Email attribute key"),+ ).not.toBeInTheDocument();+ });- const submitButton = screen.getByRole("button", {- name: "Save changes",+ it("opens the attributes card and shows the claim a provider customized", async () => {+ await setup({+ providers: [+ {+ ...EXISTING_PROVIDER,+ scopes: ["openid", "email"],+ "attribute-map": {+ ...EXISTING_PROVIDER["attribute-map"],+ first_name: "givenName",+ },+ },+ ],+ });++ expect(+ screen.getByRole("button", { name: "Attributes" }),+ ).toHaveAttribute("aria-expanded", "true");+ expect(screen.getByLabelText(/^Scopes/)).toHaveValue("openid, email");+ expect(screen.getByLabelText("First name attribute key")).toHaveValue(+ "givenName",+ );+ expect(screen.getByLabelText("Last name attribute key")).toHaveValue("");});- await userEvent.click(submitButton);- await waitFor(async () => {- const puts = await getOidcPutCalls();- expect(puts.length).toBeGreaterThan(0);+ it("drops an email claim mapping saved earlier on the next save", async () => {+ await setup({+ providers: [+ {+ ...EXISTING_PROVIDER,+ "attribute-map": { email: "mail", first_name: "givenName" },+ },+ ],+ });++ await userEvent.type(+ screen.getByLabelText("Last name attribute key"),+ "surname",+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Save changes" }),+ );++ await waitFor(async () =>+ expect(await getOidcPutCalls()).toHaveLength(1),+ );+ const [{ body }] = await getOidcPutCalls();+ expect(body["attribute-map"]).toEqual({+ first_name: "givenName",+ last_name: "surname",+ });});- const puts = await getOidcPutCalls();- const lastPut = puts[puts.length - 1];- expect(lastPut.body["group-sync"]).toEqual(- expect.objectContaining({+ it("falls back to the default scopes and claims when the fields stay empty", async () => {+ await setup();+ await fillRequiredFields();++ await userEvent.click(+ screen.getByRole("button", { name: "Save and enable" }),+ );++ await waitFor(async () => {+ expect(await findRequests("POST")).toHaveLength(2);+ });+ const [{ body }] = (await findRequests("POST")).filter(({ url }) =>+ url.endsWith("/api/ee/sso/oidc"),+ );+ expect(body.scopes).toEqual(["openid", "email", "profile"]);+ expect(body["attribute-map"]).toEqual({});+ expect(body.enabled).toBe(true);+ expect(body["group-sync"]).toEqual({enabled: false,+ "group-attribute": "groups","group-mappings": {},- }),- );- expect(lastPut.body["group-sync"]["group-attribute"]).toBe("roles");+ });+ });++ it("sends claims set before the first save with the new provider", async () => {+ await setup();+ await fillRequiredFields();+ await expandAttributes();+ const firstNameAttribute = screen.getByLabelText(+ "First name attribute key",+ );+ await waitFor(() => expect(firstNameAttribute).toBeVisible());+ await userEvent.type(firstNameAttribute, "givenName");++ await userEvent.click(+ screen.getByRole("button", { name: "Save and enable" }),+ );++ await waitFor(async () => {+ expect(await findRequests("POST")).toHaveLength(2);+ });+ const [{ body }] = (await findRequests("POST")).filter(({ url }) =>+ url.endsWith("/api/ee/sso/oidc"),+ );+ expect(body["attribute-map"]).toEqual({ first_name: "givenName" });+ });});- it("does not overwrite group mappings added via the widget on form save", async () => {- // Scenario: user adds a mapping via GroupMappingsWidgetView (which saves- // immediately via PUT), then submits the form. The form should include the- // freshly-saved mappings, not the stale prop value from initial render.- const provider = {- ...EXISTING_PROVIDER,- "group-sync": {- enabled: true,- "group-attribute": "groups",- "group-mappings": {},- },- };- await setup({ providers: [provider] });-- // Make the form dirty so it can be saved- const groupAttrInput = screen.getByLabelText("Group attribute name");- await userEvent.clear(groupAttrInput);- await userEvent.type(groupAttrInput, "roles");-- // After the widget saves, the providers refetch returns the new mapping- fetchMock.removeRoute("oidc-providers");- fetchMock.get(- "path:/api/ee/sso/oidc",- [- {- ...provider,- "group-sync": {- ...provider["group-sync"],- "group-mappings": { "Group 1": [] },- },- },- ],- { name: "oidc-providers" },- );+ describe("user provisioning", () => {+ it("saves right away without touching the page form", async () => {+ await setup({ providers: [EXISTING_PROVIDER] });+ const toggle = screen.getByRole("switch", { name: "User provisioning" });+ await waitFor(() => {+ expect(toggle).toBeEnabled();+ expect(toggle).not.toHaveAttribute("aria-disabled");+ });- // Add a mapping via the widget: click "New mapping", type name, click Add- await userEvent.click(screen.getByRole("button", { name: "New mapping" }));- await userEvent.type(screen.getByPlaceholderText("Group name"), "Group 1");- await userEvent.click(screen.getByRole("button", { name: "Add" }));+ await userEvent.click(toggle);- // The widget saves the mapping immediately, without submitting the form- await waitFor(async () => {- const puts = await getOidcPutCalls();+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();+ const puts = await findRequests("PUT");expect(puts).toHaveLength(1);+ expect(puts[0].url).toMatch(+ /\/api\/setting\/oidc-user-provisioning-enabled%3F$/,+ );});- await userEvent.click(screen.getByRole("button", { name: "Save changes" }));+ it("does not promise to reactivate accounts, which OIDC sign-in never does", async () => {+ await setup({ providers: [EXISTING_PROVIDER] });- await waitFor(async () => {- const puts = await getOidcPutCalls();- expect(puts).toHaveLength(2);+ const toggle = screen.getByRole("switch", { name: "User provisioning" });+ expect(toggle).toHaveAccessibleDescription(+ /create accounts for new users/,+ );+ expect(toggle).not.toHaveAccessibleDescription(/reactivate/);});- const puts = await getOidcPutCalls();- const formPut = puts[puts.length - 1];- // The form submission should include the mapping added via the widget- expect(formPut.body["attribute-map"]).toBeDefined();- expect(formPut.body["group-sync"]["group-mappings"]).toEqual({- "Group 1": [],+ it("stays editable while the provider is paused", async () => {+ await setup({ providers: [{ ...EXISTING_PROVIDER, enabled: false }] });++ const provisioningSwitch = screen.getByRole("switch", {+ name: "User provisioning",+ });+ expect(provisioningSwitch).toBeEnabled();+ expect(provisioningSwitch).not.toHaveAttribute("aria-disabled");+ expect(groupMappingSwitch()).toBeEnabled();+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled");});- expect(formPut.body["group-sync"]["group-attribute"]).toBe("roles");});- it("preserves existing group mappings on form submission", async () => {- await setup({- providers: [- {- ...EXISTING_PROVIDER,- "group-sync": {- enabled: true,- "group-attribute": "groups",- "group-mappings": { admins: [2], devs: [3] },+ describe("group mapping", () => {+ it("turns group mapping on right away and keeps the provider's other group settings", async () => {+ await setup({+ providers: [+ {+ ...EXISTING_PROVIDER,+ "group-sync": {+ enabled: false,+ "group-attribute": "roles",+ "group-mappings": { admins: [2] },+ },},+ ],+ });++ await userEvent.click(groupMappingSwitch());++ expect(groupMappingSwitch()).toBeChecked();+ expect(screen.getByText("Manual group mappings")).toBeInTheDocument();+ expect(queryMappingRow("admins")).toBeDefined();+ expect(+ screen.getByRole("textbox", { name: /Group attribute name/ }),+ ).toHaveValue("roles");+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();+ const puts = await getOidcPutCalls();+ expect(puts).toHaveLength(1);+ expect(puts[0].body).toEqual({+ "group-sync": {+ enabled: true,+ "group-attribute": "roles",+ "group-mappings": { admins: [2] },},- ],+ });+ expect(+ screen.getByRole("button", { name: "Save changes" }),+ ).toBeDisabled();});- // Change the group attribute to make the form dirty- const groupAttrInput = screen.getByLabelText("Group attribute name");- await userEvent.clear(groupAttrInput);- await userEvent.type(groupAttrInput, "roles");+ it("writes the default attribute for a provider that has no group sync yet", async () => {+ await setup({ providers: [EXISTING_PROVIDER] });- const submitButton = screen.getByRole("button", {- name: "Save changes",- });- await userEvent.click(submitButton);+ await userEvent.click(groupMappingSwitch());- await waitFor(async () => {+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();const puts = await getOidcPutCalls();- expect(puts.length).toBeGreaterThan(0);+ expect(puts).toHaveLength(1);+ expect(puts[0].body).toEqual({+ "group-sync": {+ enabled: true,+ "group-attribute": "groups",+ "group-mappings": {},+ },+ });});- const puts = await getOidcPutCalls();- const lastPut = puts[puts.length - 1];- expect(lastPut.body["group-sync"]).toEqual({- enabled: true,- "group-attribute": "roles",- "group-mappings": { admins: [2], devs: [3] },+ it("keeps the switch off after a failed write", async () => {+ await setup({ providers: [EXISTING_PROVIDER], writeStatus: 500 });++ await userEvent.click(groupMappingSwitch());+ expect(+ await screen.findByText(/Error saving group mapping/),+ ).toBeInTheDocument();+ expect(groupMappingSwitch()).not.toBeChecked();});- });-});-describe("SettingsOIDCForm - user provisioning", () => {- it("sits right below the server settings", async () => {- await setup({ providers: [EXISTING_PROVIDER] });-- const cardTitles = screen- .getAllByRole("heading", { level: 2 })- .map((heading) => heading.textContent);- expect(cardTitles).toEqual([- "Server settings",- "User provisioning",- "Group mapping",- "Optional settings",- "Attribute mapping",- ]);- });+ it("holds the card while the page form saves the provider", async () => {+ await setup({ providers: [MAPPED_PROVIDER], writeDelay: 200 });+ await userEvent.type(screen.getByLabelText(/^Login prompt/), "!");++ await userEvent.click(+ screen.getByRole("button", { name: "Save changes" }),+ );++ await waitFor(() =>+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true"),+ );+ expect(screen.getByRole("button", { name: "New" })).toBeDisabled();+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(screen.getByRole("button", { name: "New" })).toBeEnabled();+ });- it("stays editable before a provider is saved", async () => {- await setup({ providers: [] });+ it("shows the new value and holds the card and the page save while the write is in flight", async () => {+ await setup({ providers: [EXISTING_PROVIDER], writeDelay: 200 });+ await userEvent.type(screen.getByLabelText(/^Login prompt/), "!");+ const saveButton = screen.getByRole("button", { name: "Save changes" });+ expect(saveButton).toBeEnabled();++ await userEvent.click(groupMappingSwitch());++ expect(groupMappingSwitch()).toBeChecked();+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true");+ expect(screen.getByText("Manual group mappings")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "New" })).toBeDisabled();+ expect(saveButton).toBeDisabled();+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(groupMappingSwitch()).toBeChecked();+ expect(screen.getByRole("button", { name: "New" })).toBeEnabled();+ await waitFor(() => expect(saveButton).toBeEnabled());+ expect(await getOidcPutCalls()).toHaveLength(1);+ });- const toggle = screen.getByRole("switch", { name: "User provisioning" });- await waitFor(() => expect(toggle).toBeEnabled());- });+ it("holds the switch until the providers refetch after the write lands", async () => {+ await setup({ providers: [EXISTING_PROVIDER], readDelay: 200 });++ await userEvent.click(groupMappingSwitch());+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();- it("saves right away without touching the page form", async () => {- await setup({ providers: [EXISTING_PROVIDER] });- const toggle = screen.getByRole("switch", { name: "User provisioning" });- await waitFor(() => expect(toggle).toBeEnabled());- expect(toggle).toBeChecked();-- await userEvent.click(toggle);-- await waitFor(() => expect(toggle).not.toBeChecked());- expect(await screen.findByText("Changes saved")).toBeInTheDocument();- const puts = await findRequests("PUT");- expect(puts).toHaveLength(1);- expect(puts[0].url).toMatch(- /\/api\/setting\/oidc-user-provisioning-enabled%3F$/,- );- expect(puts[0].body).toEqual({ value: false });- expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();+ expect(groupMappingSwitch()).toBeChecked();+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true");+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(groupMappingSwitch()).toBeChecked();+ });++ it("drops an unsaved group attribute edit when group mapping is turned off", async () => {+ await setup({+ providers: [+ {+ ...MAPPED_PROVIDER,+ "group-sync": {+ ...MAPPED_PROVIDER["group-sync"],+ "group-attribute": "roles",+ },+ },+ ],+ });+ const saveButton = () =>+ screen.getByRole("button", { name: "Save changes" });+ const attributeInput = () =>+ screen.getByRole("textbox", { name: /Group attribute name/ });++ await userEvent.type(attributeInput(), "X");+ expect(saveButton()).toBeEnabled();++ await userEvent.click(groupMappingSwitch());+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );++ expect(saveButton()).toBeDisabled();+ await userEvent.click(groupMappingSwitch());+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(attributeInput()).toHaveValue("roles");+ });++ it("asks only for internal groups, since OIDC users are never tenants", async () => {+ await setup({ providers: [MAPPED_PROVIDER] });++ await clickWhenEnabled(screen.getByRole("button", { name: "New" }));+ await userEvent.click(+ screen.getByPlaceholderText("Pick Metabase group..."),+ );+ expect(+ await screen.findByRole("option", { name: "Engineering" }),+ ).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("keeps the editor read-only and the switch held while its mapping saves", async () => {+ const gate = defer<void>();+ await setup({ providers: [MAPPED_PROVIDER], writeGate: gate.promise });++ await addMapping("devs", "Engineering");++ try {+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true");+ const nameInput = screen.getByPlaceholderText(OIDC_GROUP_PLACEHOLDER);+ const groupsInput = screen.getByLabelText("Metabase groups");+ expect(nameInput).toHaveAttribute("readonly");+ expect(groupsInput).toHaveAttribute("readonly");+ await userEvent.type(nameInput, "-team");+ expect(nameInput).toHaveValue("devs");+ // a read-only picker still drops its last group on Backspace, which would bring its placeholder back+ await userEvent.type(groupsInput, "{Backspace}");+ expect(+ screen.queryByPlaceholderText("Pick Metabase group..."),+ ).not.toBeInTheDocument();+ } finally {+ gate.resolve();+ }+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ });++ it("shows a failed write under the editor without marking the name invalid", async () => {+ await setup({+ providers: [MAPPED_PROVIDER],+ writeStatus: 400,+ writeMessage: "Unable to reach the identity provider",+ });++ await addMapping("devs", "Engineering");++ expect(+ await screen.findByText("Unable to reach the identity provider"),+ ).toHaveAttribute("role", "alert");+ const nameInput = screen.getByPlaceholderText(OIDC_GROUP_PLACEHOLDER);+ expect(nameInput).not.toBeInvalid();+ expect(nameInput).toHaveValue("devs");+ expect(screen.queryByText("Mapping added")).not.toBeInTheDocument();+ });++ it("adds a mapping on its own write and carries it along when the page form saves the group attribute", async () => {+ await setup({ providers: [MAPPED_PROVIDER] });+ const saveButton = screen.getByRole("button", { name: "Save changes" });++ await addMapping("devs", "Engineering");+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();+ expect(+ within(getMappingRow("devs")).getByText("Engineering"),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "New" })).toBeInTheDocument();+ expect(saveButton).toBeDisabled();++ const attributeInput = screen.getByRole("textbox", {+ name: /Group attribute name/,+ });+ await userEvent.clear(attributeInput);+ await userEvent.type(attributeInput, "roles");+ await userEvent.click(saveButton);++ await waitFor(async () => {+ expect(await getOidcPutCalls()).toHaveLength(2);+ });+ const [mappingPut, formPut] = await getOidcPutCalls();+ expect(mappingPut.body).toEqual({+ "group-sync": {+ enabled: true,+ "group-attribute": "groups",+ "group-mappings": { admins: [2], devs: [3] },+ },+ });+ expect(formPut.body["group-sync"]).toEqual({+ enabled: true,+ "group-attribute": "roles",+ "group-mappings": { admins: [2], devs: [3] },+ });+ });++ it("holds the switch and the page save until the delete-groups cascade finishes", async () => {+ const groupDeleteGate = defer<void>();+ await setup({+ providers: [+ {+ ...EXISTING_PROVIDER,+ "group-sync": {+ enabled: true,+ "group-attribute": "groups",+ "group-mappings": { old: [4], devs: [4, 3] },+ },+ },+ ],+ groupDeleteGate: groupDeleteGate.promise,+ });+ const saveButton = () =>+ screen.getByRole("button", { name: "Save changes" });+ await userEvent.type(+ screen.getByRole("textbox", { name: /Group attribute name/ }),+ "X",+ );+ expect(saveButton()).toBeEnabled();++ await clickWhenEnabled(+ within(getMappingRow("old")).getByRole("button", {+ name: "Delete mapping",+ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /Also delete the group/ }),+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Remove mapping and delete group" }),+ );++ try {+ await waitFor(() => expect(queryMappingRow("old")).toBeUndefined());+ // let the refetch settle, so only the cascade can still be holding the controls+ await act(async () => {+ await delay(100);+ });+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true");+ expect(saveButton()).toBeDisabled();+ } finally {+ groupDeleteGate.resolve();+ }+ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(saveButton()).toBeEnabled();+ const puts = await getOidcPutCalls();+ expect(puts.map(({ body }) => body["group-sync"])).toEqual([+ expect.objectContaining({ "group-mappings": { devs: [4, 3] } }),+ expect.objectContaining({ "group-mappings": { devs: [3] } }),+ ]);+ });});});diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/group-sync.ts b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/group-sync.tsnew file mode 100644index 00000000000..0975475508a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/group-sync.ts@@ -0,0 +1,19 @@+import { EMPTY_MAPPINGS } from "metabase/admin/settings/auth/components/GroupMappings";+import type { CustomOidcConfig } from "metabase-enterprise/api";++export const DEFAULT_GROUP_ATTRIBUTE = "groups";++export type OidcGroupSync = NonNullable<CustomOidcConfig["group-sync"]>;++/** Completes a provider's group sync map, since the API replaces the whole map on every write */+export function toGroupSync(+ current: Partial<OidcGroupSync> | undefined,+ changes: Partial<OidcGroupSync>,+): OidcGroupSync {+ return {+ enabled: current?.enabled ?? false,+ "group-attribute": current?.["group-attribute"] ?? DEFAULT_GROUP_ATTRIBUTE,+ "group-mappings": current?.["group-mappings"] ?? EMPTY_MAPPINGS,+ ...changes,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsxindex c84bbd71e5a..e16b76feb1e 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx@@ -1,18 +1,22 @@+import type { FormikHelpers } from "formik";import { useCallback } from "react";-import { jt, t } from "ttag";+import { t } from "ttag";import _ from "underscore";import * as Yup from "yup";-import { GroupMappingsWidget } from "metabase/admin/settings/components/widgets/GroupMappingsWidget";+import { SettingsGroupMappingSection } from "metabase/admin/settings/auth/components/GroupMappings";import {SETTINGS_FIELD_DESCRIPTION_PROPS,+ getDefaultPlaceholder,+ getEnvNoticeProps,getExtraFormFieldProps,+ getStoredFieldValue,+ resetFieldsToInitial,} from "metabase/admin/settings/utils";import { CopyTextInput } from "metabase/common/components/CopyTextInput";-import { ExternalLink } from "metabase/common/components/ExternalLink";+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { Markdown } from "metabase/common/components/Markdown";-import { useDocsUrl } from "metabase/common/hooks";import {Form,FormErrorMessage,@@ -36,10 +40,13 @@ import {SettingsPageWrapper,SettingsSection,} from "metabase/settings-components";-import { Flex, Stack, Text, Title } from "metabase/ui";+import { Box, Flex, Stack, Text, Title } from "metabase/ui";import { useUpdateSamlMutation } from "metabase-enterprise/api";import { UserProvisioningSection } from "metabase-enterprise/auth/components/UserProvisioningSection";-import type { EnterpriseSettings } from "metabase-types/api";+import type {+ EnterpriseSettings,+ SettingDefinitionMap,+} from "metabase-types/api";export type SAMLFormSettings = Pick<EnterpriseSettings,@@ -55,7 +62,6 @@ export type SAMLFormSettings = Pick<| "saml-keystore-alias"| "saml-keystore-path"| "saml-attribute-group"- | "saml-group-sync">;const SAML_FORM_SCHEMA = Yup.object({@@ -71,19 +77,20 @@ export function SettingsSAMLForm() {const applicationName = useSelector(getApplicationName);const isEnabled = Boolean(settingValues?.["saml-enabled"]);+ const isConfigured = settingValues?.["saml-configured"] ?? false;const handleSubmit = useCallback(- (values: SAMLFormSettings) => {- return updateSamlSettings({ ...values, "saml-enabled": true }).unwrap();+ async (+ values: SAMLFormSettings,+ helpers: FormikHelpers<SAMLFormSettings>,+ ) => {+ await updateSamlSettings({ ...values, "saml-enabled": true }).unwrap();+ // the form ignores refetches, so the saved values become its baseline+ helpers.resetForm({ values });},[updateSamlSettings],);- // eslint-disable-next-line metabase/no-unconditional-metabase-links-render -- Admin settings- const { url: docsUrl } = useDocsUrl(- "people-and-groups/authenticating-with-saml",- );-const siteUrl = useSetting("site-url");const scimEnabled = useSetting("scim-enabled");@@ -112,29 +119,25 @@ export function SettingsSAMLForm() {);return (- <SettingsPageWrapper- title={t`SAML`}- description={jt`Use the settings below to configure your SSO via SAML. If you have any questions, check out our ${(- <ExternalLink- key="link"- href={docsUrl}- >{t`documentation`}</ExternalLink>- )}.`}- >+ <SettingsPageWrapper title={t`SAML`}><FormProvider- initialValues={getFormValues(settingValues ?? {})}+ initialValues={getFormValues(settingDetails, settingValues)}onSubmit={handleSubmit}validationSchema={SAML_FORM_SCHEMA}- enableReinitialize>- {({ dirty }) => (+ {({ dirty, initialValues, isSubmitting, setFieldValue }) => (<Form>- <Stack gap="lg">+ <Stack gap="xl">+ <UserProvisioningSection+ settingKey="saml-user-provisioning-enabled?"+ providerName="SAML"+ reactivatesAccounts+ lockedNote={scimNote}+ />+<SettingsSection- title={t`Configure your identity provider (IdP)`}+ title={t`Identity provider (IdP) configuration`}titleProps={SETTINGS_CARD_TITLE_PROPS}- description={t`Your identity provider will need the following info about ${applicationName}.`}- descriptionProps={SETTINGS_CARD_DESCRIPTION_PROPS}stackProps={SETTINGS_CARD_STACK_PROPS}><CopyTextInput@@ -145,17 +148,19 @@ export function SettingsSAMLForm() {readOnly/>- <Title order={3} size="h5" mt="xxl">{t`SAML attributes`}</Title>- <Text c="text-secondary" mb="lg">- {t`In most IdPs, you'll need to put each of these in an input box labeled "Name" in the attribute statements section.`}- </Text>+ <Box mt="xxl">+ <Title order={3} size="h5">{t`SAML attributes`}</Title>+ <Text c="text-secondary" {...SETTINGS_CARD_DESCRIPTION_PROPS}>+ {t`In most IdPs, you'll need to put each of these in an input box labeled "Name" in the attribute statements section.`}+ </Text>+ </Box><Stack gap="lg"><FormTextInputname="saml-attribute-email"label={t`User's email attribute`}hasCopyButton- {...getExtraFormFieldProps(+ {...getEnvNoticeProps(settingDetails?.["saml-attribute-email"],)}/>@@ -163,7 +168,7 @@ export function SettingsSAMLForm() {name="saml-attribute-firstname"label={t`User's first name attribute`}hasCopyButton- {...getExtraFormFieldProps(+ {...getEnvNoticeProps(settingDetails?.["saml-attribute-firstname"],)}/>@@ -171,7 +176,7 @@ export function SettingsSAMLForm() {name="saml-attribute-lastname"label={t`User's last name attribute`}hasCopyButton- {...getExtraFormFieldProps(+ {...getEnvNoticeProps(settingDetails?.["saml-attribute-lastname"],)}/>@@ -180,7 +185,7 @@ export function SettingsSAMLForm() {name="saml-attribute-tenant"label={t`Tenant assignment attribute`}hasCopyButton- {...getExtraFormFieldProps(+ {...getEnvNoticeProps(settingDetails?.["saml-attribute-tenant"],)}/>@@ -189,25 +194,26 @@ export function SettingsSAMLForm() {</SettingsSection><SettingsSection- title={t`Tell ${applicationName} about your identity provider`}+ title={t`Identity provider info`}titleProps={SETTINGS_CARD_TITLE_PROPS}- description={t`${applicationName} will need the following info about your provider.`}- descriptionProps={SETTINGS_CARD_DESCRIPTION_PROPS}stackProps={SETTINGS_CARD_STACK_PROPS}><Stack gap="lg"><FormTextInputname="saml-identity-provider-uri"label={t`SAML identity provider URL`}- placeholder="https://your-org-name.yourIDP.com"+ description={t`This is the URL where your users go to log in to your identity provider.`}+ descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}+ placeholder="https://your-org-name.example.com"required- {...getExtraFormFieldProps(+ {...getEnvNoticeProps(settingDetails?.["saml-identity-provider-uri"],)}/><FormTextareaname="saml-identity-provider-certificate"label={t`SAML identity provider certificate`}+ placeholder="-----BEGIN CERTIFICATE-----...-----END CERTIFICATE-----"{...getExtraFormFieldProps(settingDetails?.["saml-identity-provider-certificate"],)}@@ -216,6 +222,9 @@ export function SettingsSAMLForm() {<FormTextInputname="saml-application-name"label={t`SAML application name`}+ placeholder={getDefaultPlaceholder(+ settingDetails["saml-application-name"],+ )}nullable{...getExtraFormFieldProps(settingDetails?.["saml-application-name"],@@ -224,29 +233,27 @@ export function SettingsSAMLForm() {<FormTextInputname="saml-identity-provider-issuer"label={t`SAML identity provider issuer`}+ description={t`This is a unique identifier for the IdP. Often referred to as Entity ID or simply 'Issuer'.`}+ descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}+ placeholder="http://www.example.com/141xkex604w0Q5PN724v"required- {...getExtraFormFieldProps(+ {...getEnvNoticeProps(settingDetails?.["saml-identity-provider-issuer"],)}/></Stack></SettingsSection>- {/* the card saves on its own, so it stays out of the form's values */}- <UserProvisioningSection- settingKey="saml-user-provisioning-enabled?"- providerName="SAML"- lockedNote={scimNote}- />-<CollapsibleSettingsSection- title={t`Sign SSO requests (optional)`}+ title={t`Sign SSO requests`}+ description={t`Use a keystore to sign authentication requests sent to your identity provider`}defaultOpened={hasKeystoreSettings}><Stack gap="lg"><FormTextInputname="saml-keystore-path"label={t`SAML keystore path`}+ placeholder="/path/to/keystore.jks"nullable{...getExtraFormFieldProps(settingDetails?.["saml-keystore-path"],@@ -258,13 +265,14 @@ export function SettingsSAMLForm() {type="password"placeholder={t`Shh...`}nullable- {...getExtraFormFieldProps(+ {...getEnvNoticeProps(settingDetails?.["saml-keystore-password"],)}/><FormTextInputname="saml-keystore-alias"label={t`SAML keystore alias`}+ placeholder="saml"nullable{...getExtraFormFieldProps(settingDetails?.["saml-keystore-alias"],@@ -273,35 +281,33 @@ export function SettingsSAMLForm() {</Stack></CollapsibleSettingsSection>- <SettingsSection- title={t`Group mapping`}- titleProps={SETTINGS_CARD_TITLE_PROPS}- description={t`To enable this, you'll need to create mappings to tell ${applicationName} which group(s) your users should be added to based on the SSO group they're in.`}- descriptionProps={SETTINGS_CARD_DESCRIPTION_PROPS}- stackProps={SETTINGS_CARD_STACK_PROPS}+ <SettingsGroupMappingSection+ syncSettingKey="saml-group-sync"+ mappingsSettingKey="saml-group-mappings"+ description={t`Automatically assign people to ${applicationName} groups based on groups from your SAML identity provider`}+ nameLabel={t`SAML group name`}+ namePlaceholder={t`Enter SAML group...`}+ data-testid="saml-group-mapping-section"+ disabled={!isConfigured}+ onToggle={(enabled) => {+ if (!enabled) {+ resetFieldsToInitial(setFieldValue, initialValues, [+ "saml-attribute-group",+ ]);+ }+ }}>- <Stack gap="lg">- <GroupMappingsWidget- isFormik- // map to legacy setting props- setting={{ key: "saml-group-sync" }}- onChange={handleSubmit}- settingValues={settingValues}- mappingSetting="saml-group-mappings"- groupHeading={t`Group name`}- groupPlaceholder={t`Group name`}- />- <FormTextInput- name="saml-attribute-group"- label={t`Group attribute name`}- placeholder="member_of"- nullable- {...getExtraFormFieldProps(- settingDetails?.["saml-attribute-group"],- )}- />- </Stack>- </SettingsSection>+ <FormTextInput+ name="saml-attribute-group"+ label={t`Group attribute name`}+ description={t`The SAML attribute that lists a user's groups. Group mapping assigns no groups until it's set.`}+ descriptionProps={SETTINGS_FIELD_DESCRIPTION_PROPS}+ placeholder="member_of"+ required+ nullable+ {...getEnvNoticeProps(settingDetails["saml-attribute-group"])}+ />+ </SettingsGroupMappingSection><FormErrorMessage /><Flex justify="end">@@ -312,6 +318,7 @@ export function SettingsSAMLForm() {/></Flex></Stack>+ <LeaveRouteConfirmModal isEnabled={dirty && !isSubmitting} /></Form>)}</FormProvider>@@ -320,9 +327,10 @@ export function SettingsSAMLForm() {}const getFormValues = (- allSettings: Partial<EnterpriseSettings>,+ settingDetails: SettingDefinitionMap,+ settingValues: Partial<EnterpriseSettings>,): SAMLFormSettings => {- const samlSettings = _.pick(allSettings, [+ const samlSettings = _.pick(settingValues, ["saml-attribute-email","saml-attribute-firstname","saml-attribute-lastname",@@ -330,14 +338,18 @@ const getFormValues = ("saml-identity-provider-uri","saml-identity-provider-issuer","saml-identity-provider-certificate",- "saml-application-name","saml-keystore-password","saml-keystore-alias","saml-keystore-path","saml-attribute-group",- "saml-group-sync",]);- // cast undefined to null- return _.mapObject(samlSettings, (val) => val ?? null) as SAMLFormSettings;+ // mapObject widens every value to one union+ return {+ ..._.mapObject(samlSettings, (val) => val ?? null),+ "saml-application-name": getStoredFieldValue(+ settingDetails["saml-application-name"],+ settingValues["saml-application-name"],+ ),+ } as SAMLFormSettings;};diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.unit.spec.tsxindex 15ba90d88b4..4429ee246e2 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.unit.spec.tsx@@ -14,39 +14,65 @@ import { SettingsSAMLForm } from "./SettingsSAMLForm";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: "Engineering", magic_group_type: null }),];+const URL_EXAMPLE = "https://your-org-name.example.com";+const ISSUER_EXAMPLE = "http://www.example.com/141xkex604w0Q5PN724v";++const fields: { label: RegExp; value: string }[] = [+ { label: /SAML Identity Provider URL/i, value: "https://example.test" },+ {+ label: /SAML Identity Provider Certificate/i,+ value: "MIIDdDCCAlygAwIBAgIGAZKb9aJvMA0GCSqGSIb3DQEBCwUAMHsx",+ },+ { label: /SAML Identity Provider Issuer/i, value: "example.test.sso" },+];++const IDP_SETTINGS = {+ "saml-enabled": true,+ "saml-identity-provider-uri": "https://example.test",+ "saml-identity-provider-certificate": fields[1].value,+ "saml-identity-provider-issuer": fields[2].value,+};++const isSamlConfigured = (settings: Record<string, unknown>) =>+ Boolean(+ settings["saml-identity-provider-uri"] &&+ settings["saml-identity-provider-certificate"],+ );+const setup = async (- settingValues?: Partial<EnterpriseSettings>,+ settingValues: Partial<EnterpriseSettings> = {},settingDefinitions: SettingDefinition[] = [],) => {- const settings = createMockSettings(settingValues ?? {});+ const settings = createMockSettings({+ ...settingValues,+ "saml-configured": isSamlConfigured(settingValues),+ });setupSettingsEndpoints(settingDefinitions);- // the provisioning switch reads its value back after saving, so the properties mock has to remember writes- setupStatefulSettingsEndpoints(settings);+ const settingsStore = setupStatefulSettingsEndpoints(settings);fetchMock.get("path:/api/permissions/group", GROUPS);- fetchMock.put("path:/api/saml/settings", { status: 204 });+ fetchMock.put("path:/api/saml/settings", ({ options }) => {+ Object.assign(settingsStore, JSON.parse(String(options.body)));+ settingsStore["saml-configured"] = isSamlConfigured(settingsStore);+ return { status: 204 };+ });renderWithProviders(<SettingsSAMLForm />, { withUndos: true });- await screen.findByText("Configure your identity provider (IdP)");- await waitFor(async () => {- const gets = await findRequests("GET");- expect(gets).toHaveLength(3);- });+ await screen.findByText("Identity provider (IdP) configuration");};-// Unjustified type cast. FIXME-const fields = [- { label: /SAML Identity Provider URL/i, value: "https://example.test" },- { label: /SAML Identity Provider Certificate/i, value: "abc-123" },- { label: /SAML Identity Provider Issuer/i, value: "example.test.sso" },-] as { label: RegExp; value: string }[];+const setupConfigured = (+ settingValues?: Partial<EnterpriseSettings>,+ settingDefinitions?: SettingDefinition[],+) => setup({ ...IDP_SETTINGS, ...settingValues }, settingDefinitions);++const groupMappingSwitch = () =>+ screen.getByRole("switch", { name: "Group mapping" });describe("SettingsSAMLForm", () => {it("Can enable SAML via form input", async () => {@@ -78,6 +104,7 @@ describe("SettingsSAMLForm", () => {expect(body["saml-identity-provider-uri"]).toBe(fields[0].value);expect(body["saml-identity-provider-certificate"]).toBe(fields[1].value);expect(body["saml-identity-provider-issuer"]).toBe(fields[2].value);+ expect(body).not.toHaveProperty("saml-group-sync");});it("Can update existing SAML settings", async () => {@@ -113,41 +140,214 @@ describe("SettingsSAMLForm", () => {expect(body["saml-identity-provider-issuer"]).toBe(fields[2].value);});- describe("user provisioning", () => {- const CONFIGURED = {- "saml-enabled": true,- "saml-identity-provider-uri": "https://example.test",- "saml-identity-provider-certificate": fields[1].value,- "saml-identity-provider-issuer": fields[2].value,- };-- it("sits right below the identity provider settings", async () => {- await setup(CONFIGURED);-- const cardTitles = screen- .getAllByRole("heading", { level: 2 })- .map((heading) => heading.textContent);- expect(cardTitles).toEqual([- "Configure your identity provider (IdP)",- "Tell Metabase about your identity provider",- "User provisioning",- "Sign SSO requests (optional)",- "Group mapping",+ it("keeps the saved URL when the settings refetch after a save fails", async () => {+ await setupConfigured();+ fetchMock.removeRoute("get-session-properties");+ fetchMock.get("path:/api/session/properties", 500, {+ name: "get-session-properties",+ });++ const urlInput = screen.getByLabelText(/SAML identity provider URL/);+ await userEvent.clear(urlInput);+ await userEvent.type(urlInput, "https://sso.example.org/saml");+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));+ await waitFor(() =>+ expect(+ screen.getByRole("button", { name: /Success|Save/ }),+ ).toBeDisabled(),+ );++ const issuerInput = screen.getByLabelText(/SAML identity provider issuer/);+ await userEvent.clear(issuerInput);+ await userEvent.type(issuerInput, "https://sso.example.org/entity");+ await userEvent.click(screen.getByRole("button", { name: /Success|Save/ }));++ await waitFor(async () =>+ expect(await findRequests("PUT")).toHaveLength(2),+ );+ const [, { body }] = await findRequests("PUT");+ expect(body["saml-identity-provider-uri"]).toBe(+ "https://sso.example.org/saml",+ );+ expect(urlInput).toHaveValue("https://sso.example.org/saml");+ });++ it("lays the cards out in the designed order", async () => {+ await setupConfigured();++ const cardTitles = screen+ .getAllByRole("heading", { level: 2 })+ .map((heading) => heading.textContent);+ expect(cardTitles).toEqual([+ "User provisioning",+ "Identity provider (IdP) configuration",+ "Identity provider info",+ "Sign SSO requests",+ "Group mapping",+ ]);+ });++ describe("defaults", () => {+ it("shows the application name default as a placeholder and leaves the field empty", async () => {+ await setup({ "saml-application-name": "Metabase" }, [+ { key: "saml-application-name", default: "Metabase" },+ ]);++ const input = screen.getByLabelText(/SAML application name/);+ expect(input).toHaveValue("");+ expect(input).toHaveAttribute("placeholder", "Metabase");+ });++ it("shows the application name an env var sets, read-only", async () => {+ await setup({ "saml-application-name": "Acme BI" }, [+ {+ key: "saml-application-name",+ is_env_setting: true,+ env_name: "MB_SAML_APPLICATION_NAME",+ },+ ]);++ const input = screen.getByLabelText(/SAML application name/);+ expect(input).toHaveValue("Acme BI");+ expect(input).toHaveAttribute("readonly");+ expect(input).not.toHaveAttribute("placeholder");+ expect(+ screen.getByText("Using MB_SAML_APPLICATION_NAME"),+ ).toBeInTheDocument();+ });++ it("moves the identity provider URL example into the placeholder", async () => {+ await setup({}, [+ {+ key: "saml-identity-provider-uri",+ description: `This is the URL where your users go to log in to your identity provider. Depending on which IdP you're using, this usually looks like \`${URL_EXAMPLE}\` or \`https://example.com/app/my_saml_app/abc123/sso/saml\``,+ },]);++ expect(+ screen.getByLabelText(/SAML identity provider URL/),+ ).toHaveAttribute("placeholder", URL_EXAMPLE);+ expect(+ screen.getByText(+ "This is the URL where your users go to log in to your identity provider.",+ ),+ ).toBeInTheDocument();+ expect(screen.queryByText(/usually looks like/)).not.toBeInTheDocument();+ });++ it("shows the identity provider URL an env var sets, read-only", async () => {+ await setup(+ { "saml-identity-provider-uri": "https://sso.example.org/saml" },+ [+ {+ key: "saml-identity-provider-uri",+ is_env_setting: true,+ env_name: "MB_SAML_IDENTITY_PROVIDER_URI",+ },+ ],+ );++ const input = screen.getByLabelText(/SAML identity provider URL/);+ expect(input).toHaveValue("https://sso.example.org/saml");+ expect(input).toHaveAttribute("readonly");+ expect(input).toHaveAccessibleDescription(+ "Using MB_SAML_IDENTITY_PROVIDER_URI",+ );});- it("stays editable before the identity provider is set up", async () => {+ it("moves the issuer example into the placeholder", async () => {+ await setup({}, [+ {+ key: "saml-identity-provider-issuer",+ description: `This is a unique identifier for the IdP. Often referred to as Entity ID or simply 'Issuer'. Depending on your IdP, this usually looks something like \`${ISSUER_EXAMPLE}\``,+ },+ ]);++ expect(+ screen.getByLabelText(/SAML identity provider issuer/),+ ).toHaveAttribute("placeholder", ISSUER_EXAMPLE);+ expect(+ screen.getByText(+ "This is a unique identifier for the IdP. Often referred to as Entity ID or simply 'Issuer'.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(/usually looks something like/),+ ).not.toBeInTheDocument();+ });++ it("shows only the env-var notice under the attribute fields", async () => {+ await setup({ "saml-attribute-firstname": "given_name" }, [+ {+ key: "saml-attribute-email",+ description: "SAML attribute for the user's email address",+ },+ {+ key: "saml-attribute-firstname",+ is_env_setting: true,+ env_name: "MB_SAML_ATTRIBUTE_FIRSTNAME",+ },+ ]);++ expect(+ screen.queryByText("SAML attribute for the user's email address"),+ ).not.toBeInTheDocument();+ const firstNameInput = screen.getByLabelText(+ /User's first name attribute/,+ );+ expect(firstNameInput).toHaveValue("given_name");+ expect(firstNameInput).toHaveAttribute("readonly");+ expect(+ screen.getByText("Using MB_SAML_ATTRIBUTE_FIRSTNAME"),+ ).toBeInTheDocument();+ });++ it("keeps the keystore card collapsed until a keystore is set", async () => {await setup();+ expect(+ screen.getByRole("button", { name: "Sign SSO requests" }),+ ).toHaveAttribute("aria-expanded", "false");+ expect(+ screen.getByText(+ "Use a keystore to sign authentication requests sent to your identity provider",+ ),+ ).toBeInTheDocument();+ expect(screen.getByLabelText(/SAML keystore path/)).not.toBeVisible();+ });++ it("opens the keystore card when a keystore is set", async () => {+ await setup({ "saml-keystore-path": "/etc/metabase/keystore.jks" }, [+ {+ key: "saml-keystore-password",+ description: "Password for opening the keystore",+ },+ ]);++ expect(+ screen.getByRole("button", { name: "Sign SSO requests" }),+ ).toHaveAttribute("aria-expanded", "true");+ expect(screen.getByLabelText(/SAML keystore path/)).toHaveValue(+ "/etc/metabase/keystore.jks",+ );+ expect(+ screen.queryByText("Password for opening the keystore"),+ ).not.toBeInTheDocument();+ });+ });++ describe("user provisioning", () => {+ it("says that SAML sign-in also reactivates deactivated accounts", async () => {+ await setupConfigured();+expect(screen.getByRole("switch", { name: "User provisioning" }),- ).toBeEnabled();+ ).toHaveAccessibleDescription(/reactivate deactivated accounts/);});it("saves right away without touching the page form", async () => {- await setup({ ...CONFIGURED, "saml-user-provisioning-enabled?": true });+ await setupConfigured({ "saml-user-provisioning-enabled?": true });const toggle = screen.getByRole("switch", { name: "User provisioning" });- expect(toggle).toBeEnabled();expect(toggle).toBeChecked();await userEvent.click(toggle);@@ -166,14 +366,13 @@ describe("SettingsSAMLForm", () => {});it("locks the switch while SCIM manages provisioning", async () => {- await setup({- ...CONFIGURED,+ await setupConfigured({"scim-enabled": true,"saml-user-provisioning-enabled?": false,});const toggle = screen.getByRole("switch", { name: "User provisioning" });- expect(toggle).toBeDisabled();+ expect(toggle).toHaveAttribute("aria-disabled", "true");expect(toggle).not.toBeChecked();expect(screen.getByRole("link", { name: "managed by SCIM" }),@@ -184,9 +383,8 @@ describe("SettingsSAMLForm", () => {});it("shows the SCIM note instead of the env line when both apply", async () => {- await setup(+ await setupConfigured({- ...CONFIGURED,"scim-enabled": true,"saml-user-provisioning-enabled?": false,},@@ -200,11 +398,187 @@ describe("SettingsSAMLForm", () => {);const toggle = screen.getByRole("switch", { name: "User provisioning" });- expect(toggle).toBeDisabled();+ expect(toggle).toHaveAttribute("aria-disabled", "true");expect(toggle).toHaveAccessibleDescription(/managed by SCIM/);expect(screen.queryByText("Using MB_SAML_USER_PROVISIONING_ENABLED"),).not.toBeInTheDocument();});++ it("stays editable while SAML is paused but configured", async () => {+ await setupConfigured({ "saml-enabled": false });++ const toggle = screen.getByRole("switch", { name: "User provisioning" });+ expect(toggle).toBeEnabled();+ expect(toggle).not.toHaveAttribute("aria-disabled");+ expect(groupMappingSwitch()).toBeEnabled();+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled");+ });+ });++ describe("group mapping", () => {+ it("keeps the group mapping card disabled until the identity provider is set up", async () => {+ await setup({ "saml-group-sync": true });++ const provisioningSwitch = screen.getByRole("switch", {+ name: "User provisioning",+ });+ expect(provisioningSwitch).toBeEnabled();+ expect(provisioningSwitch).not.toHaveAttribute("aria-disabled");+ expect(groupMappingSwitch()).toBeDisabled();+ expect(groupMappingSwitch()).toBeChecked();+ expect(+ screen.queryByText("Manual group mappings"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("textbox", { name: /Group attribute name/ }),+ ).not.toBeInTheDocument();+ });++ it("unlocks the group mapping card after the first save", async () => {+ await setup();+ expect(groupMappingSwitch()).toBeDisabled();++ for (const { label, value } of fields) {+ await userEvent.type(screen.getByLabelText(label), value);+ }+ await userEvent.click(+ screen.getByRole("button", { name: "Save and enable" }),+ );++ // the card's lock is native disabled, while a refetch holds the switch with aria-disabled+ await waitFor(() => expect(groupMappingSwitch()).toBeEnabled());+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ });++ it("turns group mapping on right away and reveals the mappings and the group attribute", 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 attribute name/ }),+ ).toBeInTheDocument();+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ expect(puts[0].url).toMatch(/\/api\/setting\/saml-group-sync$/);+ expect(puts[0].body).toEqual({ value: true });+ expect(screen.getByRole("button", { name: /Save/ })).toBeDisabled();+ });++ it("adds a mapping and writes it without touching the page form", async () => {+ await setupConfigured({ "saml-group-sync": true });++ const newButton = screen.getByRole("button", { name: "New" });+ await waitFor(() => expect(newButton).toBeEnabled());+ await userEvent.click(newButton);+ await userEvent.type(+ screen.getByPlaceholderText("Enter SAML group..."),+ "engineering",+ );+ await userEvent.click(+ screen.getByPlaceholderText("Pick Metabase group..."),+ );+ await userEvent.click(+ await screen.findByRole("option", { name: "Engineering" }),+ );+ 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({+ "saml-group-mappings": { engineering: [3] },+ });+ });++ it("shows the group attribute an env var sets, read-only", async () => {+ await setupConfigured(+ { "saml-group-sync": true, "saml-attribute-group": "memberOf" },+ [+ {+ key: "saml-attribute-group",+ is_env_setting: true,+ env_name: "MB_SAML_ATTRIBUTE_GROUP",+ },+ ],+ );++ const attributeInput = screen.getByRole("textbox", {+ name: /Group attribute name/,+ });+ expect(attributeInput).toHaveValue("memberOf");+ expect(attributeInput).toHaveAttribute("readonly");+ expect(attributeInput).toHaveAccessibleDescription(+ "Using MB_SAML_ATTRIBUTE_GROUP",+ );+ });++ it("marks the group attribute as needed while group mapping is on", async () => {+ await setupConfigured({ "saml-group-sync": true });++ const attributeInput = screen.getByRole("textbox", {+ name: /Group attribute name/,+ });+ expect(attributeInput).toBeRequired();+ expect(attributeInput).toBeInvalid();+ expect(attributeInput).toHaveAccessibleDescription(+ "The SAML attribute that lists a user's groups. Group mapping assigns no groups until it's set.",+ );+ });++ it("saves the group attribute with the page form", async () => {+ await setupConfigured({ "saml-group-sync": true });++ await userEvent.type(+ screen.getByRole("textbox", { name: /Group attribute name/ }),+ "memberOf",+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Save changes" }),+ );++ await screen.findByText("Success");+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ expect(puts[0].url).toMatch(/api\/saml\/settings/);+ expect(puts[0].body["saml-attribute-group"]).toBe("memberOf");+ expect(puts[0].body).not.toHaveProperty("saml-group-sync");+ });++ it("drops an unsaved group attribute edit when group mapping is turned off", async () => {+ await setupConfigured({+ "saml-group-sync": true,+ "saml-attribute-group": "groups",+ });+ const saveButton = () =>+ screen.getByRole("button", { name: "Save changes" });++ await userEvent.type(+ screen.getByRole("textbox", { name: /Group attribute name/ }),+ "X",+ );+ expect(saveButton()).toBeEnabled();++ await userEvent.click(groupMappingSwitch());+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );++ expect(saveButton()).toBeDisabled();+ await userEvent.click(groupMappingSwitch());+ expect(+ await screen.findByRole("textbox", { name: /Group attribute name/ }),+ ).toHaveValue("groups");+ });});});diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/UserProvisioningSection/UserProvisioningSection.module.css b/enterprise/frontend/src/metabase-enterprise/auth/components/UserProvisioningSection/UserProvisioningSection.module.cssdeleted file mode 100644index b83ca750e36..00000000000--- a/enterprise/frontend/src/metabase-enterprise/auth/components/UserProvisioningSection/UserProvisioningSection.module.css+++ /dev/null@@ -1,8 +0,0 @@-/* the title is the switch's label, so it borrows the switch's pointer */-.titleLabel {- cursor: pointer;-}--.titleLabel.disabled {- cursor: default;-}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/UserProvisioningSection/UserProvisioningSection.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/UserProvisioningSection/UserProvisioningSection.tsxindex 260a246a760..d253b0fff68 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/components/UserProvisioningSection/UserProvisioningSection.tsx+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/UserProvisioningSection/UserProvisioningSection.tsx@@ -1,24 +1,9 @@-import { useDebouncedCallback } from "@mantine/hooks";-import cx from "classnames";-import { useEffect, useId, useState } from "react";import { t } from "ttag";import { useSelector } from "metabase/redux";import { getApplicationName } from "metabase/selectors/whitelabel";-import { useAdminSetting } from "metabase/settings";-import {- SETTINGS_CARD_DESCRIPTION_PROPS,- SETTINGS_CARD_TITLE_PROPS,- SettingsSection,-} from "metabase/settings-components";-import { Box, Flex, Switch, Text, Title } from "metabase/ui";--import S from "./UserProvisioningSection.module.css";--// a burst of clicks ends in a single write for the last value-export const PROVISIONING_WRITE_DEBOUNCE_MS = 300;--type PendingWrite = { value: boolean; at: number };+import { useSettingSwitch } from "metabase/settings";+import { SwitchSettingsSection } from "metabase/settings-components";export type UserProvisioningSettingKey =| "jwt-user-provisioning-enabled?"@@ -26,120 +11,37 @@ export type UserProvisioningSettingKey =| "oidc-user-provisioning-enabled?"| "saml-user-provisioning-enabled?";-export function UserProvisioningSection({- settingKey,- providerName,- disabled = false,- lockedNote,-}: {+type UserProvisioningSectionProps = {settingKey: UserProvisioningSettingKey;// the sign-in method as the description names itproviderName: string;- // greys the card out on pages that stay read-only until their server settings are saved- disabled?: boolean;+ reactivatesAccounts?: boolean;// says why the switch cannot be toggled and keeps it disabled while shownlockedNote?: React.ReactNode;-}) {- const inputId = useId();- const descriptionId = useId();+};++export function UserProvisioningSection({+ settingKey,+ providerName,+ reactivatesAccounts = false,+ lockedNote,+}: UserProvisioningSectionProps) {const applicationName = useSelector(getApplicationName);- const {- value,- settingDetails,- updateSetting,- isLoading,- isFetching,- startedTimeStamp,- } = useAdminSetting(settingKey);- // the last written value, shown until a refetch that started after the write lands- const [pendingWrite, setPendingWrite] = useState<PendingWrite | null>(null);- const envName = settingDetails?.is_env_setting- ? settingDetails.env_name- : undefined;+ const provisioningSwitch = useSettingSwitch(settingKey);const hasLockedNote = Boolean(lockedNote);- const isLocked = envName != null || hasLockedNote;- // the lock is only known once the settings list has loaded- const isDisabled = disabled || isLocked || isLoading;-- useEffect(() => {- // an older refetch can still answer with the previous value, so only a later one counts- if (- pendingWrite != null &&- !isFetching &&- startedTimeStamp != null &&- startedTimeStamp >= pendingWrite.at- ) {- setPendingWrite(null);- }- }, [pendingWrite, isFetching, startedTimeStamp]);-- // leaving the page flushes a write that is still waiting on the debounce- const saveProvisioningSetting = useDebouncedCallback(- async (pending: PendingWrite) => {- const { error } = await updateSetting({- key: settingKey,- value: pending.value,- });- if (error) {- setPendingWrite((current) => (current === pending ? null : current));- }- },- { delay: PROVISIONING_WRITE_DEBOUNCE_MS, flushOnUnmount: true },- );-- const handleChange = (enabled: boolean) => {- const pending = { value: enabled, at: Date.now() };- setPendingWrite(pending);- saveProvisioningSetting(pending);- };-- // 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();- }- };+ const description = reactivatesAccounts+ ? t`Allow ${providerName} sign-in to create accounts for new users and reactivate deactivated accounts. When disabled, only users with active ${applicationName} accounts can sign in.`+ : t`Allow ${providerName} sign-in to create accounts for new users. When disabled, only users with active ${applicationName} accounts can sign in.`;return (- <SettingsSection disabled={disabled}>- <Flex justify="space-between" align="flex-start" gap="lg">- <Box>- <Title {...SETTINGS_CARD_TITLE_PROPS}>- {/* the title doubles as the switch's label, so clicking it toggles too */}- <Text- component="label"- htmlFor={inputId}- className={cx(S.titleLabel, isDisabled && S.disabled)}- inherit- >- {t`User provisioning`}- </Text>- </Title>- {/* the notes sit inside the description, so assistive tech hears why the switch is locked */}- <Box id={descriptionId}>- <Text c="text-secondary" {...SETTINGS_CARD_DESCRIPTION_PROPS}>- {t`Allow ${providerName} sign-in to create accounts for new users and reactivate deactivated accounts. When disabled, only users with active ${applicationName} accounts can sign in.`}- </Text>- {/* a caller's note explains the lock, so the env line steps aside */}- {envName != null && !hasLockedNote && (- <Text c="text-secondary" mt="sm">{t`Using ${envName}`}</Text>- )}- {hasLockedNote && (- <Box c="text-secondary" mt="sm">- {lockedNote}- </Box>- )}- </Box>- </Box>- <Switch- id={inputId}- aria-describedby={descriptionId}- checked={pendingWrite?.value ?? value ?? false}- disabled={isDisabled}- onChange={(event) => handleChange(event.currentTarget.checked)}- onKeyDown={handleKeyDown}- />- </Flex>- </SettingsSection>+ <SwitchSettingsSection+ title={t`User provisioning`}+ description={description}+ lockedEnvName={hasLockedNote ? undefined : provisioningSwitch.envName}+ note={lockedNote}+ checked={provisioningSwitch.checked}+ switchDisabled={hasLockedNote || provisioningSwitch.isBusy}+ onChange={provisioningSwitch.onChange}+ />);}diff --git a/enterprise/frontend/src/metabase-enterprise/auth/constants.ts b/enterprise/frontend/src/metabase-enterprise/auth/constants.tsindex 9e0509545fe..ba33b4cb28b 100644--- a/enterprise/frontend/src/metabase-enterprise/auth/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/auth/constants.ts@@ -9,6 +9,7 @@ export const JWT_SCHEMA = Yup.object({"jwt-attribute-firstname": Yup.string().nullable().default(null),"jwt-attribute-lastname": Yup.string().nullable().default(null),"jwt-attribute-groups": Yup.string().nullable().default(null),+ "jwt-attribute-tenant": Yup.string().nullable().default(null),"jwt-group-sync": Yup.boolean().default(false),"jwt-group-mappings": Yup.object().default(null),});@@ -27,6 +28,7 @@ export const SAML_SCHEMA = Yup.object({"saml-attribute-firstname": Yup.string().nullable().default(null),"saml-attribute-lastname": Yup.string().nullable().default(null),"saml-attribute-group": Yup.string().nullable().default(null),+ "saml-attribute-tenant": Yup.string().nullable().default(null),"saml-group-sync": Yup.boolean().default(false),"saml-group-mappings": Yup.object().default(null),});diff --git a/frontend/src/metabase-types/api/group.ts b/frontend/src/metabase-types/api/group.tsindex ba428b23266..9b4c848a0bd 100644--- a/frontend/src/metabase-types/api/group.ts+++ b/frontend/src/metabase-types/api/group.ts@@ -2,6 +2,8 @@ import type { UserId } from "./user";export type GroupId = number;+export type GroupMappings = Record<string, GroupId[]>;+export type Membership = {user_id: UserId;group_id: GroupId;diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex f710606d516..48cff5ea911 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -365,7 +365,6 @@ export const createMockSettings = ("saml-group-sync": null,"saml-group-mappings": null,"jwt-group-mappings": null,- "oidc-group-mappings": null,"scim-enabled": false,"scim-base-url": "http://localhost:3000/api/ee/scim/v2/","snowplow-url": "",diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 15d79ad09a5..514ab919e8a 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -5,7 +5,7 @@ import type { DashboardId } from "./dashboard";import type { DatabaseId } from "./database";import type { SdkIframeEmbedSetupTheme } from "./embedding-theme";import type { CurrencyStyle } from "./formatting";-import type { GroupId } from "./group";+import type { GroupMappings } from "./group";import type { MetabotLimitPeriod, MetabotLimitType } from "./metabot";import type { NotificationRecipient } from "./notification";import type { UserId } from "./user";@@ -630,7 +630,7 @@ interface PublicSettings {"ldap-attribute-lastname": string | null;"ldap-group-sync": boolean;"ldap-group-base": string | null;- "ldap-group-mappings": Record<string /*ldap group name */, GroupId[]> | null;+ "ldap-group-mappings": GroupMappings | null;"ldap-group-membership-filter"?: string | null;"ldap-user-provisioning-enabled?": boolean;"oidc-user-provisioning-enabled?": boolean;@@ -812,6 +812,8 @@ export interface EnterpriseSettings extends Settings {"jwt-group-sync": boolean | null;"oidc-enabled": boolean;"oidc-configured": boolean;+ // sensitive, so only the admin settings list carries it; pages use /api/ee/sso/oidc+ "oidc-providers"?: string | null;"saml-enabled": boolean;"saml-configured": boolean;"saml-user-provisioning-enabled?": boolean;@@ -828,9 +830,8 @@ export interface EnterpriseSettings extends Settings {"saml-attribute-tenant": string | null;"saml-attribute-group": string | null;"saml-group-sync": boolean | null;- "saml-group-mappings": Record<string, GroupId[]> | null;- "jwt-group-mappings": Record<string, GroupId[]> | null;- "oidc-group-mappings": Record<string, GroupId[]> | null;+ "saml-group-mappings": GroupMappings | null;+ "jwt-group-mappings": GroupMappings | null;"database-replication-enabled": boolean | null;"database-replication-connections"?: DatabaseReplicationConnections | null;"embedding-hub-test-embed-snippet-created": boolean;diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/DeleteGroupMappingModal/DeleteGroupMappingModal.tsxsimilarity index 57%rename from frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsxrename to frontend/src/metabase/admin/settings/auth/components/GroupMappings/DeleteGroupMappingModal/DeleteGroupMappingModal.tsxindex 33295eeb4bd..9af879b64b3 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx@@ -1,65 +1,74 @@import { useState } from "react";import { t } from "ttag";-import type {- DeleteMappingModalValueType,- GroupIds,-} from "metabase/admin/types";import { useSelector } from "metabase/redux";import { getApplicationName } from "metabase/selectors/whitelabel";import { Box, Button, Group, Modal, Radio, Stack, Text } from "metabase/ui";+import S from "../GroupMappings.module.css";+import type { DeleteMappingModalValueType } from "../types";+export type DeleteGroupMappingModalProps = {- name: string;- groupIds: GroupIds;- // the Administrators group is never cleared or deleted, so the copy says so when it is mapped- hasAdminGroup?: boolean;+ mappingName: string;+ clearedGroups: string[];+ keptOnClear: string[];+ deletedGroups: string[];+ keptOnDelete: string[];// an extra consequence the caller wants spelled out, shown under the lead textnote?: string;- onConfirm: (- value: DeleteMappingModalValueType,- groupIds: GroupIds,- name: string,- ) => void;+ onConfirm: (value: DeleteMappingModalValueType) => void;onHide: () => void;};+function getKeptNote(names: string[]): string | null {+ if (names.length === 0) {+ return null;+ }+ if (names.length === 1) {+ return t`The ${names[0]} group is not affected.`;+ }+ return t`These groups are not affected: ${names.join(", ")}.`;+}+export const DeleteGroupMappingModal = ({- name,- groupIds,- hasAdminGroup = false,+ mappingName,+ clearedGroups,+ keptOnClear,+ deletedGroups,+ keptOnDelete,note,onConfirm,onHide,}: DeleteGroupMappingModalProps) => {const [value, setValue] = useState<DeleteMappingModalValueType>("nothing");const applicationName = useSelector(getApplicationName);- const isPlural = groupIds.length > 1;- // with only the Administrators group, or no group at all, there is nothing a cascade could touch- const canCascade = groupIds.length > (hasAdminGroup ? 1 : 0);+ const groupCount = clearedGroups.length + keptOnClear.length;+ const isPlural = groupCount > 1;+ const canCascade = clearedGroups.length > 0 || deletedGroups.length > 0;+ const keptOnClearNote = getKeptNote(keptOnClear);+ const keptOnDeleteNote = getKeptNote(keptOnDelete);+ const hasDeleteDescription =+ deletedGroups.length > 0 || keptOnDeleteNote != null;const handleChange = (newValue: DeleteMappingModalValueType) => {setValue(newValue);};const handleConfirm = () => {- onConfirm(value, groupIds, name);+ onConfirm(value);};const submitButtonLabels: Record<DeleteMappingModalValueType, string> = {nothing: t`Remove mapping`,clear: t`Remove mapping and members`,- delete: isPlural- ? t`Remove mapping and delete groups`- : t`Remove mapping and delete group`,+ delete:+ deletedGroups.length > 1+ ? t`Remove mapping and delete groups`+ : t`Remove mapping and delete group`,};- const adminNote = hasAdminGroup- ? t`The Administrators group is not affected.`- : null;-let lead: string;- if (groupIds.length === 0) {+ if (groupCount === 0) {lead = t`This mapping isn't linked to any group.`;} else if (isPlural) {lead = t`Membership of these groups will no longer be synced when users log in.`;@@ -70,9 +79,14 @@ export const DeleteGroupMappingModal = ({return (<Modal opened onClose={onHide} title={t`Remove this group mapping?`}><Stack gap="xl" mt="sm">- <Text>{lead}</Text>+ <Box>+ <Text fw="bold" className={S.wrappableText}>+ {mappingName}+ </Text>+ <Text>{lead}</Text>+ </Box>{note && <Text>{note}</Text>}- {!canCascade && adminNote && <Text>{adminNote}</Text>}+ {!canCascade && keptOnDeleteNote && <Text>{keptOnDeleteNote}</Text>}{canCascade && (<Box>@@ -95,26 +109,44 @@ export const DeleteGroupMappingModal = ({/><Radiovalue="clear"+ disabled={clearedGroups.length === 0}label={- isPlural+ clearedGroups.length > 1? t`Also remove all members from these groups`: t`Also remove all members from this group`}description={<>+ {clearedGroups.length > 0 && (+ <Box component="span" display="block">+ {clearedGroups.join(", ")}+ </Box>+ )}{t`Members keep their ${applicationName} accounts.`}{" "}- {adminNote}+ {keptOnClearNote}</>}/><Radiovalue="delete"+ disabled={deletedGroups.length === 0}label={- isPlural+ deletedGroups.length > 1? t`Also delete the groups`: t`Also delete the group`}- description={adminNote}+ description={+ hasDeleteDescription && (+ <>+ {deletedGroups.length > 0 && (+ <Box component="span" display="block">+ {deletedGroups.join(", ")}+ </Box>+ )}+ {keptOnDeleteNote}+ </>+ )+ }/></Stack></Radio.Group>diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsxsimilarity index 53%rename from frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsxrename to frontend/src/metabase/admin/settings/auth/components/GroupMappings/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsxindex 7e382299094..531040bc34d 100644--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx@@ -9,9 +9,14 @@ import {type SetupOpts = Partial<DeleteGroupMappingModalProps>;+const DEVS_DN = "cn=devs,ou=groups,dc=example,dc=org";+const DEFAULT_PROPS = {- name: "cn=People",- groupIds: [1],+ mappingName: DEVS_DN,+ clearedGroups: ["Engineering"],+ keptOnClear: [],+ deletedGroups: ["Engineering"],+ keptOnDelete: [],onConfirm: jest.fn(),onHide: jest.fn(),};@@ -30,14 +35,15 @@ describe("DeleteGroupMappingModal", () => {it("shows options for when mapping is linked to just one group", () => {setup();+ expect(screen.getByText(DEVS_DN)).toBeInTheDocument();expect(screen.getByText("Membership of this group will no longer be synced when users log in.",),).toBeInTheDocument();expect(- screen.getByText("Nothing, just remove the mapping"),- ).toBeInTheDocument();+ screen.getByLabelText("Nothing, just remove the mapping"),+ ).toBeChecked();expect(screen.getByText("Also remove all members from this group"),).toBeInTheDocument();@@ -49,7 +55,10 @@ describe("DeleteGroupMappingModal", () => {});it("shows options for when mapping is linked to more than one group", () => {- setup({ groupIds: [1, 2] });+ setup({+ clearedGroups: ["Engineering", "Marketing"],+ deletedGroups: ["Engineering", "Marketing"],+ });expect(screen.getByText(@@ -65,16 +74,75 @@ describe("DeleteGroupMappingModal", () => {expect(screen.getByText("Also delete the groups")).toBeInTheDocument();});- it("notes that the Administrators group is left alone when it is mapped", () => {- setup({ groupIds: [1, 2], hasAdminGroup: true });+ it("names the groups each option acts on and the built-in groups it leaves alone", () => {+ setup({+ clearedGroups: ["Data Analysts", "Engineering"],+ keptOnClear: ["Administrators"],+ deletedGroups: ["Engineering"],+ keptOnDelete: ["Administrators", "Data Analysts"],+ });expect(- screen.getAllByText(/The Administrators group is not affected/),- ).toHaveLength(2);+ screen.getByLabelText("Also remove all members from these groups"),+ ).toBeEnabled();+ expect(screen.getByText("Data Analysts, Engineering")).toBeInTheDocument();+ expect(screen.getByLabelText("Also delete the group")).toBeEnabled();+ expect(screen.getByText("Engineering")).toBeInTheDocument();+ expect(+ screen.getByText(/The Administrators group is not affected\./),+ ).toBeInTheDocument();+ expect(+ screen.getByText(+ "These groups are not affected: Administrators, Data Analysts.",+ ),+ ).toBeInTheDocument();+ });++ it("counts only the groups an option acts on", async () => {+ setup({+ clearedGroups: ["Engineering"],+ keptOnClear: ["Administrators"],+ deletedGroups: ["Engineering"],+ keptOnDelete: ["Administrators"],+ });++ expect(+ screen.getByText(+ "Membership of these groups will no longer be synced when users log in.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByLabelText("Also remove all members from this group"),+ ).toBeEnabled();+ await userEvent.click(screen.getByLabelText("Also delete the group"));+ expect(+ screen.getByRole("button", { name: "Remove mapping and delete group" }),+ ).toBeInTheDocument();+ });++ it("still offers clearing a built-in group that cannot be deleted", () => {+ setup({+ clearedGroups: ["Data Analysts"],+ deletedGroups: [],+ keptOnDelete: ["Data Analysts"],+ });++ expect(+ screen.getByLabelText("Also remove all members from this group"),+ ).toBeEnabled();+ expect(screen.getByLabelText("Also delete the group")).toBeDisabled();+ expect(+ screen.getByText("The Data Analysts group is not affected."),+ ).toBeInTheDocument();});it("offers no group options when only the Administrators group is mapped", () => {- setup({ groupIds: [1], hasAdminGroup: true });+ setup({+ clearedGroups: [],+ keptOnClear: ["Administrators"],+ deletedGroups: [],+ keptOnDelete: ["Administrators"],+ });expect(screen.getByText("The Administrators group is not affected."),@@ -86,7 +154,7 @@ describe("DeleteGroupMappingModal", () => {});it("offers no group options when no group is mapped", () => {- setup({ groupIds: [] });+ setup({ clearedGroups: [], deletedGroups: [] });expect(screen.getByText("This mapping isn't linked to any group."),@@ -97,14 +165,6 @@ describe("DeleteGroupMappingModal", () => {).toBeInTheDocument();});- it("starts with 'Nothing' option checked", () => {- setup();-- expect(- screen.getByLabelText("Nothing, just remove the mapping"),- ).toBeChecked();- });-it("confirms when clearing members", async () => {setup();@@ -116,11 +176,7 @@ describe("DeleteGroupMappingModal", () => {screen.getByRole("button", { name: "Remove mapping and members" }),);- expect(DEFAULT_PROPS.onConfirm).toHaveBeenCalledWith(- "clear",- DEFAULT_PROPS.groupIds,- DEFAULT_PROPS.name,- );+ expect(DEFAULT_PROPS.onConfirm).toHaveBeenCalledWith("clear");});it("confirms when deleting groups", async () => {@@ -132,10 +188,6 @@ describe("DeleteGroupMappingModal", () => {screen.getByRole("button", { name: "Remove mapping and delete group" }),);- expect(DEFAULT_PROPS.onConfirm).toHaveBeenCalledWith(- "delete",- DEFAULT_PROPS.groupIds,- DEFAULT_PROPS.name,- );+ expect(DEFAULT_PROPS.onConfirm).toHaveBeenCalledWith("delete");});});diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/index.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/DeleteGroupMappingModal/index.tsxsimilarity index 100%rename from frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/index.tsxrename to frontend/src/metabase/admin/settings/auth/components/GroupMappings/DeleteGroupMappingModal/index.tsxdiff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingList.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingList.tsxindex 2c830d539bf..d0a5cdbf3f3 100644--- a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingList.tsx+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingList.tsx@@ -1,19 +1,33 @@import { t } from "ttag";-import { DeleteGroupMappingModal } from "metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal";+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";import { getGroupNameLocalized } from "metabase/common/utils/groups";import { Stack, Text } from "metabase/ui";+import type { GroupMappings } from "metabase-types/api";+import { DeleteGroupMappingModal } from "./DeleteGroupMappingModal";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";+type GroupMappingListProps = {+ mappings: GroupMappings;+ groupLookup: GroupLookup;+ editor: MappingEditorState;+ deletion: MappingDeletionState;+ readOnly: boolean;+ disabled: boolean;+ nameLabel: string;+ namePlaceholder: string;+ emptyMessage: string;+ deleteNote?: string;+};+/** The mapping rows with the inline editor and the delete confirmation, driven by the caller's hooks */export function GroupMappingList({- groupMapping,+ mappings,groupLookup,editor,deletion,@@ -22,19 +36,10 @@ export function GroupMappingList({nameLabel,namePlaceholder,emptyMessage,-}: {- groupMapping: GroupMappingsState;- groupLookup: GroupLookup;- editor: MappingEditorState;- deletion: MappingDeletionState;- readOnly: boolean;- disabled: boolean;- nameLabel: string;- namePlaceholder: string;- emptyMessage: string;-}) {+ deleteNote,+}: GroupMappingListProps) {const { draft } = editor;- const hasMappings = Object.keys(groupMapping.mappings).length > 0;+ const hasMappings = Object.keys(mappings).length > 0;const groupOptions = groupLookup.mappableGroups.map((group) => ({value: String(group.id),label: getGroupNameLocalized(group),@@ -43,9 +48,11 @@ export function GroupMappingList({groupOptions,nameLabel,namePlaceholder,- canSubmit: editor.canSave,+ // a hold for another reason blocks only the submit, so the draft stays editable+ canSubmit: editor.canSave && !disabled,nameError: editor.nameError,- isSubmitting: disabled,+ saveError: editor.saveError,+ isSubmitting: editor.isSubmitting,onChange: editor.change,onCancel: editor.cancel,onSubmit: editor.save,@@ -57,7 +64,7 @@ export function GroupMappingList({{!hasMappings && draft == null && !readOnly && (<Text c="text-secondary">{emptyMessage}</Text>)}- {Object.entries(groupMapping.mappings).map(([name, groupIds]) =>+ {Object.entries(mappings).map(([name, groupIds]) =>draft?.originalName === name ? (<MappingEditorRowkey={name}@@ -78,7 +85,7 @@ export function GroupMappingList({/>),)}- {draft != null && draft.originalName == null && (+ {draft != null && editor.isDraftNew && (<MappingEditorRowdraft={draft}submitLabel={t`Add mapping`}@@ -88,13 +95,29 @@ export function GroupMappingList({</Stack>{deletion.target != null && (<DeleteGroupMappingModal- name={deletion.target}- groupIds={deletion.targetGroupIds}- hasAdminGroup={groupLookup.hasAdminGroup(deletion.targetGroupIds)}+ mappingName={deletion.target}+ clearedGroups={groupLookup.actionableGroupNames(+ deletion.targetGroupIds,+ "clear",+ )}+ keptOnClear={groupLookup.keptGroupNames(+ deletion.targetGroupIds,+ "clear",+ )}+ deletedGroups={groupLookup.actionableGroupNames(+ deletion.targetGroupIds,+ "delete",+ )}+ keptOnDelete={groupLookup.keptGroupNames(+ deletion.targetGroupIds,+ "delete",+ )}+ note={deleteNote}onConfirm={deletion.confirmDelete}onHide={deletion.cancelDelete}/>)}+ <LeaveRouteConfirmModal isEnabled={editor.hasUnsavedChanges} /></>);}diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingsPanel.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingsPanel.tsxnew file mode 100644index 00000000000..f1ccde3b442--- /dev/null+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/GroupMappingsPanel.tsx@@ -0,0 +1,90 @@+import { t } from "ttag";++import { Button, Flex, Icon, Stack, Text } from "metabase/ui";+import type { GroupMappings } from "metabase-types/api";++import { GroupMappingList } from "./GroupMappingList";+import type { SaveMappings } from "./use-group-mappings";+import { useMappingDeletion } from "./use-mapping-deletion";+import { useMappingEditor } from "./use-mapping-editor";+import type { GroupLookup } from "./utils";++type GroupMappingsPanelProps = {+ mappings: GroupMappings;+ saveMappings: SaveMappings;+ onDeletingChange?: (isDeleting: boolean) => void;+ groupLookup: GroupLookup;+ disabled?: boolean;+ readOnly?: boolean;+ lockedEnvName?: string;+ namesValidatedOnSave?: boolean;+ nameLabel: string;+ namePlaceholder: string;+};++/** One provider's manual group mappings, with their header and inline editor */+export function GroupMappingsPanel({+ mappings,+ saveMappings,+ onDeletingChange,+ groupLookup,+ disabled = false,+ readOnly = false,+ lockedEnvName,+ namesValidatedOnSave,+ nameLabel,+ namePlaceholder,+}: GroupMappingsPanelProps) {+ const deletion = useMappingDeletion({+ mappings,+ saveMappings,+ onDeletingChange,+ groupLookup,+ });+ const editor = useMappingEditor({+ mappings,+ saveMappings,+ groupLookup,+ namesValidatedOnSave,+ });+ const isDisabled =+ disabled ||+ editor.isSubmitting ||+ deletion.isDeleting ||+ !groupLookup.isLoaded;+ const isReadOnly = readOnly || lockedEnvName != null;++ return (+ <Stack gap="sm">+ <Flex justify="space-between" align="center" gap="lg">+ <Text fw="bold">{t`Manual group mappings`}</Text>+ {!isReadOnly && editor.draft == null && (+ <Button+ variant="subtle"+ flex="0 0 auto"+ leftSection={<Icon name="add" aria-hidden />}+ disabled={isDisabled}+ onClick={editor.startNew}+ >{t`New`}</Button>+ )}+ </Flex>+ {lockedEnvName != null && (+ <Text c="text-secondary">{t`Using ${lockedEnvName}`}</Text>+ )}+ {groupLookup.loadFailed && (+ <Text c="error">{t`Groups could not be loaded`}</Text>+ )}+ <GroupMappingList+ mappings={mappings}+ groupLookup={groupLookup}+ editor={editor}+ deletion={deletion}+ readOnly={isReadOnly}+ disabled={isDisabled}+ nameLabel={nameLabel}+ namePlaceholder={namePlaceholder}+ emptyMessage={t`No mappings yet`}+ />+ </Stack>+ );+}diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingEditorRow.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingEditorRow.tsxindex a9e37fe5636..60000211b0f 100644--- a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingEditorRow.tsx+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingEditorRow.tsx@@ -17,6 +17,21 @@ import {import S from "./GroupMappings.module.css";import type { MappingDraft } from "./use-mapping-editor";+type MappingEditorRowProps = {+ draft: MappingDraft;+ groupOptions: { value: string; label: string }[];+ nameLabel: string;+ namePlaceholder: string;+ submitLabel: string;+ canSubmit: boolean;+ nameError: string | null;+ saveError: string | null;+ isSubmitting: boolean;+ onChange: (draft: MappingDraft) => void;+ onCancel: () => void;+ onSubmit: () => void;+};+export function MappingEditorRow({draft,groupOptions,@@ -25,35 +40,35 @@ export function MappingEditorRow({submitLabel,canSubmit,nameError,+ saveError,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;-}) {+}: MappingEditorRowProps) {const applicationName = useSelector(getApplicationName);const errorId = useId();+ const errorMessage = nameError ?? saveError;++ // Mantine's read-only MultiSelect still drops its last group on Backspace+ const handleChange = (nextDraft: MappingDraft) => {+ if (!isSubmitting) {+ onChange(nextDraft);+ }+ };// the editor is inside the page form, so Enter must not reach its submit buttonconst handleNameKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.nativeEvent.isComposing) {+ return;+ }if (event.key === "Enter") {event.preventDefault();if (canSubmit && !isSubmitting) {onSubmit();}}- if (event.key === "Escape") {+ if (event.key === "Escape" && !isSubmitting) {onCancel();}};@@ -61,6 +76,9 @@ export function MappingEditorRow({const handleGroupsKeyDown = (event: React.KeyboardEvent<HTMLInputElement>,) => {+ if (event.nativeEvent.isComposing) {+ return;+ }if (event.key === "Enter") {event.preventDefault();}@@ -73,66 +91,71 @@ export function MappingEditorRow({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- />+ <Stack 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}+ // keeps the focus in the field during the write+ readOnly={isSubmitting}+ onChange={(event) =>+ handleChange({ ...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}+ readOnly={isSubmitting}+ onChange={(groupValues) => handleChange({ ...draft, groupValues })}+ onKeyDown={handleGroupsKeyDown}+ searchable+ />+ <Flex align="center" gap="lg">+ <Button+ variant="subtle"+ color="neutral"+ disabled={isSubmitting}+ onClick={onCancel}+ >{t`Cancel`}</Button>+ <Button+ variant="filled"+ disabled={!canSubmit}+ loading={isSubmitting}+ onClick={onSubmit}+ >+ {submitLabel}+ </Button></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>+ {errorMessage != null && (+ <Text id={errorId} role="alert" c="error" fz="sm">+ {errorMessage}+ </Text>+ )}+ </Stack></Box>);}diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingRow.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingRow.tsxindex 6d51a0f08a3..83ef537d5ba 100644--- a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingRow.tsx+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/MappingRow.tsx@@ -1,3 +1,4 @@+import { useId } from "react";import { t } from "ttag";import { getGroupNameLocalized } from "metabase/common/utils/groups";@@ -7,6 +8,16 @@ import type { GroupId } from "metabase-types/api";import S from "./GroupMappings.module.css";import type { GroupLookup } from "./utils";+type MappingRowProps = {+ name: string;+ groupIds: GroupId[];+ groupLookup: GroupLookup;+ readOnly: boolean;+ disabled: boolean;+ onEdit: () => void;+ onDelete: () => void;+};+export function MappingRow({name,groupIds,@@ -15,15 +26,9 @@ export function MappingRow({disabled,onEdit,onDelete,-}: {- name: string;- groupIds: GroupId[];- groupLookup: GroupLookup;- readOnly: boolean;- disabled: boolean;- onEdit: () => void;- onDelete: () => void;-}) {+}: MappingRowProps) {+ const nameId = useId();+return (<FlexclassName={S.mappingRow}@@ -32,16 +37,27 @@ export function MappingRow({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}>+ <Text+ id={nameId}+ 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} />+ {groupLookup.isLoaded && (+ <>+ <FixedSizeIcon aria-hidden name="arrow_right" c="text-secondary" />+ <MappingRowGroups groupIds={groupIds} groupLookup={groupLookup} />+ </>+ )}</Flex>{!readOnly && (<Flex className={S.rowActions} gap="sm"><ActionIconaria-label={t`Edit mapping`}+ aria-describedby={nameId}disabled={disabled}onClick={onEdit}>@@ -49,6 +65,7 @@ export function MappingRow({</ActionIcon><ActionIconaria-label={t`Delete mapping`}+ aria-describedby={nameId}disabled={disabled}onClick={onDelete}>@@ -60,13 +77,12 @@ export function MappingRow({);}-function MappingRowGroups({- groupIds,- groupLookup,-}: {+type MappingRowGroupsProps = {groupIds: GroupId[];groupLookup: GroupLookup;-}) {+};++function MappingRowGroups({ groupIds, groupLookup }: MappingRowGroupsProps) {const names = groupIds.map((groupId) => {const group = groupLookup.getGroup(groupId);diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/SettingsGroupMappingSection.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/SettingsGroupMappingSection.tsxnew file mode 100644index 00000000000..1ce5a69d493--- /dev/null+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/SettingsGroupMappingSection.tsx@@ -0,0 +1,106 @@+import { t } from "ttag";++import { useAdminSetting, useSettingSwitch } from "metabase/settings";+import { SwitchSettingsSection } from "metabase/settings-components";+import type { BoxProps } from "metabase/ui";++import { GroupMappingsPanel } from "./GroupMappingsPanel";+import { useGroupLookup } from "./use-group-lookup";+import {+ type GroupMappingsSettingKey,+ useGroupMappings,+} from "./use-group-mappings";++type GroupSyncSettingKey = "ldap-group-sync" | "saml-group-sync";++type SettingsGroupMappingSectionProps = {+ syncSettingKey: GroupSyncSettingKey;+ mappingsSettingKey: GroupMappingsSettingKey;+ description: string;+ tenancy?: "internal";+ namesValidatedOnSave?: boolean;+ nameLabel: string;+ namePlaceholder: string;+ children: React.ReactNode;+ disabled?: boolean;+ onToggle?: (enabled: boolean) => void;+} & BoxProps;++/** The group mapping card of a provider whose switch and mappings are two settings */+export function SettingsGroupMappingSection({+ syncSettingKey,+ mappingsSettingKey,+ description,+ tenancy,+ namesValidatedOnSave,+ nameLabel,+ namePlaceholder,+ children,+ disabled = false,+ onToggle,+ ...boxProps+}: SettingsGroupMappingSectionProps) {+ const groupSyncSwitch = useSettingSwitch(syncSettingKey, { onToggle });+ const isLockedUntilSave = disabled && groupSyncSwitch.envName === undefined;++ return (+ <SwitchSettingsSection+ title={t`Group mapping`}+ description={description}+ lockedEnvName={groupSyncSwitch.envName}+ note={+ isLockedUntilSave && t`Save the settings above to set up group mapping.`+ }+ checked={groupSyncSwitch.checked}+ disabled={disabled}+ switchDisabled={groupSyncSwitch.isBusy}+ onChange={groupSyncSwitch.onChange}+ {...boxProps}+ >+ <SettingsGroupMappings+ settingKey={mappingsSettingKey}+ tenancy={tenancy}+ namesValidatedOnSave={namesValidatedOnSave}+ nameLabel={nameLabel}+ namePlaceholder={namePlaceholder}+ />+ {children}+ </SwitchSettingsSection>+ );+}++type SettingsGroupMappingsProps = {+ settingKey: GroupMappingsSettingKey;+ tenancy?: "internal";+ namesValidatedOnSave?: boolean;+ nameLabel: string;+ namePlaceholder: string;+};++function SettingsGroupMappings({+ settingKey,+ tenancy,+ namesValidatedOnSave,+ nameLabel,+ namePlaceholder,+}: SettingsGroupMappingsProps) {+ const { settingDetails, isFetching } = useAdminSetting(settingKey);+ const groupLookup = useGroupLookup({ tenancy });+ const { mappings, saveMappings } = useGroupMappings({ settingKey });+ const envName = settingDetails?.is_env_setting+ ? settingDetails.env_name+ : undefined;++ return (+ <GroupMappingsPanel+ mappings={mappings}+ saveMappings={saveMappings}+ groupLookup={groupLookup}+ disabled={isFetching}+ lockedEnvName={envName}+ namesValidatedOnSave={namesValidatedOnSave}+ nameLabel={nameLabel}+ namePlaceholder={namePlaceholder}+ />+ );+}diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/SettingsGroupMappingSection.unit.spec.tsx b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/SettingsGroupMappingSection.unit.spec.tsxnew file mode 100644index 00000000000..96092af3e4a--- /dev/null+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/SettingsGroupMappingSection.unit.spec.tsx@@ -0,0 +1,591 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ findRequests,+ setupSettingsEndpoints,+ setupStatefulSettingsEndpoints,+} from "__support__/server-mocks";+import { createMockSettingsState, createMockState } from "__support__/state";+import {+ act,+ fireEvent,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { Route } from "metabase/router";+import { settingsApi } from "metabase/settings";+import { defer } from "metabase/utils/promise";+import { checkNotNull } from "metabase/utils/types";+import type {+ EnterpriseSettingKey,+ EnterpriseSettings,+ SettingDefinition,+} from "metabase-types/api";+import { createMockGroup, createMockSettings } from "metabase-types/api/mocks";++import { SettingsGroupMappingSection } from "./SettingsGroupMappingSection";++const GROUPS = [+ createMockGroup(),+ createMockGroup({ id: 2, name: "Administrators", magic_group_type: "admin" }),+ createMockGroup({ id: 3, name: "Engineering", magic_group_type: null }),+ createMockGroup({ id: 4, name: "Marketing", magic_group_type: null }),+];++const DEVS_DN = "cn=devs,ou=groups,dc=example,dc=org";+const OPS_DN = "cn=ops,ou=groups,dc=example,dc=org";++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 groupMappingSwitch = () =>+ screen.getByRole("switch", { name: "Group mapping" });++const findMappingRow = (name: string) =>+ screen+ .queryAllByTestId("group-mapping-row")+ .find((row) => within(row).queryByText(name) != null);++const getMappingRow = (name: string) => checkNotNull(findMappingRow(name));++const clickWhenEnabled = async (element: HTMLElement) => {+ await waitFor(() => expect(element).toBeEnabled());+ await userEvent.click(element);+};++const getRowButton = (mappingName: string, buttonName: string) =>+ within(getMappingRow(mappingName)).getByRole("button", { name: buttonName });++const holdSettingsReads = (settingsStore: Record<string, unknown>) => {+ const gate = defer<void>();+ fetchMock.removeRoute("get-session-properties");+ fetchMock.get(+ "path:/api/session/properties",+ async () => {+ await gate.promise;+ return { ...settingsStore };+ },+ { name: "get-session-properties" },+ );+ return () => gate.resolve();+};++const fillNewDraft = async (name: string) => {+ await clickWhenEnabled(screen.getByRole("button", { name: "New" }));+ await userEvent.type(screen.getByLabelText("LDAP group name"), name);+ await userEvent.click(screen.getByPlaceholderText("Pick Metabase group..."));+ await userEvent.click(+ await screen.findByRole("option", { name: "Engineering" }),+ );+};++const setup = async ({+ settingValues = {},+ settingDefinitions = [],+ updateDelay,+ readDelay,+ groupsDelay,+ groupsStatus,+ withRouter = false,+ disabled = false,+}: {+ settingValues?: Partial<EnterpriseSettings>;+ settingDefinitions?: SettingDefinition[];+ updateDelay?: number;+ readDelay?: number;+ groupsDelay?: number;+ groupsStatus?: number;+ withRouter?: boolean;+ disabled?: boolean;+} = {}) => {+ const settings = createMockSettings(settingValues);+ const listedKeys = new Set(+ settingDefinitions.map((definition) => definition.key),+ );+ setupSettingsEndpoints([+ ...settingDefinitions,+ ...toDefinitions(settingValues).filter(({ key }) => !listedKeys.has(key)),+ ]);+ const settingsStore = setupStatefulSettingsEndpoints(settings, {+ updateDelay,+ readDelay,+ });+ fetchMock.get(+ "path:/api/permissions/group",+ groupsStatus == null ? GROUPS : { status: groupsStatus },+ { delay: groupsDelay },+ );++ const onToggle = jest.fn();+ const section = (+ <SettingsGroupMappingSection+ syncSettingKey="ldap-group-sync"+ mappingsSettingKey="ldap-group-mappings"+ description="Assign people to groups based on their LDAP groups"+ nameLabel="LDAP group name"+ namePlaceholder="cn=people,ou=groups,dc=example,dc=org"+ disabled={disabled}+ onToggle={onToggle}+ >+ <div>Group fields</div>+ </SettingsGroupMappingSection>+ );+ let tree = section;+ if (withRouter) {+ tree = (+ <Route path="/">+ <Route path="ldap" element={section} />+ <Route path="people" element={<span>People</span>} />+ </Route>+ );+ }+ const { store, router } = renderWithProviders(tree, {+ withUndos: true,+ withRouter,+ initialRoute: "/ldap",+ storeInitialState: createMockState({+ settings: createMockSettingsState(settings),+ }),+ });++ if (settingValues["ldap-group-sync"] === true) {+ await screen.findByText("Manual group mappings");+ } else {+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ }+ return { store, settingsStore, router, onToggle };+};++describe("SettingsGroupMappingSection", () => {+ it("shows the new value and holds the switch while the write is in flight", async () => {+ const { onToggle } = await setup({ updateDelay: 200 });++ await userEvent.click(groupMappingSwitch());++ expect(groupMappingSwitch()).toBeChecked();+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true");+ expect(screen.getByText("Manual group mappings")).toBeInTheDocument();+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(groupMappingSwitch()).toBeChecked();+ expect(await findRequests("PUT")).toHaveLength(1);+ expect(onToggle).toHaveBeenCalledWith(true);+ });++ it("holds the switch until the settings refetch after the write lands", async () => {+ await setup({ readDelay: 200 });++ await userEvent.click(groupMappingSwitch());+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();++ expect(groupMappingSwitch()).toBeChecked();+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true");+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(groupMappingSwitch()).toBeChecked();+ });++ it("says how to unlock the card", async () => {+ await setup({ disabled: true });++ expect(groupMappingSwitch()).toBeDisabled();+ expect(groupMappingSwitch()).toHaveAccessibleDescription(+ /Save the settings above to set up group mapping/,+ );+ });++ it("says nothing about saving once the card is unlocked", async () => {+ await setup();++ expect(groupMappingSwitch()).not.toHaveAccessibleDescription(+ /Save the settings above to set up group mapping/,+ );+ });++ it("puts the old value back when the write fails", async () => {+ const { onToggle } = await setup();+ 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();+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(screen.queryByText("Manual group mappings")).not.toBeInTheDocument();+ expect(onToggle).not.toHaveBeenCalled();+ });++ it("keeps group mapping on when the last mapping is deleted", async () => {+ await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [3] },+ },+ });++ await clickWhenEnabled(getRowButton(DEVS_DN, "Delete mapping"));+ const modal = await screen.findByRole("dialog");+ 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("holds the mappings while the settings refetch after a write", async () => {+ const { settingsStore } = await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [3], [OPS_DN]: [3] },+ },+ });+ const newButton = () => screen.getByRole("button", { name: "New" });+ const deleteButton = () => getRowButton(DEVS_DN, "Delete mapping");+ await waitFor(() => expect(deleteButton()).toBeEnabled());+ const releaseReads = holdSettingsReads(settingsStore);++ await userEvent.click(deleteButton());+ const modal = await screen.findByRole("dialog");+ await userEvent.click(+ within(modal).getByRole("button", { name: "Remove mapping" }),+ );++ try {+ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();+ expect(newButton()).toBeDisabled();+ } finally {+ releaseReads();+ }+ await waitFor(() => expect(newButton()).toBeEnabled());+ expect(findMappingRow(DEVS_DN)).toBeUndefined();+ });++ it("carries on as a new mapping when the one being edited disappears", async () => {+ const { store, settingsStore } = await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [3], [OPS_DN]: [3] },+ },+ });+ await clickWhenEnabled(getRowButton(DEVS_DN, "Edit mapping"));+ expect(screen.getByRole("button", { name: "Save" })).toBeInTheDocument();++ settingsStore["ldap-group-mappings"] = { [OPS_DN]: [3] };+ store.dispatch(settingsApi.util.invalidateTags(["session-properties"]));++ const addButton = await screen.findByRole("button", {+ name: "Add mapping",+ });+ expect(screen.getByLabelText("LDAP group name")).toHaveValue(DEVS_DN);+ expect(+ screen.queryByRole("button", { name: "Save" }),+ ).not.toBeInTheDocument();++ await waitFor(() => expect(addButton).toBeEnabled());+ await userEvent.click(addButton);+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();+ expect(screen.queryByText("Mapping updated")).not.toBeInTheDocument();+ const [{ body }] = await findRequests("PUT");+ expect(body).toEqual({+ "ldap-group-mappings": { [OPS_DN]: [3], [DEVS_DN]: [3] },+ });+ });++ it("tells a screen reader which mapping a row's buttons act on", async () => {+ await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [3] },+ },+ });++ expect(getRowButton(DEVS_DN, "Edit mapping")).toHaveAccessibleDescription(+ DEVS_DN,+ );+ expect(getRowButton(DEVS_DN, "Delete mapping")).toHaveAccessibleDescription(+ DEVS_DN,+ );+ });++ it("opens another row's editor in place of an open draft", async () => {+ await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [3], [OPS_DN]: [4] },+ },+ });+ await clickWhenEnabled(getRowButton(DEVS_DN, "Edit mapping"));+ await userEvent.type(screen.getByLabelText("LDAP group name"), "-team");++ await userEvent.click(getRowButton(OPS_DN, "Edit mapping"));++ expect(screen.getByLabelText("LDAP group name")).toHaveValue(OPS_DN);+ expect(findMappingRow(DEVS_DN)).toBeDefined();+ expect(+ screen.queryByDisplayValue(`${DEVS_DN}-team`),+ ).not.toBeInTheDocument();+ });++ it("keeps an open draft editable while the panel waits for a settings refetch", async () => {+ const { store, settingsStore } = await setup({+ settingValues: { "ldap-group-sync": true },+ });+ await fillNewDraft(DEVS_DN);++ const releaseReads = holdSettingsReads(settingsStore);+ store.dispatch(settingsApi.util.invalidateTags(["session-properties"]));++ const addButton = screen.getByRole("button", { name: "Add mapping" });+ const nameInput = screen.getByLabelText("LDAP group name");+ try {+ await waitFor(() => expect(addButton).toBeDisabled());+ expect(addButton).not.toHaveAttribute("data-loading");+ expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();+ await userEvent.type(nameInput, "x");+ expect(nameInput).toHaveValue(`${DEVS_DN}x`);+ } finally {+ releaseReads();+ }+ await waitFor(() => expect(addButton).toBeEnabled());+ });++ it("leaves Enter and Escape to an input method that is composing", async () => {+ await setup({ settingValues: { "ldap-group-sync": true } });+ await fillNewDraft(DEVS_DN);+ const nameInput = screen.getByLabelText("LDAP group name");++ fireEvent.keyDown(nameInput, { key: "Enter", isComposing: true });+ expect(+ screen.getByRole("button", { name: "Add mapping" }),+ ).not.toHaveAttribute("data-loading");+ fireEvent.keyDown(nameInput, { key: "Escape", isComposing: true });+ expect(nameInput).toBeInTheDocument();+ const isGroupsEnterKept = fireEvent.keyDown(+ screen.getByRole("textbox", { name: "Metabase groups" }),+ { key: "Enter", isComposing: true },+ );+ expect(isGroupsEnterKept).toBe(true);++ await userEvent.click(nameInput);+ await userEvent.keyboard("{Enter}");+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();+ });++ it("asks before leaving with an unsaved mapping draft", async () => {+ const { router } = await setup({+ settingValues: { "ldap-group-sync": true },+ withRouter: true,+ });+ const routerWithRoutes = checkNotNull(router);+ await clickWhenEnabled(screen.getByRole("button", { name: "New" }));+ await userEvent.type(screen.getByLabelText("LDAP group name"), DEVS_DN);++ act(() => routerWithRoutes.navigate("/people"));++ expect(+ await screen.findByText("Discard your changes?"),+ ).toBeInTheDocument();+ expect(routerWithRoutes.location.pathname).toBe("/ldap");+ });++ it("leaves without asking when the draft is untouched", async () => {+ const { router } = await setup({+ settingValues: { "ldap-group-sync": true },+ withRouter: true,+ });+ await clickWhenEnabled(screen.getByRole("button", { name: "New" }));++ act(() => checkNotNull(router).navigate("/people"));++ expect(await screen.findByText("People")).toBeInTheDocument();+ expect(screen.queryByText("Discard your changes?")).not.toBeInTheDocument();+ });++ it("leaves without asking when an opened edit is untouched", async () => {+ const { router } = await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [3] },+ },+ withRouter: true,+ });+ await clickWhenEnabled(getRowButton(DEVS_DN, "Edit mapping"));++ act(() => checkNotNull(router).navigate("/people"));++ expect(await screen.findByText("People")).toBeInTheDocument();+ expect(screen.queryByText("Discard your changes?")).not.toBeInTheDocument();+ });++ it("holds the mapping controls until the groups have loaded", async () => {+ await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [3] },+ },+ groupsDelay: 200,+ });+ const newButton = () => screen.getByRole("button", { name: "New" });+ const editButton = () => getRowButton(DEVS_DN, "Edit mapping");+ expect(newButton()).toBeDisabled();+ expect(editButton()).toBeDisabled();+ const row = getMappingRow(DEVS_DN);+ expect(within(row).queryByText("No groups")).not.toBeInTheDocument();++ await waitFor(() => expect(newButton()).toBeEnabled());+ expect(editButton()).toBeEnabled();+ expect(await within(row).findByText("Engineering")).toBeInTheDocument();+ });++ it("says No groups for a mapping without groups", async () => {+ await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [] },+ },+ });++ expect(+ await within(getMappingRow(DEVS_DN)).findByText("No groups"),+ ).toBeInTheDocument();+ });++ it("says so when the groups could not be loaded", async () => {+ await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [DEVS_DN]: [3] },+ },+ groupsStatus: 500,+ });++ expect(+ await screen.findByText("Groups could not be loaded"),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "New" })).toBeDisabled();+ expect(+ within(getMappingRow(DEVS_DN)).queryByText("No groups"),+ ).not.toBeInTheDocument();+ });++ it("reports a failed clean-up after deleting a mapping's groups as part of the deletion", async () => {+ const OLD_DN = "cn=old,ou=groups,dc=example,dc=org";+ const { settingsStore } = await setup({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-mappings": { [OLD_DN]: [4], [DEVS_DN]: [4, 3] },+ },+ });+ fetchMock.delete("express:/api/permissions/group/:id", 204);+ let writeCount = 0;+ fetchMock.removeRoute("update-settings");+ fetchMock.put(+ "path:/api/setting",+ ({ options }) => {+ writeCount += 1;+ if (writeCount > 1) {+ return { status: 500 };+ }+ Object.assign(settingsStore, JSON.parse(String(options.body)));+ return { status: 204 };+ },+ { name: "update-settings" },+ );++ await clickWhenEnabled(getRowButton(OLD_DN, "Delete mapping"));+ await userEvent.click(+ await screen.findByRole("radio", { name: "Also delete the group" }),+ );+ await userEvent.click(+ screen.getByRole("button", { name: "Remove mapping and delete group" }),+ );++ expect(+ await screen.findByText(+ "Mapping deleted, but its deleted group could not be removed from the other mappings",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("Error saving group mapping"),+ ).not.toBeInTheDocument();+ await waitFor(() => expect(findMappingRow(OLD_DN)).toBeUndefined());+ });++ it("locks the mappings to the ones an env var sets", async () => {+ await setup({+ 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(+ await screen.findByText("Using MB_LDAP_GROUP_MAPPINGS"),+ ).toBeInTheDocument();+ const row = findMappingRow(DEVS_DN);+ expect(row).toBeDefined();+ expect(await within(row!).findByText("Engineering")).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 setup({+ settingValues: { "ldap-group-sync": true },+ settingDefinitions: [+ {+ key: "ldap-group-sync",+ is_env_setting: true,+ env_name: "MB_LDAP_GROUP_SYNC",+ },+ ],+ });++ expect(+ await screen.findByText("Using MB_LDAP_GROUP_SYNC"),+ ).toBeInTheDocument();+ expect(groupMappingSwitch()).toBeChecked();+ expect(groupMappingSwitch()).toHaveAttribute("aria-disabled", "true");+ expect(groupMappingSwitch()).toHaveAccessibleDescription(+ /Using MB_LDAP_GROUP_SYNC/,+ );+ expect(screen.getByText("Manual group mappings")).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/index.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/index.tsindex 260b1326e12..0a56b10df92 100644--- a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/index.ts+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/index.ts@@ -1,6 +1,11 @@export { GroupMappingList } from "./GroupMappingList";+export { GroupMappingsPanel } from "./GroupMappingsPanel";+export { SettingsGroupMappingSection } from "./SettingsGroupMappingSection";export { useGroupLookup } from "./use-group-lookup";-export { useGroupMappings } from "./use-group-mappings";+export {+ type GroupMappingsSaveResult,+ type SaveOptions,+} from "./use-group-mappings";export { useMappingDeletion } from "./use-mapping-deletion";export { useMappingEditor } from "./use-mapping-editor";-export { type GroupLookup, withMappingEntry, withoutMapping } from "./utils";+export { EMPTY_MAPPINGS } from "./utils";diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/types.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/types.tsnew file mode 100644index 00000000000..e12b0fd55fa--- /dev/null+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/types.ts@@ -0,0 +1,2 @@+export type DeleteMappingModalValueType = "nothing" | "clear" | "delete";+export type CascadeValue = Exclude<DeleteMappingModalValueType, "nothing">;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.tsindex 70b69f24524..72191055d34 100644--- 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@@ -1,12 +1,9 @@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 tenantstenancy?: "internal" | "external";@@ -15,8 +12,8 @@ type UseGroupLookupOptions = {export function useGroupLookup({tenancy,}: UseGroupLookupOptions = {}): GroupLookup {- const { data: groups = EMPTY_GROUPS } = useListPermissionsGroupsQuery(+ const { data: groups, isError } = useListPermissionsGroupsQuery(tenancy == null ? {} : { tenancy },);- return useMemo(() => createGroupLookup(groups), [groups]);+ return useMemo(() => createGroupLookup(groups, isError), [groups, isError]);}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.tsindex fbf46ca3a9f..5e5f3912004 100644--- 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@@ -1,6 +1,5 @@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";@@ -9,9 +8,11 @@ import {useSetting,useUpdateSettingsMutation,} from "metabase/settings";+import type { GroupMappings } from "metabase-types/api";++import { EMPTY_MAPPINGS } from "./utils";export type GroupMappingsSettingKey =- | "jwt-group-mappings"| "ldap-group-mappings"| "saml-group-mappings";@@ -19,34 +20,33 @@ export type GroupMappingsSaveResult =| { ok: true }| { ok: false; error: string };-type SaveOptions = {+export type SaveOptions = {successMessage?: string;showErrorToast?: boolean;};-export type GroupMappingsState = {- mappings: MappingsType;- isSaving: boolean;- saveMappings: (- mappings: MappingsType,- options?: SaveOptions,- ) => Promise<GroupMappingsSaveResult>;-};+export type SaveMappings = (+ mappings: GroupMappings,+ options?: SaveOptions,+) => Promise<GroupMappingsSaveResult>;-const EMPTY_MAPPINGS: MappingsType = {};+export type GroupMappingsSetting = {+ mappings: GroupMappings;+ saveMappings: SaveMappings;+};export function useGroupMappings({settingKey,}: {settingKey: GroupMappingsSettingKey;-}): GroupMappingsState {+}): GroupMappingsSetting {const dispatch = useDispatch();const [sendToast] = useToast();- const [updateSettings, { isLoading: isSaving }] = useUpdateSettingsMutation();+ const [updateSettings] = useUpdateSettingsMutation();const mappings = useSetting(settingKey) ?? EMPTY_MAPPINGS;const saveMappings = async (- nextMappings: MappingsType,+ nextMappings: GroupMappings,{ successMessage, showErrorToast = true }: SaveOptions = {},): Promise<GroupMappingsSaveResult> => {const response = await updateSettings({ [settingKey]: nextMappings });@@ -79,5 +79,5 @@ export function useGroupMappings({return { ok: true };};- return { mappings, isSaving, saveMappings };+ return { mappings, 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.tsindex 3cd391058ab..1c54a3547ae 100644--- 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@@ -1,42 +1,45 @@import { useState } from "react";-import { t } from "ttag";+import { msgid, ngettext, 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 { GroupId, GroupMappings } from "metabase-types/api";-import type { GroupMappingsState } from "./use-group-mappings";-import { type GroupLookup, withoutMapping } from "./utils";+import type { CascadeValue, DeleteMappingModalValueType } from "./types";+import type { SaveMappings } from "./use-group-mappings";+import { type GroupLookup, withoutGroups, withoutMapping } from "./utils";type MappingCascade = {- value: Exclude<DeleteMappingModalValueType, "nothing">;- groupIds: GroupIds;+ value: CascadeValue;+ groupIds: GroupId[];+};++type CascadeOutcome = {+ deletedIds: GroupId[];+ failureCount: number;};export type MappingDeletionState = {target: string | null;- targetGroupIds: GroupIds;+ targetGroupIds: GroupId[];isDeleting: boolean;requestDelete: (name: string) => void;cancelDelete: () => void;- confirmDelete: (- value: DeleteMappingModalValueType,- groupIds: GroupIds,- name: string,- ) => Promise<void>;+ confirmDelete: (value: DeleteMappingModalValueType) => Promise<void>;};export function useMappingDeletion({- groupMapping,+ mappings,+ saveMappings,+ onDeletingChange,groupLookup,}: {- groupMapping: GroupMappingsState;+ mappings: GroupMappings;+ saveMappings: SaveMappings;+ onDeletingChange?: (isDeleting: boolean) => void;groupLookup: GroupLookup;}): MappingDeletionState {const [sendToast] = useToast();@@ -46,14 +49,14 @@ export function useMappingDeletion({const [isDeleting, setIsDeleting] = useState(false);const targetGroupIds =- target == null- ? []- : groupLookup.existingIds(groupMapping.mappings[target] ?? []);+ target == null ? [] : groupLookup.existingIds(mappings[target] ?? []);// "nothing, just remove the mapping" arrives as null and touches no group- const runCascade = async (cascade: MappingCascade | null) => {+ const runCascade = async (+ cascade: MappingCascade | null,+ ): Promise<CascadeOutcome> => {if (cascade == null) {- return { failureCount: 0 };+ return { deletedIds: [], failureCount: 0 };}const results = await Promise.allSettled(cascade.groupIds.map((groupId) =>@@ -64,23 +67,35 @@ export function useMappingDeletion({);const failures = results.filter((result) => result.status === "rejected");failures.forEach((failure) => console.error(failure.reason));- return { failureCount: failures.length };+ let deletedIds: GroupId[] = [];+ if (cascade.value === "delete") {+ deletedIds = cascade.groupIds.filter(+ (_groupId, index) => results[index].status === "fulfilled",+ );+ }+ return { deletedIds, 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);+ // the mapping goes first, so a failed write never leaves deleted groups behind+ const nextMappings = withoutMapping(mappings, name);+ const result = await saveMappings(nextMappings);if (!result.ok) {return;}- const { failureCount } = await runCascade(cascade);+ const { deletedIds, failureCount } = await runCascade(cascade);+ const deleted = new Set(deletedIds);+ const hasDeletedGroups = Object.values(nextMappings).some((ids) =>+ ids.some((groupId) => deleted.has(groupId)),+ );+ const scrubResult = hasDeletedGroups+ ? await saveMappings(withoutGroups(nextMappings, deletedIds), {+ showErrorToast: false,+ })+ : null;if (failureCount > 0) {sendToast({message: t`Mapping deleted, but not all of its groups could be updated`,@@ -89,25 +104,40 @@ export function useMappingDeletion({});return;}+ if (scrubResult?.ok === false) {+ sendToast({+ message: ngettext(+ msgid`Mapping deleted, but its deleted group could not be removed from the other mappings`,+ `Mapping deleted, but its deleted groups could not be removed from the other mappings`,+ deletedIds.length,+ ),+ icon: "warning",+ toastColor: "feedback-negative",+ });+ return;+ }sendToast({ message: t`Mapping deleted`, icon: "check_filled" });};- const confirmDelete = async (- value: DeleteMappingModalValueType,- groupIds: GroupIds,- name: string,- ) => {+ const confirmDelete = async (value: DeleteMappingModalValueType) => {+ if (target == null) {+ return;+ }+ const name = target;+ const groupIds = targetGroupIds;setTarget(null);const cascade =value === "nothing"? null- : { value, groupIds: groupLookup.actionableIds(groupIds) };+ : { value, groupIds: groupLookup.actionableIds(groupIds, value) };// the write releases its own busy flag before the cascade, so this one covers the whole operationsetIsDeleting(true);+ onDeletingChange?.(true);try {await deleteMapping(name, cascade);} finally {setIsDeleting(false);+ onDeletingChange?.(false);}};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.tsindex 80631d9ad43..2a237e0122a 100644--- 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@@ -1,9 +1,10 @@import { useState } from "react";import { t } from "ttag";+import _ from "underscore";-import type { GroupId } from "metabase-types/api";+import type { GroupId, GroupMappings } from "metabase-types/api";-import type { GroupMappingsState } from "./use-group-mappings";+import type { SaveMappings } from "./use-group-mappings";import { type GroupLookup, withMappingEntry } from "./utils";export type MappingDraft = {@@ -16,7 +17,11 @@ export type MappingDraft = {export type MappingEditorState = {draft: MappingDraft | null;nameError: string | null;+ saveError: string | null;canSave: boolean;+ isSubmitting: boolean;+ isDraftNew: boolean;+ hasUnsavedChanges: boolean;startNew: () => void;startEdit: (name: string, groupIds: GroupId[]) => void;change: (draft: MappingDraft) => void;@@ -26,19 +31,30 @@ export type MappingEditorState = {/** Holds the mapping being added or edited and writes it into the mappings setting */export function useMappingEditor({- groupMapping,+ mappings,+ saveMappings,groupLookup,+ namesValidatedOnSave = false,}: {- groupMapping: GroupMappingsState;+ mappings: GroupMappings;+ saveMappings: SaveMappings;groupLookup: GroupLookup;+ namesValidatedOnSave?: boolean;}): MappingEditorState {const [draft, setDraft] = useState<MappingDraft | null>(null);+ const [openedDraft, setOpenedDraft] = useState<MappingDraft | null>(null);const [submitError, setSubmitError] = useState<string | null>(null);+ const [isSubmitting, setIsSubmitting] = useState(false);const trimmedName = draft?.name.trim() ?? "";+ const isDraftNew =+ draft != null &&+ (draft.originalName == null ||+ !Object.hasOwn(mappings, draft.originalName));+ const hasUnsavedChanges = draft != null && !_.isEqual(draft, openedDraft);const isDuplicateName =draft != null &&- Object.hasOwn(groupMapping.mappings, trimmedName) &&+ Object.hasOwn(mappings, trimmedName) &&trimmedName !== draft.originalName;const canSave =draft != null &&@@ -48,53 +64,67 @@ export function useMappingEditor({let nameError: string | null = null;if (isDuplicateName) {nameError = t`A mapping for this group already exists`;- } else if (submitError != null) {+ } else if (namesValidatedOnSave) {nameError = submitError;}+ const saveError = namesValidatedOnSave ? null : submitError;- const replaceDraft = (nextDraft: MappingDraft | null) => {+ const changeDraft = (nextDraft: MappingDraft | null) => {setSubmitError(null);setDraft(nextDraft);};+ const resetDraft = (nextDraft: MappingDraft | null) => {+ setOpenedDraft(nextDraft);+ changeDraft(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);+ setIsSubmitting(true);+ try {+ const result = await saveMappings(+ withMappingEntry(+ mappings,+ draft.originalName,+ trimmedName,+ draft.groupValues.map(Number),+ ),+ {+ successMessage: isDraftNew ? t`Mapping added` : t`Mapping updated`,+ showErrorToast: false,+ },+ );+ if (result.ok) {+ resetDraft(null);+ } else {+ setSubmitError(result.error);+ }+ } finally {+ setIsSubmitting(false);}};return {draft,nameError,+ saveError,canSave,+ isSubmitting,+ isDraftNew,+ hasUnsavedChanges,startNew: () =>- replaceDraft({ name: "", groupValues: [], originalName: null }),+ resetDraft({ name: "", groupValues: [], originalName: null }),startEdit: (name, groupIds) =>- replaceDraft({+ resetDraft({name,groupValues: groupLookup.existingIds(groupIds).map(String),originalName: name,}),- change: replaceDraft,- cancel: () => replaceDraft(null),+ change: changeDraft,+ cancel: () => resetDraft(null),save,};}diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.tsindex d5f04bcad8c..ba470fb5350 100644--- a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.ts+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.ts@@ -1,67 +1,103 @@-import type { MappingsType } from "metabase/admin/types";import {+ getGroupNameLocalized,isAdminGroup,isDefaultGroup,isDefaultTenantGroup,} from "metabase/common/utils/groups";-import type { GroupId, GroupListQuery } from "metabase-types/api";+import type {+ GroupId,+ GroupListQuery,+ GroupMappings,+} from "metabase-types/api";++import type { CascadeValue } from "./types";++export const EMPTY_MAPPINGS: GroupMappings = {};/** Rebuilds in place so a renamed mapping keeps its position in the list */export function withMappingEntry(- mappings: MappingsType,+ mappings: GroupMappings,originalName: string | null,name: string,groupIds: GroupId[],-): MappingsType {+): GroupMappings {const entries = Object.entries(mappings).map(([mappingName, ids]): [string, GroupId[]] =>mappingName === originalName ? [name, groupIds] : [mappingName, ids],);- if (originalName == null) {+ // an edit whose mapping was deleted meanwhile adds it back rather than vanishing+ if (originalName == null || !Object.hasOwn(mappings, originalName)) {entries.push([name, groupIds]);}// fromEntries defines own properties, so names like __proto__ stay plain keysreturn Object.fromEntries(entries);}-/** Drops one mapping and scrubs deleted group ids from the rest, since the backend keeps their ids */export function withoutMapping(- mappings: MappingsType,+ mappings: GroupMappings,name: string,- deletedGroupIds: GroupId[] = [],-): MappingsType {- const deleted = new Set(deletedGroupIds);+): GroupMappings {+ return Object.fromEntries(+ Object.entries(mappings).filter(([mappingName]) => mappingName !== name),+ );+}++/** Scrubs group ids from every mapping, since the backend keeps the ids of deleted groups in them */+export function withoutGroups(+ mappings: GroupMappings,+ groupIds: GroupId[],+): GroupMappings {+ const removed = new Set(groupIds);return Object.fromEntries(- Object.entries(mappings)- .filter(([mappingName]) => mappingName !== name)- .map(([mappingName, ids]): [string, GroupId[]] => [- mappingName,- ids.filter((groupId) => !deleted.has(groupId)),- ]),+ Object.entries(mappings).map(([mappingName, ids]): [string, GroupId[]] => [+ mappingName,+ ids.filter((groupId) => !removed.has(groupId)),+ ]),);}export type GroupLookup = ReturnType<typeof createGroupLookup>;-export function createGroupLookup(groups: GroupListQuery[]) {- const groupsById = new Map(groups.map((group) => [group.id, group]));- const isAdminGroupId = (groupId: GroupId) => {- const group = groupsById.get(groupId);- return group != null && isAdminGroup(group);+export function createGroupLookup(+ groups: GroupListQuery[] | undefined,+ loadFailed = false,+) {+ const loadedGroups = groups ?? [];+ const groupsById = new Map(loadedGroups.map((group) => [group.id, group]));+ // the backend refuses to delete any built-in group, and to clear Administrators, All Users and All tenant users+ const isKeptBy = (value: CascadeValue, group: GroupListQuery) => {+ if (value === "delete") {+ return group.magic_group_type != null;+ }+ return (+ isAdminGroup(group) ||+ isDefaultGroup(group) ||+ isDefaultTenantGroup(group)+ );};+ const existingGroups = (groupIds: GroupId[]) =>+ groupIds.flatMap((groupId) => groupsById.get(groupId) ?? []);return {- // magic groups can't be mapped to- mappableGroups: groups.filter(+ // every id reads as missing until the groups arrive+ isLoaded: groups != null,+ loadFailed,+ mappableGroups: loadedGroups.filter((group) => !isDefaultGroup(group) && !isDefaultTenantGroup(group),),getGroup: (groupId: GroupId) => groupsById.get(groupId),existingIds: (groupIds: GroupId[]) =>groupIds.filter((groupId) => groupsById.has(groupId)),- // cascades never touch the admin group, so it doesn't count as actionable- actionableIds: (groupIds: GroupId[]) =>- groupIds.filter(- (groupId) => groupsById.has(groupId) && !isAdminGroupId(groupId),- ),- hasAdminGroup: (groupIds: GroupId[]) => groupIds.some(isAdminGroupId),+ actionableIds: (groupIds: GroupId[], value: CascadeValue) =>+ existingGroups(groupIds)+ .filter((group) => !isKeptBy(value, group))+ .map((group) => group.id),+ actionableGroupNames: (groupIds: GroupId[], value: CascadeValue) =>+ existingGroups(groupIds)+ .filter((group) => !isKeptBy(value, group))+ .map((group) => getGroupNameLocalized(group)),+ keptGroupNames: (groupIds: GroupId[], value: CascadeValue) =>+ existingGroups(groupIds)+ .filter((group) => isKeptBy(value, group))+ .map((group) => getGroupNameLocalized(group)),};}diff --git a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.unit.spec.ts b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.unit.spec.tsindex 28196d080ac..a37713f8890 100644--- a/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.unit.spec.ts+++ b/frontend/src/metabase/admin/settings/auth/components/GroupMappings/utils.unit.spec.ts@@ -1,6 +1,11 @@import { createMockGroup } from "metabase-types/api/mocks";-import { createGroupLookup, withMappingEntry, withoutMapping } from "./utils";+import {+ createGroupLookup,+ withMappingEntry,+ withoutGroups,+ withoutMapping,+} from "./utils";describe("withMappingEntry", () => {it("appends a new mapping", () => {@@ -31,6 +36,12 @@ describe("withMappingEntry", () => {expect(Object.hasOwn(result, "__proto__")).toBe(true);expect(Object.getPrototypeOf(result)).toBe(Object.prototype);});+ it("adds the entry when the mapping it edits is already gone", () => {+ expect(withMappingEntry({ ops: [3] }, "devs", "devs", [4])).toEqual({+ ops: [3],+ devs: [4],+ });+ });});describe("withoutMapping", () => {@@ -39,10 +50,13 @@ describe("withoutMapping", () => {devs: [4, 3],});});+});- it("scrubs deleted group ids from the remaining mappings", () => {- expect(withoutMapping({ old: [4], devs: [4, 3] }, "old", [4])).toEqual({+describe("withoutGroups", () => {+ it("scrubs the given group ids from every mapping", () => {+ expect(withoutGroups({ devs: [4, 3], ops: [4] }, [4])).toEqual({devs: [3],+ ops: [],});});});@@ -56,19 +70,58 @@ describe("createGroupLookup", () => {magic_group_type: "admin",}),createMockGroup({ id: 3, name: "foo", magic_group_type: null }),+ createMockGroup({+ id: 4,+ name: "Data Analysts",+ magic_group_type: "data-analyst",+ }),+ createMockGroup({+ id: 5,+ name: "All tenant users",+ magic_group_type: "all-external-users",+ }),]);- it("excludes magic groups from the mappable ones", () => {- expect(groupLookup.mappableGroups.map((group) => group.id)).toEqual([2, 3]);+ it("excludes the default groups from the mappable ones", () => {+ expect(groupLookup.mappableGroups.map((group) => group.id)).toEqual([+ 2, 3, 4,+ ]);});it("filters ids of groups that no longer exist", () => {expect(groupLookup.existingIds([3, 9])).toEqual([3]);});- it("leaves the admin group out of cascades", () => {- expect(groupLookup.actionableIds([2, 3, 9])).toEqual([3]);- expect(groupLookup.hasAdminGroup([2, 3])).toBe(true);- expect(groupLookup.hasAdminGroup([3])).toBe(false);+ it("knows whether the groups have arrived and whether the load failed", () => {+ expect(groupLookup.isLoaded).toBe(true);+ expect(groupLookup.loadFailed).toBe(false);+ expect(createGroupLookup([]).isLoaded).toBe(true);+ expect(createGroupLookup(undefined).isLoaded).toBe(false);+ expect(createGroupLookup(undefined, true).loadFailed).toBe(true);+ });++ it("leaves every built-in group out of a delete cascade", () => {+ expect(groupLookup.actionableIds([2, 3, 4, 9], "delete")).toEqual([3]);+ expect(groupLookup.actionableGroupNames([2, 3, 4, 9], "delete")).toEqual([+ "foo",+ ]);+ expect(groupLookup.keptGroupNames([2, 3, 4], "delete")).toEqual([+ "Administrators",+ "Data Analysts",+ ]);+ });++ it("leaves Administrators, All Users and All tenant users out of a clear cascade", () => {+ expect(groupLookup.actionableIds([1, 2, 3, 4, 5, 9], "clear")).toEqual([+ 3, 4,+ ]);+ expect(+ groupLookup.actionableGroupNames([1, 2, 3, 4, 5, 9], "clear"),+ ).toEqual(["foo", "Data Analysts"]);+ expect(groupLookup.keptGroupNames([1, 2, 3, 4, 5], "clear")).toEqual([+ "All Users",+ "Administrators",+ "All tenant users",+ ]);});});diff --git a/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.module.css b/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.module.cssdeleted file mode 100644index 08c281b4f4e..00000000000--- a/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.module.css+++ /dev/null@@ -1,7 +0,0 @@-.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.tsxdeleted file mode 100644index b82b1cfc96b..00000000000--- a/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/LdapGroupMappingSection.tsx+++ /dev/null@@ -1,180 +0,0 @@-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.tsdeleted file mode 100644index 84cf8ccb734..00000000000--- a/frontend/src/metabase/admin/settings/components/LdapGroupMappingSection/index.ts+++ /dev/null@@ -1 +0,0 @@-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.tsxindex 829874457b0..5b61cce70a4 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@@ -48,65 +48,37 @@ const setup = async (describe("SettingsLdapForm (EE)", () => {describe("user provisioning", () => {- it("sits right above the attributes", async () => {+ it("sits at the top of the page", async () => {await setup();const cardTitles = screen.getAllByRole("heading", { level: 2 }).map((heading) => heading.textContent);expect(cardTitles).toEqual([+ "User provisioning","Server settings","User schema",- "User provisioning","Attributes","Group mapping",]);});- 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,- });+ it("does not promise to reactivate accounts, which LDAP sign-in never does", async () => {+ await setup();const toggle = screen.getByRole("switch", { name: "User provisioning" });- await waitFor(() => expect(toggle).toBeEnabled());+ expect(toggle).toHaveAccessibleDescription(+ /create accounts for new users/,+ );+ expect(toggle).not.toHaveAccessibleDescription(/reactivate/);});- 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,- },- {- settingDefinitions: [- {- key: "ldap-user-provisioning-enabled?",- is_env_setting: true,- env_name: "MB_LDAP_USER_PROVISIONING_ENABLED",- },- ],- },- );+ it("stays editable before LDAP is configured", async () => {+ await setup({ "ldap-host": null, "ldap-configured?": false });const toggle = screen.getByRole("switch", { name: "User provisioning" });- expect(toggle).toBeDisabled();- expect(toggle).toBeChecked();- expect(toggle).toHaveAccessibleDescription(- /Using MB_LDAP_USER_PROVISIONING_ENABLED/,- );+ expect(toggle).toBeEnabled();+ expect(toggle).not.toHaveAttribute("aria-disabled");});it("saves right away without touching the page form", async () => {@@ -117,7 +89,7 @@ describe("SettingsLdapForm (EE)", () => {"ldap-user-provisioning-enabled?": true,});const toggle = screen.getByRole("switch", { name: "User provisioning" });- await waitFor(() => expect(toggle).toBeEnabled());+ await waitFor(() => expect(toggle).not.toHaveAttribute("aria-disabled"));expect(toggle).toBeChecked();await userEvent.click(toggle);@@ -154,6 +126,28 @@ describe("SettingsLdapForm (EE)", () => {expect(filterInput).toHaveAttribute("placeholder", "(member={dn})");});+ it("rejects an unbalanced membership filter", async () => {+ await setup(+ { "ldap-configured?": true, "ldap-group-sync": true },+ {+ settingDefinitions: [+ { key: "ldap-group-membership-filter", default: "(member={dn})" },+ ],+ },+ );++ await userEvent.type(+ screen.getByRole("textbox", { name: /Group membership filter/ }),+ "(objectClass=group",+ );+ await userEvent.tab();++ expect(+ await screen.findByText("Check your parentheses"),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Save/ })).toBeDisabled();+ });+it("is saved with the page form", async () => {// the required server fields have to be filled for the browser to let the form submitawait setup(@@ -211,6 +205,7 @@ describe("SettingsLdapForm (EE)", () => {const [{ url, body }] = await findRequests("PUT");expect(url).toMatch(/api\/ldap\/settings/);expect(body["ldap-host"]).toBe("ldap.example.test.internal");+ expect(body).not.toHaveProperty("ldap-group-membership-filter");});});});diff --git a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsxindex 7040f2aa16e..21c995a1f32 100644--- a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx@@ -1,12 +1,19 @@+import type { FormikHelpers } from "formik";import { useCallback, useMemo } from "react";import { c, t } from "ttag";+import _ from "underscore";import type { TestConfig } from "yup";import * as Yup from "yup";+import { SettingsGroupMappingSection } from "metabase/admin/settings/auth/components/GroupMappings";import {getDefaultPlaceholder,+ getEnvNoticeProps,getExtraFormFieldProps,+ getStoredFieldValue,+ resetFieldsToInitial,} from "metabase/admin/settings/utils";+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import {Form,@@ -39,28 +46,31 @@ import type {import { useUpdateLdapMutation } from "../api/ldap";-import { LdapGroupMappingSection } from "./LdapGroupMappingSection";--const testParentheses: TestConfig<string | null | undefined> = {- name: "test-parentheses",- message: "Check your parentheses",- test: (value) =>- (value?.match(/\(/g) || []).length === (value?.match(/\)/g) || []).length,-};-// 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),+const getLdapSchema = (isGroupMappingOn: boolean) => {+ const parenthesesTest: TestConfig<string | null | undefined> = {+ name: "test-parentheses",+ message: t`Check your parentheses`,+ test: (value) =>+ (value?.match(/\(/g) || []).length === (value?.match(/\)/g) || []).length,+ };+ const portMessage = t`Port must be a whole number between 1 and 65535`;+ return Yup.object({+ "ldap-port": Yup.number()+ .integer(portMessage)+ .min(1, portMessage)+ .max(65535, portMessage)+ .nullable(),+ "ldap-user-filter": Yup.string().nullable().test(parenthesesTest),"ldap-group-membership-filter": isGroupMappingOn- ? Yup.string().nullable().test(testParentheses)+ ? Yup.string().nullable().test(parenthesesTest): Yup.string().nullable(),});+};-// an empty port means the default, so the form allows null where the setting does not+// the port field holds the input's text, and an empty port means the defaultexport type LdapFormValues = Omit<LdapSettingValues, "ldap-port"> & {- "ldap-port": number | null;+ "ldap-port": string | null;};type LdapSettingValues = Pick<@@ -90,6 +100,11 @@ const LDAP_ATTRIBUTE_KEYS = ["ldap-attribute-lastname",] as const;+const GROUP_MAPPING_FIELD_KEYS = [+ "ldap-group-base",+ "ldap-group-membership-filter",+] satisfies (keyof LdapFormValues)[];+// the backend copy for a few fields predates the design, so the page supplies its own descriptionconst withDescription = (setting: SettingDefinition | undefined,@@ -122,14 +137,20 @@ export const SettingsLdapForm = () => {settingDetails?.["ldap-port"]?.default ?? FALLBACK_LDAP_PORT;const handleSubmit = useCallback(- (values: LdapFormValues) => {- return updateLdapSettings({- ...values,+ async (values: LdapFormValues, helpers: FormikHelpers<LdapFormValues>) => {+ // hidden group fields stay out of the save, so they cannot fail the connection test unseen+ const valuesToSave = isGroupMappingOn+ ? values+ : _.omit(values, GROUP_MAPPING_FIELD_KEYS);+ await updateLdapSettings({+ ...valuesToSave,"ldap-port": Number(values["ldap-port"] ?? defaultPort),"ldap-enabled": true,}).unwrap();+ // the form ignores refetches, so the saved values become its baseline+ helpers.resetForm({ values });},- [updateLdapSettings, defaultPort],+ [updateLdapSettings, defaultPort, isGroupMappingOn],);if (isLoadingDetails || isLoadingValues) {@@ -153,11 +174,11 @@ export const SettingsLdapForm = () => {initialValues={getFormValues(settingDetails, settingValues)}onSubmit={handleSubmit}validationSchema={schema}- enableReinitialize>- {({ dirty }) => (+ {({ dirty, initialValues, isSubmitting, setFieldValue }) => (<Form><Stack gap="xl">+ <PLUGIN_LDAP_FORM_FIELDS.LdapUserProvisioning /><SettingsSectiontitle={t`Server settings`}titleProps={SETTINGS_CARD_TITLE_PROPS}@@ -183,8 +204,7 @@ export const SettingsLdapForm = () => {<FormRadioGroupname="ldap-security"label={t`LDAP security`}- {...getExtraFormFieldProps(settingDetails["ldap-security"])}- description={null}+ {...getEnvNoticeProps(settingDetails["ldap-security"])}><Stack mt="xxs" gap="sm"><Radio value="none" label={t`None`} />@@ -241,10 +261,6 @@ export const SettingsLdapForm = () => {/></Stack></SettingsSection>- {/* the card saves on its own, so it stays out of the form's values */}- <PLUGIN_LDAP_FORM_FIELDS.LdapUserProvisioning- disabled={!isConfigured}- /><CollapsibleSettingsSectiontitle={t`Attributes`}description={t`Map LDAP attributes to the email, first name, and last name fields in ${applicationName}`}@@ -278,9 +294,25 @@ export const SettingsLdapForm = () => {/></Stack></CollapsibleSettingsSection>- <LdapGroupMappingSection+ <SettingsGroupMappingSection+ syncSettingKey="ldap-group-sync"+ mappingsSettingKey="ldap-group-mappings"+ description={t`Automatically assign people to ${applicationName} groups based on their LDAP group membership`}+ tenancy="internal"+ nameLabel={t`LDAP group name`}+ namePlaceholder="cn=people,ou=groups,dc=example,dc=org"+ namesValidatedOnSavedata-testid="ldap-group-mapping-section"disabled={!isConfigured}+ onToggle={(enabled) => {+ if (!enabled) {+ resetFieldsToInitial(+ setFieldValue,+ initialValues,+ GROUP_MAPPING_FIELD_KEYS,+ );+ }+ }}><FormTextInputname="ldap-group-base"@@ -293,7 +325,7 @@ export const SettingsLdapForm = () => {)}/><PLUGIN_LDAP_FORM_FIELDS.LdapGroupMembershipFilter />- </LdapGroupMappingSection>+ </SettingsGroupMappingSection><Flex justify="end" gap="md"><Box><FormErrorMessage />@@ -305,6 +337,7 @@ export const SettingsLdapForm = () => {/></Flex></Stack>+ <LeaveRouteConfirmModal isEnabled={dirty && !isSubmitting} /></Form>)}</FormProvider>@@ -316,21 +349,17 @@ 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;- };+ const storedValue = (key: LdapTextKey): string | null =>+ getStoredFieldValue(settingDetails[key], settingValues[key]);++ const port = getStoredFieldValue(+ settingDetails["ldap-port"],+ settingValues["ldap-port"],+ );- 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-port": port === null ? null : String(port),"ldap-security": settingValues["ldap-security"] ?? "none","ldap-bind-dn": storedValue("ldap-bind-dn"),"ldap-password": storedValue("ldap-password"),diff --git a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.unit.spec.tsxindex 32986e40ae1..52a285f2298 100644--- a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.unit.spec.tsx@@ -91,7 +91,7 @@ const setup = async ({fetchMock.delete("express:/api/permissions/group/:id", 204);fetchMock.put("path:/api/ldap/settings", { status: 204 });- const { store } = renderWithProviders(<SettingsLdapForm />, {+ renderWithProviders(<SettingsLdapForm />, {withUndos: true,storeInitialState: createMockState({settings: createMockSettingsState(settings),@@ -99,7 +99,7 @@ const setup = async ({});await screen.findByText("Server settings");- return { store, settingsStore };+ return { settingsStore };};const setupConfigured = (options: Parameters<typeof setup>[0] = {}) =>@@ -120,8 +120,13 @@ const findMappingRow = (name: string) =>.queryAllByTestId("group-mapping-row").find((row) => within(row).queryByText(name) != null);+const clickWhenEnabled = async (element: HTMLElement) => {+ await waitFor(() => expect(element).toBeEnabled());+ await userEvent.click(element);+};+const addMapping = async (name: string, groupName: string) => {- await userEvent.click(screen.getByRole("button", { name: "New" }));+ await clickWhenEnabled(screen.getByRole("button", { name: "New" }));await userEvent.type(screen.getByPlaceholderText(LDAP_GROUP_PLACEHOLDER),name,@@ -229,6 +234,34 @@ describe("SettingsLdapForm", () => {);});+ it("keeps the saved host when the settings refetch after a save fails", async () => {+ await setup({ settingValues: ATTRS });+ fetchMock.removeRoute("settings-list");+ fetchMock.get("path:/api/setting", 500, { name: "settings-list" });++ const hostInput = screen.getByLabelText(/LDAP host/);+ await userEvent.clear(hostInput);+ await userEvent.type(hostInput, "ldap.new.example.org");+ await userEvent.click(screen.getByRole("button", { name: /Save/ }));+ await waitFor(() =>+ expect(+ screen.getByRole("button", { name: /Success|Save/ }),+ ).toBeDisabled(),+ );++ const bindDnInput = screen.getByLabelText(/Username or DN/);+ await userEvent.clear(bindDnInput);+ await userEvent.type(bindDnInput, "cn=admin,dc=example,dc=org");+ await userEvent.click(screen.getByRole("button", { name: /Success|Save/ }));++ await waitFor(async () =>+ expect(await findRequests("PUT")).toHaveLength(2),+ );+ const [, { body }] = await findRequests("PUT");+ expect(body["ldap-host"]).toBe("ldap.new.example.org");+ expect(hostInput).toHaveValue("ldap.new.example.org");+ });+it("does not offer user provisioning on OSS", async () => {await setup();@@ -297,6 +330,37 @@ describe("SettingsLdapForm", () => {expect(body["ldap-port"]).toBe(636);});+ it.each(["0", "99999"])(+ "rejects the out-of-range port %s",+ async (value) => {+ await setupConfigured();++ const port = screen.getByLabelText(/LDAP port/);+ await userEvent.clear(port);+ await userEvent.type(port, value);+ await userEvent.tab();++ expect(+ await screen.findByText(+ "Port must be a whole number between 1 and 65535",+ ),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Save/ })).toBeDisabled();+ },+ );++ it("stays clean after typing the saved port back", async () => {+ await setup({ settingValues: { "ldap-port": 636 } });++ const port = screen.getByLabelText(/LDAP port/);+ await userEvent.type(port, "1");+ expect(screen.getByRole("button", { name: /Save/ })).toBeEnabled();+ await userEvent.type(port, "{Backspace}");++ expect(port).toHaveValue(636);+ expect(screen.getByRole("button", { name: /Save/ })).toBeDisabled();+ });+it("shows the value an env var gives a field, read-only", async () => {await setup({settingValues: { "ldap-host": "ldap.env.test" },@@ -311,6 +375,35 @@ describe("SettingsLdapForm", () => {expect(screen.getByText("Using MB_LDAP_HOST")).toBeInTheDocument();});+ it("says which env var locks the security setting", async () => {+ await setup({+ settingValues: { "ldap-security": "ssl" },+ settingDefinitions: [+ {+ key: "ldap-security",+ is_env_setting: true,+ env_name: "MB_LDAP_SECURITY",+ },+ ],+ });++ expect(screen.getByRole("radio", { name: "SSL" })).toBeChecked();+ expect(screen.getByText("Using MB_LDAP_SECURITY")).toBeInTheDocument();+ });++ it("shows no description under the security setting otherwise", async () => {+ await setup({+ settingDefinitions: [+ { key: "ldap-security", description: "Use SSL, TLS or plain text." },+ ],+ });++ expect(screen.getByRole("radio", { name: "None" })).toBeChecked();+ expect(+ screen.queryByText("Use SSL, TLS or plain text."),+ ).not.toBeInTheDocument();+ });+it("keeps the attributes card disabled until LDAP is configured", async () => {await setup({ settingValues: { "ldap-attribute-email": "uid" } });@@ -375,25 +468,6 @@ describe("SettingsLdapForm", () => {).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();@@ -413,51 +487,77 @@ describe("SettingsLdapForm", () => {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 };+ it("drops an unsaved group search base edit when group mapping is turned off", async () => {+ await setupConfigured({+ settingValues: {+ "ldap-group-sync": true,+ "ldap-group-base": "ou=groups,dc=example,dc=org",},- { name: "update-setting", delay: 200 },- );+ });+ const saveButton = () => screen.getByRole("button", { name: /Save/ });+ const groupBase = () =>+ screen.getByRole("textbox", { name: /Group search base/ });++ await userEvent.type(groupBase(), "X");+ expect(saveButton()).toBeEnabled();await userEvent.click(groupMappingSwitch());+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );- 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);+ expect(saveButton()).toBeDisabled();+ await userEvent.click(groupMappingSwitch());+ await waitFor(() =>+ expect(groupMappingSwitch()).not.toHaveAttribute("aria-disabled"),+ );+ expect(groupBase()).toHaveValue("ou=groups,dc=example,dc=org");});- 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",+ it("leaves the hidden group fields out of a save while group mapping is off", async () => {+ await setupConfigured({+ settingValues: {+ "ldap-host": "ldap.example.org",+ "ldap-user-base": "ou=users,dc=example,dc=org",+ "ldap-group-base": "ou=groups,dc=example,dc=org",+ "ldap-group-sync": false,+ },});- await userEvent.click(groupMappingSwitch());+ await userEvent.type(screen.getByLabelText(/LDAP host/), ".internal");+ await userEvent.click(screen.getByRole("button", { name: /Save/ }));- expect(await screen.findByText(/Error saving/)).toBeInTheDocument();- expect(groupMappingSwitch()).not.toBeChecked();- expect(groupMappingSwitch()).toBeEnabled();- expect(- screen.queryByText("Manual group mappings"),- ).not.toBeInTheDocument();+ const [{ body }] = await findRequests("PUT");+ expect(body["ldap-host"]).toBe("ldap.example.org.internal");+ expect(body).not.toHaveProperty("ldap-group-base");+ });++ it("leaves the save hint out while an env var holds group mapping", async () => {+ await setup({+ settingValues: { "ldap-group-sync": false },+ settingDefinitions: [+ {+ key: "ldap-group-sync",+ is_env_setting: true,+ env_name: "MB_LDAP_GROUP_SYNC",+ },+ ],+ });++ await waitFor(() =>+ expect(groupMappingSwitch()).toHaveAccessibleDescription(+ /Using MB_LDAP_GROUP_SYNC/,+ ),+ );+ expect(groupMappingSwitch()).not.toHaveAccessibleDescription(+ /Save the settings above to set up group mapping/,+ );});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 clickWhenEnabled(screen.getByRole("button", { name: "New" }));await userEvent.click(screen.getByPlaceholderText("Pick Metabase group..."),);@@ -476,7 +576,7 @@ describe("SettingsLdapForm", () => {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" }));+ await clickWhenEnabled(screen.getByRole("button", { name: "New" }));expect(screen.queryByRole("button", { name: "New" }),).not.toBeInTheDocument();@@ -506,7 +606,7 @@ describe("SettingsLdapForm", () => {expect(screen.getByRole("button", { name: /Save/ })).toBeDisabled();});- it("keeps the row editor busy while the mapping write is in flight", async () => {+ it("keeps the row editor busy and open while the mapping write is in flight", async () => {const { settingsStore } = await setupConfigured({settingValues: { "ldap-group-sync": true },});@@ -521,94 +621,27 @@ describe("SettingsLdapForm", () => {{ name: "update-settings", delay: 200 },);- await addMapping(DEVS_DN, "bar");+ await clickWhenEnabled(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" }));+ // Enter keeps the focus in the field, so the Escape that follows reaches the editor+ await userEvent.click(nameInput);+ await userEvent.keyboard("{Enter}");const addButton = screen.getByRole("button", { name: "Add mapping" });expect(addButton).toHaveAttribute("data-loading", "true");+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();+ await userEvent.keyboard("{Escape}");+ expect(nameInput).toBeInTheDocument();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({@@ -643,7 +676,7 @@ describe("SettingsLdapForm", () => {await userEvent.type(screen.getByLabelText(/LDAP host/), "ldap.test");expect(screen.getByRole("button", { name: /Save/ })).toBeEnabled();- await userEvent.click(screen.getByRole("button", { name: "New" }));+ await clickWhenEnabled(screen.getByRole("button", { name: "New" }));const nameInput = screen.getByPlaceholderText(LDAP_GROUP_PLACEHOLDER);await userEvent.type(nameInput, DEVS_DN);await userEvent.click(@@ -661,7 +694,7 @@ describe("SettingsLdapForm", () => {expect(puts[0].url).toMatch(/\/api\/setting$/);});- it("edits an existing mapping in place", async () => {+ it("edits a mapping in place and rejects a name another mapping uses", async () => {await setupConfigured({settingValues: {"ldap-group-sync": true,@@ -669,7 +702,7 @@ describe("SettingsLdapForm", () => {},});- await userEvent.click(+ await clickWhenEnabled(within(findMappingRow(DEVS_DN)!).getByRole("button", {name: "Edit mapping",}),@@ -678,6 +711,12 @@ describe("SettingsLdapForm", () => {expect(nameInput).toHaveValue(DEVS_DN);expect(screen.getByText("foo")).toBeInTheDocument();await userEvent.clear(nameInput);+ await userEvent.type(nameInput, OPS_DN);+ expect(+ screen.getByText("A mapping for this group already exists"),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();+ await userEvent.clear(nameInput);await userEvent.type(nameInput, RENAMED_DN);await userEvent.click(screen.getByLabelText("Metabase groups"));await userEvent.click(await screen.findByRole("option", { name: "bar" }));@@ -702,7 +741,7 @@ describe("SettingsLdapForm", () => {},});- await userEvent.click(+ await clickWhenEnabled(within(findMappingRow(DEVS_DN)!).getByRole("button", {name: "Delete mapping",}),diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/test/AuthenticationSettingsPage.enterprise.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/test/AuthenticationSettingsPage.enterprise.unit.spec.tsxindex 8368ff591b7..4f125d2e7dc 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/test/AuthenticationSettingsPage.enterprise.unit.spec.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/test/AuthenticationSettingsPage.enterprise.unit.spec.tsx@@ -1,5 +1,11 @@+import userEvent from "@testing-library/user-event";+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";-import { screen } from "__support__/ui";+import {+ findRequests,+ setupUpdateSettingsEndpoint,+} from "__support__/server-mocks";+import { screen, waitFor, within } from "__support__/ui";import type { AuthSettingsPageTab } from "metabase/plugins";import type { EnterpriseSettings } from "metabase-types/api";@@ -13,6 +19,23 @@ const setup = async (return OSSSetup(extraSettings, true, tab);};+const deactivate = async (cardTestId: string) => {+ const card = await screen.findByTestId(cardTestId);+ await userEvent.click(within(card).getByRole("button", { name: "Actions" }));+ await userEvent.click(+ await screen.findByRole("menuitem", { name: "Deactivate" }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Deactivate" }),+ );+ await waitFor(async () => {+ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);+ });+ const [{ body }] = await findRequests("PUT");+ return body;+};+describe("AuthenticationSettingsPage (EE)", () => {it("should contain enterprise auth options", async () => {await setup({@@ -27,6 +50,26 @@ describe("AuthenticationSettingsPage (EE)", () => {expect(await screen.findByText("Session timeout")).toBeInTheDocument();});+ it("clears the tenant assignment attribute when SAML is deactivated", async () => {+ setupUpdateSettingsEndpoint();+ await setup({ "saml-configured": true, "saml-enabled": true });++ const body = await deactivate("saml-setting");++ expect(body).toHaveProperty("saml-identity-provider-uri", null);+ expect(body).toHaveProperty("saml-attribute-tenant", null);+ });++ it("clears the tenant assignment attribute when JWT is deactivated", async () => {+ setupUpdateSettingsEndpoint();+ await setup({ "jwt-configured": true, "jwt-enabled": true });++ const body = await deactivate("jwt-setting");++ expect(body).toHaveProperty("jwt-identity-provider-uri", null);+ expect(body).toHaveProperty("jwt-attribute-tenant", null);+ });+it("should also include OSS auth providers", async () => {await setup();diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.module.css b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.module.cssdeleted file mode 100644index baeb96916af..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.module.css+++ /dev/null@@ -1,17 +0,0 @@-/* A bare borderless input: Mantine's TextInput (even variant="unstyled")- keeps a themed border in Metabase, which would double up with the brand- border on the surrounding row. */-.input {- flex: 1 0 auto;- margin-left: var(--mantine-spacing-sm);- border: none;- background: transparent;- box-shadow: none;- outline: 0;- font-size: var(--mantine-font-size-lg);-}--.input:focus {- box-shadow: none;- outline: 0;-}diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.tsxdeleted file mode 100644index 92022f20603..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.tsx+++ /dev/null@@ -1,80 +0,0 @@-import { useState } from "react";-import { t } from "ttag";--import type { MappingsType } from "metabase/admin/types";-import { Button, Flex, Group } from "metabase/ui";--import S from "./AddMappingRow.module.css";--type AddMappingRowProps = {- mappings: MappingsType;- placeholder: string;- onCancel: () => void;- onAdd: (value: string) => void | Promise<void>;-};--export function AddMappingRow({- mappings,- placeholder,- onCancel,- onAdd,-}: AddMappingRowProps) {- const [value, setValue] = useState("");-- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {- if (e.key === "Enter") {- // don't natively submit an enclosing settings form- e.preventDefault();- if (isMappingNameUnique) {- handleAdd();- }- }- };-- const handleAdd = async () => {- await onAdd(value);- setValue("");- };-- const handleCancelClick = () => {- onCancel();- setValue("");- };-- const isMappingNameUnique = value && mappings[value] === undefined;-- return (- <Flex- align="center"- justify="space-between"- bd="1px solid var(--mb-color-core-brand)"- bdrs="sm"- m="lg"- p="sm"- >- <input- aria-label={t`New group mapping name`}- className={S.input}- type="text"- value={value}- placeholder={placeholder}- autoFocus- onChange={(e) => setValue(e.target.value)}- onKeyDown={handleKeyDown}- />- <Group gap="lg">- <Button- variant="subtle"- color="neutral"- onClick={handleCancelClick}- >{t`Cancel`}</Button>- <Button- type="button"- variant={isMappingNameUnique ? "filled" : "default"}- disabled={!isMappingNameUnique}- onClick={() => (isMappingNameUnique ? handleAdd() : undefined)}- >{t`Add`}</Button>- </Group>- </Flex>- );-}diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/index.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/index.tsxdeleted file mode 100644index 41ab0ef6cd5..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/index.tsx+++ /dev/null@@ -1 +0,0 @@-export * from "./AddMappingRow";diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.module.css b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.module.cssdeleted file mode 100644index 5be2d4c8823..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.module.css+++ /dev/null@@ -1,28 +0,0 @@-/* Fixed column widths so a long mapping name can't widen the first column- and push the other columns around. */-.mappingsTable {- table-layout: fixed;-}--.mappingsTable th:first-child,-.mappingsTable td:first-child {- width: 50%;- overflow-wrap: anywhere;-}--.mappingsTable th:nth-child(2),-.mappingsTable td:nth-child(2) {- width: 40%;-}--.mappingsTable th:nth-child(3),-.mappingsTable td:nth-child(3) {- width: 10%;-}--/* Only the top corners are rounded to match the card; bdrs prop can't express- a partial radius. */-.header {- border-top-left-radius: var(--mantine-radius-sm);- border-top-right-radius: var(--mantine-radius-sm);-}diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.tsxdeleted file mode 100644index e40df92437c..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.tsx+++ /dev/null@@ -1,80 +0,0 @@-import { useCallback } from "react";--import {- useClearGroupMembershipMutation,- useDeletePermissionsGroupMutation,- useListPermissionsGroupsQuery,-} from "metabase/api";-import { useDispatch, useSelector } from "metabase/redux";-import {- getSetting,- settingsApi,- useUpdateSettingMutation,-} from "metabase/settings";-import type { GroupId, GroupInfo } from "metabase-types/api";--import type { MappingSettingKey } from "./GroupMappingsWidgetView";-import { GroupMappingsWidgetView } from "./GroupMappingsWidgetView";--const EMPTY_GROUP_LIST: GroupInfo[] = [];--type GroupMappingsWidgetProps = {- mappingSetting: MappingSettingKey;- [key: string]: unknown;-};--export function GroupMappingsWidget(props: GroupMappingsWidgetProps) {- const dispatch = useDispatch();- const [updateSetting] = useUpdateSettingMutation();- const { data } = useListPermissionsGroupsQuery({});- const allGroups = data ?? EMPTY_GROUP_LIST;- const mappings = useSelector(- (state) => getSetting(state, props.mappingSetting) ?? {},- );-- const [deletePermissionsGroup] = useDeletePermissionsGroupMutation();- const [clearGroupMembership] = useClearGroupMembershipMutation();-- const deleteGroup = useCallback(- ({ id }: { id: GroupId }) => deletePermissionsGroup(id).unwrap(),- [deletePermissionsGroup],- );- const clearGroupMember = useCallback(- ({ id }: { id: GroupId }) => clearGroupMembership(id).unwrap(),- [clearGroupMembership],- );- const handleUpdateSetting = useCallback(- async (args: {- key: MappingSettingKey;- value: Record<string, GroupId[]>;- }) => {- await updateSetting(args).unwrap();- // For this particular setting we don't need to fully wait for the refetch.- // So long as unwrap succeeds, we can update the cache to reflect the new value- dispatch(- settingsApi.util.updateQueryData(- "getSessionProperties",- undefined,- (draft) => {- draft[args.key] = args.value;- },- ),- );- },- [updateSetting, dispatch],- );-- return (- <GroupMappingsWidgetView- // Unjustified type cast. FIXME- {...(props as unknown as React.ComponentProps<- typeof GroupMappingsWidgetView- >)}- allGroups={allGroups}- mappings={mappings}- deleteGroup={deleteGroup}- clearGroupMember={clearGroupMember}- updateSetting={handleUpdateSetting}- />- );-}diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsxdeleted file mode 100644index 774dafc8e61..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx+++ /dev/null@@ -1,276 +0,0 @@-import userEvent from "@testing-library/user-event";--import { renderWithProviders, screen, waitFor, within } from "__support__/ui";-import { FormProvider } from "metabase/forms";-import type { GroupId, GroupInfo } from "metabase-types/api";-import { createMockGroup } from "metabase-types/api/mocks";--import type { MappingSettingKey } from "./GroupMappingsWidgetView";-import { GroupMappingsWidgetView } from "./GroupMappingsWidgetView";--const defaultGroups: GroupInfo[] = [- createMockGroup({- id: 1,- name: "Administrators",- member_count: 1,- magic_group_type: "admin",- }),-];-const defaultMappings: Record<string, GroupId[]> = {- "group=Administrators": [1],-};--type SetupOptions = {- mappings?: Record<string, GroupId[]>;- mappingSetting?: MappingSettingKey;- clearGroupMember?: jest.Mock;- deleteGroup?: jest.Mock;- updateSetting?: jest.Mock;- setting?: { key: string; value: boolean };- groups?: GroupInfo[];-};--const setup = ({- mappings = defaultMappings,- mappingSetting = "ldap-group-mappings",- clearGroupMember = jest.fn(),- deleteGroup = jest.fn(),- updateSetting = jest.fn(),- setting = { key: "key", value: true },- groups = defaultGroups,-}: SetupOptions = {}) => {- return renderWithProviders(- <FormProvider- initialValues={{ [setting.key]: setting.value }}- onSubmit={() => {}}- >- <GroupMappingsWidgetView- groupHeading=""- groupPlaceholder=""- allGroups={groups}- mappings={mappings}- mappingSetting={mappingSetting}- setting={setting}- clearGroupMember={clearGroupMember}- deleteGroup={deleteGroup}- updateSetting={updateSetting}- />- </FormProvider>,- { withUndos: true },- );-};--describe("GroupMappingsWidgetView", () => {- describe("tooltip text", () => {- it("shows the tooltip text", async () => {- setup({ mappingSetting: "ldap-group-mappings" });-- const aboutMappingsElement = await screen.findByText("About mappings");- await userEvent.hover(aboutMappingsElement);-- expect(- await screen.findByText(- /If a group isn‘t mapped, its membership won‘t be synced/,- ),- ).toBeInTheDocument();- });- });-- describe("no mappings message", () => {- it("shows the sync-off message when group sync is disabled", async () => {- setup({- mappings: {},- setting: { key: "ldap-group-sync", value: false },- });-- expect(- await screen.findByText("No mappings yet, group sync is not on"),- ).toBeInTheDocument();- });-- it("shows the no mappings message", async () => {- setup({ mappings: {} });-- expect(await screen.findByText("No mappings yet")).toBeInTheDocument();- });-- it("hides the table column headers when there are no mappings", async () => {- setup({ mappings: {} });-- expect(await screen.findByText("No mappings yet")).toBeInTheDocument();- expect(screen.queryByRole("columnheader")).not.toBeInTheDocument();- });-- it("shows the table column headers once a mapping exists", async () => {- setup({ mappingSetting: "ldap-group-mappings" });-- expect(- await screen.findByRole("columnheader", { name: "Groups" }),- ).toBeInTheDocument();- });- });-- describe("adding a mapping", () => {- it("adds a mapping with a unique name on Enter", async () => {- const updateSettingSpy = jest.fn();- setup({ updateSetting: updateSettingSpy });-- await userEvent.click(- await screen.findByRole("button", { name: "New mapping" }),- );- await userEvent.type(- screen.getByLabelText("New group mapping name"),- "cn=People{Enter}",- );-- await waitFor(() => {- expect(updateSettingSpy).toHaveBeenCalledWith({- key: "ldap-group-mappings",- value: { "group=Administrators": [1], "cn=People": [] },- });- });-- // the mapping autosaves, so the user gets a toast confirming it- expect(await screen.findByText("Mapping added")).toBeInTheDocument();- });-- it("does not add a mapping with a duplicate name on Enter", async () => {- const updateSettingSpy = jest.fn();- setup({ updateSetting: updateSettingSpy });-- await userEvent.click(- await screen.findByRole("button", { name: "New mapping" }),- );- await userEvent.type(- screen.getByLabelText("New group mapping name"),- "group=Administrators{Enter}",- );-- expect(updateSettingSpy).not.toHaveBeenCalled();- });- });-- describe("when a mapping is set for admin group", () => {- it("handles deleting mapping", async () => {- const updateSettingSpy = jest.fn();- setup({ updateSetting: updateSettingSpy });-- expect(- await screen.findByText("group=Administrators"),- ).toBeInTheDocument();- expect(await screen.findByText("Admin")).toBeInTheDocument();-- // Click on button to delete mapping- await userEvent.click(await screen.findByLabelText("close icon"));-- // Confirm remove- await userEvent.click(screen.getByText("Yes"));-- await waitFor(() => {- expect(updateSettingSpy).toHaveBeenCalledTimes(1);- });-- expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();- });- });-- describe("when a mapping is set for more than one group", () => {- const mappings: Record<string, GroupId[]> = { "cn=People": [3, 4] };-- // magic_group_type: null so these aren't filtered out by isDefaultGroup.- const groups = [- createMockGroup({- id: 1,- name: "All Users",- member_count: 5,- magic_group_type: null,- }),- createMockGroup({- id: 2,- name: "Administrators",- member_count: 1,- magic_group_type: null,- }),- createMockGroup({- id: 3,- name: "Group 1",- member_count: 2,- magic_group_type: null,- }),- createMockGroup({- id: 4,- name: "Group 2",- member_count: 2,- magic_group_type: null,- }),- ];-- it("handles clearing mapped groups after deleting mapping", async () => {- const clearGroupMemberSpy = jest.fn();- setup({ groups, mappings, clearGroupMember: clearGroupMemberSpy });-- expect(await screen.findByText("cn=People")).toBeInTheDocument();- expect(await screen.findByText("2 other groups")).toBeInTheDocument();-- // Click on button to delete mapping- await userEvent.click(await screen.findByLabelText("close icon"));-- await userEvent.click(screen.getByLabelText(/Also remove all members/i));- await userEvent.click(- await screen.findByRole("button", {- name: "Remove mapping and members",- }),- );-- await waitFor(() => {- // One call for each group deleted- expect(clearGroupMemberSpy).toHaveBeenCalledTimes(2);- });- });-- it("handles deleting mapped groups after deleting mapping", async () => {- const deleteGroupSpy = jest.fn();- setup({ groups, mappings, deleteGroup: deleteGroupSpy });-- expect(await screen.findByText("cn=People")).toBeInTheDocument();- expect(await screen.findByText("2 other groups")).toBeInTheDocument();-- // Click on button to delete mapping- await userEvent.click(await screen.findByLabelText("close icon"));-- await userEvent.click(screen.getByLabelText(/Also delete the groups/i));- await userEvent.click(- await screen.findByRole("button", {- name: "Remove mapping and delete groups",- }),- );-- await waitFor(() => {- // One call for each group deleted- expect(deleteGroupSpy).toHaveBeenCalledTimes(2);- });- });- });-- it("keeps a row's group options out of the DOM until its dropdown opens (metabase#81838)", async () => {- const groups = [- ...defaultGroups,- createMockGroup({ id: 2, name: "group-2", magic_group_type: null }),- createMockGroup({ id: 3, name: "group-3", magic_group_type: null }),- ];- setup({ groups, mappings: { "cn=a": [1], "cn=b": [2], "cn=c": [3] } });-- // role queries skip hidden nodes by default, and a mounted hidden option still costs DOM and memory- expect(screen.queryAllByRole("option", { hidden: true })).toHaveLength(0);-- const [firstMappingRow] = screen.getAllByRole("row").slice(1);- const [groupSelectToggle] = within(firstMappingRow).getAllByRole("button");- await userEvent.click(groupSelectToggle);- expect(await screen.findAllByRole("option")).toHaveLength(3);-- await userEvent.click(groupSelectToggle);- await waitFor(() => {- expect(screen.queryAllByRole("option", { hidden: true })).toHaveLength(0);- });- });-});diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsxdeleted file mode 100644index a2167264afb..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx+++ /dev/null@@ -1,234 +0,0 @@-import { useField } from "formik";-import { useState } from "react";-import { t } from "ttag";-import _ from "underscore";--import NoResults from "assets/img/no_results.svg";-import { AdminContentTable } from "metabase/admin/components/AdminContentTable";-import { getErrorMessage } from "metabase/api/utils/errors";-import { EmptyState } from "metabase/common/components/EmptyState";-import { useToast } from "metabase/common/hooks";-import { isDefaultGroup } from "metabase/common/utils/groups";-import { FormSwitch } from "metabase/forms";-import {- Box,- Button,- Flex,- Group,- Icon,- Text,- Tooltip,- rem,-} from "metabase/ui";-import type { GroupId, GroupInfo } from "metabase-types/api";--import { AddMappingRow } from "./AddMappingRow";-import S from "./GroupMappingsWidget.module.css";-import { MappingRow } from "./MappingRow";--const groupIsMappable = (group: GroupInfo) => !isDefaultGroup(group);--/** The auth-provider group-mapping settings this widget can edit. */-export type MappingSettingKey =- | "ldap-group-mappings"- | "saml-group-mappings"- | "oidc-group-mappings";--const helpText = () =>- t`Mappings allow Metabase to automatically add and remove users from groups based on the membership information provided by the directory server. If a group isn‘t mapped, its membership won‘t be synced.`;--const noMappingText = (syncSwitchValue: boolean) => {- if (!syncSwitchValue) {- return t`No mappings yet, group sync is not on`;- }- return t`No mappings yet`;-};--interface GroupMappingsWidgetViewProps {- groupHeading: string;- groupPlaceholder: string;- allGroups: GroupInfo[];- mappingSetting: MappingSettingKey;- deleteGroup: ({ id }: { id: number }) => Promise<void>;- clearGroupMember: ({ id }: { id: number }) => Promise<void>;- updateSetting: ({- key,- value,- }: {- key: MappingSettingKey;- value: Record<string, GroupId[]>;- }) => Promise<void>;- mappings: Record<string, GroupId[]>;- setting: { key: string };-}--export function GroupMappingsWidgetView({- groupHeading,- groupPlaceholder,- allGroups = [],- mappingSetting,- deleteGroup,- clearGroupMember,- updateSetting,- mappings,- setting,-}: GroupMappingsWidgetViewProps) {- const [showAddRow, setShowAddRow] = useState(false);- const [saveError, setSaveError] = useState<string | null>(null);- const [sendToast] = useToast();-- const groups = allGroups.filter(groupIsMappable);-- const handleShowAddRow = () => {- setShowAddRow(true);- };-- const handleHideAddRow = () => {- setShowAddRow(false);- };-- const handleAddMapping = async (name: string) => {- const mappingsPlusNewMapping = { ...mappings, [name]: [] };-- try {- await updateSetting({- key: mappingSetting,- value: mappingsPlusNewMapping,- });- setShowAddRow(false);- setSaveError(null);- sendToast({ message: t`Mapping added`, icon: "check" });- } catch (error) {- setSaveError(getErrorMessage(error));- }- };-- const handleChangeMapping =- (name: string) => async (group: { id: GroupId }, selected: boolean) => {- const updatedMappings = selected- ? { ...mappings, [name]: [...mappings[name], group.id] }- : {- ...mappings,- [name]: mappings[name].filter((id) => id !== group.id),- };-- try {- await updateSetting({ key: mappingSetting, value: updatedMappings });- setSaveError(null);- sendToast({ message: t`Mapping updated`, icon: "check" });- } catch (error) {- setSaveError(getErrorMessage(error));- }- };-- const handleDeleteMapping = async ({- name,- onSuccess,- }: {- name: string;- onSuccess?: () => void;- }) => {- const mappingsMinusDeletedMapping = _.omit(mappings, name);-- try {- await updateSetting({- key: mappingSetting,- value: mappingsMinusDeletedMapping,- });-- if (onSuccess) {- await onSuccess();- }- setSaveError(null);- sendToast({ message: t`Mapping deleted`, icon: "check" });- } catch (error) {- setSaveError(getErrorMessage(error));- }- };-- const [{ value: groupSyncSwitchValue }] = useField<boolean>(setting.key);-- const hasMappings = Object.keys(mappings).length > 0;-- return (- <Flex direction="column" w="100%">- <Group mb="lg" gap="sm">- <Text fw="bold">{t`Synchronize Group Memberships`}</Text>- <FormSwitch data-testid="group-sync-switch" name={setting.key} />- </Group>-- <Flex- bd="1px solid var(--mb-color-border-neutral)"- bdrs="sm"- direction="column"- w="100%"- >- <Flex- className={S.header}- align="center"- bg="background-secondary"- mih={rem(56)}- px="lg"- py="sm"- >- {!showAddRow && (- <Button variant="filled" type="button" onClick={handleShowAddRow}>- {t`New mapping`}- </Button>- )}- <Tooltip label={helpText()} position="top" maw="20rem">- <Flex align="center" gap="sm" c="text-secondary" ml="auto">- <Icon name="info" />- <span>{t`About mappings`}</span>- </Flex>- </Tooltip>- </Flex>-- {showAddRow && (- <AddMappingRow- mappings={mappings}- placeholder={groupPlaceholder}- onCancel={handleHideAddRow}- onAdd={handleAddMapping}- />- )}- {hasMappings ? (- <AdminContentTable- className={S.mappingsTable}- columnTitles={[groupHeading, t`Groups`, ""]}- >- {Object.entries(mappings).map(([name, selectedGroupIds]) => {- return groups?.length > 0 ? (- <MappingRow- key={name}- name={name}- groups={groups}- selectedGroupIds={selectedGroupIds}- clearGroupMember={clearGroupMember}- deleteGroup={deleteGroup}- onChange={handleChangeMapping(name)}- onDeleteMapping={handleDeleteMapping}- />- ) : null;- })}- </AdminContentTable>- ) : (- !showAddRow && (- <Box pb="lg">- <EmptyState- illustrationElement={<img src={NoResults} alt="" />}- message={noMappingText(groupSyncSwitchValue)}- spacing="sm"- />- </Box>- )- )}- </Flex>- {saveError && (- <Text c="feedback-negative" fw="bold" m="sm">- {saveError}- </Text>- )}- </Flex>- );-}diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.module.css b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.module.cssdeleted file mode 100644index 2e374e9c059..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.module.css+++ /dev/null@@ -1,7 +0,0 @@-/* Mantine's default Combobox group label color is not themed in Metabase- (resolves to transparent), so make the section header visible. */-.groupLabel {- color: var(--mb-color-text-secondary);- font-weight: 700;- text-transform: uppercase;-}diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsxdeleted file mode 100644index c2371544a19..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx+++ /dev/null@@ -1,152 +0,0 @@-import { Fragment } from "react";-import { t } from "ttag";--import { GroupSummary } from "metabase/admin/people/components/GroupSummary";-import type { GroupIds, UserGroupType } from "metabase/admin/types";-import {- canEditMembership,- getGroupNameLocalized,- isAdminGroup,- isDefaultGroup,-} from "metabase/common/utils/groups";-import {- Box,- Checkbox,- Combobox,- Flex,- Icon,- UnstyledButton,- rem,- useCombobox,-} from "metabase/ui";-import { isNotNull } from "metabase/utils/types";-import type { GroupInfo } from "metabase-types/api";--import S from "./GroupSelect.module.css";--function getGroupColor(group: Pick<GroupInfo, "magic_group_type">) {- if (isAdminGroup(group)) {- return "var(--mb-color-core-filter)";- }- if (isDefaultGroup(group)) {- return "var(--mb-color-text-secondary)";- }- return "var(--mb-color-text-primary)";-}--type GroupSelectProps = {- groups: GroupInfo[];- selectedGroupIds: GroupIds;- onGroupChange: (group: UserGroupType, selected: boolean) => void;- isCurrentUser?: boolean;- emptyListMessage?: string;-};--function getSections(groups: GroupInfo[]) {- const adminGroup = groups.find(isAdminGroup);- const defaultGroup = groups.find(isDefaultGroup);- const topGroups = [defaultGroup, adminGroup].filter(isNotNull);- const groupsExceptDefaultAndAdmin = groups.filter(- (group) => !isAdminGroup(group) && !isDefaultGroup(group),- );-- if (topGroups.length === 0) {- return [{ items: groupsExceptDefaultAndAdmin }];- }-- return [- { items: topGroups },- groupsExceptDefaultAndAdmin.length > 0- ? { items: groupsExceptDefaultAndAdmin, name: t`Groups` }- : null,- ].filter(isNotNull);-}--export const GroupSelect = ({- groups,- selectedGroupIds = [],- onGroupChange,- isCurrentUser = false,- emptyListMessage = t`No groups`,-}: GroupSelectProps) => {- const combobox = useCombobox();-- const handleOptionSubmit = (value: string) => {- const groupId = Number(value);- const group = groups.find((candidate) => candidate.id === groupId);- if (group == null) {- return;- }- onGroupChange(group, !selectedGroupIds.includes(groupId));- };-- const sections = getSections(groups);-- return (- <Combobox- store={combobox}- // a closed dropdown stays unmounted, or a page with many rows carries every group per row- keepMounted={false}- position="bottom-start"- width={rem(240)}- classNames={{ groupLabel: S.groupLabel }}- onOptionSubmit={handleOptionSubmit}- >- <Combobox.Target>- <UnstyledButton onClick={() => combobox.toggleDropdown()}>- <Flex align="center">- <GroupSummary- mr="sm"- groups={groups}- selectedGroupIds={selectedGroupIds}- />- <Icon c="text-disabled" name="chevrondown" size={10} />- </Flex>- </UnstyledButton>- </Combobox.Target>-- <Combobox.Dropdown>- {groups.length === 0 ? (- <Box p="sm">{emptyListMessage}</Box>- ) : (- <Combobox.Options>- {sections.map((section, index) => {- const options = section.items.map((group) => (- <Combobox.Option- key={group.id}- value={String(group.id)}- aria-label={getGroupNameLocalized(group)}- disabled={- (isAdminGroup(group) && isCurrentUser) ||- !canEditMembership(group)- }- >- <Flex align="center" gap="sm">- <Checkbox- checked={selectedGroupIds.includes(group.id)}- readOnly- aria-hidden- tabIndex={-1}- style={{ pointerEvents: "none" }}- />- <span style={{ color: getGroupColor(group) }}>- {getGroupNameLocalized(group)}- </span>- </Flex>- </Combobox.Option>- ));-- return "name" in section ? (- <Combobox.Group key={index} label={section.name}>- {options}- </Combobox.Group>- ) : (- <Fragment key={index}>{options}</Fragment>- );- })}- </Combobox.Options>- )}- </Combobox.Dropdown>- </Combobox>- );-};diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/index.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/index.tsxdeleted file mode 100644index cb8dfbf2811..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/index.tsx+++ /dev/null@@ -1 +0,0 @@-export * from "./GroupSelect";diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.module.css b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.module.cssdeleted file mode 100644index 5de311a61ae..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.module.css+++ /dev/null@@ -1,7 +0,0 @@-.deleteButton {- color: var(--mb-color-text-primary);-}--.deleteButton:hover {- color: var(--mb-color-feedback-negative);-}diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsxdeleted file mode 100644index cafeb640055..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx+++ /dev/null@@ -1,188 +0,0 @@-import { useDisclosure } from "@mantine/hooks";-import { t } from "ttag";-import _ from "underscore";--import type {- DeleteMappingModalValueType,- GroupIds,-} from "metabase/admin/types";-import { ConfirmModal } from "metabase/common/components/ConfirmModal";-import { IconButtonWrapper } from "metabase/common/components/IconButtonWrapper";-import { isAdminGroup } from "metabase/common/utils/groups";-import AdminS from "metabase/css/admin.module.css";-import { Flex, Icon, Tooltip } from "metabase/ui";-import type { GroupId, GroupInfo } from "metabase-types/api";--import { DeleteGroupMappingModal } from "../DeleteGroupMappingModal";-import { GroupSelect } from "../GroupSelect";--import S from "./MappingRow.module.css";--type OnDeleteMappingType = (arg: {- name: string;- groupIdsToDelete?: GroupIds;- onSuccess?: () => void;-}) => void;--type MappingRowProps = {- name: string;- groups: GroupInfo[];- selectedGroupIds: GroupIds;- clearGroupMember: ({ id }: { id: number }) => void;- deleteGroup: ({ id }: { id: number }) => void;- onChange: (group: { id: GroupId }, selected: boolean) => void;- onDeleteMapping: OnDeleteMappingType;-};--export const MappingRow = ({- name,- groups,- selectedGroupIds,- clearGroupMember,- deleteGroup,- onChange,- onDeleteMapping,-}: MappingRowProps) => {- const [- deleteGroupMappingModalOpened,- { open: openDeleteGroupMappingModal, close: closeDeleteGroupMappingModal },- ] = useDisclosure();- const [- deleteMappingModalOpened,- { open: openDeleteMappingModal, close: closeDeleteMappingModal },- ] = useDisclosure();-- // Mappings may receive group ids even from the back-end- // if the groups themselves have been deleted.- // Let's ensure this row works with the ones that exist.- const selectedGroupIdsFromGroupsThatExist = selectedGroupIds.filter((id) =>- _.findWhere(groups, { id: id }),- );-- const handleConfirmDeleteMapping = (- whatToDoAboutGroups: DeleteMappingModalValueType,- groups: GroupIds,- ) => {- const onSuccess = getCallbackForGroupsAfterDeletingMapping(- whatToDoAboutGroups,- groups,- );-- const groupIdsToDelete =- whatToDoAboutGroups === "delete" ? selectedGroupIds : [];-- onDeleteMapping({ name, onSuccess, groupIdsToDelete });- };-- const getCallbackForGroupsAfterDeletingMapping = (- whatToDoAboutGroups: DeleteMappingModalValueType,- groupIds: GroupIds,- ) => {- switch (whatToDoAboutGroups) {- case "clear":- return () =>- Promise.all(- groupIds.map(async (id) => {- try {- const group = groups.find((group) => group.id === id);- if (group && !isAdminGroup(group)) {- await clearGroupMember({ id });- }- } catch (error) {- console.error(error);- }- }),- );- case "delete":- return () =>- Promise.all(- groupIds.map(async (id) => {- try {- const group = groups.find((group) => group.id === id);- if (group && !isAdminGroup(group)) {- await deleteGroup({ id });- }- } catch (error) {- console.error(error);- }- }),- );- default:- return () => null;- }- };-- const firstGroupInMapping = groups.find(- (group) => group.id === selectedGroupIdsFromGroupsThatExist[0],- );-- const isMappingLinkedOnlyToAdminGroup =- groups.length > 0 &&- selectedGroupIdsFromGroupsThatExist.length === 1 &&- firstGroupInMapping &&- isAdminGroup(firstGroupInMapping);-- const shouldUseDeleteGroupMappingModal =- selectedGroupIdsFromGroupsThatExist.length > 0 &&- !isMappingLinkedOnlyToAdminGroup;-- const hasAdminGroup = groups.some(- (group) => isAdminGroup(group) && selectedGroupIds.includes(group.id),- );-- return (- <>- <tr>- <td>{name}</td>- <td>- <GroupSelect- groups={groups}- selectedGroupIds={selectedGroupIdsFromGroupsThatExist}- onGroupChange={onChange}- />- </td>- <td className={AdminS.TableActions}>- <Flex justify="flex-end" mr="sm">- <DeleteButton- onDelete={() =>- shouldUseDeleteGroupMappingModal- ? openDeleteGroupMappingModal()- : openDeleteMappingModal()- }- />- </Flex>- </td>- </tr>- <ConfirmModal- opened={deleteMappingModalOpened}- title={t`Delete this mapping?`}- onClose={closeDeleteMappingModal}- onConfirm={() => {- onDeleteMapping({ name });- closeDeleteMappingModal();- }}- />- {deleteGroupMappingModalOpened && (- <DeleteGroupMappingModal- name={name}- groupIds={selectedGroupIds}- hasAdminGroup={hasAdminGroup}- onHide={closeDeleteGroupMappingModal}- onConfirm={handleConfirmDeleteMapping}- />- )}- </>- );-};--const DeleteButton = ({- onDelete,-}: {- onDelete?: React.MouseEventHandler<HTMLButtonElement>;-}) => (- <Tooltip label={t`Remove mapping`} position="top">- <IconButtonWrapper className={S.deleteButton} onClick={onDelete}>- <Icon name="close" />- </IconButtonWrapper>- </Tooltip>-);diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/index.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/index.tsxdeleted file mode 100644index 58045f52dfb..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/index.tsx+++ /dev/null@@ -1 +0,0 @@-export * from "./MappingRow";diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/index.ts b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/index.tsdeleted file mode 100644index e4c69d678ba..00000000000--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./GroupMappingsWidget";diff --git a/frontend/src/metabase/admin/settings/tests/setup.tsx b/frontend/src/metabase/admin/settings/tests/setup.tsxindex cc43ff3c682..ec48c2479c0 100644--- a/frontend/src/metabase/admin/settings/tests/setup.tsx+++ b/frontend/src/metabase/admin/settings/tests/setup.tsx@@ -89,7 +89,7 @@ export const enterpriseRoutes: RouteMap = {export const premiumRoutes: RouteMap = {saml: {path: "/authentication/saml",- testPattern: /Configure your identity provider/i,+ testPattern: /Identity provider \(IdP\) configuration/i,},jwt: { path: "/authentication/jwt", testPattern: /Server Settings/i },};diff --git a/frontend/src/metabase/admin/settings/utils.ts b/frontend/src/metabase/admin/settings/utils.tsindex b826f0f55df..43e5486ab70 100644--- a/frontend/src/metabase/admin/settings/utils.ts+++ b/frontend/src/metabase/admin/settings/utils.ts@@ -1,7 +1,12 @@+import type { FormikHelpers } from "formik";import { t } from "ttag";import { useDocsUrl } from "metabase/common/hooks";-import type { SettingDefinition } from "metabase-types/api";+import type {+ EnterpriseSettingKey,+ EnterpriseSettingValue,+ SettingDefinition,+} from "metabase-types/api";export const useGetEnvVarDocsUrl = (envName: string | undefined) => {return useDocsUrl("configuring-metabase/environment-variables", {@@ -32,6 +37,10 @@ export const getExtraFormFieldProps = (setting?: SettingDefinition) => {};};+/** Spread after a field's props: an env-managed setting turns readOnly and shows "Using MB_..." as its description */+export const getEnvNoticeProps = (setting?: SettingDefinition) =>+ setting?.is_env_setting ? getExtraFormFieldProps(setting) : {};+// env-locked settings show the readOnly notice instead of a placeholderexport const getDefaultPlaceholder = (setting?: SettingDefinition,@@ -41,3 +50,28 @@ export const getDefaultPlaceholder = (}return setting.default;};++/** A field's initial value: empty when unset, so the default shows as the placeholder; the env value when env-locked */+export const getStoredFieldValue = <Key extends EnterpriseSettingKey>(+ setting: SettingDefinition<Key> | undefined,+ envValue: EnterpriseSettingValue<Key> | undefined,+): NonNullable<EnterpriseSettingValue<Key>> | null => {+ if (setting?.is_env_setting) {+ return envValue ?? null;+ }+ return setting?.value ?? null;+};++/** Puts fields a card just hid back to their saved values, so an unsaved edit never rides along on the next save */+export const resetFieldsToInitial = <Values extends object>(+ setFieldValue: FormikHelpers<Values>["setFieldValue"],+ initialValues: Values,+ fieldNames: (keyof Values & string)[],+) => {+ for (const name of fieldNames) {+ // a key can be missing from the form, like the EE-only membership filter on OSS+ if (name in initialValues) {+ setFieldValue(name, initialValues[name]);+ }+ }+};diff --git a/frontend/src/metabase/admin/types.ts b/frontend/src/metabase/admin/types.tsdeleted file mode 100644index 64bc232490d..00000000000--- a/frontend/src/metabase/admin/types.ts+++ /dev/null@@ -1,5 +0,0 @@-export type MappingsType = Record<string, number[]>;-export type GroupIds = number[];-export type DeleteMappingModalValueType = "nothing" | "clear" | "delete";-export type UserGroupType = { id: number; name: string; member_count?: number };-export type UserGroupsType = UserGroupType[];diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex 6ac4e8406b2..18ac210734f 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -10,7 +10,6 @@ export {PLUGIN_ADMIN_USER_FORM_FIELDS,type AuthSettingsPageProps,type AuthSettingsPageTab,- type LdapUserProvisioningProps,} from "./oss/auth";export {PLUGIN_CACHING,diff --git a/frontend/src/metabase/plugins/oss/auth.ts b/frontend/src/metabase/plugins/oss/auth.tsindex 58d8425a276..5e03bd491b8 100644--- a/frontend/src/metabase/plugins/oss/auth.ts+++ b/frontend/src/metabase/plugins/oss/auth.ts@@ -33,12 +33,8 @@ export const PLUGIN_AUTH_PROVIDERS = definePluginSlot(getDefaultPluginAuthProviders,);-export type LdapUserProvisioningProps = {- disabled?: boolean;-};-const getDefaultPluginLdapFormFields = () => ({- LdapUserProvisioning: PluginPlaceholder<LdapUserProvisioningProps>,+ LdapUserProvisioning: PluginPlaceholder,LdapGroupMembershipFilter: PluginPlaceholder,});diff --git a/frontend/src/metabase/settings-components/SettingsSection/CollapsibleSettingsSection.tsx b/frontend/src/metabase/settings-components/SettingsSection/CollapsibleSettingsSection.tsxnew file mode 100644index 00000000000..c237f347366--- /dev/null+++ b/frontend/src/metabase/settings-components/SettingsSection/CollapsibleSettingsSection.tsx@@ -0,0 +1,67 @@+import cx from "classnames";+import type React from "react";+import { useState } from "react";++import { Accordion, Box, type BoxProps, Icon, Text } from "metabase/ui";++import { SETTINGS_CARD_DESCRIPTION_PROPS } from "./SettingsSection";+import S from "./SettingsSection.module.css";++const COLLAPSIBLE_SECTION_VALUE = "section";++export function CollapsibleSettingsSection({+ title,+ description,+ defaultOpened = false,+ disabled = false,+ children,+ className,+ ...boxProps+}: {+ title: React.ReactNode;+ description?: React.ReactNode;+ defaultOpened?: boolean;+ // greys the card out, keeps it closed and keeps it from toggling+ disabled?: boolean;+ children?: React.ReactNode;+} & BoxProps) {+ // a card that defaults open while disabled opens once it is enabled+ const [isOpened, setIsOpened] = useState(defaultOpened);+ return (+ <Accordion+ className={cx(+ S.CollapsibleAccordion,+ disabled && S.DisabledSection,+ className,+ )}+ classNames={{+ item: S.CollapsibleItem,+ control: S.CollapsibleControl,+ label: S.CollapsibleLabel,+ chevron: S.CollapsibleChevron,+ content: S.CollapsibleContent,+ panel: S.CollapsiblePanel,+ }}+ chevron={<Icon aria-hidden name="chevrondown" />}+ order={2}+ value={isOpened && !disabled ? COLLAPSIBLE_SECTION_VALUE : null}+ onChange={(value) => setIsOpened(value != null)}+ {...boxProps}+ >+ <Accordion.Item value={COLLAPSIBLE_SECTION_VALUE}>+ {/* the header wrapper anchors the control's stretched hit area, so+ the whole header row toggles while the description stays outside+ the control button and out of its accessible name */}+ <Box className={S.CollapsibleHeader}>+ <Accordion.Control disabled={disabled}>{title}</Accordion.Control>+ {description && (+ <Text c="text-secondary" {...SETTINGS_CARD_DESCRIPTION_PROPS}>+ {description}+ </Text>+ )}+ </Box>+ <Accordion.Panel>{children}</Accordion.Panel>+ </Accordion.Item>+ </Accordion>+ );+}diff --git a/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.unit.spec.tsx b/frontend/src/metabase/settings-components/SettingsSection/CollapsibleSettingsSection.unit.spec.tsxsimilarity index 97%rename from frontend/src/metabase/settings-components/SettingsSection/SettingsSection.unit.spec.tsxrename to frontend/src/metabase/settings-components/SettingsSection/CollapsibleSettingsSection.unit.spec.tsxindex 005fccc88e0..13dcc590fe8 100644--- a/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.unit.spec.tsx+++ b/frontend/src/metabase/settings-components/SettingsSection/CollapsibleSettingsSection.unit.spec.tsx@@ -2,7 +2,7 @@ import userEvent from "@testing-library/user-event";import { renderWithProviders, screen, waitFor } from "__support__/ui";-import { CollapsibleSettingsSection } from "./SettingsSection";+import { CollapsibleSettingsSection } from "./CollapsibleSettingsSection";type SetupOptions = { defaultOpened?: boolean; disabled?: boolean };diff --git a/frontend/src/metabase/settings-components/SettingsSection/SettingsPageWrapper.tsx b/frontend/src/metabase/settings-components/SettingsSection/SettingsPageWrapper.tsxnew file mode 100644index 00000000000..459bddf8b3d--- /dev/null+++ b/frontend/src/metabase/settings-components/SettingsSection/SettingsPageWrapper.tsx@@ -0,0 +1,44 @@+import type React from "react";++import {+ Stack,+ type StackProps,+ Text,+ type TextProps,+ Title,+} from "metabase/ui";++import S from "./SettingsSection.module.css";++export function SettingsPageWrapper({+ title,+ description,+ descriptionProps,+ children,+ ...stackProps+}: {+ title?: React.ReactNode;+ description?: React.ReactNode;+ descriptionProps?: TextProps;+ children: React.ReactNode;+} & Omit<StackProps, "title">) {+ return (+ <Stack gap="xl" {...stackProps}>+ {(title || description) && (+ <Stack gap="sm">+ {title && (+ <Title order={1} display="flex" className={S.PageTitle}>+ {title}+ </Title>+ )}+ {description && (+ <Text c="text-secondary" lh={1.5} maw="40rem" {...descriptionProps}>+ {description}+ </Text>+ )}+ </Stack>+ )}+ {children}+ </Stack>+ );+}diff --git a/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.module.css b/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.module.cssindex 2a3e4250183..4177b69eb31 100644--- a/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.module.css+++ b/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.module.css@@ -104,3 +104,7 @@.CollapsibleAccordion .CollapsibleControl:disabled::after {cursor: default;}++.TitleLabel {+ cursor: pointer;+}diff --git a/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.tsx b/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.tsxindex 5aab64f1b7e..cf8b1d70bfb 100644--- a/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.tsx+++ b/frontend/src/metabase/settings-components/SettingsSection/SettingsSection.tsx@@ -1,12 +1,9 @@import cx from "classnames";import type React from "react";-import { useState } from "react";import {- Accordion,Box,type BoxProps,- Icon,Stack,type StackProps,Text,@@ -81,95 +78,3 @@ export function SettingsSection({</Box>);}--const COLLAPSIBLE_SECTION_VALUE = "section";--export function CollapsibleSettingsSection({- title,- description,- defaultOpened = false,- disabled = false,- children,- className,- ...boxProps-}: {- title: React.ReactNode;- description?: React.ReactNode;- defaultOpened?: boolean;- // greys the card out, keeps it closed and keeps it from toggling- disabled?: boolean;- children?: React.ReactNode;-} & BoxProps) {- // a card that defaults open while disabled opens once it is enabled- const [isOpened, setIsOpened] = useState(defaultOpened);- return (- <Accordion- className={cx(- S.CollapsibleAccordion,- disabled && S.DisabledSection,- className,- )}- classNames={{- item: S.CollapsibleItem,- control: S.CollapsibleControl,- label: S.CollapsibleLabel,- chevron: S.CollapsibleChevron,- content: S.CollapsibleContent,- panel: S.CollapsiblePanel,- }}- chevron={<Icon aria-hidden name="chevrondown" />}- order={2}- value={isOpened && !disabled ? COLLAPSIBLE_SECTION_VALUE : null}- onChange={(value) => setIsOpened(value != null)}- {...boxProps}- >- <Accordion.Item value={COLLAPSIBLE_SECTION_VALUE}>- {/* the header wrapper anchors the control's stretched hit area, so- the whole header row toggles while the description stays outside- the control button and out of its accessible name */}- <Box className={S.CollapsibleHeader}>- <Accordion.Control disabled={disabled}>{title}</Accordion.Control>- {description && (- <Text c="text-secondary" {...SETTINGS_CARD_DESCRIPTION_PROPS}>- {description}- </Text>- )}- </Box>- <Accordion.Panel>{children}</Accordion.Panel>- </Accordion.Item>- </Accordion>- );-}--export function SettingsPageWrapper({- title,- description,- descriptionProps,- children,- ...stackProps-}: {- title?: React.ReactNode;- description?: React.ReactNode;- descriptionProps?: TextProps;- children: React.ReactNode;-} & Omit<StackProps, "title">) {- return (- <Stack gap="xl" {...stackProps}>- {(title || description) && (- <Stack gap="sm">- {title && (- <Title order={1} display="flex" className={S.PageTitle}>- {title}- </Title>- )}- {description && (- <Text c="text-secondary" lh={1.5} maw="40rem" {...descriptionProps}>- {description}- </Text>- )}- </Stack>- )}- {children}- </Stack>- );-}diff --git a/frontend/src/metabase/settings-components/SettingsSection/SwitchSettingsSection.tsx b/frontend/src/metabase/settings-components/SettingsSection/SwitchSettingsSection.tsxnew file mode 100644index 00000000000..6b4626fe0e3--- /dev/null+++ b/frontend/src/metabase/settings-components/SettingsSection/SwitchSettingsSection.tsx@@ -0,0 +1,115 @@+import type React from "react";+import { useId } from "react";+import { t } from "ttag";++import {+ Box,+ type BoxProps,+ Flex,+ Stack,+ Switch,+ Text,+ Title,+} from "metabase/ui";++import {+ SETTINGS_CARD_DESCRIPTION_PROPS,+ SETTINGS_CARD_STACK_PROPS,+ SETTINGS_CARD_TITLE_PROPS,+ SettingsSection,+} from "./SettingsSection";+import S from "./SettingsSection.module.css";++type SwitchSettingsSectionProps = {+ title: string;+ description: React.ReactNode;+ note?: React.ReactNode;+ checked: boolean;+ disabled?: boolean;+ // locks only the switch and keeps it focusable, so focus survives a write+ switchDisabled?: boolean;+ lockedEnvName?: string;+ onChange: (checked: boolean) => void;+ children?: React.ReactNode;+} & BoxProps;++/** A settings card whose title doubles as the label of a switch, revealing its children while on */+export function SwitchSettingsSection({+ title,+ description,+ note,+ checked,+ disabled = false,+ switchDisabled = false,+ lockedEnvName,+ onChange,+ children,+ ...boxProps+}: SwitchSettingsSectionProps) {+ const inputId = useId();+ const descriptionId = useId();+ const isSwitchLocked = switchDisabled || lockedEnvName != null;++ const handleChange = (nextChecked: boolean) => {+ if (isSwitchLocked) {+ return;+ }+ onChange(nextChecked);+ };++ // Enter would otherwise submit the page form the card sits in+ 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={disabled || isSwitchLocked ? undefined : S.TitleLabel}+ inherit+ >+ {title}+ </Text>+ </Title>+ <Box id={descriptionId}>+ <Text c="text-secondary" {...SETTINGS_CARD_DESCRIPTION_PROPS}>+ {description}+ </Text>+ {lockedEnvName != null && (+ <Text+ c="text-secondary"+ mt="sm"+ >{t`Using ${lockedEnvName}`}</Text>+ )}+ {note && (+ <Text c="text-secondary" mt="sm">+ {note}+ </Text>+ )}+ </Box>+ </Box>+ <Switch+ id={inputId}+ aria-describedby={descriptionId}+ checked={checked}+ disabled={disabled}+ aria-disabled={isSwitchLocked || undefined}+ onChange={(event) => handleChange(event.currentTarget.checked)}+ onKeyDown={handleKeyDown}+ />+ </Flex>+ {checked && !disabled && children && <Stack gap="lg">{children}</Stack>}+ </SettingsSection>+ );+}diff --git a/frontend/src/metabase/settings-components/SettingsSection/SwitchSettingsSection.unit.spec.tsx b/frontend/src/metabase/settings-components/SettingsSection/SwitchSettingsSection.unit.spec.tsxnew file mode 100644index 00000000000..da7efca992d--- /dev/null+++ b/frontend/src/metabase/settings-components/SettingsSection/SwitchSettingsSection.unit.spec.tsx@@ -0,0 +1,92 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen } from "__support__/ui";++import { SwitchSettingsSection } from "./SwitchSettingsSection";++type SetupOptions = {+ checked?: boolean;+ switchDisabled?: boolean;+ note?: React.ReactNode;+};++const onChange = jest.fn();++const getSection = ({+ checked = false,+ switchDisabled,+ note,+}: SetupOptions = {}) => (+ <SwitchSettingsSection+ title="Group mapping"+ description="Assign people to groups automatically"+ note={note}+ checked={checked}+ switchDisabled={switchDisabled}+ onChange={onChange}+ >+ <div>Mapping editor</div>+ </SwitchSettingsSection>+);++const getSwitch = () => screen.getByRole("switch", { name: "Group mapping" });++describe("SwitchSettingsSection", () => {+ afterEach(() => {+ jest.clearAllMocks();+ });++ it("puts the description and the note on the switch as its accessible description", () => {+ renderWithProviders(getSection({ note: "SCIM manages provisioning" }));++ expect(+ screen.getByRole("heading", { name: "Group mapping" }),+ ).toBeInTheDocument();+ expect(getSwitch()).toHaveAccessibleDescription(+ /Assign people to groups automatically/,+ );+ expect(getSwitch()).toHaveAccessibleDescription(+ /SCIM manages provisioning/,+ );+ });++ it("locks the switch on its own without taking its focus away", async () => {+ const { rerender } = renderWithProviders(+ getSection({ checked: true, switchDisabled: true }),+ );+ const toggle = getSwitch();+ toggle.focus();++ expect(toggle).toBeEnabled();+ expect(toggle).toHaveAttribute("aria-disabled", "true");+ expect(screen.getByText("Mapping editor")).toBeInTheDocument();++ await userEvent.click(toggle);++ expect(onChange).not.toHaveBeenCalled();+ expect(toggle).toHaveFocus();++ rerender(getSection({ checked: true, switchDisabled: false }));++ expect(toggle).not.toHaveAttribute("aria-disabled");+ expect(toggle).toHaveFocus();+ });++ it("keeps Enter from submitting the form the card sits in", async () => {+ const onSubmit = jest.fn((event: React.FormEvent) =>+ event.preventDefault(),+ );+ // Enter on a checkbox submits through the form's submit button, so the form needs one+ renderWithProviders(+ <form onSubmit={onSubmit}>+ {getSection()}+ <button type="submit">Save</button>+ </form>,+ );++ getSwitch().focus();+ await userEvent.keyboard("{Enter}");++ expect(onSubmit).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/metabase/settings-components/SettingsSection/index.ts b/frontend/src/metabase/settings-components/SettingsSection/index.tsindex bbcde8c4373..4bb2e2d6eab 100644--- a/frontend/src/metabase/settings-components/SettingsSection/index.ts+++ b/frontend/src/metabase/settings-components/SettingsSection/index.ts@@ -1 +1,4 @@+export * from "./CollapsibleSettingsSection";+export * from "./SettingsPageWrapper";export * from "./SettingsSection";+export * from "./SwitchSettingsSection";diff --git a/frontend/src/metabase/settings-components/index.ts b/frontend/src/metabase/settings-components/index.tsindex 745a0cc787d..c5273a76675 100644--- a/frontend/src/metabase/settings-components/index.ts+++ b/frontend/src/metabase/settings-components/index.ts@@ -13,4 +13,5 @@ export {SETTINGS_CARD_TITLE_PROPS,SettingsPageWrapper,SettingsSection,+ SwitchSettingsSection,} from "./SettingsSection";diff --git a/frontend/src/metabase/settings/index.ts b/frontend/src/metabase/settings/index.tsindex fde5882de17..a5831ea408c 100644--- a/frontend/src/metabase/settings/index.ts+++ b/frontend/src/metabase/settings/index.ts@@ -22,6 +22,7 @@ export {} from "./selectors";export { useAdminSetting, useAdminSettings } from "./use-admin-setting";export { useSetting, useUserSetting } from "./use-setting";+export { useSettingSwitch } from "./use-setting-switch";export { useTokenRefresh, useTokenRefreshUntil } from "./use-token-refresh";export {getPlan,diff --git a/frontend/src/metabase/settings/use-setting-switch.ts b/frontend/src/metabase/settings/use-setting-switch.tsnew file mode 100644index 00000000000..7cd7c91eb00--- /dev/null+++ b/frontend/src/metabase/settings/use-setting-switch.ts@@ -0,0 +1,68 @@+import { useDispatch } from "metabase/redux";+import type {+ EnterpriseSettingKey,+ EnterpriseSettings,+} from "metabase-types/api";++import { settingsApi } from "./api";+import { useAdminSetting } from "./use-admin-setting";++type BooleanSettingKey = {+ [Key in EnterpriseSettingKey]: EnterpriseSettings[Key] extends+ | boolean+ | null+ | undefined+ ? Key+ : never;+}[EnterpriseSettingKey];++export type SettingSwitchState = {+ checked: boolean;+ envName: string | undefined;+ isBusy: boolean;+ onChange: (enabled: boolean) => Promise<void>;+};++/** A switch that writes its boolean setting at once: the click shows immediately and is undone if the write fails */+export function useSettingSwitch(+ settingKey: BooleanSettingKey,+ { onToggle }: { onToggle?: (enabled: boolean) => void } = {},+): SettingSwitchState {+ const dispatch = useDispatch();+ const {+ value,+ settingDetails,+ updateSetting,+ updateSettingResult,+ isFetching,+ } = useAdminSetting(settingKey);+ const envName = settingDetails?.is_env_setting+ ? settingDetails.env_name+ : undefined;++ const onChange = async (enabled: boolean) => {+ const patch = dispatch(+ settingsApi.util.updateQueryData(+ "getSessionProperties",+ undefined,+ (draft) => {+ draft[settingKey] = enabled;+ },+ ),+ );+ const { error } = await updateSetting({ key: settingKey, value: enabled });+ if (error) {+ patch.undo();+ } else {+ onToggle?.(enabled);+ }+ };++ return {+ checked: value ?? false,+ envName,+ // a fetch still in flight could answer with the value from before the write+ isBusy: isFetching || updateSettingResult.isLoading,+ onChange,+ };+}diff --git a/frontend/src/metabase/ui/components/inputs/Switch/Switch.module.css b/frontend/src/metabase/ui/components/inputs/Switch/Switch.module.cssindex d4a81cbfc14..f6113475c6d 100644--- a/frontend/src/metabase/ui/components/inputs/Switch/Switch.module.css+++ b/frontend/src/metabase/ui/components/inputs/Switch/Switch.module.css@@ -13,7 +13,7 @@margin-bottom: 0;}- &:has(input:disabled) {+ &:has(input:disabled, input[aria-disabled="true"]) {.label,.description {color: var(--mb-color-text-disabled);@@ -61,7 +61,8 @@background-color: var(--mb-color-switch-checked);}- input:disabled + & {+ input:disabled + &,+ input[aria-disabled="true"] + & {background-color: var(--mb-color-switch-disabled);border-color: transparent;cursor: not-allowed;@@ -72,7 +73,8 @@background-color: var(--mb-color-core-white_constant);box-shadow: var(--mantine-shadow-sm_outline);- input:disabled + * > & {+ input:disabled + * > &,+ input[aria-disabled="true"] + * > & {background-color: var(--mb-color-switch_thumb-disabled);box-shadow: none;}diff --git a/frontend/test/__support__/server-mocks/settings.ts b/frontend/test/__support__/server-mocks/settings.tsindex fe0b3485f49..76e8d951c18 100644--- a/frontend/test/__support__/server-mocks/settings.ts+++ b/frontend/test/__support__/server-mocks/settings.ts@@ -48,12 +48,14 @@ export function setupUpdateSettingEndpoint(*/export function setupStatefulSettingsEndpoints(initialSettings: Partial<EnterpriseSettings> | Record<string, unknown>,+ { updateDelay, readDelay }: { updateDelay?: number; readDelay?: number } = {},) {const store: Record<string, unknown> = { ...initialSettings };fetchMock.removeRoute("get-session-properties");fetchMock.get("path:/api/session/properties", () => ({ ...store }), {name: "get-session-properties",+ delay: readDelay,});fetchMock.removeRoute("update-setting");@@ -65,7 +67,7 @@ export function setupStatefulSettingsEndpoints(store[key] = value;return { status: 204 };},- { name: "update-setting" },+ { name: "update-setting", delay: updateDelay },);fetchMock.removeRoute("update-settings");@@ -75,7 +77,7 @@ export function setupStatefulSettingsEndpoints(Object.assign(store, JSON.parse(String(options.body)));return { status: 204 };},- { name: "update-settings" },+ { name: "update-settings", delay: updateDelay },);return store;