Skip to content

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

Support Group Sync in OIDC (#71176)

Nathan Voxland28093ce8030b
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj b/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj
index 7377db655e8..ce2cb74cb70 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/oidc.clj
@@ -67,8 +67,10 @@
Obfuscates the client-secret and ensures keys are strings."
[provider]
(cond-> provider
- (:client-secret provider) (update :client-secret setting/obfuscate-value)
- (:attribute-map provider) (update :attribute-map walk/stringify-keys)))
+ (:client-secret provider) (update :client-secret setting/obfuscate-value)
+ (:attribute-map provider) (update :attribute-map walk/stringify-keys)
+ (get-in provider [:group-sync :group-mappings])
+ (update-in [:group-sync :group-mappings] walk/stringify-keys)))
(defn- check-oidc-connection!
"Run OIDC configuration check and throw a 400 if it fails. Returns the check result on success."
diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj
index 0ed8a060fc5..7eb5501bcf2 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/oidc.clj
@@ -94,17 +94,19 @@
;; Handle group sync if configured
(when-let [provider-key (:oidc-provider-key result)]
(when-let [provider-config (sso-settings/get-oidc-provider provider-key)]
- (when (get-in provider-config [:group-sync :enabled])
- (let [group-attribute (get-in provider-config [:group-sync :group-attribute])
- group-mappings (get-in provider-config [:group-sync :group-mappings])
- claims (:claims result)
- user-groups (when (and claims group-attribute)
- (get claims (keyword 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)))))))))
+ (let [group-sync-config (get provider-config :group-sync)]
+ (when (:enabled group-sync-config)
+ (let [group-attribute (get group-sync-config :group-attribute)
+ group-mappings (get group-sync-config :group-mappings)
+ claims (:claims result)
+ user-groups (when (and claims group-attribute)
+ (or (get claims (keyword group-attribute))
+ (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))))))))))
result)
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj
index 7f5b4973dd2..c34c6cf91e8 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/oidc_test.clj
@@ -11,7 +11,8 @@
[metabase.test.http-client :as client]
[metabase.util.encryption :as encryption]
[methodical.core :as methodical]
- [ring.util.codec :as codec]))
+ [ring.util.codec :as codec]
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -183,3 +184,206 @@
(:status (mt/client-full-response :get 400 "/auth/sso/test-idp"
{:request-options {:redirect-strategy :none}}
:redirect redirect-uri))))))))))
+
+;;; -------------------------------------------------- Group Sync Tests --------------------------------------------------
+
+(def ^:private ^:dynamic *group-sync-claims*
+ "Dynamic var to control what claims the group sync mock returns."
+ {:groups ["test-group"]})
+
+(def ^:private ^:dynamic *group-sync-email*
+ "Dynamic var to control the email returned by the group sync mock."
+
+;; Mock that returns claims with group membership
+(methodical/defmethod auth-identity/authenticate :provider/test-oidc-with-groups
+ [_provider request]
+ (if (some #(contains? request %) [:code :error :state])
+ {:success? true
+ :claims *group-sync-claims*
+ :user-data {:email *group-sync-email*
+ :first_name "OIDC"
+ :last_name "GroupUser"}
+ :provider-id "test-oidc-provider-id"}
+ {:success? :redirect
+ :redirect-url "https://test.idp.example.com/authorize"
+ :state "test-state"
+ :nonce "test-nonce"}))
+
+(methodical/prefer-method! #'auth-identity/authenticate :provider/test-oidc-with-groups :provider/oidc)
+
+(defmacro ^:private with-group-sync-oidc! [& body]
+ `(do
+ (derive :provider/custom-oidc :provider/test-oidc-with-groups)
+ (try
+ ~@body
+ (finally
+ (underive :provider/custom-oidc :provider/test-oidc-with-groups)))))
+
+(defn- do-with-group-sync-login!
+ "Helper that sets up the OIDC provider with group sync config, performs a login, and calls `f`
+ with the login result."
+ [provider-config claims email f]
+ (mt/test-helpers-set-global-values!
+ (mt/with-premium-features #{:audit-app}
+ (sso.test-setup/do-with-other-sso-types-disabled!
+ (fn []
+ (mt/with-additional-premium-features #{:sso-oidc}
+ (sso.test-setup/call-with-login-attributes-cleared!
+ (fn []
+ (mt/with-temporary-setting-values
+ [oidc-providers [provider-config]]
+ (binding [*group-sync-claims* claims
+ *group-sync-email* email]
+ (with-group-sync-oidc!
+ (with-redefs [oidc.state/validate-oidc-callback
+ (fn [_request _state _provider & _opts]
+ {:valid? true :nonce "test-nonce" :redirect "/"})]
+ (let [result (auth-identity/login!
+ :provider/custom-oidc
+ {:oidc-provider-key "test-idp"
+ :code "test-code"
+ :state "test-state"})]
+ (f result))))))))))))))
+
+(deftest oidc-group-sync-test
+ (testing "OIDC login with group sync enabled adds user to mapped groups"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name (str "OIDC Test Group " (random-uuid))}]
+ (let [provider-config (assoc test-provider
+ :group-sync {:enabled true
+ :group-attribute "groups"
+ :group-mappings {:test-group [group-id]}})]
+ (do-with-group-sync-login!
+ provider-config {:groups ["test-group"]} "[email protected]"
+ (fn [result]
+ (is (true? (:success? result)) (str "login result: " (pr-str result)))
+ (testing "user is added to the mapped group"
+ (let [user (t2/select-one :model/User :%lower.email "[email protected]")]
+ (is (some? user))
+ (is (contains?
+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (:id user))
+ group-id))))))))))
+
+(deftest oidc-group-sync-disabled-test
+ (testing "Group sync disabled — should not sync even with mappings configured"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name (str "OIDC No-Sync Group " (random-uuid))}]
+ (let [email (str "oidc-nosync-" (random-uuid) "@example.com")
+ provider-config (assoc test-provider
+ :group-sync {:enabled false
+ :group-attribute "groups"
+ :group-mappings {:test-group [group-id]}})]
+ (do-with-group-sync-login!
+ provider-config {:groups ["test-group"]} email
+ (fn [result]
+ (is (true? (:success? result)))
+ (testing "user is NOT added to the mapped group because sync is disabled"
+ (let [user (t2/select-one :model/User :%lower.email email)]
+ (is (some? user))
+ (is (not (contains?
+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (:id user))
+ group-id)))))))))))
+
+(deftest oidc-group-sync-no-mappings-test
+ (testing "No mappings configured — should not add user to any extra groups"
+ (let [email (str "oidc-nomap-" (random-uuid) "@example.com")
+ 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)))
+ (testing "user exists but only has the All Users group"
+ (let [user (t2/select-one :model/User :%lower.email email)]
+ (is (some? user))
+ ;; 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-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))}]
+ (let [email (str "oidc-strgrp-" (random-uuid) "@example.com")
+ provider-config (assoc test-provider
+ :group-sync {:enabled true
+ :group-attribute "groups"
+ :group-mappings {:single-group [group-id]}})]
+ (do-with-group-sync-login!
+ provider-config {:groups "single-group"} email
+ (fn [result]
+ (is (true? (:success? result)))
+ (testing "user is added to the mapped group even with a string claim value"
+ (let [user (t2/select-one :model/User :%lower.email email)]
+ (is (some? user))
+ (is (contains?
+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (:id user))
+ group-id))))))))))
+
+(deftest oidc-group-sync-removal-test
+ (testing "Group removal — user removed from old mapped groups on re-login"
+ (mt/with-temp [:model/PermissionsGroup {group-a-id :id} {:name (str "OIDC Group A " (random-uuid))}
+ :model/PermissionsGroup {group-b-id :id} {:name (str "OIDC Group B " (random-uuid))}]
+ (let [email (str "oidc-removal-" (random-uuid) "@example.com")
+ provider-config (assoc test-provider
+ :group-sync {:enabled true
+ :group-attribute "groups"
+ :group-mappings {:group-a [group-a-id]
+ :group-b [group-b-id]}})]
+ ;; First login: user has both groups
+ (do-with-group-sync-login!
+ provider-config {:groups ["group-a" "group-b"]} email
+ (fn [result]
+ (is (true? (:success? result)))
+ (let [user (t2/select-one :model/User :%lower.email email)]
+ (is (some? user))
+ (let [group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (:id user))]
+ (is (contains? group-ids group-a-id))
+ (is (contains? group-ids group-b-id))))))
+ ;; Second login: user only has group-a — should be removed from group-b
+ (do-with-group-sync-login!
+ provider-config {:groups ["group-a"]} email
+ (fn [result]
+ (is (true? (:success? result)))
+ (testing "user is removed from group-b but still in group-a"
+ (let [user (t2/select-one :model/User :%lower.email email)
+ group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (:id user))]
+ (is (contains? group-ids group-a-id))
+ (is (not (contains? group-ids group-b-id)))))))))))
+
+(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))}]
+ (let [email (str "oidc-custom-attr-" (random-uuid) "@example.com")
+ provider-config (assoc test-provider
+ :group-sync {:enabled true
+ :group-attribute "roles"
+ :group-mappings {:admin-role [group-id]}})]
+ (do-with-group-sync-login!
+ provider-config {:roles ["admin-role"]} email
+ (fn [result]
+ (is (true? (:success? result)))
+ (testing "user is added to the mapped group via custom claim attribute"
+ (let [user (t2/select-one :model/User :%lower.email email)]
+ (is (some? user))
+ (is (contains?
+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (:id user))
+ group-id))))))))))
+
+(deftest oidc-group-sync-string-keys-in-claims-test
+ (testing "Claims with string keys (not keyword keys) should still work"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name (str "OIDC StrKey Group " (random-uuid))}]
+ (let [email (str "oidc-strkey-" (random-uuid) "@example.com")
+ provider-config (assoc test-provider
+ :group-sync {:enabled true
+ :group-attribute "groups"
+ :group-mappings {:my-team [group-id]}})]
+ (do-with-group-sync-login!
+ provider-config {"groups" ["my-team"]} email
+ (fn [result]
+ (is (true? (:success? result)))
+ (testing "user is added to the mapped group even with string-keyed claims"
+ (let [user (t2/select-one :model/User :%lower.email email)]
+ (is (some? user))
+ (is (contains?
+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (:id user))
+ group-id))))))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx
index 6a64417209c..f0d9bce59ee 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.tsx
@@ -1,5 +1,5 @@
import { useDisclosure } from "@mantine/hooks";
-import { useCallback, useMemo } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import { t } from "ttag";
import * as Yup from "yup";
@@ -8,6 +8,12 @@ import {
SettingsSection,
} from "metabase/admin/components/SettingsSection";
import { AdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";
+import { GroupMappingsWidgetView } from "metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView";
+import {
+ useClearGroupMembershipMutation,
+ useDeletePermissionsGroupMutation,
+ useListPermissionsGroupsQuery,
+} from "metabase/api";
import { getErrorMessage } from "metabase/api/utils/errors";
import { ConfirmModal } from "metabase/common/components/ConfirmModal";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
@@ -33,6 +39,7 @@ import {
useUpdateCustomOidcMutation,
} from "metabase-enterprise/api";
import { provisioningOptions } from "metabase-enterprise/auth/utils";
+import type { Group, GroupId } from "metabase-types/api";
function getOidcFormSchema() {
return Yup.object({
@@ -50,6 +57,8 @@ function getOidcFormSchema() {
"attribute-email": Yup.string().nullable().default("email"),
"attribute-firstname": Yup.string().nullable().default("given_name"),
"attribute-lastname": Yup.string().nullable().default("family_name"),
+ "group-sync-enabled": Yup.boolean().default(false),
+ "group-attribute": Yup.string().nullable().default("groups"),
});
}
@@ -63,6 +72,8 @@ interface OIDCFormValues {
"attribute-email": string | null;
"attribute-firstname": string | null;
"attribute-lastname": string | null;
+ "group-sync-enabled": boolean;
+ "group-attribute": string | null;
}
function providerToFormValues(
@@ -79,10 +90,13 @@ function providerToFormValues(
"attribute-email": "email",
"attribute-firstname": "given_name",
"attribute-lastname": "family_name",
+ "group-sync-enabled": false,
+ "group-attribute": "groups",
};
}
const attributeMap = provider["attribute-map"] ?? {};
+ const groupSync = provider["group-sync"] ?? {};
return {
"login-prompt": provider["login-prompt"] ?? "",
@@ -94,11 +108,14 @@ function providerToFormValues(
"attribute-email": attributeMap["email"] ?? "email",
"attribute-firstname": attributeMap["first_name"] ?? "given_name",
"attribute-lastname": attributeMap["last_name"] ?? "family_name",
+ "group-sync-enabled": groupSync.enabled ?? false,
+ "group-attribute": groupSync["group-attribute"] ?? "groups",
};
}
function formValuesToProvider(
values: OIDCFormValues,
+ groupMappings: Record<string, number[]>,
): Partial<CustomOidcConfig> {
const scopes = values.scopes
? values.scopes
@@ -126,6 +143,11 @@ function formValuesToProvider(
scopes,
enabled: true,
"attribute-map": attributeMap,
+ "group-sync": {
+ enabled: values["group-sync-enabled"],
+ "group-attribute": values["group-attribute"] ?? undefined,
+ "group-mappings": groupMappings,
+ },
};
if (values["client-secret"]) {
@@ -151,6 +173,16 @@ export function SettingsOIDCForm() {
const isExisting = existingProvider !== 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],
@@ -202,7 +234,10 @@ export function SettingsOIDCForm() {
// Run the connection check before saving — will throw on failure
await runCheck(values);
- const providerData = formValuesToProvider(values);
+ const providerData = formValuesToProvider(
+ values,
+ groupMappingsRef.current,
+ );
if (isExisting && existingProvider) {
const { key: _key, ...updateData } = providerData;
@@ -214,7 +249,54 @@ export function SettingsOIDCForm() {
await createProvider(providerData as CustomOidcConfig).unwrap();
}
},
- [isExisting, existingProvider, createProvider, updateProvider, runCheck],
+ [
+ isExisting,
+ existingProvider,
+ createProvider,
+ updateProvider,
+ runCheck,
+ groupMappingsRef,
+ ],
+ );
+
+ const { data: allGroupsData } = useListPermissionsGroupsQuery(undefined);
+ 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],
);
const handleToggleEnabled = useCallback(async () => {
@@ -329,6 +411,39 @@ export function SettingsOIDCForm() {
</Stack>
</FormSection>
+ {isExisting && (
+ <FormSection
+ title={t`Synchronize group membership with your SSO`}
+ >
+ <Text c="text-secondary" mb="lg">
+ {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.`}
+ </Text>
+ <Stack gap="md">
+ <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.`}
+ nullable
+ />
+ </Stack>
+ </FormSection>
+ )}
+
<FormSection title={t`Optional settings`} collapsible>
<Stack gap="md">
<FormTextInput
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.tsx
new file mode 100644
index 00000000000..8c4ab5e60ad
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx
@@ -0,0 +1,282 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ findRequests,
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { CustomOidcConfig } from "metabase-enterprise/api";
+import { createMockGroup, createMockSettings } from "metabase-types/api/mocks";
+
+import { SettingsOIDCForm } from "./SettingsOIDCForm";
+
+const GROUPS = [
+ createMockGroup({
+ id: 1,
+ 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" }),
+];
+
+const EXISTING_PROVIDER: CustomOidcConfig = {
+ key: "okta",
+ "login-prompt": "Sign in with Okta",
+ "issuer-uri": "https://okta.example.com",
+ "client-id": "client-123",
+ scopes: ["openid", "email", "profile"],
+ enabled: true,
+ "attribute-map": {
+ email: "email",
+ first_name: "given_name",
+ last_name: "family_name",
+ },
+};
+
+function setupEndpoints({
+ providers = [],
+}: {
+ providers?: CustomOidcConfig[];
+} = {}) {
+ const settings = createMockSettings();
+ setupSettingsEndpoints([]);
+ setupPropertiesEndpoints(settings);
+
+ fetchMock.get("path:/api/permissions/group", GROUPS);
+ fetchMock.get("path:/api/ee/sso/oidc", providers);
+ fetchMock.post("path:/api/ee/sso/oidc", 200);
+ fetchMock.put("path:/api/ee/sso/oidc/okta", 200);
+ fetchMock.post("path:/api/ee/sso/oidc/check", {
+ ok: true,
+ discovery: { step: "discovery", success: true },
+ credentials: { step: "credentials", success: true, verified: true },
+ });
+}
+
+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);
+
+ renderWithProviders(<SettingsOIDCForm />);
+
+ await screen.findByText("OpenID Connect");
+};
+
+describe("SettingsOIDCForm - Group Sync", () => {
+ it("does not show group sync section for new providers", async () => {
+ await setup({ providers: [] });
+
+ expect(
+ screen.queryByText("Synchronize group membership with your SSO"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows group sync section for existing providers", async () => {
+ await setup({ providers: [EXISTING_PROVIDER] });
+
+ expect(
+ screen.getByText("Synchronize group membership with your SSO"),
+ ).toBeInTheDocument();
+ });
+
+ it("renders group sync toggle", async () => {
+ await setup({ providers: [EXISTING_PROVIDER] });
+
+ expect(screen.getByTestId("group-sync-switch")).toBeInTheDocument();
+ });
+
+ it("renders group attribute text input", async () => {
+ await setup({ providers: [EXISTING_PROVIDER] });
+
+ expect(screen.getByLabelText("Group attribute name")).toBeInTheDocument();
+ });
+
+ it("populates group sync fields from existing provider config", async () => {
+ await setup({
+ providers: [
+ {
+ ...EXISTING_PROVIDER,
+ "group-sync": {
+ enabled: true,
+ "group-attribute": "groups",
+ "group-mappings": { engineers: [3] },
+ },
+ },
+ ],
+ });
+
+ const groupAttrInput = screen.getByLabelText("Group attribute name");
+ expect(groupAttrInput).toHaveValue("groups");
+ });
+
+ it("shows existing group mappings from provider config", async () => {
+ await setup({
+ providers: [
+ {
+ ...EXISTING_PROVIDER,
+ "group-sync": {
+ enabled: true,
+ "group-attribute": "groups",
+ "group-mappings": { admins: [2], devs: [3] },
+ },
+ },
+ ],
+ });
+
+ expect(screen.getByText("admins")).toBeInTheDocument();
+ expect(screen.getByText("devs")).toBeInTheDocument();
+ });
+
+ it("renders New mapping button", async () => {
+ await setup({
+ providers: [
+ {
+ ...EXISTING_PROVIDER,
+ "group-sync": { enabled: true, "group-mappings": {} },
+ },
+ ],
+ });
+
+ expect(
+ screen.getByRole("button", { name: "New mapping" }),
+ ).toBeInTheDocument();
+ });
+
+ it("includes group sync in form submission", async () => {
+ await setup({ providers: [EXISTING_PROVIDER] });
+
+ // Change group attribute to make the form dirty
+ const groupAttrInput = screen.getByLabelText("Group attribute name");
+ await userEvent.clear(groupAttrInput);
+ await userEvent.type(groupAttrInput, "roles");
+
+ const submitButton = screen.getByRole("button", {
+ name: "Save changes",
+ });
+ await userEvent.click(submitButton);
+
+ await waitFor(async () => {
+ const puts = await getOidcPutCalls();
+ expect(puts.length).toBeGreaterThan(0);
+ });
+
+ const puts = await getOidcPutCalls();
+ const lastPut = puts[puts.length - 1];
+ expect(lastPut.body["group-sync"]).toEqual(
+ expect.objectContaining({
+ enabled: false,
+ "group-mappings": {},
+ }),
+ );
+ expect(lastPut.body["group-sync"]["group-attribute"]).toBe("roles");
+ });
+
+ 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.
+ await setup({
+ providers: [
+ {
+ ...EXISTING_PROVIDER,
+ "group-sync": {
+ enabled: true,
+ "group-attribute": "groups",
+ "group-mappings": {},
+ },
+ },
+ ],
+ });
+
+ // Make the form dirty first so we can detect the form-level submit
+ const groupAttrInput = screen.getByLabelText("Group attribute name");
+ await userEvent.clear(groupAttrInput);
+ await userEvent.type(groupAttrInput, "roles");
+
+ // Add a mapping via the widget: click "New mapping", type name, click Add
+ const newMappingButton = screen.getByRole("button", {
+ name: "New mapping",
+ });
+ await userEvent.click(newMappingButton);
+
+ const input = screen.getByPlaceholderText("Group name");
+ await userEvent.type(input, "Group 1");
+ const addButton = screen.getByRole("button", { name: "Add" });
+ await userEvent.click(addButton);
+
+ // The "Add" button (type="submit") also submits the Formik form, so
+ // multiple PUTs fire. The form submit that includes full provider data
+ // (attribute-map, scopes, etc.) is the one from the Formik handler.
+ // Due to event ordering, the first form PUT may have stale mappings,
+ // but the second one (after the ref is updated) should have the correct
+ // mappings. We verify the LAST form-level PUT has the right data.
+ await waitFor(async () => {
+ const puts = await getOidcPutCalls();
+ const formPuts = puts.filter(
+ (p: { body: Record<string, unknown> }) => p.body["attribute-map"],
+ );
+ expect(formPuts.length).toBeGreaterThanOrEqual(1);
+ });
+
+ const puts = await getOidcPutCalls();
+ const formPuts = puts.filter(
+ (p: { body: Record<string, unknown> }) => p.body["attribute-map"],
+ );
+ const lastFormPut = formPuts[formPuts.length - 1];
+ // The last form submission should include the mapping added via the widget
+ expect(lastFormPut.body["group-sync"]["group-mappings"]).toEqual({
+ "Group 1": [],
+ });
+ expect(lastFormPut.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] },
+ },
+ },
+ ],
+ });
+
+ // 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");
+
+ const submitButton = screen.getByRole("button", {
+ name: "Save changes",
+ });
+ await userEvent.click(submitButton);
+
+ await waitFor(async () => {
+ const puts = await getOidcPutCalls();
+ expect(puts.length).toBeGreaterThan(0);
+ });
+
+ 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] },
+ });
+ });
+});
diff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.clj
index 24b72c8b77b..1b4272a0695 100644
--- a/src/metabase/auth_identity/provider.clj
+++ b/src/metabase/auth_identity/provider.clj
@@ -298,7 +298,7 @@
(next-method provider $)
(cond-> $
(:user $) (create-session! provider))
- (select-keys $ [:success? :user :redirect-url :error :message :user-data :session :jwt-data])))
+ (select-keys $ [:success? :user :redirect-url :error :message :user-data :session :jwt-data :claims :oidc-provider-key])))
(defenterprise sso-user-fields
"Return the list of User model fields that should be populated from SSO user data.