Skip to content

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

Let users disconnect their Slack accounts (#83918)

Andrei Simionescu6c2714c33b27
diff --git a/docs/ai/metabot-slack.md b/docs/ai/metabot-slack.md
index 13c94829fc2..2ee2148f635 100644
--- a/docs/ai/metabot-slack.md
+++ b/docs/ai/metabot-slack.md
@@ -42,6 +42,8 @@ If you already have a Slack integration from before this feature existed, your S
To chat with Metabot, people will need to link their Slack account to their Metabase account. The first time you message Metabot, it kicks off an OAuth flow that connects the two accounts. This connection lets Metabot use your Metabase permissions, so Metabot will only see data you're allowed to see.
+To disconnect your Slack account, go to the **Authentication** tab in your [account settings](../people-and-groups/account-settings.md) and click **Disconnect**.
+
## Chatting with Metabot in Slack
- **Message Metabot directly** for private conversations with your data. No @mention needed.
diff --git a/frontend/src/metabase-types/api/user.ts b/frontend/src/metabase-types/api/user.ts
index d3273ddb364..e4ae543d901 100644
--- a/frontend/src/metabase-types/api/user.ts
+++ b/frontend/src/metabase-types/api/user.ts
@@ -77,10 +77,19 @@ export interface User extends BaseUser {
is_installer: boolean;
has_invited_second_user: boolean;
has_question_and_dashboard: boolean;
+ slack_account_status?: "active" | "inactive" | null;
can_write_any_collection: boolean;
personal_collection_id: CollectionId | null;
tenant_collection_id: CollectionId | null;
- sso_source: "jwt" | "ldap" | "google" | "scim" | "saml" | "oidc" | null;
+ sso_source:
+ | "jwt"
+ | "ldap"
+ | "google"
+ | "scim"
+ | "saml"
+ | "oidc"
+ | "slack"
+ | null;
custom_homepage: {
dashboard_id: DashboardId;
} | null;
diff --git a/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.tsx b/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.tsx
index ce47f483047..bd3ed7836be 100644
--- a/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.tsx
+++ b/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.tsx
@@ -1,8 +1,8 @@
import { useMemo } from "react";
import { t } from "ttag";
+import { hasAuthenticationSettings } from "metabase/account/utils";
import { UserAvatar } from "metabase/common/components/UserAvatar";
-import { PLUGIN_IS_PASSWORD_USER } from "metabase/plugins";
import { useSetting } from "metabase/settings";
import { Box, Flex, Tabs, Title, rem } from "metabase/ui";
import { getFullName } from "metabase/utils/user";
@@ -21,14 +21,8 @@ export const AccountHeader = ({
path,
onChangeLocation,
}: AccountHeaderProps) => {
- const canChangePassword = useMemo(
- () => PLUGIN_IS_PASSWORD_USER.every((predicate) => predicate(user)),
- [user],
- );
const mfaEnforcement = useSetting("mfa-enforcement");
- const isMfaEnabled = mfaEnforcement != null && mfaEnforcement !== "off";
- const hasAuthenticationTab =
- canChangePassword || (isMfaEnabled && user.sso_source === "ldap");
+ const hasAuthenticationTab = hasAuthenticationSettings(user, mfaEnforcement);
const tabs = useMemo(
() => [
diff --git a/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.unit.spec.tsx b/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.unit.spec.tsx
index d3dcf029b43..452fbc75ea8 100644
--- a/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.unit.spec.tsx
+++ b/frontend/src/metabase/account/app/components/AccountHeader/AccountHeader.unit.spec.tsx
@@ -61,6 +61,19 @@ describe("AccountHeader", () => {
});
describe("authentication tab", () => {
+ it.each(["active", "inactive"] as const)(
+ "should show the tab for an SSO user with an %s Slack account",
+ (status) => {
+ setup({
+ user: getUser({ sso_source: "google", slack_account_status: status }),
+ });
+
+ expect(
+ screen.getByRole("tab", { name: "Authentication" }),
+ ).toBeInTheDocument();
+ },
+ );
+
it("should show the tab for a user who can change their password", () => {
setup({ user: getUser({ sso_source: null }) });
diff --git a/frontend/src/metabase/account/password/components/SlackAccount/SlackAccount.tsx b/frontend/src/metabase/account/password/components/SlackAccount/SlackAccount.tsx
new file mode 100644
index 00000000000..84c32ef9f6e
--- /dev/null
+++ b/frontend/src/metabase/account/password/components/SlackAccount/SlackAccount.tsx
@@ -0,0 +1,48 @@
+import { t } from "ttag";
+
+import { useConfirmation } from "metabase/common/hooks/use-confirmation";
+import { useSelector } from "metabase/redux";
+import { getApplicationName } from "metabase/selectors/whitelabel";
+import { Box, Button, Group, Stack } from "metabase/ui";
+
+type SlackAccountProps = {
+ isActive: boolean;
+ isDisconnecting: boolean;
+ onDisconnect: () => void;
+};
+
+export function SlackAccount({
+ isActive,
+ isDisconnecting,
+ onDisconnect,
+}: SlackAccountProps) {
+ const applicationName = useSelector(getApplicationName);
+ const { modalContent, show } = useConfirmation();
+
+ const handleDisconnect = () =>
+ show({
+ title: t`Disconnect your Slack account?`,
+ message: t`You'll need to connect again to use this account with Metabot in Slack.`,
+ confirmButtonText: t`Disconnect`,
+ onConfirm: onDisconnect,
+ });
+
+ return (
+ <>
+ <Group justify="space-between" align="flex-start" wrap="nowrap">
+ <Stack gap="xxs">
+ <Box fw="bold">{t`Slack`}</Box>
+ <Box c="text-secondary">
+ {isActive
+ ? t`Your Slack account is connected to ${applicationName}.`
+ : t`Your Slack connection is no longer active.`}
+ </Box>
+ </Stack>
+ <Button loading={isDisconnecting} onClick={handleDisconnect}>
+ {t`Disconnect`}
+ </Button>
+ </Group>
+ {modalContent}
+ </>
+ );
+}
diff --git a/frontend/src/metabase/account/password/containers/UserPasswordApp/UserPasswordApp.tsx b/frontend/src/metabase/account/password/containers/UserPasswordApp/UserPasswordApp.tsx
index 16ab16e494a..9a8abe54456 100644
--- a/frontend/src/metabase/account/password/containers/UserPasswordApp/UserPasswordApp.tsx
+++ b/frontend/src/metabase/account/password/containers/UserPasswordApp/UserPasswordApp.tsx
@@ -1,17 +1,75 @@
+import { useMountedState } from "react-use";
+import { t } from "ttag";
+
import { getIsSsoUser } from "metabase/account/selectors";
+import { hasAuthenticationSettings } from "metabase/account/utils";
+import { Api, useDisconnectSlackMutation } from "metabase/api";
+import { getErrorStatus } from "metabase/api/client/errors";
+import { getErrorMessage } from "metabase/api/utils";
import { useValidatePassword } from "metabase/common/hooks";
-import { getUser } from "metabase/current-user";
+import { useToast } from "metabase/common/hooks/use-toast";
+import {
+ refetchCurrentUser,
+ useGetCurrentUserQuery,
+} from "metabase/current-user";
import { PLUGIN_MULTI_FACTOR_AUTH } from "metabase/plugins";
-import { useSelector } from "metabase/redux";
+import { useDispatch, useSelector } from "metabase/redux";
+import { useNavigate } from "metabase/router";
+import { useSetting } from "metabase/settings";
import { Stack } from "metabase/ui";
import { checkNotNull } from "metabase/utils/types";
+import { SlackAccount } from "../../components/SlackAccount/SlackAccount";
import { UserPasswordForm } from "../../components/UserPasswordForm";
const UserPasswordApp = () => {
- const user = checkNotNull(useSelector(getUser));
+ const { data, isFetching } = useGetCurrentUserQuery();
+ const user = checkNotNull(data);
const isSsoUser = useSelector(getIsSsoUser);
const validatePassword = useValidatePassword();
+ const [disconnectSlack, { isLoading }] = useDisconnectSlackMutation();
+ const [sendToast] = useToast();
+ const navigate = useNavigate();
+ const dispatch = useDispatch();
+ const mfaEnforcement = useSetting("mfa-enforcement");
+ const isMounted = useMountedState();
+
+ const handleDisconnect = async () => {
+ const result = await disconnectSlack(user.id);
+ if (result.error) {
+ sendToast({
+ icon: "warning",
+ toastColor: "feedback-negative",
+ message: getErrorMessage(
+ result.error,
+ t`Couldn't disconnect your Slack account.`,
+ ),
+ });
+ return;
+ }
+
+ const currentUser = await dispatch(refetchCurrentUser());
+ if (currentUser.error && getErrorStatus(currentUser.error) !== 401) {
+ sendToast({
+ icon: "warning",
+ toastColor: "feedback-negative",
+ message: t`Couldn't refresh your account settings. Please reload the page.`,
+ });
+ return;
+ }
+
+ sendToast({ message: t`Your Slack account has been disconnected.` });
+ if (getErrorStatus(currentUser.error) === 401) {
+ dispatch(Api.util.resetApiState());
+ navigate("/auth/login");
+ } else if (
+ isMounted() &&
+ currentUser.data &&
+ !hasAuthenticationSettings(currentUser.data, mfaEnforcement)
+ ) {
+ navigate("/account/profile", { replace: true });
+ }
+ };
return (
<Stack gap="xxl">
@@ -21,6 +79,13 @@ const UserPasswordApp = () => {
</Stack>
)}
<PLUGIN_MULTI_FACTOR_AUTH.AccountSecurityPanel />
+ {user.slack_account_status != null && (
+ <SlackAccount
+ isActive={user.slack_account_status === "active"}
+ isDisconnecting={isLoading || isFetching}
+ onDisconnect={handleDisconnect}
+ />
+ )}
</Stack>
);
};
diff --git a/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/common.unit.spec.tsx b/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/common.unit.spec.tsx
index a1273bf884a..4bc26c82178 100644
--- a/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/common.unit.spec.tsx
@@ -1,9 +1,142 @@
-import { screen, waitForLoaderToBeRemoved } from "__support__/ui";
-import { createMockMfaStatus } from "metabase-types/api/mocks";
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ screen,
+ waitFor,
+ waitForLoaderToBeRemoved,
+ within,
+} from "__support__/ui";
+import { createMockMfaStatus, createMockUser } from "metabase-types/api/mocks";
import { setup } from "./setup";
describe("UserPasswordApp (OSS)", () => {
+ it("should hide Slack settings for a user without a Slack account", () => {
+ setup({ user: createMockUser({ slack_account_status: null }) });
+
+ expect(screen.queryByText("Slack")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Disconnect" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should disconnect a Slack account and refresh the user", async () => {
+ const user = createMockUser({
+ slack_account_status: "active",
+ });
+ const { router, disconnect } = setup({
+ user,
+ disconnectResponse: { delay: 50 },
+ });
+
+ expect(screen.getByText("Slack")).toBeInTheDocument();
+ await disconnect();
+ expect(screen.getByRole("button", { name: "Disconnect" })).toBeDisabled();
+
+ await waitFor(() =>
+ expect(screen.queryByText("Slack")).not.toBeInTheDocument(),
+ );
+ expect(
+ fetchMock.callHistory.called(`path:/api/user/${user.id}/slack`, {
+ method: "DELETE",
+ }),
+ ).toBe(true);
+ expect(screen.getByLabelText("Current password")).toBeInTheDocument();
+ expect(router?.location.pathname).toBe("/account/authentication");
+ });
+
+ it("should keep the Slack account when the confirmation is cancelled", async () => {
+ const user = createMockUser({ slack_account_status: "active" });
+ const { openDisconnectDialog } = setup({ user });
+
+ await userEvent.click(
+ within(await openDisconnectDialog()).getByRole("button", {
+ name: "Cancel",
+ }),
+ );
+
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(screen.getByText("Slack")).toBeInTheDocument();
+ expect(
+ fetchMock.callHistory.called(`path:/api/user/${user.id}/slack`, {
+ method: "DELETE",
+ }),
+ ).toBe(false);
+ });
+
+ it("should show an inactive link that can still be disconnected", () => {
+ setup({ user: createMockUser({ slack_account_status: "inactive" }) });
+
+ expect(
+ screen.getByText("Your Slack connection is no longer active."),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(/Your Slack account is connected/),
+ ).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Disconnect" })).toBeEnabled();
+ });
+
+ it.each(["google", "ldap", "jwt"] as const)(
+ "should confirm disconnecting and go to Profile when a %s user's Authentication page becomes empty",
+ async (ssoSource) => {
+ const user = createMockUser({
+ sso_source: ssoSource,
+ slack_account_status: "active",
+ });
+ const { router, disconnect } = setup({
+ user,
+ mfaStatus: createMockMfaStatus({ mfa_enabled: false }),
+ });
+
+ await disconnect();
+
+ expect(
+ await screen.findByText("Your Slack account has been disconnected."),
+ ).toBeInTheDocument();
+ await waitFor(() =>
+ expect(router?.location.pathname).toBe("/account/profile"),
+ );
+ },
+ );
+
+ it("should keep the Slack account and show an error when disconnecting fails", async () => {
+ const user = createMockUser({ slack_account_status: "active" });
+ const { disconnect } = setup({
+ user,
+ disconnectResponse: {
+ status: 500,
+ body: { message: "Could not disconnect Slack" },
+ },
+ });
+
+ await disconnect();
+
+ expect(
+ await screen.findByText("Could not disconnect Slack"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Slack")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Disconnect" })).toBeEnabled();
+ });
+
+ it("should explain a failed refresh without showing a success toast", async () => {
+ const { disconnect } = setup({
+ user: createMockUser({ slack_account_status: "active" }),
+ currentUserStatus: 500,
+ });
+
+ await disconnect();
+
+ expect(
+ await screen.findByText(
+ "Couldn't refresh your account settings. Please reload the page.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Your Slack account has been disconnected."),
+ ).not.toBeInTheDocument();
+ });
+
it("should show the password form", () => {
setup();
diff --git a/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/enterprise.unit.spec.tsx
index e34803a4b0d..ebeb1c2f924 100644
--- a/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/enterprise.unit.spec.tsx
+++ b/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/enterprise.unit.spec.tsx
@@ -1,14 +1,20 @@
-import { screen, waitForLoaderToBeRemoved } from "__support__/ui";
+import { screen, waitFor, waitForLoaderToBeRemoved } from "__support__/ui";
import { createMockMfaStatus, createMockUser } from "metabase-types/api/mocks";
-import { setup } from "./setup";
+import { type SetupOpts, setup as setupCommon } from "./setup";
+
+function setup(options: SetupOpts = {}) {
+ return setupCommon({
+ hasMfaPlugin: true,
+ hasAuthPlugin: true,
+ tokenFeatures: { "multi-factor-auth": true, disable_password_login: true },
+ ...options,
+ });
+}
describe("UserPasswordApp (EE)", () => {
it("should show two-factor authentication settings alongside the password form", async () => {
- setup({
- hasMfaPlugin: true,
- tokenFeatures: { "multi-factor-auth": true },
- });
+ setup();
expect(
await screen.findByText("Two-factor authentication"),
@@ -18,9 +24,7 @@ describe("UserPasswordApp (EE)", () => {
it("should not show two-factor authentication settings when the instance has it off", async () => {
setup({
- hasMfaPlugin: true,
mfaStatus: createMockMfaStatus({ mfa_enabled: false, enrolled: true }),
- tokenFeatures: { "multi-factor-auth": true },
});
await waitForLoaderToBeRemoved();
@@ -34,8 +38,6 @@ describe("UserPasswordApp (EE)", () => {
it("should show only two-factor authentication settings for an LDAP user", async () => {
setup({
user: createMockUser({ sso_source: "ldap" }),
- hasMfaPlugin: true,
- tokenFeatures: { "multi-factor-auth": true },
});
expect(
@@ -43,4 +45,62 @@ describe("UserPasswordApp (EE)", () => {
).toBeInTheDocument();
expect(screen.queryByLabelText("Current password")).not.toBeInTheDocument();
});
+
+ it("should keep the MFA settings after an LDAP user disconnects Slack", async () => {
+ const user = createMockUser({
+ sso_source: "ldap",
+ slack_account_status: "active",
+ });
+ const { router, disconnect } = setup({
+ user,
+ });
+
+ await screen.findByText("Two-factor authentication");
+ await disconnect();
+ await screen.findByText("Your Slack account has been disconnected.");
+
+ expect(screen.getByText("Two-factor authentication")).toBeInTheDocument();
+ expect(screen.queryByText("Slack")).not.toBeInTheDocument();
+ expect(router?.location.pathname).toBe("/account/authentication");
+ });
+
+ it("should go to Profile after an OIDC user disconnects with password login and MFA disabled", async () => {
+ const user = createMockUser({
+ sso_source: "oidc",
+ slack_account_status: "active",
+ });
+ const { router, disconnect } = setup({
+ user,
+ mfaStatus: createMockMfaStatus({ mfa_enabled: false }),
+ isPasswordLoginEnabled: false,
+ });
+
+ expect(screen.queryByLabelText("Current password")).not.toBeInTheDocument();
+ await disconnect();
+
+ expect(
+ await screen.findByText("Your Slack account has been disconnected."),
+ ).toBeInTheDocument();
+ await waitFor(() =>
+ expect(router?.location.pathname).toBe("/account/profile"),
+ );
+ });
+
+ it("should show the Slack row for an SSO user", async () => {
+ setup({
+ user: createMockUser({
+ sso_source: "google",
+ slack_account_status: "active",
+ }),
+ });
+
+ expect(await screen.findByText("Slack")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Disconnect" }),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByText("Two-factor authentication"),
+ ).toBeInTheDocument();
+ expect(screen.queryByLabelText("Current password")).not.toBeInTheDocument();
+ });
});
diff --git a/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/setup.tsx b/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/setup.tsx
index 595d4a33cab..254f2afc824 100644
--- a/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/setup.tsx
+++ b/frontend/src/metabase/account/password/containers/UserPasswordApp/tests/setup.tsx
@@ -1,8 +1,21 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
-import { setupMfaStatusEndpoint } from "__support__/server-mocks";
+import {
+ setupCurrentUserEndpoint,
+ setupDisconnectSlackEndpoint,
+ setupMfaStatusEndpoint,
+} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
-import { renderWithProviders } from "__support__/ui";
+import {
+ renderRoutes,
+ renderWithProviders,
+ screen,
+ within,
+} from "__support__/ui";
+import { PLUGIN_IS_PASSWORD_USER } from "metabase/plugins";
import type { MfaStatus, TokenFeatures, User } from "metabase-types/api";
import {
createMockMfaStatus,
@@ -12,31 +25,96 @@ import {
import UserPasswordApp from "../UserPasswordApp";
-type SetupOpts = {
+let authPasswordUserPredicates: typeof PLUGIN_IS_PASSWORD_USER = [];
+
+export type SetupOpts = {
user?: User;
+ currentUserResponse?: User;
+ currentUserStatus?: number;
+ disconnectResponse?: Parameters<typeof setupDisconnectSlackEndpoint>[1];
+ routes?: Parameters<typeof renderRoutes>[0];
mfaStatus?: MfaStatus;
hasMfaPlugin?: boolean;
+ hasAuthPlugin?: boolean;
+ isPasswordLoginEnabled?: boolean;
tokenFeatures?: Partial<TokenFeatures>;
};
export function setup({
user = createMockUser(),
+ currentUserResponse = { ...user, slack_account_status: null },
+ currentUserStatus = 200,
+ disconnectResponse,
+ routes,
mfaStatus = createMockMfaStatus(),
hasMfaPlugin = false,
+ hasAuthPlugin = false,
+ isPasswordLoginEnabled = true,
tokenFeatures = {},
}: SetupOpts = {}) {
+ const passwordUserPredicates = PLUGIN_IS_PASSWORD_USER.filter(
+ (predicate) => !authPasswordUserPredicates.includes(predicate),
+ );
+ PLUGIN_IS_PASSWORD_USER.splice(
+ 0,
+ PLUGIN_IS_PASSWORD_USER.length,
+ ...passwordUserPredicates,
+ );
+ authPasswordUserPredicates = [];
+ if (currentUserStatus === 200) {
+ setupCurrentUserEndpoint(currentUserResponse);
+ } else {
+ fetchMock.get("path:/api/user/current", { status: currentUserStatus });
+ }
setupMfaStatusEndpoint(mfaStatus);
+ setupDisconnectSlackEndpoint(user.id, disconnectResponse);
+
+ const state = createMockState({
+ currentUser: user,
+ settings: mockSettings({
+ "enable-password-login": isPasswordLoginEnabled,
+ "mfa-enforcement": mfaStatus.mfa_enabled ? "optional" : "off",
+ "token-features": createMockTokenFeatures(tokenFeatures),
+ }),
+ });
if (hasMfaPlugin) {
setupEnterpriseOnlyPlugin("multi_factor_auth");
}
+ if (hasAuthPlugin) {
+ const predicateCount = PLUGIN_IS_PASSWORD_USER.length;
+ setupEnterpriseOnlyPlugin("auth");
+ authPasswordUserPredicates = PLUGIN_IS_PASSWORD_USER.slice(predicateCount);
+ }
- renderWithProviders(<UserPasswordApp />, {
- storeInitialState: createMockState({
- currentUser: user,
- settings: mockSettings({
- "token-features": createMockTokenFeatures(tokenFeatures),
- }),
- }),
+ const options = {
+ withRouter: true,
+ initialRoute: "/account/authentication",
+ withUndos: true,
+ storeInitialState: state,
+ };
+ const rendered = routes
+ ? renderRoutes(routes, options)
+ : renderWithProviders(<UserPasswordApp />, options);
+
+ return {
+ ...rendered,
+ user,
+ openDisconnectDialog,
+ disconnect: async () =>
+ userEvent.click(
+ within(await openDisconnectDialog()).getByRole("button", {
+ name: "Disconnect",
+ }),
+ ),
+ };
+}
+
+async function openDisconnectDialog() {
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Disconnect" }),
+ );
+ return screen.findByRole("dialog", {
+ name: "Disconnect your Slack account?",
});
}
diff --git a/frontend/src/metabase/account/utils.ts b/frontend/src/metabase/account/utils.ts
new file mode 100644
index 00000000000..6d763bcc131
--- /dev/null
+++ b/frontend/src/metabase/account/utils.ts
@@ -0,0 +1,15 @@
+import { PLUGIN_IS_PASSWORD_USER } from "metabase/plugins";
+import type { MfaEnforcement, User } from "metabase-types/api";
+
+export function hasAuthenticationSettings(
+ user: User,
+ mfaEnforcement: MfaEnforcement | undefined,
+) {
+ return (
+ PLUGIN_IS_PASSWORD_USER.every((predicate) => predicate(user)) ||
+ user.slack_account_status != null ||
+ (mfaEnforcement != null &&
+ mfaEnforcement !== "off" &&
+ user.sso_source === "ldap")
+ );
+}
diff --git a/frontend/src/metabase/api/user.ts b/frontend/src/metabase/api/user.ts
index 83c6f6c5103..c7e63d15aee 100644
--- a/frontend/src/metabase/api/user.ts
+++ b/frontend/src/metabase/api/user.ts
@@ -67,6 +67,14 @@ export const userApi = Api.injectEndpoints({
invalidatesTags: (_, error, { id }) =>
invalidateTags(error, [listTag("user"), idTag("user", id)]),
}),
+ disconnectSlack: builder.mutation<void, UserId>({
+ query: (id) => ({
+ method: "DELETE",
+ url: `/api/user/${id}/slack`,
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [tag("current-user")]),
+ }),
deactivateUser: builder.mutation<void, UserId>({
query: (id) => ({
method: "DELETE",
@@ -128,6 +136,7 @@ export const {
useGetUserQuery,
useCreateUserMutation,
useUpdatePasswordMutation,
+ useDisconnectSlackMutation,
useDeactivateUserMutation,
useReactivateUserMutation,
useUpdateUserMutation,
diff --git a/frontend/src/metabase/routes.unit.spec.tsx b/frontend/src/metabase/routes.unit.spec.tsx
index b41bee0c1f9..4740da84631 100644
--- a/frontend/src/metabase/routes.unit.spec.tsx
+++ b/frontend/src/metabase/routes.unit.spec.tsx
@@ -1,4 +1,6 @@
-import { waitFor } from "@testing-library/react";
+import { act, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import {
setupCurrentUserEndpoint,
@@ -6,8 +8,12 @@ import {
setupUserKeyValueEndpoints,
} from "__support__/server-mocks";
import { renderRoutes, renderWithProviders, screen } from "__support__/ui";
+import { setup as setupAccountPassword } from "metabase/account/password/containers/UserPasswordApp/tests/setup";
+import { getUser } from "metabase/current-user";
import { PLUGIN_AUDIT, reinitialize } from "metabase/plugins";
import { Route } from "metabase/router";
+import { defer } from "metabase/utils/promise";
+import type { User } from "metabase-types/api";
import { createMockUser } from "metabase-types/api/mocks";
import { LegacyBrowseRedirect, getRoutes } from "./routes";
@@ -162,6 +168,137 @@ describe("application routes", () => {
});
});
+describe("disconnecting Slack with application routes", () => {
+ afterEach(reinitialize);
+
+ it.each([200, 401])(
+ "should confirm Disconnect after leaving the page when the refresh returns %s",
+ async (currentUserStatus) => {
+ const user = createMockUser({
+ sso_source: "slack",
+ slack_account_status: "active",
+ });
+ const expectedPathname =
+ currentUserStatus === 401 ? "/auth/login" : "/account/profile";
+ const expectedUser =
+ currentUserStatus === 401
+ ? null
+ : { ...user, slack_account_status: null };
+ const response = defer<{ status: number }>();
+ fetchMock.delete(
+ `path:/api/user/${user.id}/slack`,
+ () => response.promise,
+ );
+ const { router, store, disconnect } = setupAccountPassword({
+ user,
+ currentUserStatus,
+ routes: getRoutes,
+ });
+
+ await disconnect();
+ await userEvent.click(
+ await screen.findByRole("tab", { name: "Profile" }),
+ );
+ await waitFor(() =>
+ expect(router?.location.pathname).toBe("/account/profile"),
+ );
+
+ await act(async () => response.resolve({ status: 204 }));
+
+ expect(
+ await screen.findByText("Your Slack account has been disconnected."),
+ ).toBeInTheDocument();
+ await waitFor(() =>
+ expect(router?.location.pathname).toBe(expectedPathname),
+ );
+ expect(getUser(store.getState())).toEqual(expectedUser);
+ },
+ );
+
+ it("should stay on the chosen page when the refresh finishes after leaving Authentication", async () => {
+ const user = createMockUser({
+ sso_source: "google",
+ slack_account_status: "active",
+ });
+ const response = defer<User>();
+ fetchMock.get("path:/api/user/current", () => response.promise, {
+ name: "current-user-refresh",
+ });
+ fetchMock.get("path:/api/pulse", []);
+ fetchMock.get("path:/api/notification", []);
+ const { router, disconnect } = setupAccountPassword({
+ user,
+ hasAuthPlugin: true,
+ tokenFeatures: { disable_password_login: true },
+ routes: getRoutes,
+ });
+
+ await disconnect();
+ await waitFor(() =>
+ expect(fetchMock.callHistory.called("current-user-refresh")).toBe(true),
+ );
+ await userEvent.click(
+ await screen.findByRole("tab", { name: "Notifications" }),
+ );
+ await waitFor(() =>
+ expect(router?.location.pathname).toBe("/account/notifications"),
+ );
+
+ await act(async () =>
+ response.resolve({ ...user, slack_account_status: null }),
+ );
+
+ expect(
+ await screen.findByText("Your Slack account has been disconnected."),
+ ).toBeInTheDocument();
+ expect(router?.location.pathname).toBe("/account/notifications");
+ });
+
+ it("should clear the cached user and render sign in when the Slack session ends", async () => {
+ const { router, store, disconnect } = setupAccountPassword({
+ user: createMockUser({
+ sso_source: "slack",
+ slack_account_status: "active",
+ }),
+ currentUserStatus: 401,
+ routes: getRoutes,
+ });
+ const visited: string[] = [];
+ router?.onLocationChange((location) => visited.push(location.pathname));
+
+ await disconnect();
+
+ expect(await screen.findByText(/Sign in to/)).toBeInTheDocument();
+ expect(router?.location.pathname).toBe("/auth/login");
+ expect(getUser(store.getState())).toBeNull();
+ expect(visited).not.toContain("/");
+ expect(screen.queryByText("Slack")).not.toBeInTheDocument();
+ });
+
+ it("should replace the empty Authentication page in browser history", async () => {
+ const { router, disconnect } = setupAccountPassword({
+ user: createMockUser({
+ sso_source: "google",
+ slack_account_status: "active",
+ }),
+ hasAuthPlugin: true,
+ tokenFeatures: { disable_password_login: true },
+ routes: getRoutes,
+ });
+
+ await disconnect();
+ await waitFor(() =>
+ expect(router?.location.pathname).toBe("/account/profile"),
+ );
+ expect(await screen.findByTestId("user-locale-select")).toBeInTheDocument();
+
+ act(() => router?.back());
+
+ expect(router?.location.pathname).toBe("/account/profile");
+ expect(screen.getByTestId("user-locale-select")).toBeInTheDocument();
+ });
+});
+
describe("collection modal routes", () => {
it("renders the move-questions-into-dashboards modal with a single dialog", async () => {
setupUserKeyValueEndpoints({
diff --git a/frontend/test/__support__/server-mocks/user.ts b/frontend/test/__support__/server-mocks/user.ts
index 568e2ca70ce..ffdec3894e2 100644
--- a/frontend/test/__support__/server-mocks/user.ts
+++ b/frontend/test/__support__/server-mocks/user.ts
@@ -25,6 +25,25 @@ export function setupUpdatePasswordEndpoint(userId: UserId) {
fetchMock.put(`path:/api/user/${userId}/password`, {});
}
+export function setupDisconnectSlackEndpoint(
+ userId: UserId,
+ {
+ status = 204,
+ body,
+ delay = 0,
+ }: {
+ status?: number;
+ body?: { message: string };
+ delay?: number;
+ } = {},
+) {
+ fetchMock.delete(
+ `path:/api/user/${userId}/slack`,
+ { status, body },
+ { delay },
+ );
+}
+
export function setupUsersEndpoints(users: UserListResult[]) {
users.forEach((user) => setupUserEndpoints(user));
return fetchMock.get("path:/api/user", { data: users, total: users.length });
diff --git a/src/metabase/slackbot/api.clj b/src/metabase/slackbot/api.clj
index ceff2622cf5..8ec81eb4a7c 100644
--- a/src/metabase/slackbot/api.clj
+++ b/src/metabase/slackbot/api.clj
@@ -21,6 +21,7 @@
[metabase.slackbot.settings :as slackbot.settings]
[metabase.slackbot.streaming :as slackbot.streaming]
[metabase.slackbot.uploads :as slackbot.uploads]
+ [metabase.sso.core :as sso]
[metabase.sso.settings :as sso-settings]
[metabase.system.core :as system]
[metabase.util :as u]
@@ -89,22 +90,12 @@
;; ------------------------- AUTHENTICATION ------------------------------
-(defn- current-signing-secret-version
- []
- (or (server.settings/slack-connect-signing-secret-version) 0))
-
-(defn- auth-identity-signing-secret-version
- [identity]
- (or (get-in identity [:metadata :signing_secret_version]) 0))
-
(defn- slack-id->user-id
- "Look up a Metabase user ID from Slack user ID. Only returns a match if the identity was created under the current
- signing secret version, so that rotating the secret automatically invalidates existing identity links. Legacy
- identities without an explicit version are treated as version 0."
+ "Return the user ID of the newest Slack link if the link is active and so is its user, or nil.
+ Turning off Slack Connect or rotating the signing secret makes existing links inactive."
[slack-user-id]
(let [identity (slackbot.db/active-slack-connect-identity slack-user-id)]
- (when (= (auth-identity-signing-secret-version identity)
- (current-signing-secret-version))
+ (when (sso/slack-connect-identity-active? identity)
(:user_id identity))))
(defn- slack-user-authorize-link
@@ -467,7 +458,7 @@
:slack-connect-enabled (boolean all-set?)})
(when signing-secret-changed?
(server.settings/slack-connect-signing-secret-version!
- (inc (current-signing-secret-version))))
+ (inc (server.settings/slack-connect-signing-secret-version))))
{:ok true}))
;; ------------------------- FEEDBACK BUTTONS ------------------------------
diff --git a/src/metabase/slackbot/db.clj b/src/metabase/slackbot/db.clj
index 4c43e950cf4..db584d337b1 100644
--- a/src/metabase/slackbot/db.clj
+++ b/src/metabase/slackbot/db.clj
@@ -11,7 +11,7 @@
[slack-user-id :- :string]
(t2/select-one [:model/AuthIdentity :user_id :metadata]
:provider "slack-connect"
- :provider_id slack-user-id
+ :provider_id [:auto/param slack-user-id]
{:join [[:core_user :user] [:= :user.id :auth_identity.user_id]]
:where [:= :user.is_active true]
:order-by [[:created_at :desc]]}))
diff --git a/src/metabase/sso/core.clj b/src/metabase/sso/core.clj
index d183735f37d..d276e488b61 100644
--- a/src/metabase/sso/core.clj
+++ b/src/metabase/sso/core.clj
@@ -8,6 +8,7 @@
[metabase.sso.oidc.check]
[metabase.sso.oidc.state]
[metabase.sso.settings]
+ [metabase.sso.slack-connect]
[potemkin :as p]))
(p/import-vars
@@ -30,6 +31,10 @@
send-new-sso-user-admin-email?
sso-enabled?
sso-source-enabled?]
+ [metabase.sso.slack-connect
+ disconnect-slack-account!
+ slack-account-status
+ slack-connect-identity-active?]
[metabase.sso.ldap.settings
ldap-enabled])
diff --git a/src/metabase/sso/db.clj b/src/metabase/sso/db.clj
index 9e8490b3809..243fe375ac6 100644
--- a/src/metabase/sso/db.clj
+++ b/src/metabase/sso/db.clj
@@ -35,6 +35,17 @@
provider :- :string]
(t2/exists? :model/AuthIdentity :user_id user-id :provider provider))
+(mu/defn slack-connect-identity
+ "The user's Slack identity with `:provider_id` and `:metadata` selected, or nil."
+ [user-id :- ::lib.schema.id/user]
+ (t2/select-one [:model/AuthIdentity :provider_id :metadata]
+ :user_id [:auto/param (long user-id)] :provider "slack-connect"))
+
+(mu/defn delete-slack-connect-identity!
+ "Delete the user's Slack identity, returning the number deleted."
+ [user-id :- ::lib.schema.id/user]
+ (t2/delete! :model/AuthIdentity :user_id [:auto/param (long user-id)] :provider "slack-connect"))
+
(mu/defn insert-auth-identity!
"Insert an AuthIdentity linking the User with `user-id` to `provider-id` at `provider`."
[user-id :- ::lib.schema.id/user
diff --git a/src/metabase/sso/slack_connect.clj b/src/metabase/sso/slack_connect.clj
new file mode 100644
index 00000000000..c0146f4cb35
--- /dev/null
+++ b/src/metabase/sso/slack_connect.clj
@@ -0,0 +1,27 @@
+(ns metabase.sso.slack-connect
+ (:require
+ [metabase.server.settings :as server.settings]
+ [metabase.sso.db :as sso.db]
+ [metabase.sso.settings :as sso-settings]))
+
+(defn slack-connect-identity-active?
+ "Whether Slack Connect is enabled and `identity` was linked under the current signing secret. Missing versions are
+ treated as zero."
+ [identity]
+ (and (some? identity)
+ (sso-settings/slack-connect-enabled)
+ (= (or (get-in identity [:metadata :signing_secret_version]) 0)
+ (server.settings/slack-connect-signing-secret-version))))
+
+(defn slack-account-status
+ "Return \"active\" or \"inactive\" for the user's Slack identity, or nil when none exists."
+ [user-id]
+ (when-let [identity (sso.db/slack-connect-identity user-id)]
+ (if (slack-connect-identity-active? identity)
+ "active"
+ "inactive")))
+
+(defn disconnect-slack-account!
+ "Remove the Slack link of the user with `user-id`."
+ [user-id]
+ (sso.db/delete-slack-connect-identity! user-id))
diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.clj
index bde00494c8e..58dcfe1f8f5 100644
--- a/src/metabase/users_rest/api.clj
+++ b/src/metabase/users_rest/api.clj
@@ -380,6 +380,7 @@
[:has_invited_second_user :boolean]
[:has_question_and_dashboard :boolean]
[:has_model :boolean]
+ [:slack_account_status [:maybe [:enum "active" "inactive"]]]
[:can_write_any_collection :boolean]
[:sso_source [:maybe :keyword]]
[:locale [:maybe :string]]
@@ -409,7 +410,18 @@
maybe-add-advanced-permissions
maybe-add-sso-source
add-custom-homepage-info
- add-can-write-any-collection))
+ add-can-write-any-collection
+ (assoc :slack_account_status (sso/slack-account-status api/*current-user-id*))))
+
+(api.macros/defendpoint :delete "/:id/slack" :- [:map {:closed true}
+ [:status [:= 204]]
+ [:body :nil]]
+ "Remove the current user's Slack Connect link."
+ [{:keys [id]} :- [:map {:closed true}
+ [:id ms/PositiveInt]]]
+ (api/check-403 (= id api/*current-user-id*))
+ (sso/disconnect-slack-account! id)
+ api/generic-204-no-content)
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
diff --git a/test/metabase/slackbot/api_test.clj b/test/metabase/slackbot/api_test.clj
index 98a65515488..778506431c2 100644
--- a/test/metabase/slackbot/api_test.clj
+++ b/test/metabase/slackbot/api_test.clj
@@ -480,75 +480,107 @@
(deftest slack-id->user-id-test
(testing "slack-id->user-id only returns active users with sso_source 'slack'"
(let [slack-id "U12345SLACK"]
- (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 0]
- (mt/with-temp [:model/User {active-slack-user-id :id} {:email "[email protected]"
- :is_active true
- :sso_source "slack"}
- :model/User {inactive-slack-user-id :id} {:email "[email protected]"
- :is_active false
- :sso_source "slack"}
- :model/User {active-google-user-id :id} {:email "[email protected]"
- :is_active true
- :sso_source "google"}]
- (testing "returns user ID for active user with sso_source 'slack'"
- (mt/with-temp [:model/AuthIdentity _ {:user_id active-slack-user-id
- :provider "slack-connect"
- :provider_id slack-id
- :metadata {:signing_secret_version 0}}]
- (is (= active-slack-user-id
- (#'slackbot/slack-id->user-id slack-id)))))
- (testing "returns user ID for active user with sso_source 'google'"
- (mt/with-temp [:model/AuthIdentity _ {:user_id active-google-user-id
- :provider "slack-connect"
- :provider_id slack-id
- :metadata {:signing_secret_version 0}}]
- (is (= active-google-user-id
- (#'slackbot/slack-id->user-id slack-id)))))
- (testing "returns nil for inactive user with sso_source 'slack'"
- (mt/with-temp [:model/AuthIdentity _ {:user_id inactive-slack-user-id
- :provider "slack-connect"
- :provider_id slack-id
- :metadata {:signing_secret_version 0}}]
- (is (nil? (#'slackbot/slack-id->user-id slack-id)))))
- (testing "returns nil for active user with different provider"
- (mt/with-temp [:model/AuthIdentity _ {:user_id active-google-user-id
- :provider "google"
- :provider_id slack-id}]
- (is (nil? (#'slackbot/slack-id->user-id slack-id)))))
- (testing "returns nil when no AuthIdentity exists"
- (is (nil? (#'slackbot/slack-id->user-id slack-id)))))))))
+ (tu/with-slackbot-setup
+ (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 0]
+ (mt/with-temp [:model/User {active-slack-user-id :id} {:email "[email protected]"
+ :is_active true
+ :sso_source "slack"}
+ :model/User {inactive-slack-user-id :id} {:email "[email protected]"
+ :is_active false
+ :sso_source "slack"}
+ :model/User {active-google-user-id :id} {:email "[email protected]"
+ :is_active true
+ :sso_source "google"}]
+ (testing "returns user ID for active user with sso_source 'slack'"
+ (mt/with-temp [:model/AuthIdentity _ {:user_id active-slack-user-id
+ :provider "slack-connect"
+ :provider_id slack-id
+ :metadata {:signing_secret_version 0}}]
+ (is (= active-slack-user-id
+ (#'slackbot/slack-id->user-id slack-id)))))
+ (testing "returns user ID for active user with sso_source 'google'"
+ (mt/with-temp [:model/AuthIdentity _ {:user_id active-google-user-id
+ :provider "slack-connect"
+ :provider_id slack-id
+ :metadata {:signing_secret_version 0}}]
+ (is (= active-google-user-id
+ (#'slackbot/slack-id->user-id slack-id)))))
+ (testing "returns nil for inactive user with sso_source 'slack'"
+ (mt/with-temp [:model/AuthIdentity _ {:user_id inactive-slack-user-id
+ :provider "slack-connect"
+ :provider_id slack-id
+ :metadata {:signing_secret_version 0}}]
+ (is (nil? (#'slackbot/slack-id->user-id slack-id)))))
+ (testing "returns nil for active user with different provider"
+ (mt/with-temp [:model/AuthIdentity _ {:user_id active-google-user-id
+ :provider "google"
+ :provider_id slack-id}]
+ (is (nil? (#'slackbot/slack-id->user-id slack-id)))))
+ (testing "returns nil when no AuthIdentity exists"
+ (is (nil? (#'slackbot/slack-id->user-id slack-id))))))))))
+
+(deftest disconnect-slack-account-sends-auth-link-test
+ (tu/with-slackbot-setup
+ (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 0]
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity _ {:user_id user-id
+ :provider "slack-connect"
+ :provider_id "U-DISCONNECT"
+ :metadata {:signing_secret_version 0}}]
+ (is (= user-id (#'slackbot/slack-id->user-id "U-DISCONNECT")))
+ (mt/user-http-request user-id :delete 204 (str "user/" user-id "/slack"))
+ (let [post-calls (atom [])]
+ (mt/with-dynamic-fn-redefs [slackbot.client/post-message (fn [_ payload] (swap! post-calls conj payload))]
+ (is (nil? (#'slackbot/require-authenticated-slack-user!
+ {} (assoc (:event tu/base-dm-event) :user "U-DISCONNECT"))))
+ (is (=? [{:text #"Connect your Slack account to Metabase.*"
+ :blocks [{:type "section"} {:type "actions"}]}]
+ @post-calls))))))))
(deftest slack-id->user-id-signing-secret-version-test
(testing "slack-id->user-id respects signing secret version"
(let [slack-id "U12345VERSION"]
- (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"
- :is_active true}]
- (testing "identity with current version is accepted"
- (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 1]
- (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
- :provider "slack-connect"
- :provider_id slack-id
- :metadata {:signing_secret_version 1}}]
- (is (= user-id (#'slackbot/slack-id->user-id slack-id))))))
- (testing "identity with old version is rejected after rotation"
- (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 2]
- (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
- :provider "slack-connect"
- :provider_id slack-id
- :metadata {:signing_secret_version 1}}]
- (is (nil? (#'slackbot/slack-id->user-id slack-id))))))
- (testing "legacy identity with no version is accepted before any rotation"
- (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 0]
- (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
- :provider "slack-connect"
- :provider_id slack-id}]
- (is (= user-id (#'slackbot/slack-id->user-id slack-id))))))
- (testing "legacy identity with no version is rejected after rotation"
- (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 1]
- (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
- :provider "slack-connect"
- :provider_id slack-id}]
- (is (nil? (#'slackbot/slack-id->user-id slack-id))))))))))
+ (tu/with-slackbot-setup
+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"
+ :is_active true}]
+ (testing "identity with current version is accepted"
+ (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 1]
+ (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
+ :provider "slack-connect"
+ :provider_id slack-id
+ :metadata {:signing_secret_version 1}}]
+ (is (= user-id (#'slackbot/slack-id->user-id slack-id))))))
+ (testing "identity with old version is rejected after rotation"
+ (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 2]
+ (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
+ :provider "slack-connect"
+ :provider_id slack-id
+ :metadata {:signing_secret_version 1}}]
+ (is (nil? (#'slackbot/slack-id->user-id slack-id))))))
+ (testing "legacy identity with no version is accepted before any rotation"
+ (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 0]
+ (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
+ :provider "slack-connect"
+ :provider_id slack-id}]
+ (is (= user-id (#'slackbot/slack-id->user-id slack-id))))))
+ (testing "legacy identity with no version is rejected after rotation"
+ (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 1]
+ (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
+ :provider "slack-connect"
+ :provider_id slack-id}]
+ (is (nil? (#'slackbot/slack-id->user-id slack-id)))))))))))
+
+(deftest slack-id->user-id-slack-connect-disabled-test
+ (testing "slack-id->user-id returns nil while Slack Connect is disabled"
+ (tu/with-slackbot-setup
+ (mt/with-temporary-setting-values [server.settings/slack-connect-signing-secret-version 0]
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity _ {:user_id user-id
+ :provider "slack-connect"
+ :provider_id "U-DISABLED"}]
+ (is (= user-id (#'slackbot/slack-id->user-id "U-DISABLED")))
+ (mt/with-temporary-setting-values [sso-settings/slack-connect-enabled false]
+ (is (nil? (#'slackbot/slack-id->user-id "U-DISABLED")))))))))
(deftest ^:synchronized channel-message-without-mention-no-auth-test
(testing "POST /events with channel message (no @mention) from unlinked user should NOT send auth message"
diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.clj
index 840643d12ea..5de0abff56c 100644
--- a/test/metabase/users_rest/api_test.clj
+++ b/test/metabase/users_rest/api_test.clj
@@ -444,6 +444,83 @@
:has_invited_second_user (= 1 (mt/user->id :rasta))}
(mt/user-http-request :rasta :get 200 "user/current")))))))
+(deftest current-user-slack-account-test
+ (doseq [[enabled? version metadata expected-status]
+ [[true 0 nil "active"]
+ [true 2 {:signing_secret_version 2} "active"]
+ [true 2 {:signing_secret_version 1} "inactive"]
+ [true 2 nil "inactive"]
+ [false 2 {:signing_secret_version 2} "inactive"]]]
+ (testing (str "Slack enabled=" enabled? ", version=" version ", metadata=" metadata)
+ (mt/with-temporary-setting-values [slack-connect-client-id "test-client"
+ slack-connect-client-secret "test-secret"
+ slack-connect-enabled enabled?
+ slack-connect-signing-secret-version version]
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (is (nil? (:slack_account_status (mt/user-http-request user-id :get 200 "user/current"))))
+ (mt/with-temp [:model/AuthIdentity _ {:user_id user-id
+ :provider "slack-connect"
+ :provider_id "U-LINKED"
+ :metadata metadata}]
+ (is (= expected-status
+ (:slack_account_status (mt/user-http-request user-id :get 200 "user/current"))))))))))
+
+(deftest ^:parallel disconnect-slack-account-test
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/User {other-user-id :id} {}
+ :model/AuthIdentity {slack-identity-id :id} {:user_id user-id
+ :provider "slack-connect"
+ :provider_id "U-DISCONNECT"}
+ :model/AuthIdentity {other-identity-id :id} {:user_id other-user-id
+ :provider "slack-connect"
+ :provider_id "U-DISCONNECT"}
+ :model/AuthIdentity {google-identity-id :id} {:user_id user-id
+ :provider "google"
+ :provider_id "U-DISCONNECT"}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request user-id :delete 403 (str "user/" other-user-id "/slack"))))
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :crowberto :delete 403 (str "user/" user-id "/slack"))))
+ (is (t2/exists? :model/AuthIdentity :id slack-identity-id))
+ (is (nil? (mt/user-http-request user-id :delete 204 (str "user/" user-id "/slack"))))
+ (is (not (t2/exists? :model/AuthIdentity :id slack-identity-id)))
+ (is (t2/exists? :model/AuthIdentity :id other-identity-id))
+ (is (t2/exists? :model/AuthIdentity :id google-identity-id))
+ (is (nil? (:slack_account_status (mt/user-http-request user-id :get 200 "user/current"))))
+ (is (nil? (mt/user-http-request user-id :delete 204 (str "user/" user-id "/slack"))))))
+
+(deftest ^:parallel disconnect-slack-account-revokes-slack-sessions-test
+ (let [slack-session-key (session/generate-session-key)
+ other-slack-session-key (session/generate-session-key)
+ password-session-key (session/generate-session-key)]
+ (mt/with-temp [:model/User {user-id :id} {:sso_source "slack"}
+ :model/AuthIdentity {slack-identity-id :id} {:user_id user-id
+ :provider "slack-connect"
+ :provider_id "U-SLACK-SESSION"}
+ :model/AuthIdentity {password-identity-id :id} {:user_id user-id
+ :provider "password"
+ :credentials {:password_hash "hash"
+ :password_salt "salt"}}
+ :model/Session {slack-session-id :id} {:id (session/generate-session-id)
+ :user_id user-id
+ :session_key slack-session-key
+ :auth_identity_id slack-identity-id}
+ :model/Session {other-slack-session-id :id} {:id (session/generate-session-id)
+ :user_id user-id
+ :session_key other-slack-session-key
+ :auth_identity_id slack-identity-id}
+ :model/Session {password-session-id :id} {:id (session/generate-session-id)
+ :user_id user-id
+ :session_key password-session-key
+ :auth_identity_id password-identity-id}]
+ (is (nil? (client/client slack-session-key :delete 204 (str "user/" user-id "/slack"))))
+ (is (not (t2/exists? :model/Session :id slack-session-id)))
+ (is (not (t2/exists? :model/Session :id other-slack-session-id)))
+ (is (t2/exists? :model/Session :id password-session-id))
+ (is (= "Unauthenticated" (client/client slack-session-key :get 401 "user/current")))
+ (is (= "Unauthenticated" (client/client other-slack-session-key :get 401 "user/current")))
+ (is (nil? (:slack_account_status (client/client password-session-key :get 200 "user/current")))))))
+
(deftest ^:parallel get-current-user-test-2
(testing "GET /api/user/current"
(testing "check that `has_question_and_dashboard` is `true`."