The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Security center: send test notifications to unsaved recipients (#74339)
Nicola Mometto7f9d472da2e6
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/api.clj b/enterprise/backend/src/metabase_enterprise/security_center/api.cljindex 552bec4f5f1..0768d849958 100644--- a/enterprise/backend/src/metabase_enterprise/security_center/api.clj+++ b/enterprise/backend/src/metabase_enterprise/security_center/api.clj@@ -10,6 +10,7 @@[metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :as routes.common :refer [+auth]]+ [metabase.notification.models :as models.notification][metabase.premium-features.core :as premium-features][metabase.util.i18n :refer [tru]][metabase.util.malli.schema :as ms]@@ -112,10 +113,25 @@{:status (if submitted? "started" "already-in-progress")}))(api.macros/defendpoint :post "/test-notification" :- [:map [:success :boolean]]- "Send a test notification through the configured Security Center channels."- []+ "Send a test notification through the given Security Center channels.++ The request body lets callers pass the unsaved notification config from the+ dialog so the test reflects current form state, not the persisted settings.+ Both fields are optional; when omitted, the saved setting is used."+ [_route-params+ _query-params+ body+ :- [:map+ [:email_recipients {:optional true} [:maybe [:sequential ::models.notification/NotificationRecipient]]]+ [:slack_channel {:optional true} [:maybe :string]]]](api/check-superuser)- (notification/send-test-notification!)+ (notification/send-test-notification!+ {:email-recipients (if (contains? body :email_recipients)+ (:email_recipients body)+ (settings/security-center-email-recipients))+ :slack-channel (if (contains? body :slack_channel)+ (:slack_channel body)+ (settings/security-center-slack-channel))}){:success true})(def +check-security-center-enableddiff --git a/enterprise/backend/src/metabase_enterprise/security_center/notification.clj b/enterprise/backend/src/metabase_enterprise/security_center/notification.cljindex 75e6d4909f2..c9e2fc537d1 100644--- a/enterprise/backend/src/metabase_enterprise/security_center/notification.clj+++ b/enterprise/backend/src/metabase_enterprise/security_center/notification.clj@@ -51,39 +51,39 @@(= permissions_group_id admin-group-id)))recipients))))-(defn- email-recipients- "Resolve email recipients from the `security-center-email-recipients` setting.- When that list targets the admin group (\"Send to all instance admins\" is on)- and the site admin email is set, the admin email is appended as a raw-value- recipient. When the toggle is off, only the explicitly configured recipients- are used."- []- (let [raw (or (settings/security-center-email-recipients) [])- configured (or (some-> (not-empty raw) (t2/hydrate :recipients-detail))- [])+(defn- compute-email-recipients+ "Resolve email recipients from the given configured list. When that list+ targets the admin group (\"Send to all instance admins\" is on) and the+ site admin email is set, the admin email is appended as a raw-value+ recipient. When the toggle is off, only the explicitly configured+ recipients are used."+ [configured-recipients]+ (let [raw (or configured-recipients [])+ configured (or (some-> (not-empty raw) (t2/hydrate :recipients-detail))+ [])admin-email (system/admin-email)](if (and admin-email (sends-to-all-admins? raw))- (conj configured {:type :notification-recipient/raw-value- :details {:value admin-email}})+ (conj (vec configured) {:type :notification-recipient/raw-value+ :details {:value admin-email}})configured)))-(defn- slack-recipients- "Resolve Slack recipient from the `security-center-slack-channel` setting.- Returns a vector with a single raw-value recipient, or empty if Slack is not configured."- []- (when-let [channel (settings/security-center-slack-channel)]- (when (setting/get-value-of-type :boolean :slack-token-valid?)- [{:type :notification-recipient/raw-value- :details {:value channel}}])))+(defn- compute-slack-recipients+ "Resolve Slack recipient from the given channel name.+ Returns a vector with a single raw-value recipient, or nil if Slack is not configured."+ [channel]+ (when (and channel (setting/get-value-of-type :boolean :slack-token-valid?))+ [{:type :notification-recipient/raw-value+ :details {:value channel}}]))(defn- build-handlers- "Build the notification handlers (email + optional Slack) with dynamically resolved recipients."- []+ "Build the notification handlers (email + optional Slack) from the given+ configured email recipients and Slack channel."+ [{:keys [email-recipients slack-channel]}](let [handlers (when (channel.settings/email-configured?)[{:channel_type :channel/email:template email-template- :recipients (email-recipients)}])]- (if-let [slack-recipients (slack-recipients)]+ :recipients (compute-email-recipients email-recipients)}])]+ (if-let [slack-recipients (compute-slack-recipients slack-channel)](conj handlers {:channel_type :channel/slack:recipients slack-recipients})handlers)))@@ -91,11 +91,11 @@(defn- build-notification"Build a notification map for a security advisory. This is a plain map (not aToucan2 instance), so `send-notification!` skips DB hydration and uses it as-is."- [advisory]+ [advisory config]{:payload_type :notification/system-event:payload {:event_info (advisory-event-info advisory):event_topic :event/security-advisory-match}- :handlers (build-handlers)})+ :handlers (build-handlers config)})(def ^:private channel-type->name"Map channel_type keywords to short names for Snowplow tracking."@@ -123,23 +123,31 @@:remediation "No action required — this is only a test.":affected_versions []})+(defn- saved-config+ "Read the email recipients and Slack channel from the persisted settings."+ []+ {:email-recipients (settings/security-center-email-recipients)+ :slack-channel (settings/security-center-slack-channel)})+(defn send-test-notification!- "Send a test notification through the configured channels so admins can verify+ "Send a test notification through the given channels so admins can verifydelivery without waiting for a real advisory. Does NOT publish an audit event- or update any advisory row."- []- (let [handlers (build-handlers)]- (when (empty? handlers)+ or update any advisory row.++ `config` is a map of `{:email-recipients [...] :slack-channel \"...\"}`+ reflecting the (possibly unsaved) form state in the notification config dialog."+ [config]+ (let [notif (build-notification test-advisory config)]+ (when (empty? (:handlers notif))(throw (ex-info "No notification channels are configured."{:status-code 400})))(log/info "Sending test security center notification")- (let [notif (build-notification test-advisory)]- (try- (notification/send-notification! notif :notification/sync? true)- (track-notification-sent! notif "test" "success")- (catch Exception e- (track-notification-sent! notif "test" "failure")- (throw e))))))+ (try+ (notification/send-notification! notif :notification/sync? true)+ (track-notification-sent! notif "test" "success")+ (catch Exception e+ (track-notification-sent! notif "test" "failure")+ (throw e)))))(defn notify-advisory!"Send notifications for a security advisory and update `last_notified_at`.@@ -156,7 +164,7 @@(advisory-event-info advisory));; Send email + Slack via notification pipeline;; sync, so failure doesn't set last_notified_at- (let [notif (build-notification advisory)]+ (let [notif (build-notification advisory (saved-config))](try(notification/send-notification! notif :notification/sync? true)(track-notification-sent! notif triggered-from "success")diff --git a/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/api_test.cljindex 6de3c81ba0e..8334dbd1251 100644--- a/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj@@ -4,6 +4,7 @@[metabase-enterprise.security-center.fetch :as fetch][metabase-enterprise.security-center.matching :as matching][metabase-enterprise.security-center.notification :as notification]+ [metabase-enterprise.security-center.settings :as settings][metabase.premium-features.core :as premium-features][metabase.premium-features.token-check :as token-check][metabase.test :as mt]@@ -181,12 +182,54 @@(mt/with-premium-features #{:admin-security-center}(testing "non-superuser gets 403"(mt/user-http-request :rasta :post 403 "ee/security-center/test-notification"))- (testing "superuser can send test notification"+ (testing "superuser can send test notification with no body — falls back to saved settings"(with-redefs [notification/send-test-notification! (constantly nil)](is (= {:success true}(mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification")))))(testing "returns 400 when no channels are configured"(with-redefs [notification/send-test-notification!- (fn [] (throw (ex-info "No notification channels are configured."- {:status-code 400})))]+ (fn [_] (throw (ex-info "No notification channels are configured."+ {:status-code 400})))](mt/user-http-request :crowberto :post 400 "ee/security-center/test-notification"))))))++(deftest test-notification-uses-body-test+ (testing "POST /api/ee/security-center/test-notification forwards the request body so the test reflects unsaved form state"+ (mt/with-premium-features #{:admin-security-center}+ (testing "body values are passed through to send-test-notification!"+ (let [captured (atom nil)]+ (with-redefs [notification/send-test-notification! #(reset! captured %)]+ (mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification"+ {:email_recipients [{:type "notification-recipient/raw-value"+ :details {:value "[email protected]"}}+ {:type "notification-recipient/user"+ :user_id (str (mt/user->id :crowberto))}]+ :slack_channel "#form-channel"})+ (is (= [{:type :notification-recipient/raw-value+ :details {:value "[email protected]"}}+ {:type :notification-recipient/user+ :user_id (mt/user->id :crowberto)}]+ (:email-recipients @captured)))+ (is (= "#form-channel" (:slack-channel @captured))))))+ (testing "body distinguishes explicit nil slack_channel (disable) from missing key (fall back to setting)"+ (let [captured (atom nil)]+ (with-redefs [notification/send-test-notification! #(reset! captured %)+ settings/security-center-slack-channel (constantly "#saved-channel")]+ (mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification"+ {:email_recipients [{:type "notification-recipient/group"+ :permissions_group_id 2}]+ :slack_channel nil})+ (is (nil? (:slack-channel @captured)) "explicit nil disables Slack for the test"))+ (with-redefs [notification/send-test-notification! #(reset! captured %)+ settings/security-center-slack-channel (constantly "#saved-channel")]+ (mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification"+ {:email_recipients [{:type "notification-recipient/group"+ :permissions_group_id 2}]})+ (is (= "#saved-channel" (:slack-channel @captured)) "missing key falls back to saved setting"))))+ (testing "missing email_recipients falls back to saved setting"+ (let [captured (atom nil)+ saved-emails [{:type :notification-recipient/raw-value :details {:value "[email protected]"}}]]+ (with-redefs [notification/send-test-notification! #(reset! captured %)+ settings/security-center-email-recipients (constantly saved-emails)+ settings/security-center-slack-channel (constantly nil)]+ (mt/user-http-request :crowberto :post 200 "ee/security-center/test-notification" {})+ (is (= saved-emails (:email-recipients @captured)))))))))diff --git a/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.cljindex c00d405ef9a..e6236536b8a 100644--- a/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj+++ b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj@@ -373,7 +373,7 @@(testing "send-test-notification! sends a notification with test advisory data"(let [sent (atom nil)](with-send-redef (fn [notif & _] (reset! sent notif))- (notification/send-test-notification!)+ (notification/send-test-notification! {:email-recipients nil :slack-channel nil})(is (= :notification/system-event (:payload_type @sent)))(is (= :event/security-advisory-match (get-in @sent [:payload :event_topic])))(let [obj (get-in @sent [:payload :event_info :object])]@@ -382,21 +382,44 @@(is (re-find #"(?i)test" (:title obj)))(is (re-find #"(?i)test" (:description obj))))))))+(deftest send-test-notification-uses-passed-config-test+ (testing "send-test-notification! uses the passed config — not the saved settings"+ (let [sent (atom nil)+ form-emails [{:type :notification-recipient/external-email :details {:email "[email protected]"}}]+ saved-emails [{:type :notification-recipient/external-email :details {:email "[email protected]"}}]+ form-slack-channel "#form-channel"]+ (mt/with-temporary-setting-values [admin-email nil+ slack-token-valid? true]+ (with-redefs [settings/security-center-email-recipients (constantly saved-emails)+ settings/security-center-slack-channel (constantly "#saved-channel")]+ (with-send-redef (fn [notif & _] (reset! sent notif))+ (notification/send-test-notification! {:email-recipients form-emails+ :slack-channel form-slack-channel})+ (let [email-handler (first (filter #(= :channel/email (:channel_type %)) (:handlers @sent)))+ slack-handler (first (filter #(= :channel/slack (:channel_type %)) (:handlers @sent)))]+ (is (= [{:type :notification-recipient/external-email+ :details {:email "[email protected]"}}]+ (:recipients email-handler))+ "uses the email recipients from the passed config, not the saved setting")+ (is (= "#form-channel"+ (get-in (first (:recipients slack-handler)) [:details :value]))+ "uses the Slack channel from the passed config, not the saved setting"))))))))+(deftest send-test-notification-does-not-publish-event-test(testing "send-test-notification! does not publish an audit event"(let [published (atom [])](with-redefs [events/publish-event! (fn [topic _] (swap! published conj topic))channel.settings/email-configured? (constantly true)notification.send/send-notification! (constantly nil)]- (notification/send-test-notification!)+ (notification/send-test-notification! {:email-recipients nil :slack-channel nil})(is (empty? @published))))))(deftest send-test-notification-throws-when-no-channels-test(testing "send-test-notification! throws when no channels are configured"- (with-redefs [channel.settings/email-configured? (constantly false)- settings/security-center-slack-channel (constantly nil)]+ (with-redefs [channel.settings/email-configured? (constantly false)](is (thrown-with-msg? Exception #"No notification channels are configured"- (notification/send-test-notification!))))))+ (notification/send-test-notification! {:email-recipients nil+ :slack-channel nil}))))));;; -------------------------------------------- Notification payload -------------------------------------------------diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.tsxindex bf96af6ce38..2b534550f55 100644--- a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.tsx@@ -6,7 +6,10 @@ import { useSetting, useToast } from "metabase/common/hooks";import { useIsSmallScreen } from "metabase/common/hooks/use-is-small-screen";import { Button, Flex, Group, Icon, Modal, Stack } from "metabase/ui";-import { useNotificationConfig } from "../../hooks/use-notification-config";+import {+ serializeNotificationConfig,+ useNotificationConfig,+} from "../../hooks/use-notification-config";import { EmailChannelCard } from "./EmailChannelCard/EmailChannelCard";import { SlackChannelCard } from "./SlackChannelCard/SlackChannelCard";@@ -53,7 +56,7 @@ export function NotificationChannelConfigModal({const handleSendTest = useCallback(async () => {setIsSendingTest(true);try {- await sendTestNotification().unwrap();+ await sendTestNotification(serializeNotificationConfig(config)).unwrap();sendToast({message: t`Test notification sent`,toastColor: "success",@@ -67,7 +70,7 @@ export function NotificationChannelConfigModal({} finally {setIsSendingTest(false);}- }, [sendTestNotification, sendToast]);+ }, [sendTestNotification, sendToast, config]);const emailHasRecipients =config.email.sendToAllAdmins || config.email.handler.recipients.length > 0;diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsxindex b985324d542..97bfd3bb250 100644--- a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsx@@ -323,6 +323,13 @@ async function getSavedSettings() {return puts.find((r) => r.url.includes("/api/setting"))?.body;}+async function getTestNotificationBody() {+ const posts = await findRequests("POST");+ return posts.find((r) =>+ r.url.includes("/api/ee/security-center/test-notification"),+ )?.body;+}+describe("NotificationChannelConfigModal — save payload", () => {describe("slack channel", () => {it("saves the selected slack channel", async () => {@@ -464,3 +471,94 @@ describe("NotificationChannelConfigModal — save payload", () => {});});});++// ── Send-test-notification payload tests (real hook + context) ──────++describe("NotificationChannelConfigModal — test notification payload", () => {+ it("sends the saved config when the form has not been touched", async () => {+ setupWithRealHook({ slackConfigured: true, slackChannel: "#general" });++ await userEvent.click(+ screen.getByRole("button", { name: /Send test notification/i }),+ );++ await waitFor(async () => {+ const body = await getTestNotificationBody();+ expect(body).toEqual({+ email_recipients: expect.arrayContaining([+ expect.objectContaining(ADMIN_GROUP_RECIPIENT),+ ]),+ slack_channel: "#general",+ });+ });+ });++ it("sends unsaved Slack channel changes (metabase#74147)", async () => {+ setupWithRealHook({ slackConfigured: true, slackChannel: "#general" });++ // Wait for the Slack channels query to resolve before interacting with+ // the picker — Slack starts enabled (slackChannel is set), but the+ // picker isn't rendered until channelInfo loads.+ const channelInput = await screen.findByPlaceholderText(+ "Pick a user or channel...",+ );+ await userEvent.clear(channelInput);+ await userEvent.type(channelInput, "#alerts");++ await userEvent.click(+ screen.getByRole("button", { name: /Send test notification/i }),+ );++ await waitFor(async () => {+ const body = await getTestNotificationBody();+ expect(body?.slack_channel).toBe("#alerts");+ });+ });++ it("sends null slack_channel when the user toggles Slack off without saving (metabase#74147)", async () => {+ setupWithRealHook({ slackConfigured: true, slackChannel: "#general" });++ await userEvent.click(screen.getByTestId("slack-toggle"));++ await userEvent.click(+ screen.getByRole("button", { name: /Send test notification/i }),+ );++ await waitFor(async () => {+ const body = await getTestNotificationBody();+ expect(body?.slack_channel).toBeNull();+ });+ });++ it("sends unsaved 'send to all admins' toggle changes (metabase#74147)", async () => {+ setupWithRealHook({ emailConfigured: true });++ // Default state has the admin group recipient — flip the toggle off+ await userEvent.click(screen.getByTestId("send-to-admins-toggle"));+ await userEvent.type(+ screen.getByPlaceholderText(/Enter user names or email/i),+ "[email protected]{enter}",+ );++ await userEvent.click(+ screen.getByRole("button", { name: /Send test notification/i }),+ );++ await waitFor(async () => {+ const body = await getTestNotificationBody();+ expect(body?.email_recipients).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining(ADMIN_GROUP_RECIPIENT),+ ]),+ );+ expect(body?.email_recipients).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: "notification-recipient/raw-value",+ details: { value: "[email protected]" },+ }),+ ]),+ );+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/hooks/use-notification-config.ts b/enterprise/frontend/src/metabase-enterprise/security_center/hooks/use-notification-config.tsindex 1d6afcbeb77..8561a486212 100644--- a/enterprise/frontend/src/metabase-enterprise/security_center/hooks/use-notification-config.ts+++ b/enterprise/frontend/src/metabase-enterprise/security_center/hooks/use-notification-config.ts@@ -17,6 +17,7 @@ import type {NotificationHandlerEmail,NotificationHandlerSlack,NotificationRecipient,+ SendTestNotificationRequest,User,} from "metabase-types/api";@@ -62,6 +63,29 @@ function isAdminGroupRecipient(r: NotificationRecipient): boolean {);}+/**+ * Flatten the modal's config into a serializable shape used by both+ * POST /api/ee/security-center/test-notification (for unsaved test sends)+ * and PUT /api/setting/security-center-email-recipients (for saving).+ */+export function serializeNotificationConfig(+ config: NotificationConfig,+): SendTestNotificationRequest {+ const adminGroupRecipient: NotificationRecipient = {+ type: "notification-recipient/group",+ permissions_group_id: ADMIN_GROUP_ID,+ };+ const emailRecipients: NotificationRecipient[] = [+ ...(config.email.sendToAllAdmins ? [adminGroupRecipient] : []),+ ...config.email.handler.recipients,+ ];+ const slackChannel: string | null =+ config.slack.enabled && config.slack.handler.recipients.length > 0+ ? config.slack.handler.recipients[0].details.value+ : null;+ return { emailRecipients, slackChannel };+}+function configFromSettings(emailRecipients: NotificationRecipient[] | null,slackChannel: string | null,@@ -183,21 +207,8 @@ export function useNotificationConfigState(): NotificationConfigValue {}, []);const save = useCallback(async () => {- const adminGroupRecipient: NotificationRecipient = {- type: "notification-recipient/group",- permissions_group_id: ADMIN_GROUP_ID,- };-- const emailRecipients: NotificationRecipient[] = [- ...(config.email.sendToAllAdmins ? [adminGroupRecipient] : []),- ...config.email.handler.recipients,- ];-- const slackChannel: string | null =- config.slack.enabled && config.slack.handler.recipients.length > 0- ? config.slack.handler.recipients[0].details.value- : null;-+ const { emailRecipients, slackChannel } =+ serializeNotificationConfig(config);await updateSettings({"security-center-email-recipients": emailRecipients,"security-center-slack-channel": slackChannel,diff --git a/frontend/src/metabase-types/api/security-center.ts b/frontend/src/metabase-types/api/security-center.tsindex c3814c924b0..578642d7dc0 100644--- a/frontend/src/metabase-types/api/security-center.ts+++ b/frontend/src/metabase-types/api/security-center.ts@@ -1,3 +1,5 @@+import type { NotificationRecipient } from "./notification";+export type AdvisoryMatchStatus =| "active"| "resolved"@@ -41,3 +43,8 @@ export type AcknowledgeAdvisoryResponse = {};export type AcknowledgeAdvisoriesResponse = AcknowledgeAdvisoryResponse[];++export type SendTestNotificationRequest = {+ emailRecipients: NotificationRecipient[];+ slackChannel: string | null;+};diff --git a/frontend/src/metabase/api/security-center.ts b/frontend/src/metabase/api/security-center.tsindex 2420e97a26c..0bc52b36070 100644--- a/frontend/src/metabase/api/security-center.ts+++ b/frontend/src/metabase/api/security-center.ts@@ -3,10 +3,12 @@ import type {AcknowledgeAdvisoryResponse,AdvisoryId,ListAdvisoriesResponse,+ SendTestNotificationRequest,} from "metabase-types/api";import { Api } from "./api";import { listTag } from "./tags";+export const securityCenterApi = Api.injectEndpoints({endpoints: (builder) => ({listSecurityAdvisories: builder.query<ListAdvisoriesResponse, void>({@@ -41,10 +43,17 @@ export const securityCenterApi = Api.injectEndpoints({}),invalidatesTags: [listTag("security-advisory")],}),- sendTestNotification: builder.mutation<{ success: boolean }, void>({- query: () => ({+ sendTestNotification: builder.mutation<+ { success: boolean },+ SendTestNotificationRequest+ >({+ query: ({ emailRecipients, slackChannel }) => ({method: "POST",url: "/api/ee/security-center/test-notification",+ body: {+ email_recipients: emailRecipients,+ slack_channel: slackChannel,+ },}),}),}),