Skip to content

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

Prevent Admin from mistakenly resetting the password of an SSO user. (#84940)

Ethan McCuec74d08cda8c9
diff --git a/frontend/src/metabase/admin/people/components/PeopleListRow.tsx b/frontend/src/metabase/admin/people/components/PeopleListRow.tsx
index adb16c16e70..188162194cf 100644
--- a/frontend/src/metabase/admin/people/components/PeopleListRow.tsx
+++ b/frontend/src/metabase/admin/people/components/PeopleListRow.tsx
@@ -27,6 +27,7 @@ import type {
} from "metabase-types/api";
import { userToColor } from "../colors";
+import { getIsUserSsoSourceEnabled } from "../selectors";
import { MembershipSelect } from "./MembershipSelect";
import { ReactivateUserButton } from "./ReactivateUserButton";
@@ -71,6 +72,10 @@ export const PeopleListRow = ({
const isPasswordLoginEnabled = useSelector((state) =>
getSetting(state, enablePasswordLoginKey),
);
+ const isUserSsoSourceEnabled = useSelector((state) =>
+ getIsUserSsoSourceEnabled(state, user),
+ );
+ const canResetPassword = isPasswordLoginEnabled && !isUserSsoSourceEnabled;
return (
<tr key={user.id}>
@@ -145,7 +150,7 @@ export const PeopleListRow = ({
{t`Edit user`}
</Menu.Item>
- {isPasswordLoginEnabled && (
+ {canResetPassword && (
<Menu.Item
component={ForwardRefLink}
to={Urls.resetPassword(user)}
diff --git a/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.unit.spec.tsx b/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.unit.spec.tsx
index 346974f425f..c30f36fd2eb 100644
--- a/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.unit.spec.tsx
+++ b/frontend/src/metabase/admin/people/containers/PeopleListingApp/PeopleListingApp.unit.spec.tsx
@@ -1,3 +1,5 @@
+import userEvent from "@testing-library/user-event";
+
import { setupEnterprisePlugins } from "__support__/enterprise";
import {
setupGroupsEndpoint,
@@ -8,7 +10,7 @@ import {
import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
-import type { Tenant, User } from "metabase-types/api";
+import type { EnterpriseSettings, Tenant, User } from "metabase-types/api";
import {
createMockGroup,
createMockTokenFeatures,
@@ -17,6 +19,17 @@ import {
import { PeopleListingApp } from "./PeopleListingApp";
+interface SetupOpts {
+ external?: boolean;
+ showInviteButton?: boolean;
+ noResultsMessage?: string;
+ users?: User[];
+ currentUser?: User;
+ tenants?: Tenant[];
+ useTenants?: boolean;
+ settings?: Partial<EnterpriseSettings>;
+}
+
const setup = ({
external = false,
showInviteButton = true,
@@ -27,20 +40,14 @@ const setup = ({
}),
tenants = [],
useTenants = true,
-}: {
- external?: boolean;
- showInviteButton?: boolean;
- noResultsMessage?: string;
- users?: User[];
- currentUser?: User;
- tenants?: Tenant[];
- useTenants?: boolean;
-} = {}) => {
+ settings: settingOverrides = {},
+}: SetupOpts = {}) => {
const settings = mockSettings({
"token-features": createMockTokenFeatures({
tenants: true,
}),
"use-tenants": useTenants,
+ ...settingOverrides,
});
setupEnterprisePlugins();
@@ -168,3 +175,45 @@ describe("no results message", () => {
expect(await screen.findByText(noResultsMessage)).toBeInTheDocument();
});
});
+
+describe("user menu", () => {
+ const ssoUser = createMockUser({
+ id: 10,
+ email: "[email protected]",
+ sso_source: "saml",
+ });
+
+ const openUserMenu = async () => {
+ await userEvent.click(
+ await screen.findByRole("button", { name: /ellipsis/i }),
+ );
+ await screen.findByRole("menuitem", { name: "Edit user" });
+ };
+
+ it("should offer to reset the password of a password user", async () => {
+ setup({ users: [createMockUser({ id: 10, sso_source: null })] });
+ await openUserMenu();
+
+ expect(
+ screen.getByRole("menuitem", { name: "Reset password" }),
+ ).toBeInTheDocument();
+ });
+
+ it("should not offer to reset the password of a user whose SSO provider is enabled", async () => {
+ setup({ users: [ssoUser], settings: { "saml-enabled": true } });
+ await openUserMenu();
+
+ expect(
+ screen.queryByRole("menuitem", { name: "Reset password" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should offer to reset the password of an SSO user once their provider is disabled", async () => {
+ setup({ users: [ssoUser], settings: { "saml-enabled": false } });
+ await openUserMenu();
+
+ expect(
+ screen.getByRole("menuitem", { name: "Reset password" }),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/admin/people/containers/UserPasswordResetModal.tsx b/frontend/src/metabase/admin/people/containers/UserPasswordResetModal.tsx
index b4410509e00..f316fa2db55 100644
--- a/frontend/src/metabase/admin/people/containers/UserPasswordResetModal.tsx
+++ b/frontend/src/metabase/admin/people/containers/UserPasswordResetModal.tsx
@@ -20,7 +20,10 @@ import MetabaseSettings from "metabase/utils/settings";
import type { User } from "metabase-types/api";
import { clearTemporaryPassword, storeTemporaryPassword } from "../people";
-import { getUserTemporaryPassword } from "../selectors";
+import {
+ getIsUserSsoSourceEnabled,
+ getUserTemporaryPassword,
+} from "../selectors";
interface UserPasswordResetModalInnerProps {
clearTemporaryPassword: () => void;
@@ -142,6 +145,27 @@ const UserPasswordResetModalInner = ({
);
};
+interface SsoUserPasswordResetModalProps {
+ user: User;
+ onClose: () => void;
+}
+
+const SsoUserPasswordResetModal = ({
+ user,
+ onClose,
+}: SsoUserPasswordResetModalProps) => (
+ <ConfirmModal
+ opened
+ title={t`Can't reset ${user.common_name}'s password`}
+ onConfirm={onClose}
+ confirmButtonProps={{ color: "brand", variant: "filled" }}
+ confirmButtonText={t`Done`}
+ closeButtonText={null}
+ onClose={onClose}
+ message={t`This user signs in with single sign-on. Manage their access through your identity provider.`}
+ />
+);
+
interface UserPasswordResetModalProps {
params: { userId?: string };
onClose: () => void;
@@ -156,10 +180,16 @@ export const UserPasswordResetModal = (props: UserPasswordResetModalProps) => {
const temporaryPassword = useSelector((state) =>
getUserTemporaryPassword(state, { userId }),
);
+ const isUserSsoSourceEnabled = useSelector(
+ (state) => user != null && getIsUserSsoSourceEnabled(state, user),
+ );
return (
<LoadingAndErrorWrapper loading={isLoading} error={error}>
- {user && (
+ {user && isUserSsoSourceEnabled && (
+ <SsoUserPasswordResetModal user={user} onClose={props.onClose} />
+ )}
+ {user && !isUserSsoSourceEnabled && (
<UserPasswordResetModalInner
{...props}
clearTemporaryPassword={() =>
diff --git a/frontend/src/metabase/admin/people/containers/UserPasswordResetModal.unit.spec.tsx b/frontend/src/metabase/admin/people/containers/UserPasswordResetModal.unit.spec.tsx
index f56c50160c8..0ce00dc05f4 100644
--- a/frontend/src/metabase/admin/people/containers/UserPasswordResetModal.unit.spec.tsx
+++ b/frontend/src/metabase/admin/people/containers/UserPasswordResetModal.unit.spec.tsx
@@ -10,6 +10,7 @@ import {
import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
+import type { EnterpriseSettings, User } from "metabase-types/api";
import { createMockSettings, createMockUser } from "metabase-types/api/mocks";
import { UserPasswordResetModal } from "./UserPasswordResetModal";
@@ -22,24 +23,35 @@ const TEST_USER = createMockUser({
common_name: "Ash Ketchum",
});
-function setup({ emailConfigured = false } = {}) {
- setupUserEndpoints(TEST_USER);
- setupPasswordResetUrlEndpoint(TEST_USER.id);
+interface SetupOpts {
+ user?: User;
+ emailConfigured?: boolean;
+ settings?: Partial<EnterpriseSettings>;
+}
+
+function setup({
+ user = TEST_USER,
+ emailConfigured = false,
+ settings = {},
+}: SetupOpts = {}) {
+ setupUserEndpoints(user);
+ setupPasswordResetUrlEndpoint(user.id);
setupForgotPasswordEndpoint();
- setupUpdatePasswordEndpoint(TEST_USER.id);
+ setupUpdatePasswordEndpoint(user.id);
const storeInitialState = createMockState({
settings: mockSettings(
createMockSettings({
"email-configured?": emailConfigured,
+ ...settings,
}),
),
});
- const onCloseSpy = jest.fn();
+ const onCloseSpy = jest.fn<void, []>();
renderWithProviders(
<UserPasswordResetModal
- params={{ userId: String(TEST_USER.id) }}
+ params={{ userId: String(user.id) }}
onClose={onCloseSpy}
/>,
{ storeInitialState },
@@ -95,4 +107,47 @@ describe("UserPasswordResetModal", () => {
await userEvent.click(screen.getByRole("button", { name: "Done" }));
expect(onCloseSpy).toHaveBeenCalled();
});
+
+ describe("for a user who signs in with SSO", () => {
+ const ssoUser = createMockUser({
+ ...TEST_USER,
+ sso_source: "saml",
+ });
+
+ it("should explain that the password can't be reset while their provider is enabled", async () => {
+ const { onCloseSpy } = setup({
+ user: ssoUser,
+ settings: { "saml-enabled": true },
+ });
+
+ expect(
+ await screen.findByText("Can't reset Ash Ketchum's password"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Get reset link" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Reset password" }),
+ ).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("button", { name: "Done" }));
+ expect(onCloseSpy).toHaveBeenCalledTimes(1);
+ expect(
+ fetchMock.callHistory.called(
+ `path:/api/user/${ssoUser.id}/password-reset-url`,
+ ),
+ ).toBe(false);
+ });
+
+ it("should allow resetting the password once their provider is disabled", async () => {
+ setup({ user: ssoUser, settings: { "saml-enabled": false } });
+
+ expect(
+ await screen.findByRole("button", { name: "Get reset link" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Reset password" }),
+ ).toBeInTheDocument();
+ });
+ });
});
diff --git a/frontend/src/metabase/admin/people/selectors.ts b/frontend/src/metabase/admin/people/selectors.ts
index 7f1a63d4ea7..e8934811fbc 100644
--- a/frontend/src/metabase/admin/people/selectors.ts
+++ b/frontend/src/metabase/admin/people/selectors.ts
@@ -4,12 +4,38 @@ import { ACTIVE_USERS_NUDGE_THRESHOLD } from "metabase/admin/people/constants";
import { getUserIsAdmin } from "metabase/current-user";
import type { State } from "metabase/redux/store";
import { getSetting, hasAnySsoFeature } from "metabase/settings";
+import type { EnterpriseSettingKey, User } from "metabase-types/api";
export const getUserTemporaryPassword = (
state: State,
props: { userId: number },
) => state.admin.people.temporaryPasswords[props.userId];
+const SSO_SOURCE_ENABLED_SETTING = {
+ google: "google-auth-enabled",
+ ldap: "ldap-enabled",
+ saml: "saml-enabled",
+ jwt: "jwt-enabled",
+ oidc: "oidc-enabled",
+ slack: "slack-connect-enabled",
+ scim: "scim-enabled",
+} as const satisfies Record<
+ NonNullable<User["sso_source"]>,
+ EnterpriseSettingKey
+>;
+
+/**
+ * Whether the user signs in through an SSO provider that is currently enabled.
+ * Admins can't reset passwords for these users; once the provider is disabled
+ * (or its license lapses) the user falls back to password login.
+ */
+export const getIsUserSsoSourceEnabled = (
+ state: State,
+ { sso_source }: Pick<User, "sso_source">,
+): boolean =>
+ sso_source != null &&
+ Boolean(getSetting(state, SSO_SOURCE_ENABLED_SETTING[sso_source]));
+
export const shouldNudgeToPro = createSelector(
(state) => getSetting(state, "token-features"),
(state) => getUserIsAdmin(state),
diff --git a/src/metabase/audit_app/events/audit_log.clj b/src/metabase/audit_app/events/audit_log.clj
index b6956152395..1b4ccd267fa 100644
--- a/src/metabase/audit_app/events/audit_log.clj
+++ b/src/metabase/audit_app/events/audit_log.clj
@@ -182,6 +182,7 @@
(events/derive! :event/user-reactivated ::user-event)
(events/derive! :event/password-reset-initiated ::user-event)
(events/derive! :event/password-reset-successful ::user-event)
+(events/derive! :event/password-changed ::user-event)
(events/derive! :event/mfa-verification-failed ::user-event)
(events/derive! :event/mfa-required-enrollment-failed ::user-event)
(events/derive! :event/mfa-enrolled ::user-event)
diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.clj
index 58dcfe1f8f5..25241dae0c1 100644
--- a/src/metabase/users_rest/api.clj
+++ b/src/metabase/users_rest/api.clj
@@ -641,6 +641,11 @@
request]
(users/check-self-or-superuser id)
(api/let-404 [user (users-rest.db/active-personal-user-login-columns id)]
+ ;; admins can't give a password to a user who signs in through an enabled SSO provider; that would let them log
+ ;; in as that user while bypassing the provider.
+ (when api/*is-superuser?*
+ (api/check-404 (or (nil? (:sso_source user))
+ (not (sso/sso-source-enabled? (:sso_source user))))))
;; admins are allowed to reset anyone's password (in the admin people list) so no need to check the value of
;; `old_password` for them regular users have to know their password, however
(when-not api/*is-superuser?*
@@ -659,6 +664,7 @@
:mfa_auth_identity_id)]
;; set-password! invalidates the user's existing sessions; a self-change gets a fresh one below
(auth-identity/set-password! id password {:ended-by api/*current-user-id*})
+ (events/publish-event! :event/password-changed {:object user :user-id api/*current-user-id*})
;; after a successful password update go ahead and offer the client a new session that they can use
(when (= id api/*current-user-id*)
(let [{session-key :key, :as session} (auth-identity/create-session-with-auth-tracking!
@@ -680,9 +686,11 @@
[{:keys [id]} :- [:map {:closed true}
[:id ms/PositiveInt]]]
(api/check-superuser)
- (let [user (api/check-404 (users-rest.db/user-active-and-type id))]
+ (let [user (api/check-404 (users-rest.db/user-active-type-and-sso-source id))]
(api/check-404 (:is_active user))
(api/check-404 (= :personal (:type user)))
+ (api/check-404 (or (nil? (:sso_source user))
+ (not (sso/sso-source-enabled? (:sso_source user)))))
(let [reset-token (auth-identity/create-password-reset! id)
password-reset-url (str (system/site-url) "/auth/reset_password/" reset-token)]
(events/publish-event! :event/password-reset-initiated
diff --git a/src/metabase/users_rest/db.clj b/src/metabase/users_rest/db.clj
index 3a6d5ae04da..a5970d10132 100644
--- a/src/metabase/users_rest/db.clj
+++ b/src/metabase/users_rest/db.clj
@@ -117,14 +117,14 @@
:id user-id))
(mu/defn active-personal-user-login-columns
- "The id, email, and last login of the active personal User with `user-id`, or nil."
+ "The id, email, last login, and `sso_source` of the active personal User with `user-id`, or nil."
[user-id :- ::lib.schema.id/user]
- (t2/select-one [:model/User :id :email :last_login], :id user-id, :type :personal, :is_active true))
+ (t2/select-one [:model/User :id :email :last_login :sso_source], :id user-id, :type :personal, :is_active true))
-(mu/defn user-active-and-type
- "The id, active flag, and type of the User with `user-id`, or nil."
+(mu/defn user-active-type-and-sso-source
+ "The id, active flag, type, and sso_source of the User with `user-id`, or nil."
[user-id :- ::lib.schema.id/user]
- (t2/select-one [:model/User :id :is_active :type] :id user-id))
+ (t2/select-one [:model/User :id :is_active :type :sso_source] :id user-id))
(mu/defn user-exists?
"Whether a User with `user-id` exists."
diff --git a/test/metabase/audit_app/events/audit_log_test.clj b/test/metabase/audit_app/events/audit_log_test.clj
index 219786c7b54..77586c1b6f4 100644
--- a/test/metabase/audit_app/events/audit_log_test.clj
+++ b/test/metabase/audit_app/events/audit_log_test.clj
@@ -480,6 +480,19 @@
:model "User"}
(mt/latest-audit-log-entry :password-reset-successful (mt/user->id :rasta))))))))
+(deftest password-changed-event-test
+ (testing :event/password-changed
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [user (mt/fetch-user :rasta)]
+ (is (= {:object user :user-id (mt/user->id :crowberto)}
+ (events/publish-event! :event/password-changed {:object user :user-id (mt/user->id :crowberto)})))
+ (is (= {:model_id (mt/user->id :rasta)
+ :user_id (mt/user->id :crowberto)
+ :details {}
+ :topic :password-changed
+ :model "User"}
+ (mt/latest-audit-log-entry :password-changed (mt/user->id :rasta))))))))
+
(deftest create-channel-event-test
(mt/with-current-user (mt/user->id :rasta)
(mt/with-temp [:model/Channel channel notification.tu/default-can-connect-channel]
diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.clj
index 84907bef0eb..65317a73e07 100644
--- a/test/metabase/users_rest/api_test.clj
+++ b/test/metabase/users_rest/api_test.clj
@@ -1837,6 +1837,60 @@
{:password "whateverUP12!!"
:old_password "whatever"}))))))
+(deftest reset-password-sso-user-not-found-test
+ (testing "PUT /api/user/:id/password as an admin for a user whose SSO provider is enabled gets a 404"
+ (mt/with-temp [:model/User {user-id :id} {:first_name "Test"
+ :last_name "User"
+ :sso_source "google"}]
+ (let [set-password! (fn [expected-status]
+ (mt/user-http-request :crowberto :put expected-status (format "user/%d/password" user-id)
+ {:password "whateverUP12!!"}))
+ password-hash (fn []
+ (:password_hash (t2/select-one-fn :credentials :model/AuthIdentity
+ :user_id user-id, :provider "password")))
+ original-hash (password-hash)]
+ (mt/with-premium-features #{}
+ (mt/with-temporary-setting-values [google-auth-client-id "pretend-client-id.apps.googleusercontent.com"
+ google-auth-enabled true]
+ (set-password! 404)
+ (is (= original-hash (password-hash))))
+ (testing "once the provider is disabled the admin can set a password again"
+ (set-password! 204)
+ (is (not= original-hash (password-hash)))))))))
+
+(deftest reset-password-audit-log-test
+ (testing "PUT /api/user/:id/password records who changed whose password in the audit log"
+ (mt/with-premium-features #{:audit-app}
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (auth-identity/set-password! user-id "oldPASSWORD12!!")
+ (testing "when an admin sets another user's password"
+ (mt/user-http-request :crowberto :put 204 (format "user/%d/password" user-id)
+ {:password "adminSET12!!pw"})
+ (is (= {:topic :password-changed
+ :user_id (mt/user->id :crowberto)
+ :model "User"
+ :model_id user-id
+ :details {}}
+ (mt/latest-audit-log-entry :password-changed user-id))))
+ (testing "when a user changes their own password"
+ (mt/user-http-request user-id :put 200 (format "user/%d/password" user-id)
+ {:password "selfSET12!!pw"
+ :old_password "adminSET12!!pw"})
+ (is (= {:topic :password-changed
+ :user_id user-id
+ :model "User"
+ :model_id user-id
+ :details {}}
+ (mt/latest-audit-log-entry :password-changed user-id)))))
+ (testing "nothing is recorded when the change is refused"
+ (mt/with-temp [:model/User {sso-user-id :id} {:sso_source "google"}]
+ (mt/with-temporary-setting-values [google-auth-client-id "pretend-client-id.apps.googleusercontent.com"
+ google-auth-enabled true]
+ (mt/user-http-request :crowberto :put 404 (format "user/%d/password" sso-user-id)
+ {:password "whateverUP12!!"})
+ (is (nil? (mt/latest-audit-log-entry :password-changed sso-user-id)))))))))
+
(deftest reset-password-input-validation-test
(testing "PUT /api/user/:id/password"
(testing "Test input validations on password change"
@@ -2127,6 +2181,22 @@
(mt/user-http-request :crowberto :post 404
(format "user/%d/password-reset-url" user-id)))))
+(deftest password-reset-url-sso-user-not-found-test
+ (testing "POST /api/user/:id/password-reset-url with a user having sso configured gets a 404"
+ (mt/with-temp [:model/User {user-id :id} {:first_name "Test"
+ :last_name "User"
+ :sso_source "google"}]
+ (mt/with-premium-features #{}
+ (mt/with-temporary-setting-values [google-auth-client-id "pretend-client-id.apps.googleusercontent.com"
+ google-auth-enabled true]
+ (mt/user-http-request :crowberto :post 404
+ (format "user/%d/password-reset-url" user-id)))
+ (mt/user-http-request :crowberto :post 200
+ (format "user/%d/password-reset-url" user-id)))
+ (mt/user-http-request :crowberto :post 200
+ (format "user/%d/password-reset-url" user-id)))))
+
(deftest password-reset-url-nonexistent-user-not-found-test
(testing "POST /api/user/:id/password-reset-url nonexistent user gets 404"
(mt/user-http-request :crowberto :post 404