Skip to content

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

Security Center (#71661)

Nicola Mometto07325c8057ea
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 309b9fb955f..912c61dcb8b 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -2150,7 +2150,10 @@
premium-features
search
util}
- :model-imports #{:model/AiUsageLog :model/Card :model/Dashboard}}
+ :model-imports #{:model/AiUsageLog
+ :model/Card
+ :model/Dashboard
+ :model/SecurityAdvisory}}
tiles
{:team "UX West"
@@ -3116,6 +3119,28 @@
:uses #{premium-features
search}}
+ enterprise/security-center
+ {:team "Gadget"
+ :api #{metabase-enterprise.security-center.api
+ metabase-enterprise.security-center.init}
+ :uses #{analytics
+ api
+ app-db
+ channel
+ config
+ driver
+ events
+ models
+ notification
+ permissions
+ premium-features
+ settings
+ system
+ task
+ util}
+ :model-exports #{:model/SecurityAdvisory}
+ :model-imports #{:model/User}}
+
enterprise/semantic-search
{:team "Metabot"
:api #{metabase-enterprise.semantic-search.api
diff --git a/.gitignore b/.gitignore
index 61a6b7e326c..0f2ab705ec7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -175,3 +175,4 @@ CLAUDE.local.md
/resources/python-sources/.lock
__pycache__/
.mcp.json
+.claude/worktrees
diff --git a/deps.edn b/deps.edn
index 5b6008b3e38..c21af58bfa9 100644
--- a/deps.edn
+++ b/deps.edn
@@ -180,6 +180,7 @@
{:mvn/version "2.7.10"} ; MySQL/MariaDB driver
org.mindrot/jbcrypt {:mvn/version "0.4"} ; Crypto library
org.postgresql/postgresql {:mvn/version "42.7.8"} ; Postgres driver
+ org.semver4j/semver4j {:mvn/version "6.0.0"} ; Semantic versioning parsing & comparison
org.slf4j/slf4j-api {:mvn/version "2.0.17"} ; abstraction for logging frameworks -- allows end user to plug in desired logging framework at deployment time
org.tcrawley/dynapath {:mvn/version "1.1.0"} ; Dynamically add Jars (e.g. Oracle or Vertica) to classpath
org.threeten/threeten-extra {:mvn/version "1.8.0"} ; extra Java 8 java.time classes like DayOfMonth and Quarter
diff --git a/e2e/support/helpers/api/index.ts b/e2e/support/helpers/api/index.ts
index 6bf188ddf11..749a3d37ac2 100644
--- a/e2e/support/helpers/api/index.ts
+++ b/e2e/support/helpers/api/index.ts
@@ -28,6 +28,8 @@ export type {
export { createQuestionAndAddToDashboard } from "./createQuestionAndAddToDashboard";
export { createQuestionAndDashboard } from "./createQuestionAndDashboard";
export { createReaction } from "./createReaction";
+export { seedSecurityAdvisories } from "./seedSecurityAdvisories";
+export type { SecurityAdvisorySpec } from "./seedSecurityAdvisories";
export { createSnippet } from "./createSnippet";
export { createSnippetFolder } from "./createSnippetFolder";
export { createTestQuery, createTestNativeQuery } from "./createTestQuery";
diff --git a/e2e/support/helpers/api/seedSecurityAdvisories.ts b/e2e/support/helpers/api/seedSecurityAdvisories.ts
new file mode 100644
index 00000000000..375b2b6cce6
--- /dev/null
+++ b/e2e/support/helpers/api/seedSecurityAdvisories.ts
@@ -0,0 +1,21 @@
+export type SecurityAdvisorySpec = {
+ advisory_id: string;
+ severity: "critical" | "high" | "medium" | "low";
+ title: string;
+ description: string;
+ remediation: string;
+ advisory_url?: string | null;
+ affected_versions: { min: string; fixed: string }[];
+ matching_query?: Record<string, string> | null;
+ match_status: "unknown" | "active" | "resolved" | "not_affected" | "error";
+ published_at: string;
+ updated_at?: string;
+};
+
+export function seedSecurityAdvisories(
+ advisories: SecurityAdvisorySpec[],
+): Cypress.Chainable {
+ return cy.request("POST", "/api/testing/security-advisories", {
+ advisories,
+ });
+}
diff --git a/e2e/test/scenarios/admin-2/security-center.cy.spec.ts b/e2e/test/scenarios/admin-2/security-center.cy.spec.ts
new file mode 100644
index 00000000000..d7fe5df2098
--- /dev/null
+++ b/e2e/test/scenarios/admin-2/security-center.cy.spec.ts
@@ -0,0 +1,284 @@
+const { H } = cy;
+
+const ADVISORIES = {
+ critical: {
+ advisory_id: "TEST-001",
+ severity: "critical",
+ title: "Critical RCE vulnerability",
+ description: "Remote code execution via crafted input.",
+ remediation: "Upgrade to 0.59.5",
+ advisory_url: "https://example.com/advisory/TEST-001",
+ affected_versions: [{ min: "0.58.0", fixed: "0.59.5" }],
+ match_status: "active",
+ published_at: "2026-03-20T00:00:00Z",
+ updated_at: "2026-03-20T00:00:00Z",
+ },
+ high: {
+ advisory_id: "TEST-002",
+ severity: "high",
+ title: "SQL injection in query builder",
+ description: "Postgres databases are vulnerable to SQL injection.",
+ remediation: "Upgrade to 0.58.8",
+ affected_versions: [{ min: "0.54.0", fixed: "0.58.8" }],
+ match_status: "resolved",
+ published_at: "2026-03-15T00:00:00Z",
+ updated_at: "2026-03-15T00:00:00Z",
+ },
+ medium: {
+ advisory_id: "TEST-003",
+ severity: "medium",
+ title: "SSRF in GeoJSON endpoint",
+ description: "Custom GeoJSON endpoints can be used for SSRF.",
+ remediation: "Upgrade to 0.58.7",
+ affected_versions: [{ min: "0.50.0", fixed: "0.58.7" }],
+ match_status: "not_affected",
+ published_at: "2026-03-10T00:00:00Z",
+ updated_at: "2026-03-10T00:00:00Z",
+ },
+} as const;
+
+function seedAllAdvisories() {
+ H.seedSecurityAdvisories([
+ ADVISORIES.critical,
+ ADVISORIES.high,
+ ADVISORIES.medium,
+ ]);
+}
+
+function securityCenterContent() {
+ return cy.findByTestId("security-center-page");
+}
+
+describe("scenarios > admin > security center", { tags: "@EE" }, () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+ });
+
+ describe("feature gating", () => {
+ it("should not show security center without a valid token", () => {
+ H.deleteToken();
+ cy.visit("/admin/security-center");
+ cy.findByTestId("security-center-page").should("not.exist");
+ });
+
+ it("should render the security center page with a valid token", () => {
+ seedAllAdvisories();
+ cy.visit("/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText("Security Center").should("be.visible");
+ cy.findByTestId("current-version").should("be.visible");
+ });
+ });
+ });
+
+ describe("advisory list", () => {
+ beforeEach(() => {
+ seedAllAdvisories();
+ cy.visit("/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText("Security Center").should("be.visible");
+ });
+ });
+
+ it("should display advisory cards with severity and affected status", () => {
+ cy.findAllByTestId("advisory-card").should("have.length", 3);
+ securityCenterContent().within(() => {
+ cy.findByText("Critical RCE vulnerability").should("be.visible");
+ cy.findByText("SQL injection in query builder").should("be.visible");
+ cy.findByText("SSRF in GeoJSON endpoint")
+ .scrollIntoView()
+ .should("be.visible");
+ });
+ });
+
+ it("should sort advisories with affected first, then by severity", () => {
+ cy.findAllByTestId("advisory-card")
+ .first()
+ .within(() => {
+ cy.findByText("Critical RCE vulnerability").should("exist");
+ cy.findByTestId("affected-status").should("have.text", "Affected");
+ });
+ });
+
+ it("should show empty state when no advisories exist", () => {
+ // Don't seed any — restore already cleared them
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+ cy.visit("/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText(/up to date/).should("be.visible");
+ });
+ });
+ });
+
+ describe("filtering", () => {
+ beforeEach(() => {
+ seedAllAdvisories();
+ cy.visit("/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText("Security Center").should("be.visible");
+ });
+ });
+
+ it("should filter by severity", () => {
+ cy.findByTestId("severity-filter").click();
+ cy.findByRole("option", { name: "Critical" }).click();
+ cy.findAllByTestId("advisory-card").should("have.length", 1);
+ securityCenterContent().within(() => {
+ cy.findByText("Critical RCE vulnerability").should("be.visible");
+ });
+ });
+
+ it("should filter by affected status", () => {
+ cy.findByTestId("status-filter").click();
+ cy.findByRole("option", { name: "Affected" }).click();
+ cy.findAllByTestId("advisory-card").should("have.length", 1);
+ securityCenterContent().within(() => {
+ cy.findByText("Critical RCE vulnerability").should("be.visible");
+ });
+ });
+
+ it("should toggle show dismissed", () => {
+ // Dismiss the critical advisory first
+ cy.findAllByTestId("advisory-card")
+ .first()
+ .findByTestId("acknowledge-button")
+ .click();
+
+ // It should be hidden by default (dismissed are hidden)
+ cy.findAllByTestId("advisory-card").should("have.length", 2);
+
+ // Show dismissed
+ cy.findByTestId("show-acknowledged-filter").click();
+ cy.findAllByTestId("advisory-card").should("have.length", 3);
+ });
+ });
+
+ describe("dismiss advisory", () => {
+ beforeEach(() => {
+ seedAllAdvisories();
+ cy.visit("/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText("Security Center").should("be.visible");
+ });
+ });
+
+ it("should dismiss an advisory and show the badge", () => {
+ cy.intercept("POST", "/api/ee/security-center/*/acknowledge").as(
+ "acknowledge",
+ );
+
+ cy.findAllByTestId("advisory-card")
+ .first()
+ .findByTestId("acknowledge-button")
+ .click();
+
+ cy.wait("@acknowledge");
+
+ cy.findByTestId("show-acknowledged-filter").click();
+ cy.findAllByTestId("advisory-card")
+ .first()
+ .findByTestId("acknowledged-badge")
+ .should("have.text", "Dismissed");
+ });
+
+ it("should hide dismissed advisories by default", () => {
+ cy.findAllByTestId("advisory-card")
+ .first()
+ .findByTestId("acknowledge-button")
+ .click();
+
+ // After dismissing, the card should disappear
+ cy.findAllByTestId("advisory-card").should("have.length", 2);
+ });
+ });
+
+ describe("navigation and badge", () => {
+ it("should show Security nav item with badge when active advisories exist", () => {
+ seedAllAdvisories();
+ cy.visit("/admin/security-center");
+ cy.findByTestId("admin-navbar").within(() => {
+ cy.findByText("Security").should("be.visible");
+ });
+ cy.findByTestId("security-center-badge").should("be.visible");
+ });
+
+ it("should navigate to security center when clicking nav item", () => {
+ seedAllAdvisories();
+ cy.visit("/admin");
+ cy.findByTestId("admin-navbar").within(() => {
+ cy.findByText("Security").click();
+ });
+ cy.url().should("include", "/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText("Security Center").should("be.visible");
+ });
+ });
+ });
+
+ describe("notification settings modal", () => {
+ beforeEach(() => {
+ seedAllAdvisories();
+ cy.visit("/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText("Security Center").should("be.visible");
+ });
+ });
+
+ it("should open the notification settings modal", () => {
+ cy.findByTestId("notification-config-toggle").click();
+ H.modal().within(() => {
+ cy.findByText("Notification settings").should("be.visible");
+ cy.findByText("Email").should("be.visible");
+ cy.findByText("Slack").should("be.visible");
+ });
+ });
+
+ it("should show send-to-all-admins toggle checked by default", () => {
+ H.setupSMTP();
+ cy.visit("/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText("Security Center").should("be.visible");
+ });
+ cy.findByTestId("notification-config-toggle").click();
+ cy.findByTestId("send-to-admins-toggle").should("be.checked");
+ });
+
+ it("should show Slack not configured state", () => {
+ cy.findByTestId("notification-config-toggle").click();
+ H.modal().within(() => {
+ cy.findByText("Slack is not configured.").should("be.visible");
+ cy.findByText("Set up Slack").should("be.visible");
+ });
+ });
+
+ it("should save notification settings", () => {
+ cy.intercept("PUT", "/api/setting").as("saveSettings");
+
+ cy.findByTestId("notification-config-toggle").click();
+ cy.findByRole("button", { name: "Save" }).click();
+
+ cy.wait("@saveSettings").then(({ request }) => {
+ expect(request.body).to.have.property(
+ "security-center-email-recipients",
+ );
+ });
+ });
+ });
+
+ describe("sync", () => {
+ it("should trigger sync when clicking Check now", () => {
+ cy.intercept("POST", "/api/ee/security-center/sync").as("sync");
+ cy.visit("/admin/security-center");
+ securityCenterContent().within(() => {
+ cy.findByText("Security Center").should("be.visible");
+ });
+
+ cy.findByTestId("sync-advisories").click();
+ cy.wait("@sync");
+ });
+ });
+});
diff --git a/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js b/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js
index 566ed66d1bd..85b9aba4f8e 100644
--- a/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js
+++ b/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js
@@ -19,7 +19,9 @@ export function crudGroupMappingsWidget(authenticationMethod) {
cy.findByText("data").should("not.exist");
cy.findByText("nosql").should("not.exist");
- cy.icon("close").click({ force: true });
+ cy.findByTestId("admin-content-table").within(() => {
+ cy.icon("close").click({ force: true });
+ });
cy.findByText(/remove all group members/i).click();
cy.button("Remove mapping and members").click();
diff --git a/e2e/test/scenarios/admin/security-center-snowplow.cy.spec.ts b/e2e/test/scenarios/admin/security-center-snowplow.cy.spec.ts
new file mode 100644
index 00000000000..fe003987498
--- /dev/null
+++ b/e2e/test/scenarios/admin/security-center-snowplow.cy.spec.ts
@@ -0,0 +1,41 @@
+const { H } = cy;
+const IS_ENTERPRISE = Cypress.expose("IS_ENTERPRISE");
+
+describe("Security Center > Snowplow tracking", { tags: "@enterprise" }, () => {
+ before(() => {
+ if (!IS_ENTERPRISE) {
+ cy.log("Skipping — requires EE build");
+ return;
+ }
+ });
+
+ beforeEach(function () {
+ if (!IS_ENTERPRISE) {
+ this.skip();
+ }
+ H.resetSnowplow();
+ H.restore();
+ cy.signInAsAdmin();
+ H.enableTracking();
+ H.activateToken("pro-self-hosted");
+ // Stub the API so the page renders without a real EE backend
+ cy.intercept("GET", "/api/ee/security-center", {
+ last_checked_at: null,
+ advisories: [],
+ });
+ cy.intercept("GET", "/api/user/recipients", { data: [] });
+ cy.intercept("GET", "/api/channel", { channels: {} });
+ });
+
+ afterEach(() => {
+ H.expectNoBadSnowplowEvents();
+ });
+
+ it("should send a page viewed event when visiting the security center", () => {
+ cy.visit("/admin/security-center");
+ cy.findByRole("heading", { name: "Security Center" });
+ H.expectUnstructuredSnowplowEvent({
+ event: "security_center_page_viewed",
+ });
+ });
+});
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index ccac301cdc7..3e1423f9ba9 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -30,6 +30,7 @@
[metabase-enterprise.replacement.api]
[metabase-enterprise.sandbox.api.routes]
[metabase-enterprise.scim.routes]
+ [metabase-enterprise.security-center.api]
[metabase-enterprise.semantic-search.api]
[metabase-enterprise.serialization.api]
[metabase-enterprise.stale.api]
@@ -60,6 +61,7 @@
:etl-connections-pg (deferred-tru "ETL Connections PG replication")
:scim (deferred-tru "SCIM configuration")
:semantic-search (deferred-tru "Semantic Search")
+ :admin-security-center (deferred-tru "Security Center")
:serialization (deferred-tru "Serialization")
:table-data-editing (deferred-tru "Table Data Editing")
:tenants (deferred-tru "Tenants")
@@ -122,6 +124,7 @@
"/transforms-python" (premium-handler metabase-enterprise.transforms-python.api/routes :transforms-python)
"/scim" (premium-handler metabase-enterprise.scim.routes/routes :scim)
"/semantic-search" (premium-handler metabase-enterprise.semantic-search.api/routes :semantic-search)
+ "/security-center" (premium-handler metabase-enterprise.security-center.api/routes :admin-security-center)
"/serialization" (premium-handler metabase-enterprise.serialization.api/routes :serialization)
"/stale" (premium-handler metabase-enterprise.stale.api/routes :collection-cleanup)
"/support-access-grant" (premium-handler metabase-enterprise.support-access-grants.api/routes :support-users)
diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.clj
index a265b9855d1..51a9f40dd5c 100644
--- a/enterprise/backend/src/metabase_enterprise/core/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj
@@ -16,6 +16,7 @@
[metabase-enterprise.metabot.init]
[metabase-enterprise.remote-sync.init]
[metabase-enterprise.scim.init]
+ [metabase-enterprise.security-center.init]
[metabase-enterprise.semantic-search.init]
[metabase-enterprise.sso.init]
[metabase-enterprise.stale.init]
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/api.clj b/enterprise/backend/src/metabase_enterprise/security_center/api.clj
new file mode 100644
index 00000000000..028361b1150
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/api.clj
@@ -0,0 +1,123 @@
+(ns metabase-enterprise.security-center.api
+ "API endpoints for Security Center advisories."
+ (:require
+ [clojure.set :as set]
+ [metabase-enterprise.security-center.models.security-advisory :as security-advisory]
+ [metabase-enterprise.security-center.notification :as notification]
+ [metabase-enterprise.security-center.schema :as security-center.schema]
+ [metabase-enterprise.security-center.settings :as settings]
+ [metabase-enterprise.security-center.task.sync-advisories :as sync-advisories]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :as routes.common :refer [+auth]]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.malli.schema :as ms]
+ [toucan2.core :as t2])
+ (:import
+ (java.util.concurrent ExecutorService RejectedExecutionException
+ SynchronousQueue ThreadPoolExecutor ThreadPoolExecutor$AbortPolicy
+ TimeUnit)))
+
+(set! *warn-on-reflection* true)
+
+(defn- advisory-response
+ "Format a SecurityAdvisory row for API response. Expects `:acknowledged_by_user` to be hydrated."
+ [advisory]
+ (-> (select-keys advisory [:advisory_id :title :severity :description :advisory_url :remediation
+ :published_at :match_status :last_evaluated_at
+ :acknowledged_by_user :acknowledged_at :affected_versions])
+ (set/rename-keys {:acknowledged_by_user :acknowledged_by})))
+
+(def ^:private AcknowledgedByUser
+ "Schema for a hydrated acknowledged_by user map."
+ [:map
+ [:id ms/PositiveInt]
+ [:common_name ms/NonBlankString]
+ [:email ms/Email]])
+
+(def ^:private AdvisoryResponse
+ "Schema for a single advisory in the API response."
+ [:map
+ [:advisory_id ::security-center.schema/advisory-id]
+ [:title ms/NonBlankString]
+ [:severity ::security-center.schema/severity]
+ [:description ms/NonBlankString]
+ [:advisory_url [:maybe ms/NonBlankString]]
+ [:remediation ms/NonBlankString]
+ [:published_at ms/TemporalInstant]
+ [:match_status ::security-center.schema/match-status]
+ [:last_evaluated_at [:maybe ms/TemporalInstant]]
+ [:acknowledged_by [:maybe AcknowledgedByUser]]
+ [:acknowledged_at [:maybe ms/TemporalInstant]]
+ [:affected_versions ::security-center.schema/affected-versions]])
+
+(def ^:private AcknowledgeResponse
+ "Schema for the acknowledge endpoint response."
+ [:map
+ [:advisory_id ::security-center.schema/advisory-id]
+ [:match_status ::security-center.schema/match-status]
+ [:acknowledged_by [:maybe AcknowledgedByUser]]
+ [:acknowledged_at [:maybe ms/TemporalInstant]]])
+
+(api.macros/defendpoint :get "/" :- [:map
+ [:last_checked_at [:maybe ms/TemporalInstant]]
+ [:advisories [:sequential AdvisoryResponse]]]
+ "List all security advisories with match status."
+ []
+ (api/check-superuser)
+ (let [advisories (t2/hydrate (t2/select :model/SecurityAdvisory {:order-by [[:published_at :desc]]})
+ :acknowledged_by_user)]
+ {:last_checked_at (settings/security-center-last-synced-at)
+ :advisories (mapv advisory-response advisories)}))
+
+(defn- acknowledge-response
+ "Format a slim response for the acknowledge endpoint."
+ [advisory]
+ (-> (select-keys advisory [:advisory_id :match_status :acknowledged_by_user :acknowledged_at])
+ (set/rename-keys {:acknowledged_by_user :acknowledged_by})))
+
+(api.macros/defendpoint :post "/:advisory-id/acknowledge" :- AcknowledgeResponse
+ "Acknowledge a security advisory. Stops repeat notifications."
+ [{:keys [advisory-id]} :- [:map [:advisory-id ms/NonBlankString]]]
+ (api/check-superuser)
+ (let [advisory (t2/select-one :model/SecurityAdvisory :advisory_id advisory-id)]
+ (api/check-404 advisory)
+ (acknowledge-response (security-advisory/acknowledge! advisory api/*current-user-id*))))
+
+(defonce ^:private ^ExecutorService sync-executor
+ (ThreadPoolExecutor. 1 1 0 TimeUnit/MILLISECONDS
+ (SynchronousQueue.) (ThreadPoolExecutor$AbortPolicy.)))
+
+(api.macros/defendpoint :post "/sync" :- [:map [:status ms/NonBlankString]]
+ "Trigger an async advisory sync + re-evaluation.
+ Returns immediately. If a sync is already running, the request is a no-op."
+ []
+ (api/check-superuser)
+ (let [submitted? (try
+ (.submit sync-executor ^Runnable sync-advisories/sync-and-evaluate!)
+ true
+ (catch RejectedExecutionException _e
+ false))]
+ {: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."
+ []
+ (api/check-superuser)
+ (notification/send-test-notification!)
+ {:success true})
+
+(def +check-security-center-enabled
+ "Middleware that returns 402 if Security Center is not available on this instance."
+ (routes.common/wrap-middleware-for-open-api-spec-generation
+ (fn [handler]
+ (fn [request respond raise]
+ (when-not (premium-features/security-center-enabled?)
+ (throw (ex-info (tru "Security Center is not available on this instance.")
+ {:status-code 402 :status "error-premium-feature-not-available"})))
+ (handler request respond raise)))))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/security-center` routes."
+ (api.macros/ns-handler *ns* +check-security-center-enabled api/+check-superuser +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/fetch.clj b/enterprise/backend/src/metabase_enterprise/security_center/fetch.clj
new file mode 100644
index 00000000000..4822ceabc58
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/fetch.clj
@@ -0,0 +1,160 @@
+(ns metabase-enterprise.security-center.fetch
+ "Fetch security advisories from the MetaStore and upsert into the appdb."
+ (:require
+ [clj-http.client :as http]
+ [clojure.edn :as edn]
+ [clojure.set :as set]
+ [java-time.api :as t]
+ [metabase-enterprise.security-center.schema :as security-center.schema]
+ [metabase.app-db.core :as mdb]
+ [metabase.config.core :as config]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]))
+
+(set! *warn-on-reflection* true)
+
+;;; ---------------------------------------- Store API response schemas ----------------------------------------
+
+(mr/def ::severity
+ [:enum "critical" "high" "medium" "low"])
+
+(mr/def ::affected-version
+ [:map {:closed true}
+ [:min ::security-center.schema/semver]
+ [:fixed ::security-center.schema/semver]])
+
+(mr/def ::driver
+ [:enum :default :postgres :mysql :h2])
+
+(mr/def ::matching-query
+ "A map of driver -> honeysql query stored as EDN string."
+ [:map-of ::driver :string])
+
+(mr/def ::advisory
+ [:map
+ [:id ::security-center.schema/advisory-id]
+ [:title [:string {:min 1}]]
+ [:severity ::severity]
+ [:description [:string {:min 1}]]
+ [:published_at ms/TemporalString]
+ [:updated_at ms/TemporalString]
+ [:advisory_url [:maybe :string]]
+ [:affected_versions [:vector {:min 1} ::affected-version]]
+ [:matching_query [:maybe ::matching-query]]
+ [:remediation [:string {:min 1}]]])
+
+;;; ---------------------------------------- Fetch helpers ----------------------------------------
+
+(def ^:private ^String hm-url
+ "Base URL for the Harbormaster / MetaStore API."
+ premium-features/token-check-url)
+
+(defn- advisories-url [token base-url]
+ (format "%s/api/%s/v2/security-advisories" base-url token))
+
+(defn- latest-updated-at
+ "Return the maximum `updated_at` across all advisories as an ISO-8601 string, or nil if none exist."
+ []
+ (some-> (mdb/query {:select [[[:max :updated_at]]]
+ :from [:security_advisory]})
+ first
+ vals
+ first
+ t/instant
+ t/format))
+
+(defn- validate-select-query
+ "Validate that a parsed HoneySQL map is a SELECT-only query (has :select but no mutation keys)."
+ [query driver-key]
+ (when-not (map? query)
+ (throw (ex-info "Matching query must be a map" {:driver driver-key :query query})))
+ (when-not (contains? query :select)
+ (throw (ex-info "Matching query must contain :select" {:driver driver-key :query query})))
+ (let [mutation-keys #{:insert-into :update :delete :delete-from :truncate :drop-table :alter-table :create-table}
+ found (set/intersection mutation-keys (set (keys query)))]
+ (when (seq found)
+ (throw (ex-info "Matching query must be SELECT-only, found mutation keys" {:driver driver-key :keys found}))))
+ query)
+
+(defn- parse-matching-query
+ "Parse each EDN string value in a matching_query map into Clojure data, validating each is a SELECT query."
+ [matching-query]
+ (when matching-query
+ (reduce-kv (fn [m driver-key edn-str]
+ (assoc m driver-key (validate-select-query (edn/read-string edn-str) driver-key)))
+ {}
+ matching-query)))
+
+(defn- parse-advisory
+ "Parse matching_query EDN strings, convert temporal strings, and rename :id to :advisory_id."
+ [advisory]
+ {:advisory_id (:id advisory)
+ :title (:title advisory)
+ :severity (:severity advisory)
+ :description (:description advisory)
+ :advisory_url (:advisory_url advisory)
+ :remediation (:remediation advisory)
+ :affected_versions (:affected_versions advisory)
+ :matching_query (parse-matching-query (:matching_query advisory))
+ :published_at (t/offset-date-time (:published_at advisory))
+ :updated_at (t/offset-date-time (:updated_at advisory))})
+
+(mu/defn ^:private fetch-advisories-from-store :- [:maybe [:sequential [:map]]]
+ "GET advisories from the MetaStore. Returns a seq of advisory maps or nil on failure.
+ Sends the latest `updated_at` as a `since` cursor so only changed advisories are returned."
+ []
+ (when-let [token (premium-features/premium-embedding-token)]
+ (let [site-uuid (premium-features/site-uuid-for-premium-features-token-checks)
+ url (advisories-url token hm-url)
+ since (latest-updated-at)
+ query-params (cond-> {:site-uuid site-uuid
+ :mb-version (:tag config/mb-version-info)}
+ since (assoc :since (str since)))
+ resp (http/get url
+ {:query-params query-params
+ :throw-exceptions false
+ :socket-timeout 5000
+ :connection-timeout 2000})]
+ (if (http/success? resp)
+ (let [advisories (:advisories (json/decode+kw (:body resp)))]
+ (mu/validate-throw [:sequential ::advisory] advisories)
+ (mapv parse-advisory advisories))
+ (log/warnf "Advisory fetch failed with status %s" (:status resp))))))
+
+(defn- upsert-advisory!
+ "Insert or update a single advisory by :advisory_id.
+ On insert, match_status starts as :unknown until the matching engine evaluates it.
+ On update, merges new data but preserves :match_status, :last_evaluated_at, and acknowledgement fields."
+ [advisory]
+ (mdb/update-or-insert! :model/SecurityAdvisory
+ {:advisory_id (:advisory_id advisory)}
+ (fn [existing]
+ (if existing
+ advisory
+ (assoc advisory :match_status :unknown)))))
+
+(defn sync-advisories!
+ "Fetch advisories from the MetaStore and upsert into the appdb."
+ []
+ (let [advisories (try
+ (fetch-advisories-from-store)
+ (catch Exception e
+ (log/warn e "Error fetching advisories from MetaStore")))]
+ (if (seq advisories)
+ (let [total (count advisories)
+ failures (reduce (fn [n advisory]
+ (try
+ (upsert-advisory! advisory)
+ n
+ (catch Exception e
+ (log/warnf e "Error upserting advisory %s" (:advisory_id advisory))
+ (inc n))))
+ 0
+ advisories)
+ synced (- total failures)]
+ (log/infof "Synced %d/%d advisories from MetaStore" synced total))
+ (log/info "No new advisories from MetaStore"))))
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/init.clj b/enterprise/backend/src/metabase_enterprise/security_center/init.clj
new file mode 100644
index 00000000000..89dd33f1fae
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/init.clj
@@ -0,0 +1,9 @@
+(ns metabase-enterprise.security-center.init
+ (:require
+ [metabase-enterprise.security-center.models.security-advisory]
+ [metabase-enterprise.security-center.settings]
+ [metabase-enterprise.security-center.task.sync-advisories]))
+
+(comment metabase-enterprise.security-center.models.security-advisory/keep-me
+ metabase-enterprise.security-center.settings/keep-me
+ metabase-enterprise.security-center.task.sync-advisories/keep-me)
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/matching.clj b/enterprise/backend/src/metabase_enterprise/security_center/matching.clj
new file mode 100644
index 00000000000..2cfe1d107b6
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/matching.clj
@@ -0,0 +1,145 @@
+(ns metabase-enterprise.security-center.matching
+ "Advisory matching engine. Evaluates HoneySQL queries against the appdb
+ and combines with version checks to determine match status."
+ (:require
+ [metabase-enterprise.security-center.schema :as schema]
+ [metabase.app-db.core :as mdb]
+ [metabase.config.core :as config]
+ [metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
+ [metabase.models.interface :as mi]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [next.jdbc.result-set :as rs]
+ [toucan2.core :as t2])
+ (:import
+ (org.semver4j Semver)))
+
+(set! *warn-on-reflection* true)
+
+;;; ------------------------------------------------ Version Parsing ------------------------------------------------
+
+(def ^:private QueryResult
+ "Result of executing a matching query: true (matched), false (no match), or :error."
+ [:or :boolean [:= :error]])
+
+(mu/defn parse-version :- [:maybe [:fn #(instance? Semver %)]]
+ "Parse a version string into a Semver instance. Returns nil on failure.
+ Handles Metabase version strings like \"v0.55.3\", \"0.55.17.5\", \"v1.2.3-RC1\"."
+ [version-string :- [:maybe :string]]
+ (when version-string
+ (try
+ (Semver/coerce version-string)
+ (catch Exception _
+ nil))))
+
+(defn- version-in-range?
+ "True if `version` is >= min and < fixed."
+ [^Semver version {:keys [min fixed]}]
+ (let [^Semver min-v (parse-version min)
+ ^Semver fixed-v (parse-version fixed)]
+ (and min-v fixed-v
+ (.isGreaterThanOrEqualTo version min-v)
+ (.isLowerThan version fixed-v))))
+
+(defn- affected-by-version?
+ "True if `version` falls in any of the affected version ranges."
+ [version ranges]
+ (boolean (some #(version-in-range? version %) ranges)))
+
+;;; ---------------------------------------------- Query Execution ------------------------------------------------
+
+(defn- select-query-for-dialect
+ "Pick the matching query for the current appdb dialect, falling back to :default."
+ [matching-query]
+ (or (get matching-query (mdb/db-type))
+ (get matching-query :default)))
+
+(def ^:private ^:dynamic *query-timeout-seconds*
+ "Maximum execution time in seconds for advisory matching queries."
+ 120)
+
+(defn- query-read-only!
+ "Execute a HoneySQL query on a fresh connection with defense-in-depth:
+ 1. setReadOnly(true) — driver-level write rejection
+ 2. Explicit transaction with unconditional rollback — guarantees no writes persist
+ even if the driver doesn't enforce read-only
+ 3. setQueryTimeout — kills the query if it exceeds [[*query-timeout-seconds*]]"
+ [hsql-query]
+ (let [[sql & params] (mdb/compile hsql-query)
+ driver (mdb/db-type)]
+ (with-open [^java.sql.Connection conn (.getConnection (mdb/data-source))]
+ (.setReadOnly conn true)
+ (.setAutoCommit conn false)
+ (try
+ (with-open [stmt (doto (sql-jdbc.execute/prepared-statement driver conn sql params)
+ (.setQueryTimeout *query-timeout-seconds*))
+ rs (sql-jdbc.execute/execute-prepared-statement! driver stmt)]
+ (rs/datafiable-result-set rs conn {}))
+ (finally
+ (.rollback conn))))))
+
+(mu/defn execute-matching-query! :- QueryResult
+ "Execute a matching query against the appdb.
+ Returns true if rows matched, false if no rows, :error if query failed.
+ nil matching_query means 'affects all instances' — returns true."
+ [matching-query :- [:maybe :map]]
+ (if (nil? matching-query)
+ true
+ (if-let [query (select-query-for-dialect matching-query)]
+ (try
+ (boolean (seq (query-read-only! query)))
+ (catch Throwable e
+ (log/warnf e "Matching query failed: %s" (pr-str query))
+ :error))
+ (do
+ (log/warnf "No matching query for dialect %s or default" (name (mdb/db-type)))
+ :error))))
+
+;;; ------------------------------------------- Advisory Evaluation ------------------------------------------------
+
+(mu/defn evaluate-advisory :- ::schema/match-status
+ "Pure evaluation: given an advisory, instance version, and query result, return the resolved match status.
+ Does not perform I/O — call [[execute-matching-query!]] separately to obtain `query-result`.
+ `query-result` is true (matched), false (no match), or :error."
+ [advisory :- [:map [:affected_versions ::schema/affected-versions]]
+ instance-version :- [:maybe [:fn #(instance? Semver %)]]
+ query-result :- QueryResult]
+ (cond
+ (= query-result :error)
+ :error
+
+ (not query-result)
+ :not_affected
+
+ (or (nil? instance-version)
+ (affected-by-version? instance-version (:affected_versions advisory)))
+ :active
+
+ :else
+ :resolved))
+
+(defn evaluate-advisory!
+ "Evaluate a single advisory: run matching query, resolve status, update DB.
+ 2-arity takes a pre-parsed instance version to avoid re-parsing in batch."
+ ([advisory]
+ (evaluate-advisory! advisory (parse-version (:tag config/mb-version-info))))
+ ([advisory instance-version]
+ (let [query-result (execute-matching-query! (:matching_query advisory))
+ match-status (evaluate-advisory advisory instance-version query-result)]
+ (t2/update! :model/SecurityAdvisory (:id advisory)
+ {:match_status match-status
+ :last_evaluated_at (mi/now)}))))
+
+(defn evaluate-all-advisories!
+ "Re-evaluate all non-acknowledged advisories."
+ []
+ (let [instance-version (parse-version (:tag config/mb-version-info))
+ advisories (t2/select :model/SecurityAdvisory :acknowledged_at nil)]
+ (doseq [advisory advisories]
+ (try
+ (evaluate-advisory! advisory instance-version)
+ (catch Exception e
+ (log/warnf e "Error evaluating advisory %s" (:advisory_id advisory))
+ (t2/update! :model/SecurityAdvisory (:id advisory)
+ {:match_status :error
+ :last_evaluated_at (mi/now)}))))))
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/models/security_advisory.clj b/enterprise/backend/src/metabase_enterprise/security_center/models/security_advisory.clj
new file mode 100644
index 00000000000..e835609c860
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/models/security_advisory.clj
@@ -0,0 +1,56 @@
+(ns metabase-enterprise.security-center.models.security-advisory
+ (:require
+ [metabase.analytics.snowplow :as snowplow]
+ [metabase.events.core :as events]
+ [metabase.models.interface :as mi]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/SecurityAdvisory [_model] :security_advisory)
+
+(doto :model/SecurityAdvisory
+ (derive :metabase/model))
+
+(t2/deftransforms :model/SecurityAdvisory
+ {:severity mi/transform-keyword
+ :match_status mi/transform-keyword
+ :affected_versions mi/transform-json
+ ;; EDN because HoneySQL treats keywords as identifiers and strings as values.
+ :matching_query mi/transform-edn})
+
+(t2/define-before-insert :model/SecurityAdvisory
+ [advisory]
+ (assoc advisory :fetched_at (mi/now)))
+
+(methodical/defmethod t2/batched-hydrate [:model/SecurityAdvisory :acknowledged_by_user]
+ "Hydrate `:acknowledged_by_user` from the `:acknowledged_by` FK to a User map with `:id`, `:common_name`, and `:email`."
+ [_model k advisories]
+ (let [user-ids (keep :acknowledged_by advisories)
+ id->user (when (seq user-ids)
+ (t2/select-fn->fn :id #(select-keys % [:id :common_name :email])
+ [:model/User :id :first_name :last_name :email]
+ :id [:in (set user-ids)]))]
+ (mi/instances-with-hydrated-data
+ advisories k
+ (constantly id->user)
+ :acknowledged_by {:default nil})))
+
+(defn acknowledge!
+ "Acknowledge a security advisory. Sets `acknowledged_by` and `acknowledged_at`,
+ and publishes an audit event. Returns the updated advisory with `:acknowledged_by` hydrated.
+ Throws if already acknowledged."
+ [advisory user-id]
+ (when (:acknowledged_at advisory)
+ (throw (ex-info "Advisory already acknowledged" {:status-code 409})))
+ (let [now (mi/now)]
+ (t2/update! :model/SecurityAdvisory (:id advisory)
+ {:acknowledged_by user-id
+ :acknowledged_at now})
+ (events/publish-event! :event/security-advisory-acknowledge
+ {:object advisory
+ :user-id user-id})
+ (snowplow/track-event! :snowplow/simple_event
+ {:event "security_advisory_acknowledged"
+ :event_detail (name (:severity advisory))})
+ (-> (t2/select-one :model/SecurityAdvisory :id (:id advisory))
+ (t2/hydrate :acknowledged_by_user))))
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/notification.clj b/enterprise/backend/src/metabase_enterprise/security_center/notification.clj
new file mode 100644
index 00000000000..d5b68ff159c
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/notification.clj
@@ -0,0 +1,149 @@
+(ns metabase-enterprise.security-center.notification
+ "Sends notifications for security advisories that match (active/error).
+ Handles both the initial notification on status change and repeat
+ notifications via the Quartz task.
+
+ Rather than going through the seeded event→notification pipeline, this
+ namespace constructs notifications directly so it can resolve recipients
+ dynamically from the `security-center-email-recipients` setting and the
+ `security-center-slack-channel` setting. The site admin email is always
+ included as a recipient when set."
+ (:require
+ [metabase-enterprise.security-center.settings :as settings]
+ [metabase.analytics.snowplow :as snowplow]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.events.core :as events]
+ [metabase.models.interface :as mi]
+ [metabase.notification.core :as notification]
+ [metabase.settings.core :as setting]
+ [metabase.system.core :as system]
+ [metabase.util.log :as log]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn- advisory-event-info
+ "Build the event-info map for a security advisory notification."
+ [advisory]
+ {:object (select-keys advisory [:advisory_id :severity :title :description
+ :match_status :advisory_url :remediation
+ :affected_versions])})
+
+(def ^:private email-template
+ "Inline template definition for the security advisory email."
+ {:channel_type :channel/email
+ :details {:type "email/handlebars-resource"
+ :subject "[{{payload.custom.severity_label}}] Security Advisory: {{payload.event_info.object.title}}"
+ :path "metabase/channel/email/security_advisory.hbs"
+ :recipient-type "bcc"}})
+
+(defn- email-recipients
+ "Resolve email recipients: configured recipients from the setting,
+ plus the site admin email (if set) as a raw-value recipient."
+ []
+ (let [configured (or (some-> (settings/security-center-email-recipients)
+ (t2/hydrate :recipients-detail))
+ [])]
+ (if-let [admin-email (system/admin-email)]
+ (conj 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- build-handlers
+ "Build the notification handlers (email + optional Slack) with dynamically resolved recipients."
+ []
+ (let [handlers (when (channel.settings/email-configured?)
+ [{:channel_type :channel/email
+ :template email-template
+ :recipients (email-recipients)}])]
+ (if-let [slack-recipients (slack-recipients)]
+ (conj handlers {:channel_type :channel/slack
+ :recipients slack-recipients})
+ handlers)))
+
+(defn- build-notification
+ "Build a notification map for a security advisory. This is a plain map (not a
+ Toucan2 instance), so `send-notification!` skips DB hydration and uses it as-is."
+ [advisory]
+ {:payload_type :notification/system-event
+ :payload {:event_info (advisory-event-info advisory)
+ :event_topic :event/security-advisory-match}
+ :handlers (build-handlers)})
+
+(def ^:private channel-type->name
+ "Map channel_type keywords to short names for Snowplow tracking."
+ {:channel/email "email"
+ :channel/slack "slack"})
+
+(defn- track-notification-sent!
+ "Track a Snowplow event for each channel in the notification's handlers."
+ [notification triggered-from result]
+ (doseq [{:keys [channel_type]} (:handlers notification)]
+ (snowplow/track-event! :snowplow/simple_event
+ {:event "security_advisory_notification_sent"
+ :event_detail (channel-type->name channel_type)
+ :triggered_from triggered-from
+ :result result})))
+
+(def ^:private test-advisory
+ "A synthetic advisory used for test notifications so admins can verify delivery."
+ {:advisory_id "TEST-0000"
+ :severity :medium
+ :title "[TEST] Test Notification"
+ :description "This is a test notification from the Security Center. If you received this, your notification settings are working correctly. No action is required."
+ :match_status :active
+ :advisory_url nil
+ :remediation "No action required — this is only a test."
+ :affected_versions []})
+
+(defn send-test-notification!
+ "Send a test notification through the configured channels so admins can verify
+ delivery without waiting for a real advisory. Does NOT publish an audit event
+ or update any advisory row."
+ []
+ (let [handlers (build-handlers)]
+ (when (empty? handlers)
+ (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))))))
+
+(defn notify-advisory!
+ "Send notifications for a security advisory and update `last_notified_at`.
+ Publishes the system event for audit logging, then sends email (to admins or
+ configured recipients) and Slack (to configured channel) via the notification
+ pipeline."
+ ([advisory]
+ (notify-advisory! advisory "scheduled"))
+ ([advisory triggered-from]
+ (log/infof "Sending notification for advisory %s (severity=%s, status=%s)"
+ (:advisory_id advisory) (name (:severity advisory)) (name (:match_status advisory)))
+ ;; Publish event for audit log
+ (events/publish-event! :event/security-advisory-match
+ (advisory-event-info advisory))
+ ;; Send email + Slack via notification pipeline
+ ;; sync, so failure doesn't set last_notified_at
+ (let [notif (build-notification advisory)]
+ (try
+ (notification/send-notification! notif :notification/sync? true)
+ (track-notification-sent! notif triggered-from "success")
+ (t2/update! :model/SecurityAdvisory (:id advisory)
+ {:last_notified_at (mi/now)})
+ (catch Exception e
+ (track-notification-sent! notif triggered-from "failure")
+ (throw e))))))
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/schema.clj b/enterprise/backend/src/metabase_enterprise/security_center/schema.clj
new file mode 100644
index 00000000000..c43f522536a
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/schema.clj
@@ -0,0 +1,30 @@
+(ns metabase-enterprise.security-center.schema
+ "Malli schemas for the Security Center module."
+ (:require
+ [metabase.util.malli.registry :as mr]))
+
+(mr/def ::advisory-id
+ [:string {:min 1}])
+
+(mr/def ::semver
+ [:re #"^\d+\.\d+\.\d+$"])
+
+(mr/def ::severity
+ [:enum :critical :high :medium :low])
+
+(mr/def ::match-status
+ [:enum :unknown :active :resolved :not_affected :error])
+
+(mr/def ::version-range
+ "A single affected version range with inclusive min and exclusive fixed."
+ [:map
+ [:min ::semver]
+ [:fixed ::semver]])
+
+(mr/def ::affected-versions
+ [:sequential ::version-range])
+
+(mr/def ::matching-query
+ "HoneySQL query keyed by dialect. nil means affects all instances.
+ Stored as EDN to preserve keywords that HoneySQL requires for identifiers/operators."
+ [:maybe [:map-of :keyword :map]])
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/settings.clj b/enterprise/backend/src/metabase_enterprise/security_center/settings.clj
new file mode 100644
index 00000000000..b0a8964410d
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/settings.clj
@@ -0,0 +1,81 @@
+(ns metabase-enterprise.security-center.settings
+ "Settings for Security Center notification channels."
+ (:require
+ [metabase.permissions.core :as perms]
+ [metabase.settings.core :as setting :refer [defsetting]]
+ [metabase.util.i18n :refer [deferred-tru]]))
+
+(defsetting security-center-email-recipients
+ (deferred-tru "List of email recipients for Security Center notifications.")
+ :type :json
+ :default nil
+ :encryption :no
+ :feature :admin-security-center
+ :visibility :admin
+ :export? false
+ :doc false
+ :audit :getter
+ :getter (fn []
+ (or
+ (some->> (setting/get-value-of-type :json :security-center-email-recipients)
+ (mapv #(update % :type keyword))
+ not-empty)
+ ;; default to all admins -- can't use (perms/admin-group) inline in :default as the group may not exist yet
+ [{:type :notification-recipient/group, :permissions_group_id (:id (perms/admin-group))}]))
+ :setter (fn [new-value]
+ (when (empty? new-value)
+ (throw (ex-info (str (deferred-tru "At least one email recipient is required."))
+ {:status-code 400})))
+ (setting/set-value-of-type! :json :security-center-email-recipients new-value)))
+
+(defsetting security-center-slack-channel
+ (deferred-tru "Slack channel for Security Center notifications. Null means Slack notifications are disabled.")
+ :type :string
+ :default nil
+ :encryption :no
+ :feature :admin-security-center
+ :visibility :admin
+ :export? false
+ :doc false
+ :audit :getter
+ :setter (fn [new-value]
+ (when (and (some? new-value)
+ (not (setting/get-value-of-type :boolean :slack-token-valid?)))
+ (throw (ex-info (str (deferred-tru "Slack is not configured for this instance."))
+ {:status-code 400})))
+ (setting/set-value-of-type! :string :security-center-slack-channel new-value)))
+
+(def ^:private default-severity-repeat-days
+ {:critical 1 :high 3 :medium 7 :low 7})
+
+(defsetting security-center-severity-repeat-days
+ (deferred-tru "Number of days between repeat notifications for each severity level.")
+ :type :json
+ :default default-severity-repeat-days
+ :encryption :no
+ :feature :admin-security-center
+ :visibility :internal
+ :export? false
+ :doc false
+ :audit :never
+ :getter (fn []
+ (some-> (setting/get-value-of-type :json :security-center-severity-repeat-days)
+ (update-keys keyword))))
+
+(defsetting security-center-last-synced-at
+ (deferred-tru "Timestamp of the last successful Security Center advisory sync.")
+ :type :timestamp
+ :default nil
+ :encryption :no
+ :feature :admin-security-center
+ :visibility :internal
+ :export? false
+ :doc false
+ :audit :never
+ :include-in-list? false
+ :can-read-from-env? false)
+
+(defn repeat-days-for-severity
+ "Return repeat days for severity, defaults to 1 if not configured"
+ [severity]
+ (get (security-center-severity-repeat-days) severity 1))
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/task/sync_advisories.clj b/enterprise/backend/src/metabase_enterprise/security_center/task/sync_advisories.clj
new file mode 100644
index 00000000000..77a8b185ae4
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/security_center/task/sync_advisories.clj
@@ -0,0 +1,97 @@
+(ns metabase-enterprise.security-center.task.sync-advisories
+ "Quartz task that periodically fetches advisories from HM, re-evaluates
+ matching queries against the appdb, and sends repeat notifications for
+ unacknowledged active/error advisories."
+ (:require
+ [clojurewerkz.quartzite.jobs :as jobs]
+ [clojurewerkz.quartzite.schedule.cron :as cron]
+ [clojurewerkz.quartzite.triggers :as triggers]
+ [java-time.api :as t]
+ [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.task.core :as task]
+ [metabase.util.log :as log]
+ [toucan2.core :as t2])
+ (:import
+ (org.quartz DisallowConcurrentExecution)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private job-key "metabase.task.security-center.sync-advisories.job")
+(def ^:private trigger-key "metabase.task.security-center.sync-advisories.trigger")
+
+;;; ----------------------------------------- Repeat notifications --------------------------------------------------
+
+(defn- due-for-notification?
+ "True if enough time has passed since `last_notified_at` for this advisory's
+ severity cadence. Always true if never notified."
+ [{:keys [severity last_notified_at]}]
+ (if (nil? last_notified_at)
+ true
+ (let [days (settings/repeat-days-for-severity severity)
+ cutoff (t/minus (t/offset-date-time) (t/days days))]
+ (t/before? (t/offset-date-time last_notified_at) cutoff))))
+
+(defn- unacknowledged-active-advisories
+ "Return all unacknowledged advisories with match_status in (:active :error)."
+ []
+ (t2/select :model/SecurityAdvisory
+ :acknowledged_at nil
+ :match_status [:in ["active" "error"]]))
+
+(defn send-repeat-notifications!
+ "Check all unacknowledged active/error advisories and send repeat notifications
+ for those that are due based on their severity cadence."
+ []
+ (doseq [advisory (unacknowledged-active-advisories)
+ :when (due-for-notification? advisory)]
+ (try
+ (notification/notify-advisory! advisory)
+ (catch Exception e
+ (log/warnf e "Failed to send repeat notification for advisory %s"
+ (:advisory_id advisory))))))
+
+;;; ----------------------------------------- Sync + evaluate + notify -----------------------------------------------
+
+(defn sync-and-evaluate!
+ "Fetch advisories, re-evaluate all, and send repeat notifications."
+ []
+ (when (premium-features/security-center-enabled?)
+ (log/info "Syncing security advisories")
+ (try
+ (fetch/sync-advisories!)
+ (catch Exception e
+ (log/warn e "Error fetching advisories from HM")))
+ (try
+ (matching/evaluate-all-advisories!)
+ (catch Exception e
+ (log/warn e "Error re-evaluating advisories")))
+ (try
+ (send-repeat-notifications!)
+ (catch Exception e
+ (log/warn e "Error sending repeat notifications")))
+ (settings/security-center-last-synced-at! (t/offset-date-time))))
+
+(task/defjob ^{:doc "Periodically fetch and re-evaluate security advisories."
+ DisallowConcurrentExecution true} SyncAdvisories [_]
+ (sync-and-evaluate!))
+
+(defmethod task/init! ::SyncAdvisories [_]
+ (when (premium-features/security-center-enabled?)
+ (let [minute (rand-int 60)
+ ;; Run at a random minute past 0:00, 6:00, 12:00, 18:00 UTC
+ cron-str (format "0 %d 0/6 * * ? *" minute)
+ job (jobs/build
+ (jobs/of-type SyncAdvisories)
+ (jobs/with-identity (jobs/key job-key)))
+ trigger (triggers/build
+ (triggers/with-identity (triggers/key trigger-key))
+ (triggers/start-now)
+ (triggers/with-schedule
+ (cron/schedule
+ (cron/cron-schedule cron-str)
+ (cron/with-misfire-handling-instruction-do-nothing))))]
+ (task/schedule-task! job trigger))))
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index b6f89905ebe..b8b4ebee670 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -124,6 +124,7 @@
"Sandbox"
"SearchIndexMetadata"
"Secret"
+ "SecurityAdvisory"
"SemanticSearchTokenTracking"
"Session"
"SupportAccessGrantLog"
diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
index 3ab3dda39e8..cb829ab7db7 100644
--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
@@ -15,7 +15,8 @@
(use-fixtures :once (fixtures/initialize :db))
(deftest properties-token-features-test
- (mt/with-premium-features #{:advanced-permissions
+ (mt/with-premium-features #{:admin-security-center
+ :advanced-permissions
:ai-controls
:attached-dwh
:audit-app
@@ -64,7 +65,8 @@
:cloud-custom-smtp
:workspaces
:writable-connection}
- (is (= {:advanced_permissions true
+ (is (= {:admin_security_center false ;; requires self-hosted (non-cloud)
+ :advanced_permissions true
:ai_controls true
:attached_dwh true
:audit_app true
@@ -117,6 +119,11 @@
:writable_connection true}
(:token-features (mt/user-http-request :crowberto :get 200 "session/properties"))))))
+(deftest security-center-token-feature-test
+ (testing "admin_security_center is true for self-hosted with the feature flag"
+ (mt/with-premium-features #{:admin-security-center}
+ (is (true? (:admin_security_center
+ (:token-features (mt/user-http-request :crowberto :get 200 "session/properties"))))))))
;;; ---------------------------------------- server-side session timeout tests -----------------------------------------
(deftest session-timeout-enforces-last-active-at-test
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj
new file mode 100644
index 00000000000..eac7c3a21af
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/security_center/api_test.clj
@@ -0,0 +1,156 @@
+(ns metabase-enterprise.security-center.api-test
+ (:require
+ [clojure.test :refer :all]
+ [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.task.sync-advisories :as sync-advisories]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.premium-features.token-check :as token-check]
+ [metabase.task.core :as task]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(def ^:private test-advisories
+ "Default test advisories covering different severities and match statuses."
+ [{:advisory_id "SC-0000-001"
+ :severity "critical"
+ :title "Test Critical Advisory"
+ :description "Critical vulnerability in serialization."
+ :remediation "Upgrade to fix."
+ :affected_versions [{"min" "1.50.0" "fixed" "1.58.0"}]
+ :match_status "active"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}
+ {:advisory_id "SC-0000-002"
+ :severity "high"
+ :title "Test High Advisory"
+ :description "SQL injection in Redshift driver."
+ :remediation "Upgrade to fix."
+ :affected_versions [{"min" "1.54.0" "fixed" "1.58.8"}]
+ :match_status "resolved"
+ :published_at #t "2026-03-20T00:00:00Z"
+ :updated_at #t "2026-03-20T00:00:00Z"}
+ {:advisory_id "SC-0000-003"
+ :severity "medium"
+ :title "Test Medium Advisory"
+ :description "GeoJSON SSRF."
+ :remediation "Upgrade to fix."
+ :affected_versions [{"min" "1.50.0" "fixed" "1.58.7"}]
+ :match_status "not_affected"
+ :published_at #t "2026-03-15T00:00:00Z"
+ :updated_at #t "2026-03-15T00:00:00Z"}])
+
+(defmacro with-test-advisories!
+ "Create temporary SecurityAdvisories from [[test-advisories]] and execute `body`."
+ [& body]
+ (let [temps (mapcat (fn [advisory]
+ [:model/SecurityAdvisory '_ advisory])
+ test-advisories)]
+ `(mt/with-temp [~@temps]
+ ~@body)))
+
+(deftest list-advisories-test
+ (testing "GET /api/ee/security-center"
+ (testing "requires premium feature"
+ (mt/with-premium-features #{}
+ (mt/assert-has-premium-feature-error
+ "Security Center"
+ (mt/user-http-request :crowberto :get 402 "ee/security-center"))))
+ (mt/with-premium-features #{:admin-security-center}
+ (with-test-advisories!
+ (testing "superuser can list advisories"
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/security-center")]
+ (is (contains? response :last_checked_at))
+ (is (= 3 (count (:advisories response))))
+ (is (= "SC-0000-001" (-> response :advisories first :advisory_id)))))
+ (testing "non-superuser gets 403"
+ (mt/user-http-request :rasta :get 403 "ee/security-center"))))))
+
+(deftest trial-subscription-gate-test
+ (testing "Security Center is not available on trial subscriptions"
+ (mt/with-premium-features #{:admin-security-center}
+ (with-redefs [token-check/is-trial? (constantly true)]
+ (testing "GET /api/ee/security-center returns 402 for trial"
+ (is (=? {:message "Security Center is not available on this instance."
+ :status "error-premium-feature-not-available"}
+ (mt/user-http-request :crowberto :get 402 "ee/security-center"))))
+ (testing "POST acknowledge returns 402 for trial"
+ (is (=? {:message "Security Center is not available on this instance."
+ :status "error-premium-feature-not-available"}
+ (mt/user-http-request :crowberto :post 402
+ "ee/security-center/SC-0000-001/acknowledge"))))))))
+
+(deftest acknowledge-advisory-test
+ (testing "POST /api/ee/security-center/:id/acknowledge"
+ (mt/with-premium-features #{:admin-security-center :audit-app}
+ (with-test-advisories!
+ (testing "superuser can acknowledge"
+ (is (=? {:advisory_id "SC-0000-001"
+ :acknowledged_at some?
+ :acknowledged_by some?}
+ (mt/user-http-request :crowberto :post 200
+ "ee/security-center/SC-0000-001/acknowledge")))
+ (testing "creates an audit log entry"
+ (is (=? {:topic :security-advisory-acknowledge
+ :user_id (mt/user->id :crowberto)}
+ (t2/select-one [:model/AuditLog :topic :user_id]
+ :topic :security-advisory-acknowledge
+ {:order-by [[:id :desc]]})))))
+ (testing "cannot acknowledge twice"
+ (mt/user-http-request :crowberto :post 409
+ "ee/security-center/SC-0000-001/acknowledge"))
+ (testing "404 for unknown advisory"
+ (mt/user-http-request :crowberto :post 404
+ "ee/security-center/SC-0000-999/acknowledge"))
+ (testing "non-superuser gets 403"
+ (mt/user-http-request :rasta :post 403
+ "ee/security-center/SC-0000-001/acknowledge"))))))
+
+(deftest sync-endpoint-test
+ (testing "POST /api/ee/security-center/sync"
+ (mt/with-premium-features #{:admin-security-center}
+ (mt/with-temp-scheduler!
+ (with-redefs [premium-features/security-center-enabled? (constantly true)]
+ (task/init! ::sync-advisories/SyncAdvisories))
+ (testing "calling twice only runs sync once"
+ (let [call-count (atom 0)
+ started (promise)
+ finish (promise)]
+ (with-redefs [premium-features/security-center-enabled? (constantly true)
+ fetch/sync-advisories!
+ (fn []
+ (swap! call-count inc)
+ (deliver started true)
+ @finish)
+ matching/evaluate-all-advisories! (constantly nil)]
+ (is (= {:status "started"} (mt/user-http-request :crowberto :post 200 "ee/security-center/sync")))
+ @started
+ (is (= {:status "already-in-progress"} (mt/user-http-request :crowberto :post 200 "ee/security-center/sync")))
+ (deliver finish true)
+ (is (= 1 @call-count) "sync should only run once despite two API calls")))))
+ (testing "non-superuser gets 403"
+ (mt/user-http-request :rasta :post 403 "ee/security-center/sync")))))
+
+(deftest test-notification-test
+ (testing "POST /api/ee/security-center/test-notification"
+ (testing "requires premium feature"
+ (mt/with-premium-features #{}
+ (mt/assert-has-premium-feature-error
+ "Security Center"
+ (mt/user-http-request :crowberto :post 402 "ee/security-center/test-notification"))))
+ (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"
+ (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})))]
+ (mt/user-http-request :crowberto :post 400 "ee/security-center/test-notification"))))))
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/fetch_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/fetch_test.clj
new file mode 100644
index 00000000000..2c1dda8c0fb
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/security_center/fetch_test.clj
@@ -0,0 +1,178 @@
+(ns metabase-enterprise.security-center.fetch-test
+ (:require
+ [clj-http.client :as http]
+ [clojure.test :refer :all]
+ [metabase-enterprise.security-center.fetch :as fetch]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util.json :as json]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(defn- make-advisory
+ "Build a minimal advisory map matching `parse-advisory` output. `overrides` are merged in."
+ [advisory-id & {:as overrides}]
+ (merge {:advisory_id advisory-id
+ :severity "high"
+ :title (str "Advisory " advisory-id)
+ :description "Test advisory"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query nil
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}
+ overrides))
+
+(deftest sync-advisories-inserts-new-test
+ (mt/with-model-cleanup [:model/SecurityAdvisory]
+ (with-redefs [fetch/fetch-advisories-from-store (constantly [(make-advisory "SC-FETCH-001")])]
+ (fetch/sync-advisories!)
+ (let [row (t2/select-one :model/SecurityAdvisory :advisory_id "SC-FETCH-001")]
+ (is (some? row))
+ (is (=? {:advisory_id "SC-FETCH-001"
+ :match_status :unknown
+ :fetched_at some?}
+ row))))))
+
+(deftest sync-advisories-updates-existing-test
+ (mt/with-temp [:model/SecurityAdvisory _existing
+ (make-advisory "SC-FETCH-002" :severity "low" :title "Old title" :match_status "active"
+ :published_at #t "2026-03-24T00:00:00Z" :updated_at #t "2026-03-24T00:00:00Z")]
+ (with-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-FETCH-002" :title "New title" :severity "critical")])]
+ (fetch/sync-advisories!)
+ (is (=? {:title "New title"
+ :severity :critical
+ :match_status :active}
+ (t2/select-one :model/SecurityAdvisory :advisory_id "SC-FETCH-002"))))))
+
+(deftest sync-advisories-preserves-acknowledgement-test
+ (mt/with-temp [:model/User {user-id :id} {:is_superuser true}
+ :model/SecurityAdvisory _existing
+ (make-advisory "SC-FETCH-003"
+ :match_status "active"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"
+ :acknowledged_by user-id
+ :acknowledged_at #t "2026-03-25T00:00:00Z")]
+ (with-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-FETCH-003" :title "Updated title")])]
+ (fetch/sync-advisories!)
+ (is (=? {:title "Updated title"
+ :acknowledged_by some?
+ :acknowledged_at some?}
+ (t2/select-one :model/SecurityAdvisory :advisory_id "SC-FETCH-003"))))))
+
+(defn- make-json-advisory
+ "Build a JSON-shaped advisory map (as it arrives from the store API, before parsing).
+ Uses string severity and `id` instead of `advisory_id`."
+ [advisory-id & {:as overrides}]
+ (merge {"id" advisory-id
+ "severity" "high"
+ "title" (str "Advisory " advisory-id)
+ "description" "Test advisory"
+ "remediation" "Upgrade"
+ "affected_versions" [{"min" "0.1.0" "fixed" "99.99.99"}]
+ "matching_query" nil
+ "published_at" "2026-03-24T00:00:00Z"
+ "updated_at" "2026-03-24T00:00:00Z"
+ "advisory_url" nil}
+ overrides))
+
+(defn- fake-store-response
+ "Build a ring-style HTTP response whose body is JSON containing the given advisories."
+ [advisories]
+ {:status 200
+ :body (json/encode {"advisories" advisories})})
+
+(deftest fetch-advisories-from-json-test
+ (testing "full pipeline: JSON response → schema validation → EDN parsing → upsert"
+ (let [query-edn "{:select [1] :from [:core_user] :where [:= :email \"x\"] :limit 1}"
+ advisory (make-json-advisory "SC-2026-001"
+ "matching_query" {"default" query-edn})]
+ (mt/with-model-cleanup [:model/SecurityAdvisory]
+ (with-redefs [http/get (constantly (fake-store-response [advisory]))
+ premium-features/premium-embedding-token (constantly "fake-token")
+ premium-features/site-uuid-for-premium-features-token-checks (constantly "fake-uuid")]
+ (fetch/sync-advisories!)
+ (let [row (t2/select-one :model/SecurityAdvisory :advisory_id "SC-2026-001")]
+ (is (some? row))
+ (is (= {:default {:select [1] :from [:core_user] :where [:= :email "x"] :limit 1}}
+ (:matching_query row)))
+ (is (=? {:advisory_id "SC-2026-001"
+ :severity :high
+ :title "Advisory SC-2026-001"}
+ row))))))))
+
+(deftest sync-advisories-stores-updated-at-test
+ (mt/with-model-cleanup [:model/SecurityAdvisory]
+ (with-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-UPD-001" :updated_at #t "2026-04-01T12:00:00Z")])]
+ (fetch/sync-advisories!)
+ (let [row (t2/select-one :model/SecurityAdvisory :advisory_id "SC-UPD-001")]
+ (is (some? (:updated_at row)))
+ (is (not= (:published_at row) (:updated_at row)))))))
+
+(deftest sync-advisories-updates-updated-at-on-resync-test
+ (testing "updated_at is refreshed when an existing advisory is re-synced"
+ (mt/with-temp [:model/SecurityAdvisory _
+ (make-advisory "SC-UPD-003" :match_status "unknown" :published_at #t "2026-03-24T00:00:00Z" :updated_at #t "2026-03-24T00:00:00Z")]
+ (with-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-UPD-003" :updated_at #t "2026-04-02T08:00:00Z")])]
+ (fetch/sync-advisories!)
+ (is (=? {:updated_at some?}
+ (t2/select-one :model/SecurityAdvisory :advisory_id "SC-UPD-003")))
+ (is (not= #t "2026-03-24T00:00:00Z"
+ (:updated_at (t2/select-one :model/SecurityAdvisory :advisory_id "SC-UPD-003"))))))))
+
+(deftest fetch-rejects-non-select-matching-query-test
+ (testing "matching_query with mutation keys is rejected during sync"
+ (doseq [[label query-edn] [["insert" "{:insert-into :core_user :values [{:email \"x\"}]}"]
+ ["delete" "{:delete-from :core_user :where [:= :id 1]}"]
+ ["update" "{:update :core_user :set {:email \"x\"} :where [:= :id 1]}"]
+ ["truncate" "{:truncate :core_user}"]
+ ["drop-table" "{:drop-table :core_user}"]
+ ["no-select" "{:from [:core_user]}"]
+ ["not-a-map" "[:select 1]"]]]
+ (testing label
+ (let [advisory (make-json-advisory (str "SC-BAD-" label)
+ "matching_query" {"default" query-edn})]
+ (mt/with-model-cleanup [:model/SecurityAdvisory]
+ (with-redefs [http/get (constantly (fake-store-response [advisory]))
+ premium-features/premium-embedding-token (constantly "fake-token")
+ premium-features/site-uuid-for-premium-features-token-checks (constantly "fake-uuid")]
+ ;; sync should not throw — error is caught per-advisory
+ (fetch/sync-advisories!)
+ (testing "advisory was NOT inserted"
+ (is (nil? (t2/select-one :model/SecurityAdvisory :advisory_id (str "SC-BAD-" label))))))))))))
+
+(deftest fetch-allows-valid-select-queries-test
+ (doseq [[label query-edn] [["subquery" "{:select [1] :from [{:select [:id] :from [:core_user]}] :limit 1}"]
+ ["cte" "{:with [[:active_users {:select [:id] :from [:core_user]
+ :where [:= :is_active true]}]] :select [1] :from [:active_users] :limit 1}"]]]
+ (testing label
+ (let [advisory (make-json-advisory (str "SC-OK-" label)
+ "matching_query" {"default" query-edn})]
+ (mt/with-model-cleanup [:model/SecurityAdvisory]
+ (with-redefs [http/get (constantly (fake-store-response [advisory]))
+ premium-features/premium-embedding-token (constantly "fake-token")
+ premium-features/site-uuid-for-premium-features-token-checks (constantly "fake-uuid")]
+ (fetch/sync-advisories!)
+ (is (some? (t2/select-one :model/SecurityAdvisory :advisory_id (str "SC-OK-" label))))))))))
+
+(deftest sync-advisories-handles-fetch-error-test
+ (testing "network error doesn't throw"
+ (with-redefs [fetch/fetch-advisories-from-store (fn [] (throw (Exception. "connection refused")))]
+ (is (nil? (fetch/sync-advisories!))))))
+
+(deftest sync-advisories-handles-upsert-error-test
+ (testing "error on one advisory doesn't block others"
+ (mt/with-model-cleanup [:model/SecurityAdvisory]
+ (with-redefs [fetch/fetch-advisories-from-store
+ (constantly [(make-advisory "SC-FETCH-BAD" :severity "not-a-valid-severity!!!")
+ (make-advisory "SC-FETCH-GOOD")])]
+ (fetch/sync-advisories!)
+ (testing "good advisory was still inserted"
+ (is (some? (t2/select-one :model/SecurityAdvisory :advisory_id "SC-FETCH-GOOD"))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/matching_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/matching_test.clj
new file mode 100644
index 00000000000..5d614161ef7
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/security_center/matching_test.clj
@@ -0,0 +1,234 @@
+(ns metabase-enterprise.security-center.matching-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.security-center.matching :as matching]
+ [metabase.app-db.core :as mdb]
+ [metabase.models.interface :as mi]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2])
+ (:import org.semver4j.Semver))
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(set! *warn-on-reflection* true)
+
+(deftest ^:parallel parse-version-test
+ (testing "parses standard versions"
+ (doseq [input ["v1.57.0" "1.57.0" "v0.50.2" "v1.57.16"]]
+ (is (some? (matching/parse-version input)) (str "should parse: " input))))
+ (testing "edition prefix preserved — 0.57 and 1.57 are distinct for range matching"
+ (is (not= (matching/parse-version "v0.57.0")
+ (matching/parse-version "v1.57.0"))))
+ (testing "pre-release sorts before stable"
+ (is (.isLowerThan ^Semver (matching/parse-version "v0.58.0-beta")
+ ^Semver (matching/parse-version "v0.58.0"))))
+ (testing "invalid formats return nil"
+ (are [input] (nil? (matching/parse-version input))
+ "vLOCAL_DEV"
+ nil
+ "")))
+
+(deftest ^:parallel evaluate-advisory-test
+ (let [v matching/parse-version
+ single-range {:affected_versions [{:min "1.57.0" :fixed "1.57.16"}]}
+ multi-range {:affected_versions [{:min "1.57.0" :fixed "1.57.16"}
+ {:min "1.58.0" :fixed "1.58.10"}]}
+ narrow-range {:affected_versions [{:min "0.50.0" :fixed "0.50.2"}]}]
+ (testing "query result takes priority over version"
+ (are [expected version query-result]
+ (= expected (matching/evaluate-advisory single-range version query-result))
+ :not_affected (v "1.57.5") false
+ :not_affected (v "1.57.16") false
+ :error (v "1.57.5") :error
+ :error (v "1.57.16") :error))
+ (testing "single range — version determines active vs resolved"
+ (are [expected version]
+ (= expected (matching/evaluate-advisory single-range version true))
+ :active (v "1.57.0") ; at min boundary
+ :active (v "1.57.5") ; mid-range
+ :active (v "1.57.15") ; one patch before fixed
+ :resolved (v "1.57.16") ; at fixed boundary
+ :resolved (v "1.57.17") ; one patch after fixed
+ :resolved (v "1.57.20") ; well past fixed
+ :resolved (v "1.56.0") ; before range
+ :resolved (v "1.59.0") ; past range
+ :resolved (v "0.57.5"))) ; OSS doesn't match EE range
+ (testing "nil version (LOCAL_DEV) → active when query matches"
+ (is (= :active (matching/evaluate-advisory single-range nil true))))
+ (testing "nil version + no match → not_affected"
+ (is (= :not_affected (matching/evaluate-advisory single-range nil false))))
+ (testing "nil version + error → error"
+ (is (= :error (matching/evaluate-advisory single-range nil :error))))
+ (testing "multiple ranges"
+ (are [expected version]
+ (= expected (matching/evaluate-advisory multi-range version true))
+ :active (v "1.57.5") ; in first range
+ :active (v "1.58.3") ; in second range
+ :active (v "1.58.0") ; at second range min boundary
+ :resolved (v "1.57.20") ; between ranges (patched for first, before second)
+ :resolved (v "1.58.10") ; at second range fixed boundary
+ :resolved (v "1.59.0"))) ; past all ranges
+ (testing "narrow patch range [0.50.0, 0.50.2)"
+ (are [expected version]
+ (= expected (matching/evaluate-advisory narrow-range version true))
+ :active (v "0.50.0") ; at min
+ :active (v "0.50.1") ; mid-range
+ :resolved (v "0.50.2") ; at fixed
+ :resolved (v "1.0.0"))) ; major version jump
+ (testing "pre-release of fixed version is still affected"
+ (is (= :active (matching/evaluate-advisory single-range (v "1.57.16-beta") true))))
+ (testing "empty affected_versions — query matches but no ranges → resolved"
+ (is (= :resolved (matching/evaluate-advisory {:affected_versions []} (v "1.57.5") true))))))
+
+(deftest execute-matching-query-test
+ (testing "nil query means affects all — returns true"
+ (is (true? (matching/execute-matching-query! nil))))
+ (testing "query that matches"
+ (is (true? (matching/execute-matching-query!
+ {:default {:select [1] :from [:core_user] :limit 1}}))))
+ (testing "query that doesn't match"
+ (is (false? (matching/execute-matching-query!
+ {:default {:select [1] :from [:core_user]
+ :where [:= :email "[email protected]"] :limit 1}}))))
+ (testing "dialect-specific query is preferred over default"
+ (is (true? (matching/execute-matching-query!
+ {(mdb/db-type) {:select [1] :from [:core_user] :limit 1}
+ :default {:select [1] :from [:core_user]
+ :where [:= :email "[email protected]"] :limit 1}}))))
+ (testing "falls back to :default when dialect not present"
+ (is (true? (matching/execute-matching-query!
+ {:some_other_db {:select [1] :from [:core_user]
+ :where [:= :email "[email protected]"] :limit 1}
+ :default {:select [1] :from [:core_user] :limit 1}}))))
+ (testing "no dialect match and no default → :error"
+ (is (= :error (matching/execute-matching-query!
+ {:some_other_db {:select [1] :from [:core_user] :limit 1}}))))
+ (testing "query against missing table returns :error"
+ (is (= :error (matching/execute-matching-query!
+ {:default {:select [1] :from [:nonexistent_table_xyz] :limit 1}}))))
+ (when-not (= :h2 (mdb/db-type))
+ (testing "write query is rejected by read-only connection"
+ (matching/execute-matching-query!
+ {:default {:delete-from :core_user}})
+ (testing "no rows were actually deleted"
+ (is (pos? (t2/count :model/User)))))))
+
+(deftest evaluate-advisory!-test
+ (testing "query matches + version in range → active"
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ {:advisory_id "SC-MATCH-001"
+ :severity "critical"
+ :title "Test"
+ :description "Test"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query {:default {:select [1] :from [:core_user] :limit 1}}
+ :match_status "not_affected"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}]
+ (matching/evaluate-advisory! advisory)
+ (is (=? {:match_status :active
+ :last_evaluated_at some?}
+ (t2/select-one :model/SecurityAdvisory :id (:id advisory))))))
+ (testing "query doesn't match → not_affected"
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ {:advisory_id "SC-MATCH-002"
+ :severity "high"
+ :title "Test"
+ :description "Test"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query {:default {:select [1] :from [:core_user]
+ :where [:= :email "[email protected]"] :limit 1}}
+ :match_status "active"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}]
+ (matching/evaluate-advisory! advisory)
+ (is (=? {:match_status :not_affected}
+ (t2/select-one :model/SecurityAdvisory :id (:id advisory))))))
+ (testing "nil matching_query (affects all) + version in range → active"
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ {:advisory_id "SC-MATCH-003"
+ :severity "medium"
+ :title "Test"
+ :description "Test"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query nil
+ :match_status "not_affected"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}]
+ (matching/evaluate-advisory! advisory)
+ (is (=? {:match_status :active}
+ (t2/select-one :model/SecurityAdvisory :id (:id advisory))))))
+ (testing "query error → error status persisted"
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ {:advisory_id "SC-MATCH-004"
+ :severity "low"
+ :title "Test"
+ :description "Test"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query {:default {:select [1] :from [:nonexistent_table] :limit 1}}
+ :match_status "not_affected"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}]
+ (matching/evaluate-advisory! advisory)
+ (is (=? {:match_status :error
+ :last_evaluated_at some?}
+ (t2/select-one :model/SecurityAdvisory :id (:id advisory)))))))
+
+(deftest evaluate-all-advisories!-test
+ (mt/with-temp [:model/SecurityAdvisory _active
+ {:advisory_id "SC-EVAL-001"
+ :severity "high"
+ :title "Active advisory"
+ :description "Test"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query {:default {:select [1] :from [:core_user] :limit 1}}
+ :match_status "not_affected"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}
+ :model/SecurityAdvisory _not-affected
+ {:advisory_id "SC-EVAL-002"
+ :severity "medium"
+ :title "Not affected advisory"
+ :description "Test"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query {:default {:select [1] :from [:core_user]
+ :where [:= :email "[email protected]"] :limit 1}}
+ :match_status "not_affected"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}
+ :model/SecurityAdvisory _erroring
+ {:advisory_id "SC-EVAL-003"
+ :severity "low"
+ :title "Erroring advisory"
+ :description "Test"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query {:default {:select [1] :from [:nonexistent_table] :limit 1}}
+ :match_status "not_affected"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}]
+ (matching/evaluate-all-advisories!)
+ (let [fetch (fn [id] (t2/select-one :model/SecurityAdvisory :advisory_id id))]
+ (testing "each advisory gets the correct status and timestamp"
+ (is (=? {:match_status :active
+ :last_evaluated_at some?}
+ (fetch "SC-EVAL-001")))
+ (is (=? {:match_status :not_affected
+ :last_evaluated_at some?}
+ (fetch "SC-EVAL-002")))
+ (is (=? {:match_status :error
+ :last_evaluated_at some?}
+ (fetch "SC-EVAL-003"))))
+ (testing "acknowledged advisories are skipped"
+ (t2/update! :model/SecurityAdvisory {:advisory_id "SC-EVAL-001"}
+ {:acknowledged_at (mi/now) :acknowledged_by (mt/user->id :rasta)})
+ (let [before-eval (:last_evaluated_at (fetch "SC-EVAL-001"))]
+ (matching/evaluate-all-advisories!)
+ (is (= before-eval (:last_evaluated_at (fetch "SC-EVAL-001")))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj
new file mode 100644
index 00000000000..dace3b7731c
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/security_center/notification_test.clj
@@ -0,0 +1,400 @@
+(ns metabase-enterprise.security-center.notification-test
+ (:require
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase-enterprise.security-center.notification :as notification]
+ [metabase-enterprise.security-center.settings :as settings]
+ [metabase-enterprise.security-center.task.sync-advisories :as task.sync]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.events.core :as events]
+ [metabase.models.interface :as mi]
+ [metabase.notification.send :as notification.send]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(defn- advisory-fixture
+ "Common fixture map for a SecurityAdvisory row."
+ [overrides]
+ (merge {:severity "critical"
+ :title "Test Advisory"
+ :description "A test advisory"
+ :remediation "Upgrade to latest"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query {:default {:select [1] :from [:core_user] :limit 1}}
+ :match_status "not_affected"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}
+ overrides))
+
+(defmacro ^:private with-send-redef
+ "Redef send-notification!, email-configured?, and publish-event! to intercept notification sends."
+ [send-fn & body]
+ `(with-redefs [events/publish-event! (constantly nil)
+ channel.settings/email-configured? (constantly true)
+ notification.send/send-notification! ~send-fn]
+ ~@body))
+
+;; Clean the security_advisory table before each repeat-notification test
+;; so dev-seeded advisories don't interfere.
+(defn- with-clean-advisories [f]
+ (let [existing-ids (t2/select-pks-set :model/SecurityAdvisory)]
+ (try
+ (when (seq existing-ids)
+ (t2/update! :model/SecurityAdvisory {:id [:in existing-ids]}
+ {:acknowledged_at (mi/now)
+ :acknowledged_by (mt/user->id :crowberto)}))
+ (f)
+ (finally
+ (when (seq existing-ids)
+ (t2/update! :model/SecurityAdvisory {:id [:in existing-ids]}
+ {:acknowledged_at nil
+ :acknowledged_by nil}))))))
+
+;;; --------------------------------------------- Repeat notification task --------------------------------------------
+
+(deftest repeat-notification-cadence-test
+ (with-clean-advisories
+ (fn []
+ (testing "critical advisories: daily cadence"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-REPEAT-001"
+ :severity "critical"
+ :match_status "active"
+ :last_notified_at (t/minus (t/offset-date-time) (t/hours 25))})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (= ["SC-REPEAT-001"] @notified))))))
+
+ (testing "critical advisories: too soon — no repeat"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-REPEAT-002"
+ :severity "critical"
+ :match_status "active"
+ :last_notified_at (t/minus (t/offset-date-time) (t/hours 12))})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (empty? @notified))))))
+
+ (testing "high severity: 3-day cadence"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-REPEAT-003"
+ :severity "high"
+ :match_status "active"
+ :last_notified_at (t/minus (t/offset-date-time) (t/days 8))})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (= ["SC-REPEAT-003"] @notified))))))
+
+ (testing "high severity: too soon — no repeat"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-REPEAT-004"
+ :severity "high"
+ :match_status "active"
+ :last_notified_at (t/minus (t/offset-date-time) (t/days 1))})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (empty? @notified))))))
+
+ (testing "never-notified advisory is always due"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-REPEAT-005"
+ :severity "low"
+ :match_status "active"
+ :last_notified_at nil})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (= ["SC-REPEAT-005"] @notified))))))
+
+ (testing "medium severity: weekly cadence"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-MED-001"
+ :severity "medium"
+ :match_status "active"
+ :last_notified_at (t/minus (t/offset-date-time) (t/days 8))})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (= ["SC-MED-001"] @notified))))))
+
+ (testing "low severity: weekly cadence, too soon"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-LOW-001"
+ :severity "low"
+ :match_status "active"
+ :last_notified_at (t/minus (t/offset-date-time) (t/days 5))})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (empty? @notified))))))
+
+ (testing "error-status advisories are included in repeat notifications"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-ERR-001"
+ :severity "high"
+ :match_status "error"
+ :last_notified_at nil})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (= ["SC-ERR-001"] @notified)))))))))
+
+(deftest repeat-notification-exclusions-test
+ (with-clean-advisories
+ (fn []
+ (testing "acknowledged advisories are excluded from repeat notifications"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/User {user-id :id} {:is_superuser true}
+ :model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-ACK-001"
+ :severity "critical"
+ :match_status "active"
+ :last_notified_at nil
+ :acknowledged_by user-id
+ :acknowledged_at (mi/now)})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (empty? @notified))))))
+
+ (testing "not_affected advisories are excluded from repeat notifications"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-NA-001"
+ :severity "critical"
+ :match_status "not_affected"
+ :last_notified_at nil})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (empty? @notified))))))
+
+ (testing "resolved advisories are excluded from repeat notifications"
+ (let [notified (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory _advisory
+ (advisory-fixture {:advisory_id "SC-RES-001"
+ :severity "critical"
+ :match_status "resolved"
+ :last_notified_at nil})]
+ (with-redefs [notification/notify-advisory! (fn [a] (swap! notified conj (:advisory_id a)))]
+ (task.sync/send-repeat-notifications!)
+ (is (empty? @notified)))))))))
+
+(deftest repeat-notification-error-isolation-test
+ (with-clean-advisories
+ (fn []
+ (testing "failure notifying one advisory does not block others"
+ (let [notified (atom [])
+ call-count (atom 0)]
+ (mt/with-temp [:model/SecurityAdvisory _a1
+ (advisory-fixture {:advisory_id "SC-ISO-001"
+ :severity "critical"
+ :match_status "active"
+ :last_notified_at nil})
+ :model/SecurityAdvisory _a2
+ (advisory-fixture {:advisory_id "SC-ISO-002"
+ :severity "critical"
+ :match_status "active"
+ :last_notified_at nil})]
+ (with-redefs [notification/notify-advisory! (fn [a]
+ (swap! call-count inc)
+ (if (= 1 @call-count)
+ (throw (ex-info "transient failure" {}))
+ (swap! notified conj (:advisory_id a))))]
+ (task.sync/send-repeat-notifications!)
+ ;; The second advisory should still be notified despite the first one failing
+ (is (= 1 (count @notified))))))))))
+
+;;; ------------------------------------------------ notify-advisory! ------------------------------------------------
+
+(deftest notify-advisory-publishes-event-test
+ (testing "notify-advisory! publishes :event/security-advisory-match for audit logging"
+ (let [published (atom [])]
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-EVENT-001"
+ :severity "high"
+ :match_status "active"})]
+ (with-redefs [events/publish-event! (fn [topic info] (swap! published conj {:topic topic :info info}))
+ channel.settings/email-configured? (constantly true)
+ notification.send/send-notification! (constantly nil)]
+ (notification/notify-advisory! advisory)
+ (is (= 1 (count @published)))
+ (is (= :event/security-advisory-match (:topic (first @published))))
+ (is (= "SC-EVENT-001" (get-in (first @published) [:info :object :advisory_id]))))))))
+
+(deftest notify-advisory-updates-last-notified-at-test
+ (testing "notify-advisory! sets last_notified_at on the advisory"
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-TS-001"
+ :severity "critical"
+ :match_status "active"})]
+ (is (nil? (:last_notified_at advisory)))
+ (with-send-redef (constantly nil)
+ (notification/notify-advisory! advisory))
+ (is (some? (:last_notified_at (t2/select-one :model/SecurityAdvisory (:id advisory))))))))
+
+(deftest notify-advisory-does-not-update-on-send-failure-test
+ (testing "last_notified_at is NOT set when send-notification! throws"
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-FAIL-001"
+ :severity "critical"
+ :match_status "active"})]
+ (with-send-redef (fn [& _] (throw (ex-info "boom" {})))
+ (is (thrown-with-msg? Exception #"boom"
+ (notification/notify-advisory! advisory))))
+ (is (nil? (:last_notified_at (t2/select-one :model/SecurityAdvisory (:id advisory))))))))
+
+;;; -------------------------------------------- Recipient resolution -------------------------------------------------
+
+(deftest admin-email-included-when-set-test
+ (testing "site admin email is appended as a raw-value recipient"
+ (let [sent (atom nil)
+ custom-recip [{:type :notification-recipient/external-email :details {:email "[email protected]"}}]]
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-ADMIN-001"
+ :severity "critical"
+ :match_status "active"})]
+ (mt/with-temporary-setting-values [admin-email "[email protected]"]
+ (with-redefs [settings/security-center-email-recipients (constantly custom-recip)]
+ (with-send-redef (fn [notif & _] (reset! sent notif))
+ (notification/notify-advisory! advisory)
+ (let [email-handler (first (filter #(= :channel/email (:channel_type %)) (:handlers @sent)))
+ recipients (:recipients email-handler)]
+ (is (= 2 (count recipients)))
+ ;; configured recipient
+ (is (= :notification-recipient/external-email (:type (first recipients))))
+ ;; admin email appended
+ (is (= {:type :notification-recipient/raw-value :details {:value "[email protected]"}}
+ (last recipients))))))))))
+
+ (testing "no admin email appended when admin-email setting is nil"
+ (let [sent (atom nil)
+ custom-recip [{:type :notification-recipient/external-email :details {:email "[email protected]"}}]]
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-ADMIN-002"
+ :severity "high"
+ :match_status "active"})]
+ (mt/with-temporary-setting-values [admin-email nil]
+ (with-redefs [settings/security-center-email-recipients (constantly custom-recip)]
+ (with-send-redef (fn [notif & _] (reset! sent notif))
+ (notification/notify-advisory! advisory)
+ (let [email-handler (first (filter #(= :channel/email (:channel_type %)) (:handlers @sent)))
+ recipients (:recipients email-handler)]
+ (is (= 1 (count recipients)))
+ (is (= :notification-recipient/external-email (:type (first recipients))))))))))))
+
+(deftest email-recipients-custom-list-test
+ (testing "when security-center-email-recipients is set, those specific recipients are used"
+ (let [sent (atom nil)
+ custom-recip [{:type :notification-recipient/external-email :details {:email "[email protected]"}}]]
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-RECIP-002"
+ :severity "high"
+ :match_status "active"})]
+ (mt/with-temporary-setting-values [admin-email nil]
+ (with-redefs [settings/security-center-email-recipients (constantly custom-recip)]
+ (with-send-redef (fn [notif & _] (reset! sent notif))
+ (notification/notify-advisory! advisory)
+ (let [email-handler (first (filter #(= :channel/email (:channel_type %)) (:handlers @sent)))]
+ (is (= 1 (count (:recipients email-handler))))
+ (is (= :notification-recipient/external-email
+ (:type (first (:recipients email-handler)))))))))))))
+
+(deftest slack-handler-included-when-configured-test
+ (testing "Slack handler is added when channel is set and slack token is valid"
+ (let [sent (atom nil)]
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-SLACK-001"
+ :severity "critical"
+ :match_status "active"})]
+ (mt/with-temporary-setting-values [slack-token-valid? true]
+ (with-redefs [settings/security-center-slack-channel (constantly "#security-alerts")]
+ (with-send-redef (fn [notif & _] (reset! sent notif))
+ (notification/notify-advisory! advisory)
+ (let [slack-handler (first (filter #(= :channel/slack (:channel_type %)) (:handlers @sent)))]
+ (is (some? slack-handler))
+ (is (= "#security-alerts"
+ (get-in (first (:recipients slack-handler)) [:details :value])))))))))))
+
+(deftest slack-handler-omitted-when-not-configured-test
+ (testing "no Slack handler when security-center-slack-channel is nil"
+ (let [sent (atom nil)]
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-SLACK-002"
+ :severity "low"
+ :match_status "active"})]
+ (with-redefs [settings/security-center-slack-channel (constantly nil)]
+ (with-send-redef (fn [notif & _] (reset! sent notif))
+ (notification/notify-advisory! advisory)
+ (is (empty? (filter #(= :channel/slack (:channel_type %)) (:handlers @sent))))))))))
+
+(deftest slack-handler-omitted-when-token-invalid-test
+ (testing "no Slack handler when slack token is not valid"
+ (let [sent (atom nil)]
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-SLACK-003"
+ :severity "medium"
+ :match_status "active"})]
+ (mt/with-temporary-setting-values [slack-token-valid? false]
+ (with-redefs [settings/security-center-slack-channel (constantly "#alerts")]
+ (with-send-redef (fn [notif & _] (reset! sent notif))
+ (notification/notify-advisory! advisory)
+ (is (empty? (filter #(= :channel/slack (:channel_type %)) (:handlers @sent)))))))))))
+
+;;; -------------------------------------------- Test notification ----------------------------------------------------
+
+(deftest send-test-notification-sends-via-pipeline-test
+ (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!)
+ (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])]
+ (is (= "TEST-0000" (:advisory_id obj)))
+ (is (= :medium (:severity obj)))
+ (is (re-find #"(?i)test" (:title obj)))
+ (is (re-find #"(?i)test" (:description obj))))))))
+
+(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!)
+ (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)]
+ (is (thrown-with-msg? Exception #"No notification channels are configured"
+ (notification/send-test-notification!))))))
+
+;;; -------------------------------------------- Notification payload -------------------------------------------------
+
+(deftest notification-payload-structure-test
+ (testing "build-notification produces correct payload structure"
+ (let [sent (atom nil)]
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ (advisory-fixture {:advisory_id "SC-STRUCT-001"
+ :severity "high"
+ :match_status "active"
+ :title "RCE in widget parser"
+ :description "Remote code execution"})]
+ (with-send-redef (fn [notif & _] (reset! sent notif))
+ (notification/notify-advisory! advisory)
+ (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])]
+ (is (= "SC-STRUCT-001" (:advisory_id obj)))
+ (is (= :high (:severity obj)))
+ (is (= :active (:match_status obj)))
+ (is (= "RCE in widget parser" (:title obj)))
+ (is (= "Remote code execution" (:description obj)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/settings_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/settings_test.clj
new file mode 100644
index 00000000000..7e550f0d43d
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/security_center/settings_test.clj
@@ -0,0 +1,80 @@
+(ns metabase-enterprise.security-center.settings-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.premium-features.token-check :as token-check]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(deftest security-center-enabled?-test
+ (testing "enabled when feature flag present, not trial, and self-hosted"
+ (mt/with-premium-features #{:admin-security-center}
+ (is (true? (premium-features/security-center-enabled?)))))
+ (testing "disabled without the feature flag"
+ (mt/with-premium-features #{}
+ (is (false? (premium-features/security-center-enabled?)))))
+ (testing "disabled on cloud (hosted) even with the feature flag"
+ (mt/with-premium-features #{:admin-security-center :hosting}
+ (is (false? (premium-features/security-center-enabled?)))))
+ (testing "disabled on trial even with the feature flag"
+ (mt/with-premium-features #{:admin-security-center}
+ (mt/with-dynamic-fn-redefs [token-check/is-trial? (constantly true)]
+ (is (false? (premium-features/security-center-enabled?)))))))
+
+(deftest security-center-email-recipients-test
+ (testing "PUT /api/setting/security-center-email-recipients"
+ (mt/with-premium-features #{:admin-security-center}
+ (testing "superuser can set email recipients"
+ (mt/user-http-request :crowberto :put 204 "setting/security-center-email-recipients"
+ {:value [{:type "notification-recipient/user" :user_id (mt/user->id :crowberto) :details nil}]})
+ (is (= [{:type "notification-recipient/user" :user_id (mt/user->id :crowberto) :details nil}]
+ (mt/user-http-request :crowberto :get 200 "setting/security-center-email-recipients"))))
+
+ (testing "rejects null"
+ (mt/user-http-request :crowberto :put 400 "setting/security-center-email-recipients"
+ {:value nil}))
+
+ (testing "rejects empty list"
+ (mt/user-http-request :crowberto :put 400 "setting/security-center-email-recipients"
+ {:value []}))
+
+ (testing "non-superuser gets 403"
+ (mt/user-http-request :rasta :put 403 "setting/security-center-email-recipients"
+ {:value [{:type "notification-recipient/user" :user_id (mt/user->id :crowberto) :details nil}]}))))
+
+ (testing "requires premium feature"
+ (mt/with-premium-features #{}
+ (mt/user-http-request :crowberto :put 500 "setting/security-center-email-recipients"
+ {:value [{:type "notification-recipient/user" :user_id (mt/user->id :crowberto) :details nil}]}))))
+
+(deftest security-center-slack-channel-test
+ (testing "PUT /api/setting/security-center-slack-channel"
+ (mt/with-premium-features #{:admin-security-center}
+ (testing "rejects value when Slack is not configured"
+ (mt/with-temporary-setting-values [slack-token-valid? false]
+ (mt/user-http-request :crowberto :put 400 "setting/security-center-slack-channel"
+ {:value "#security"})))
+
+ (testing "superuser can set channel when Slack is configured"
+ (mt/with-temporary-setting-values [slack-token-valid? true]
+ (mt/user-http-request :crowberto :put 204 "setting/security-center-slack-channel"
+ {:value "#security"})
+ (is (= "#security"
+ (mt/user-http-request :crowberto :get 200 "setting/security-center-slack-channel")))))
+
+ (testing "superuser can set to null (disable Slack)"
+ (mt/user-http-request :crowberto :put 204 "setting/security-center-slack-channel"
+ {:value nil})
+ (mt/user-http-request :crowberto :get 204 "setting/security-center-slack-channel"))
+
+ (testing "non-superuser gets 403"
+ (mt/with-temporary-setting-values [slack-token-valid? true]
+ (mt/user-http-request :rasta :put 403 "setting/security-center-slack-channel"
+ {:value "#security"})))))
+
+ (testing "requires premium feature"
+ (mt/with-premium-features #{}
+ (mt/user-http-request :crowberto :put 500 "setting/security-center-slack-channel"
+ {:value "#security"}))))
diff --git a/enterprise/backend/test/metabase_enterprise/security_center/task/sync_advisories_test.clj b/enterprise/backend/test/metabase_enterprise/security_center/task/sync_advisories_test.clj
new file mode 100644
index 00000000000..48fdc6b7f33
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/security_center/task/sync_advisories_test.clj
@@ -0,0 +1,59 @@
+(ns metabase-enterprise.security-center.task.sync-advisories-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.security-center.fetch :as fetch]
+ [metabase-enterprise.security-center.matching :as matching]
+ [metabase-enterprise.security-center.task.sync-advisories :as sync-advisories]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(deftest sync-and-evaluate-test
+ (testing "skips when disabled"
+ (let [called (atom [])]
+ (mt/with-dynamic-fn-redefs [premium-features/security-center-enabled? (constantly false)
+ fetch/sync-advisories! #(swap! called conj :fetch)
+ matching/evaluate-all-advisories! #(swap! called conj :evaluate)]
+ (#'sync-advisories/sync-and-evaluate!)
+ (is (empty? @called)))))
+ (testing "runs fetch then evaluate"
+ (let [called (atom [])]
+ (mt/with-premium-features #{:admin-security-center}
+ (mt/with-dynamic-fn-redefs [premium-features/security-center-enabled? (constantly true)
+ fetch/sync-advisories! #(swap! called conj :fetch)
+ matching/evaluate-all-advisories! #(swap! called conj :evaluate)]
+ (#'sync-advisories/sync-and-evaluate!)
+ (is (= [:fetch :evaluate] @called))))))
+ (testing "evaluate still runs when fetch throws"
+ (let [called (atom [])]
+ (mt/with-premium-features #{:admin-security-center}
+ (mt/with-dynamic-fn-redefs [premium-features/security-center-enabled? (constantly true)
+ fetch/sync-advisories! #(throw (Exception. "fetch failed"))
+ matching/evaluate-all-advisories! #(swap! called conj :evaluate)]
+ (#'sync-advisories/sync-and-evaluate!)
+ (is (= [:evaluate] @called)))))))
+
+(deftest sync-and-evaluate-e2e-test
+ (testing "full flow: sync-and-evaluate! runs matching queries and updates match_status"
+ (mt/with-premium-features #{:admin-security-center}
+ (mt/test-helpers-set-global-values!
+ (mt/with-temp [:model/SecurityAdvisory advisory
+ {:advisory_id "SC-E2E-001"
+ :severity "critical"
+ :title "E2E test advisory"
+ :description "Tests the full sync-and-evaluate flow"
+ :remediation "Upgrade"
+ :affected_versions [{:min "0.1.0" :fixed "99.99.99"}]
+ :matching_query {:default {:select [[1 :one]]}}
+ ;; query returns rows unconditionally — tests the full evaluate flow
+ :match_status "not_affected"
+ :published_at #t "2026-03-24T00:00:00Z"
+ :updated_at #t "2026-03-24T00:00:00Z"}]
+ (mt/with-dynamic-fn-redefs [premium-features/security-center-enabled? (constantly true)
+ fetch/sync-advisories! (constantly nil)]
+ (#'sync-advisories/sync-and-evaluate!)
+ (let [updated (t2/select-one :model/SecurityAdvisory (:id advisory))]
+ (is (= :active (:match_status updated)))
+ (is (some? (:last_evaluated_at updated))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
index 15ad3c35590..24fb05e57d3 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
@@ -117,6 +117,7 @@
:model/ViewLog
:model/Sandbox
:model/ConnectionImpersonation
+ :model/SecurityAdvisory
:model/CloudMigration
:model/Comment
:model/CommentReaction
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.ts b/enterprise/frontend/src/metabase-enterprise/plugins.ts
index ad43d20ba50..cddd79d4685 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.ts
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.ts
@@ -37,6 +37,7 @@ import { initializePlugin as initializeRemoteSync } from "./remote_sync";
import { initializePlugin as initializeReplacement } from "./replacement";
import { initializePlugin as initializeResourceDownloads } from "./resource_downloads";
import { initializePlugin as initializeSandboxes } from "./sandboxes";
+import { initializePlugin as initializeSecurityCenter } from "./security_center";
import { initializePlugin as initializeSemanticSearch } from "./semantic_search";
import { initializePlugin as initializeSharing } from "./sharing";
import { initializePlugin as initializeSmtpOverride } from "./smtp-override";
@@ -92,6 +93,7 @@ export function initializePlugins() {
initializeDatabaseReplication();
initializeTableEditing();
initializeDependencies();
+ initializeSecurityCenter();
initializeSemanticSearch();
initializeTransforms();
initializeTransformsInspector();
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/analytics.ts b/enterprise/frontend/src/metabase-enterprise/security_center/analytics.ts
new file mode 100644
index 00000000000..e9eba191f91
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/analytics.ts
@@ -0,0 +1,7 @@
+import { trackSimpleEvent } from "metabase/utils/analytics";
+
+export const trackSecurityCenterPageViewed = () => {
+ trackSimpleEvent({
+ event: "security_center_page_viewed",
+ });
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryCard/AdvisoryCard.module.css b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryCard/AdvisoryCard.module.css
new file mode 100644
index 00000000000..007a4543301
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryCard/AdvisoryCard.module.css
@@ -0,0 +1,35 @@
+.affectedCard {
+ background-color: var(--mb-color-background-error);
+}
+
+.severityCritical {
+ background-color: var(--mb-color-error);
+ color: var(--mb-color-white);
+}
+
+.severityHigh {
+ background-color: var(--mb-color-warning);
+ color: var(--mb-color-white);
+}
+
+.severityMedium {
+ background-color: var(--mb-color-gold);
+ color: var(--mb-color-text-primary);
+}
+
+.severityLow {
+ background-color: var(--mb-color-success);
+ color: var(--mb-color-white);
+}
+
+.statusAffected {
+ background-color: var(--mb-color-background-error);
+ border-color: var(--mb-color-error);
+ color: var(--mb-color-error);
+}
+
+.statusNotAffected {
+ background-color: var(--mb-color-background-success);
+ border-color: var(--mb-color-success);
+ color: var(--mb-color-success);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryCard/AdvisoryCard.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryCard/AdvisoryCard.tsx
new file mode 100644
index 00000000000..ae35b2630a3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryCard/AdvisoryCard.tsx
@@ -0,0 +1,124 @@
+import { t } from "ttag";
+
+import { useIsSmallScreen } from "metabase/common/hooks/use-is-small-screen";
+import { Anchor, Badge, Card, Group, Stack, Text, Title } from "metabase/ui";
+import type {
+ Advisory,
+ AdvisoryId,
+ AdvisorySeverity,
+} from "metabase-types/api";
+
+import { isAcknowledged, isAffected } from "../../utils";
+
+import S from "./AdvisoryCard.module.css";
+
+const SEVERITY_CLASS: Record<AdvisorySeverity, string> = {
+ critical: S.severityCritical,
+ high: S.severityHigh,
+ medium: S.severityMedium,
+ low: S.severityLow,
+};
+
+function formatVersionRange(advisory: Advisory): string {
+ return advisory.affected_versions
+ .map((v) => `${v.min} – ${v.fixed}`)
+ .join(", ");
+}
+
+interface AdvisoryCardProps {
+ advisory: Advisory;
+ onAcknowledge?: (advisoryId: AdvisoryId) => void;
+}
+
+export function AdvisoryCard({ advisory, onAcknowledge }: AdvisoryCardProps) {
+ const affected = isAffected(advisory);
+ const acknowledged = isAcknowledged(advisory);
+ const isSmallScreen = useIsSmallScreen();
+
+ const badges = (
+ <>
+ <Badge className={SEVERITY_CLASS[advisory.severity]}>
+ {advisory.severity}
+ </Badge>
+ <Badge
+ variant="outline"
+ className={affected ? S.statusAffected : S.statusNotAffected}
+ data-testid="affected-status"
+ >
+ {affected ? t`Affected` : t`Not affected`}
+ </Badge>
+ {acknowledged && (
+ <Badge color="brand" variant="light" data-testid="acknowledged-badge">
+ {t`Dismissed`}
+ </Badge>
+ )}
+ </>
+ );
+
+ const acknowledgeButton = !acknowledged && onAcknowledge && (
+ <Anchor
+ component="button"
+ size="sm"
+ onClick={() => onAcknowledge(advisory.advisory_id)}
+ data-testid="acknowledge-button"
+ >
+ {t`Dismiss`}
+ </Anchor>
+ );
+
+ return (
+ <Card
+ p="lg"
+ withBorder
+ className={affected ? S.affectedCard : undefined}
+ data-testid="advisory-card"
+ mih={184}
+ >
+ <Stack gap="sm">
+ {isSmallScreen && (
+ <Group gap="sm" justify="space-between" wrap="nowrap">
+ <Group gap="sm" wrap="wrap">
+ {badges}
+ </Group>
+ {acknowledgeButton}
+ </Group>
+ )}
+ <Group gap="sm" align="center" wrap="wrap">
+ {!isSmallScreen && badges}
+ <Title order={4}>{advisory.title}</Title>
+ </Group>
+
+ <Text lineClamp={2} c="text-secondary">
+ {advisory.description}
+ </Text>
+
+ <Stack gap="xs">
+ {advisory.affected_versions.length > 0 && (
+ <Text size="sm" c="text-secondary">
+ {t`Affected versions: ${formatVersionRange(advisory)}`}
+ </Text>
+ )}
+ <Text size="sm" c="text-secondary">
+ {t`Remediation: ${advisory.remediation}`}
+ </Text>
+ </Stack>
+
+ {(advisory.advisory_url || !isSmallScreen) && (
+ <Group gap="md" h={28}>
+ {!isSmallScreen && acknowledgeButton}
+ {advisory.advisory_url && (
+ <Anchor
+ href={advisory.advisory_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ size="sm"
+ >
+ {t`View advisory`}
+ </Anchor>
+ )}
+ </Group>
+ )}
+ </Stack>
+ </Card>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryFilterBar/AdvisoryFilterBar.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryFilterBar/AdvisoryFilterBar.tsx
new file mode 100644
index 00000000000..aa6ad7681b8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryFilterBar/AdvisoryFilterBar.tsx
@@ -0,0 +1,76 @@
+import { t } from "ttag";
+
+import { useIsSmallScreen } from "metabase/common/hooks/use-is-small-screen";
+import { Checkbox, Group, Select, Stack } from "metabase/ui";
+import type { AdvisorySeverity } from "metabase-types/api";
+
+import type { AdvisoryFilter } from "../../types";
+
+interface AdvisoryFilterBarProps {
+ filter: AdvisoryFilter;
+ onChange: (filter: AdvisoryFilter) => void;
+ className?: string;
+}
+
+type SelectOption<T extends string> = { value: T; label: string };
+
+export function AdvisoryFilterBar({
+ filter,
+ onChange,
+ className,
+}: AdvisoryFilterBarProps) {
+ const isSmallScreen = useIsSmallScreen();
+
+ const severityOptions: SelectOption<AdvisorySeverity | "all">[] = [
+ { value: "all", label: t`All severities` },
+ { value: "critical", label: t`Critical` },
+ { value: "high", label: t`High` },
+ { value: "medium", label: t`Medium` },
+ { value: "low", label: t`Low` },
+ ];
+
+ const statusOptions: SelectOption<AdvisoryFilter["status"]>[] = [
+ { value: "all", label: t`All statuses` },
+ { value: "affected", label: t`Affected` },
+ { value: "not-affected", label: t`Not affected` },
+ ];
+
+ const Wrapper = isSmallScreen ? Stack : Group;
+
+ return (
+ <Wrapper gap="md" data-testid="advisory-filter-bar" className={className}>
+ <Select
+ data={severityOptions}
+ value={filter.severity}
+ onChange={(value) =>
+ onChange({
+ ...filter,
+ severity: value ?? "all",
+ })
+ }
+ w={isSmallScreen ? "100%" : 180}
+ data-testid="severity-filter"
+ />
+ <Select
+ data={statusOptions}
+ value={filter.status}
+ onChange={(value) =>
+ onChange({
+ ...filter,
+ status: value ?? "all",
+ })
+ }
+ w={isSmallScreen ? "100%" : 180}
+ data-testid="status-filter"
+ />
+ <Checkbox
+ label={t`Show dismissed`}
+ checked={filter.showAcknowledged}
+ onChange={(e) =>
+ onChange({ ...filter, showAcknowledged: e.currentTarget.checked })
+ }
+ data-testid="show-acknowledged-filter"
+ />
+ </Wrapper>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryList/AdvisoryList.module.css b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryList/AdvisoryList.module.css
new file mode 100644
index 00000000000..e0a87f29dce
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryList/AdvisoryList.module.css
@@ -0,0 +1,5 @@
+.advisoryList {
+ > :not(:last-child) {
+ margin-bottom: var(--mantine-spacing-md);
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryList/AdvisoryList.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryList/AdvisoryList.tsx
new file mode 100644
index 00000000000..c76fbd5d36a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/AdvisoryList/AdvisoryList.tsx
@@ -0,0 +1,35 @@
+import cx from "classnames";
+
+import { Box } from "metabase/ui";
+import type { Advisory, AdvisoryId } from "metabase-types/api";
+
+import { sortAdvisories } from "../../utils";
+import { AdvisoryCard } from "../AdvisoryCard/AdvisoryCard";
+
+import S from "./AdvisoryList.module.css";
+
+interface AdvisoryListProps {
+ advisories: Advisory[];
+ onAcknowledge?: (advisoryId: AdvisoryId) => void;
+ className?: string;
+}
+
+export function AdvisoryList({
+ advisories,
+ onAcknowledge,
+ className,
+}: AdvisoryListProps) {
+ const sorted = sortAdvisories(advisories);
+
+ return (
+ <Box className={cx(className, S.advisoryList)}>
+ {sorted.map((advisory) => (
+ <AdvisoryCard
+ key={advisory.advisory_id}
+ advisory={advisory}
+ onAcknowledge={onAcknowledge}
+ />
+ ))}
+ </Box>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/EmailChannelCard/EmailChannelCard.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/EmailChannelCard/EmailChannelCard.tsx
new file mode 100644
index 00000000000..78fd6f6282d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/EmailChannelCard/EmailChannelCard.tsx
@@ -0,0 +1,74 @@
+import { t } from "ttag";
+
+import { EmailChannelEdit } from "metabase/notifications/channels/EmailChannelEdit";
+import {
+ Anchor,
+ Box,
+ Card,
+ Group,
+ Icon,
+ Stack,
+ Switch,
+ Text,
+ Title,
+} from "metabase/ui";
+import { useNotificationConfig } from "metabase-enterprise/security_center/hooks/use-notification-config";
+
+export function EmailChannelCard({ isConfigured }: { isConfigured: boolean }) {
+ const { config, updateEmailHandler, toggleSendToAllAdmins, users } =
+ useNotificationConfig();
+
+ if (!isConfigured) {
+ return (
+ <Card withBorder p="lg">
+ <Group gap="sm">
+ <Icon name="mail" />
+ <Title order={4}>{t`Email`}</Title>
+ </Group>
+ <Text c="text-secondary" mt="sm">
+ {t`Email is not configured.`}{" "}
+ <Anchor href="/admin/settings/email">{t`Set up email`}</Anchor>
+ </Text>
+ </Card>
+ );
+ }
+
+ return (
+ <Card withBorder p="lg" data-testid="email-channel-card">
+ <Group gap="sm" mb="lg">
+ <Icon name="mail" />
+ <Title order={4}>{t`Email`}</Title>
+ </Group>
+ <Stack gap="lg">
+ <Switch
+ label={t`Send to all instance admins`}
+ checked={config.email.sendToAllAdmins}
+ onChange={(e) => toggleSendToAllAdmins(e.currentTarget.checked)}
+ data-testid="send-to-admins-toggle"
+ />
+ <Box>
+ <Text size="sm" fw={500} mb="xs">
+ {config.email.sendToAllAdmins
+ ? t`Additional recipients`
+ : t`Recipients`}
+ </Text>
+ <EmailChannelEdit
+ channel={config.email.handler}
+ users={users}
+ autoFocus={false}
+ invalidRecipientText={(domains) =>
+ t`Only addresses ending in ${domains} are allowed.`
+ }
+ onChange={updateEmailHandler}
+ />
+ {!config.email.sendToAllAdmins &&
+ config.email.handler.recipients.length === 0 && (
+ <Text size="sm" c="error" mt="xs">
+ {t`At least one recipient is required.`}
+ </Text>
+ )}
+ </Box>
+ </Stack>
+ </Card>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/EmailChannelCard/EmailChannelCard.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/EmailChannelCard/EmailChannelCard.unit.spec.tsx
new file mode 100644
index 00000000000..af0eab2142f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/EmailChannelCard/EmailChannelCard.unit.spec.tsx
@@ -0,0 +1,115 @@
+import { setupRecentViewsAndSelectionsEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { createMockSettings } from "metabase-types/api/mocks";
+import { createMockSettingsState } from "metabase-types/store/mocks";
+
+import type { NotificationConfig } from "../../../hooks/use-notification-config";
+import { useNotificationConfig } from "../../../hooks/use-notification-config";
+
+import { EmailChannelCard } from "./EmailChannelCard";
+
+jest.mock("../../../hooks/use-notification-config", () => ({
+ ...jest.requireActual("../../../hooks/use-notification-config"),
+ useNotificationConfig: jest.fn(),
+}));
+
+const mockedUseNotificationConfig =
+ useNotificationConfig as any as jest.MockedFn<typeof useNotificationConfig>;
+
+const DEFAULT_CONFIG: NotificationConfig = {
+ email: {
+ sendToAllAdmins: true,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ slack: {
+ enabled: false,
+ handler: { channel_type: "channel/slack", recipients: [] },
+ },
+};
+
+function setup({ isConfigured = true, config = DEFAULT_CONFIG } = {}) {
+ const settings = createMockSettings({
+ "email-configured?": isConfigured,
+ });
+
+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);
+
+ const updateEmailHandler = jest.fn();
+ const toggleSendToAllAdmins = jest.fn();
+
+ mockedUseNotificationConfig.mockReturnValue({
+ config,
+ users: [],
+ channels: undefined,
+ updateEmailHandler,
+ toggleSendToAllAdmins,
+ updateSlackHandler: jest.fn(),
+ toggleSlack: jest.fn(),
+ save: jest.fn(),
+ resetConfig: jest.fn(),
+ });
+
+ renderWithProviders(<EmailChannelCard isConfigured={isConfigured} />, {
+ storeInitialState: { settings: createMockSettingsState(settings) },
+ });
+
+ return { updateEmailHandler, toggleSendToAllAdmins };
+}
+
+describe("EmailChannelCard", () => {
+ it("renders not-configured state with setup link", () => {
+ setup({ isConfigured: false });
+
+ expect(screen.getByText("Email is not configured.")).toBeInTheDocument();
+ expect(screen.getByText("Set up email")).toHaveAttribute(
+ "href",
+ "/admin/settings/email",
+ );
+ });
+
+ it("renders configured state with admin toggle and recipient picker", () => {
+ setup();
+
+ expect(screen.getByText("Email")).toBeInTheDocument();
+ expect(screen.getByTestId("send-to-admins-toggle")).toBeChecked();
+ expect(screen.getByText("Additional recipients")).toBeInTheDocument();
+ });
+
+ it("shows 'Recipients' label when send-to-all-admins is off", () => {
+ setup({
+ config: {
+ ...DEFAULT_CONFIG,
+ email: {
+ sendToAllAdmins: false,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ },
+ });
+
+ expect(screen.getByText("Recipients")).toBeInTheDocument();
+ });
+
+ it("shows error when send-to-all-admins is off and no recipients", () => {
+ setup({
+ config: {
+ ...DEFAULT_CONFIG,
+ email: {
+ sendToAllAdmins: false,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ },
+ });
+
+ expect(
+ screen.getByText("At least one recipient is required."),
+ ).toBeInTheDocument();
+ });
+
+ it("does not show error when send-to-all-admins is on", () => {
+ setup();
+
+ expect(
+ screen.queryByText("At least one recipient is required."),
+ ).not.toBeInTheDocument();
+ });
+});
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.tsx
new file mode 100644
index 00000000000..bf96af6ce38
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.tsx
@@ -0,0 +1,122 @@
+import { useCallback, useState } from "react";
+import { t } from "ttag";
+
+import { useSendTestNotificationMutation } from "metabase/api/security-center";
+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 { EmailChannelCard } from "./EmailChannelCard/EmailChannelCard";
+import { SlackChannelCard } from "./SlackChannelCard/SlackChannelCard";
+
+type NotificationChannelConfigModalProps = {
+ opened: boolean;
+ onClose: () => void;
+};
+
+export function NotificationChannelConfigModal({
+ opened,
+ onClose,
+}: NotificationChannelConfigModalProps) {
+ const { config, save, resetConfig } = useNotificationConfig();
+
+ const isEmailConfigured = useSetting("email-configured?");
+ const isSlackConfigured = useSetting("slack-token-valid?");
+ const [sendToast] = useToast();
+ const [isSaving, setIsSaving] = useState(false);
+ const [sendTestNotification] = useSendTestNotificationMutation();
+ const [isSendingTest, setIsSendingTest] = useState(false);
+ const isSmallScreen = useIsSmallScreen();
+
+ const handleSave = useCallback(async () => {
+ setIsSaving(true);
+ try {
+ await save();
+ sendToast({
+ message: t`Notification settings saved`,
+ toastColor: "success",
+ });
+ onClose();
+ } catch {
+ sendToast({
+ icon: "warning",
+ toastColor: "error",
+ message: t`Failed to save notification settings`,
+ });
+ } finally {
+ setIsSaving(false);
+ }
+ }, [save, sendToast, onClose]);
+
+ const handleSendTest = useCallback(async () => {
+ setIsSendingTest(true);
+ try {
+ await sendTestNotification().unwrap();
+ sendToast({
+ message: t`Test notification sent`,
+ toastColor: "success",
+ });
+ } catch {
+ sendToast({
+ icon: "warning",
+ toastColor: "error",
+ message: t`Failed to send test notification`,
+ });
+ } finally {
+ setIsSendingTest(false);
+ }
+ }, [sendTestNotification, sendToast]);
+
+ const emailHasRecipients =
+ config.email.sendToAllAdmins || config.email.handler.recipients.length > 0;
+ const canSave = emailHasRecipients || !isEmailConfigured;
+
+ return (
+ <Modal
+ opened={opened}
+ onClose={() => {
+ resetConfig();
+ onClose();
+ }}
+ title={t`Notification settings`}
+ size="lg"
+ fullScreen={isSmallScreen}
+ >
+ <Stack gap="md" mt="md">
+ <EmailChannelCard isConfigured={isEmailConfigured} />
+ <SlackChannelCard isConfigured={isSlackConfigured} />
+ <Flex justify="space-between" gap="md" mt="md">
+ <Button
+ variant="subtle"
+ leftSection={<Icon name="mail" />}
+ onClick={handleSendTest}
+ loading={isSendingTest}
+ >
+ {t`Send test notification`}
+ </Button>
+ <Group gap="md">
+ <Button
+ variant="subtle"
+ onClick={() => {
+ resetConfig();
+ onClose();
+ }}
+ >
+ {t`Cancel`}
+ </Button>
+ <Button
+ variant="filled"
+ onClick={handleSave}
+ loading={isSaving}
+ disabled={!canSave}
+ >
+ {t`Save`}
+ </Button>
+ </Group>
+ </Flex>
+ </Stack>
+ </Modal>
+ );
+}
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.tsx
new file mode 100644
index 00000000000..ff74d297a3e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsx
@@ -0,0 +1,462 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupNotificationChannelsEndpoints,
+ setupRecentViewsAndSelectionsEndpoints,
+ setupUpdateSettingsEndpoint,
+ setupUserRecipientsEndpoint,
+} from "__support__/server-mocks";
+import { findRequests } from "__support__/server-mocks/util";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockSettings, createMockUser } from "metabase-types/api/mocks";
+import {
+ createMockEmailChannelSpec,
+ createMockSlackChannelSpec,
+} from "metabase-types/api/mocks/security-center";
+import { createMockSettingsState } from "metabase-types/store/mocks";
+
+import type { NotificationConfig } from "../../hooks/use-notification-config";
+import {
+ NotificationConfigProvider,
+ useNotificationConfig,
+ useNotificationConfigState,
+} from "../../hooks/use-notification-config";
+
+import { NotificationChannelConfigModal } from "./NotificationChannelConfigModal";
+
+// ── UI behaviour tests (mocked hook) ────────────────────────────────
+
+jest.mock("../../hooks/use-notification-config", () => {
+ return {
+ ...jest.requireActual("../../hooks/use-notification-config"),
+ useNotificationConfig: jest.fn(),
+ };
+});
+
+const mockedUseNotificationConfig =
+ useNotificationConfig as any as jest.MockedFn<typeof useNotificationConfig>;
+
+const DEFAULT_CONFIG: NotificationConfig = {
+ email: {
+ sendToAllAdmins: true,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ slack: {
+ enabled: false,
+ handler: { channel_type: "channel/slack", recipients: [] },
+ },
+};
+
+function setupMocked({
+ config = DEFAULT_CONFIG,
+ emailConfigured = true,
+ slackConfigured = false,
+ onClose = jest.fn(),
+ save = jest.fn(),
+} = {}) {
+ const settings = createMockSettings({
+ "email-configured?": emailConfigured,
+ "slack-token-valid?": slackConfigured,
+ });
+
+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);
+
+ const channels = {
+ email: createMockEmailChannelSpec({ configured: emailConfigured }),
+ slack: createMockSlackChannelSpec({ configured: slackConfigured }),
+ };
+
+ const resetConfig = jest.fn();
+
+ mockedUseNotificationConfig.mockImplementation(() => ({
+ config,
+ users: [],
+ channels,
+ updateEmailHandler: jest.fn(),
+ toggleSendToAllAdmins: jest.fn(),
+ updateSlackHandler: jest.fn(),
+ toggleSlack: jest.fn(),
+ save,
+ resetConfig,
+ }));
+
+ renderWithProviders(
+ <NotificationChannelConfigModal opened onClose={onClose} />,
+ {
+ storeInitialState: { settings: createMockSettingsState(settings) },
+ },
+ );
+
+ return { onClose };
+}
+
+describe("NotificationChannelConfigModal", () => {
+ it("renders email and slack sections", () => {
+ setupMocked();
+
+ expect(screen.getByText("Email")).toBeInTheDocument();
+ expect(screen.getByText("Slack")).toBeInTheDocument();
+ });
+
+ it("shows 'Send to all instance admins' toggle checked by default", () => {
+ setupMocked();
+
+ const toggle = screen.getByTestId("send-to-admins-toggle");
+ expect(toggle).toBeChecked();
+ });
+
+ it("shows recipient picker with 'Additional recipients' label when 'Send to all admins' is checked", () => {
+ setupMocked();
+
+ expect(screen.getByText("Additional recipients")).toBeInTheDocument();
+ expect(
+ screen.queryByText("At least one recipient is required."),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows recipient picker with 'Recipients' label and error when 'Send to all admins' is unchecked and no recipients", () => {
+ setupMocked({
+ config: {
+ email: {
+ sendToAllAdmins: false,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ slack: {
+ enabled: false,
+ handler: { channel_type: "channel/slack", recipients: [] },
+ },
+ },
+ });
+
+ expect(screen.getByText("Recipients")).toBeInTheDocument();
+ expect(
+ screen.getByText("At least one recipient is required."),
+ ).toBeInTheDocument();
+ });
+
+ it("shows email not configured state with setup link", () => {
+ setupMocked({ emailConfigured: false });
+
+ expect(screen.getByText("Email is not configured.")).toBeInTheDocument();
+ expect(screen.getByText("Set up email")).toHaveAttribute(
+ "href",
+ "/admin/settings/email",
+ );
+ });
+
+ it("shows slack not configured state with setup link", () => {
+ setupMocked({ slackConfigured: false });
+
+ expect(screen.getByText("Slack is not configured.")).toBeInTheDocument();
+ expect(screen.getByText("Set up Slack")).toHaveAttribute(
+ "href",
+ "/admin/settings/slack",
+ );
+ });
+
+ it("shows slack channel picker when slack is configured and enabled", () => {
+ setupMocked({
+ slackConfigured: true,
+ config: {
+ email: {
+ sendToAllAdmins: true,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ slack: {
+ enabled: true,
+ handler: { channel_type: "channel/slack", recipients: [] },
+ },
+ },
+ });
+
+ expect(
+ screen.getByPlaceholderText("Pick a user or channel..."),
+ ).toBeInTheDocument();
+ });
+
+ it("hides slack channel picker when slack toggle is off", () => {
+ setupMocked({
+ slackConfigured: true,
+ config: {
+ email: {
+ sendToAllAdmins: true,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ slack: {
+ enabled: false,
+ handler: { channel_type: "channel/slack", recipients: [] },
+ },
+ },
+ });
+
+ expect(
+ screen.queryByPlaceholderText("Pick a user or channel..."),
+ ).not.toBeInTheDocument();
+ });
+
+ it("disables save when email has no recipients and admins toggle is off", () => {
+ setupMocked({
+ config: {
+ email: {
+ sendToAllAdmins: false,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ slack: {
+ enabled: false,
+ handler: { channel_type: "channel/slack", recipients: [] },
+ },
+ },
+ });
+
+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
+ });
+
+ it("enables save when 'Send to all admins' is on", () => {
+ setupMocked();
+
+ expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();
+ });
+
+ it("calls save and onClose on successful save", async () => {
+ const save = jest.fn().mockResolvedValue(undefined);
+ const { onClose } = setupMocked({ save });
+
+ await userEvent.click(screen.getByText("Save"));
+
+ expect(save).toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it("calls onClose when cancel is clicked", async () => {
+ const { onClose } = setupMocked();
+
+ await userEvent.click(screen.getByText("Cancel"));
+
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it("does not render test buttons", () => {
+ setupMocked({ slackConfigured: true });
+
+ expect(screen.queryByText("Send test email")).not.toBeInTheDocument();
+ expect(screen.queryByText("Send test message")).not.toBeInTheDocument();
+ });
+});
+
+// ── Save‐payload tests (real hook + context) ────────────────────────
+
+function ModalWithProvider({ onClose }: { onClose: () => void }) {
+ const notificationConfig = useNotificationConfigState();
+ return (
+ <NotificationConfigProvider value={notificationConfig}>
+ <NotificationChannelConfigModal opened onClose={onClose} />
+ </NotificationConfigProvider>
+ );
+}
+
+const ADMIN_GROUP_RECIPIENT = {
+ type: "notification-recipient/group",
+ permissions_group_id: 2,
+};
+
+function setupWithRealHook({
+ emailConfigured = true,
+ slackConfigured = true,
+ slackChannel = null as string | null,
+ emailRecipients = null as any[] | null,
+} = {}) {
+ // Restore the real implementation for save-payload tests
+ mockedUseNotificationConfig.mockImplementation(
+ jest.requireActual("../../hooks/use-notification-config")
+ .useNotificationConfig,
+ );
+
+ const settings = createMockSettings({
+ "email-configured?": emailConfigured,
+ "slack-token-valid?": slackConfigured,
+ "security-center-slack-channel": slackChannel,
+ "security-center-email-recipients": emailRecipients,
+ });
+
+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);
+ setupUpdateSettingsEndpoint();
+ setupUserRecipientsEndpoint({
+ users: [
+ createMockUser({ id: 1, common_name: "Alice" }),
+ createMockUser({ id: 2, common_name: "Bob" }),
+ ],
+ });
+ setupNotificationChannelsEndpoints({
+ email: createMockEmailChannelSpec({ configured: emailConfigured }),
+ slack: createMockSlackChannelSpec({
+ configured: slackConfigured,
+ fields: [
+ {
+ name: "channel",
+ displayName: "Post to",
+ options: ["#general", "#security", "#alerts"],
+ required: true,
+ },
+ ],
+ }),
+ });
+ fetchMock.post("path:/api/ee/security-center/test-notification", {
+ success: true,
+ });
+
+ const onClose = jest.fn();
+
+ renderWithProviders(<ModalWithProvider onClose={onClose} />, {
+ storeInitialState: { settings: createMockSettingsState(settings) },
+ });
+
+ return { onClose };
+}
+
+async function getSavedSettings() {
+ const puts = await findRequests("PUT");
+ return puts.find((r) => r.url.includes("/api/setting"))?.body;
+}
+
+describe("NotificationChannelConfigModal — save payload", () => {
+ describe("slack channel", () => {
+ it("saves the selected slack channel", async () => {
+ setupWithRealHook({ slackConfigured: true });
+
+ await userEvent.click(screen.getByTestId("slack-toggle"));
+
+ const channelInput = screen.getByPlaceholderText(
+ "Pick a user or channel...",
+ );
+ await userEvent.clear(channelInput);
+ await userEvent.type(channelInput, "#security");
+
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(async () => {
+ const body = await getSavedSettings();
+ expect(body).toEqual(
+ expect.objectContaining({
+ "security-center-slack-channel": "#security",
+ }),
+ );
+ });
+ });
+
+ it("preserves an existing slack channel on save when unchanged", async () => {
+ setupWithRealHook({ slackConfigured: true, slackChannel: "#general" });
+
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(async () => {
+ const body = await getSavedSettings();
+ expect(body).toEqual(
+ expect.objectContaining({
+ "security-center-slack-channel": "#general",
+ }),
+ );
+ });
+ });
+
+ it("sends null for slack channel when slack is disabled", async () => {
+ setupWithRealHook({ slackConfigured: true, slackChannel: "#general" });
+
+ await userEvent.click(screen.getByTestId("slack-toggle"));
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(async () => {
+ const body = await getSavedSettings();
+ expect(body).toEqual(
+ expect.objectContaining({
+ "security-center-slack-channel": null,
+ }),
+ );
+ });
+ });
+ });
+
+ describe("email recipients", () => {
+ it("includes admin group recipient when send-to-all-admins is on (default)", async () => {
+ setupWithRealHook({ emailConfigured: true });
+
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(async () => {
+ const body = await getSavedSettings();
+ expect(body["security-center-email-recipients"]).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(ADMIN_GROUP_RECIPIENT),
+ ]),
+ );
+ });
+ });
+
+ it("omits admin group recipient when send-to-all-admins is toggled off", async () => {
+ setupWithRealHook({ emailConfigured: true });
+
+ 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: "Save" }));
+
+ await waitFor(async () => {
+ const body = await getSavedSettings();
+ const recipients = body["security-center-email-recipients"];
+ expect(recipients).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(ADMIN_GROUP_RECIPIENT),
+ ]),
+ );
+ });
+ });
+
+ it("preserves existing extra recipients alongside admin group", async () => {
+ const existingRecipients = [
+ ADMIN_GROUP_RECIPIENT,
+ {
+ type: "notification-recipient/raw-value",
+ details: { value: "[email protected]" },
+ },
+ ];
+ setupWithRealHook({
+ emailConfigured: true,
+ emailRecipients: existingRecipients,
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(async () => {
+ const body = await getSavedSettings();
+ const recipients = body["security-center-email-recipients"];
+ expect(recipients).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining(ADMIN_GROUP_RECIPIENT),
+ expect.objectContaining({
+ type: "notification-recipient/raw-value",
+ details: { value: "[email protected]" },
+ }),
+ ]),
+ );
+ });
+ });
+
+ it("saves both email and slack settings in a single request", async () => {
+ setupWithRealHook({ slackConfigured: true, slackChannel: "#general" });
+
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(async () => {
+ const body = await getSavedSettings();
+ expect(body).toEqual(
+ expect.objectContaining({
+ "security-center-email-recipients": expect.any(Array),
+ "security-center-slack-channel": "#general",
+ }),
+ );
+ });
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/SlackChannelCard/SlackChannelCard.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/SlackChannelCard/SlackChannelCard.tsx
new file mode 100644
index 00000000000..7ffab2bd57c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/SlackChannelCard/SlackChannelCard.tsx
@@ -0,0 +1,63 @@
+import { t } from "ttag";
+
+import { SlackChannelFieldNew } from "metabase/notifications/channels/SlackChannelFieldNew";
+import {
+ Anchor,
+ Box,
+ Card,
+ Flex,
+ Group,
+ Icon,
+ Switch,
+ Text,
+ Title,
+} from "metabase/ui";
+import { useNotificationConfig } from "metabase-enterprise/security_center/hooks/use-notification-config";
+
+export function SlackChannelCard({ isConfigured }: { isConfigured: boolean }) {
+ const { config, updateSlackHandler, toggleSlack, channels } =
+ useNotificationConfig();
+
+ if (!isConfigured) {
+ return (
+ <Card withBorder p="lg">
+ <Group gap="sm">
+ <Icon name="slack" />
+ <Title order={4}>{t`Slack`}</Title>
+ </Group>
+ <Text c="text-secondary" mt="sm">
+ {t`Slack is not configured.`}{" "}
+ <Anchor href="/admin/settings/slack">{t`Set up Slack`}</Anchor>
+ </Text>
+ </Card>
+ );
+ }
+
+ return (
+ <Card withBorder p="lg" data-testid="slack-channel-card">
+ <Flex justify="space-between" align="center" mb="lg">
+ <Group gap="sm">
+ <Icon name="slack" />
+ <Title order={4}>{t`Slack`}</Title>
+ </Group>
+ <Switch
+ checked={config.slack.enabled}
+ onChange={(e) => toggleSlack(e.currentTarget.checked)}
+ data-testid="slack-toggle"
+ />
+ </Flex>
+ {config.slack.enabled && channels?.slack && (
+ <Box>
+ <Text size="sm" fw={500} mb="xs">
+ {t`Channel`}
+ </Text>
+ <SlackChannelFieldNew
+ channel={config.slack.handler}
+ channelSpec={channels.slack}
+ onChange={updateSlackHandler}
+ />
+ </Box>
+ )}
+ </Card>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/SlackChannelCard/SlackChannelCard.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/SlackChannelCard/SlackChannelCard.unit.spec.tsx
new file mode 100644
index 00000000000..db2c5ce23eb
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/SlackChannelCard/SlackChannelCard.unit.spec.tsx
@@ -0,0 +1,97 @@
+import { renderWithProviders, screen } from "__support__/ui";
+import {
+ createMockEmailChannelSpec,
+ createMockSlackChannelSpec,
+} from "metabase-types/api/mocks/security-center";
+
+import type { NotificationConfig } from "../../../hooks/use-notification-config";
+import { useNotificationConfig } from "../../../hooks/use-notification-config";
+
+import { SlackChannelCard } from "./SlackChannelCard";
+
+jest.mock("../../../hooks/use-notification-config", () => ({
+ ...jest.requireActual("../../../hooks/use-notification-config"),
+ useNotificationConfig: jest.fn(),
+}));
+
+const mockedUseNotificationConfig =
+ useNotificationConfig as any as jest.MockedFn<typeof useNotificationConfig>;
+
+const DEFAULT_CONFIG: NotificationConfig = {
+ email: {
+ sendToAllAdmins: true,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ slack: {
+ enabled: false,
+ handler: { channel_type: "channel/slack", recipients: [] },
+ },
+};
+
+function setup({
+ isConfigured = true,
+ config = DEFAULT_CONFIG,
+ slackEnabled,
+}: {
+ isConfigured?: boolean;
+ config?: NotificationConfig;
+ slackEnabled?: boolean;
+} = {}) {
+ const channels = {
+ email: createMockEmailChannelSpec(),
+ slack: createMockSlackChannelSpec({ configured: isConfigured }),
+ };
+
+ const updateSlackHandler = jest.fn();
+ const toggleSlack = jest.fn();
+
+ mockedUseNotificationConfig.mockReturnValue({
+ config: {
+ ...config,
+ slack: { ...config.slack, enabled: slackEnabled ?? config.slack.enabled },
+ },
+ users: [],
+ channels,
+ updateEmailHandler: jest.fn(),
+ toggleSendToAllAdmins: jest.fn(),
+ updateSlackHandler,
+ toggleSlack,
+ save: jest.fn(),
+ resetConfig: jest.fn(),
+ });
+
+ renderWithProviders(<SlackChannelCard isConfigured={isConfigured} />);
+
+ return { updateSlackHandler, toggleSlack };
+}
+
+describe("SlackChannelCard", () => {
+ it("renders not-configured state with setup link", () => {
+ setup({ isConfigured: false });
+
+ expect(screen.getByText("Slack is not configured.")).toBeInTheDocument();
+ expect(screen.getByText("Set up Slack")).toHaveAttribute(
+ "href",
+ "/admin/settings/slack",
+ );
+ });
+
+ it("renders configured state with toggle", () => {
+ setup();
+
+ expect(screen.getByText("Slack")).toBeInTheDocument();
+ expect(screen.getByTestId("slack-toggle")).toBeInTheDocument();
+ });
+
+ it("does not show channel picker when slack is disabled", () => {
+ setup({ slackEnabled: false });
+
+ expect(screen.queryByText("Channel")).not.toBeInTheDocument();
+ });
+
+ it("shows channel picker when slack is enabled", () => {
+ setup({ slackEnabled: true });
+
+ expect(screen.getByText("Channel")).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.tsx
new file mode 100644
index 00000000000..14dfea8f4a6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.tsx
@@ -0,0 +1,106 @@
+import { useCallback, useState } from "react";
+import { Link } from "react-router";
+import { jt, t } from "ttag";
+
+import {
+ useGetChannelInfoQuery,
+ useListSecurityAdvisoriesQuery,
+} from "metabase/api";
+import { Banner } from "metabase/common/components/Banner";
+import { useSetting } from "metabase/common/hooks";
+import { getPlan } from "metabase/common/utils/plan";
+import { Anchor, Text } from "metabase/ui";
+
+import { isAffected } from "../../utils";
+
+const DISMISSED_KEY = "security-center-banner-dismissed";
+
+function useDismissed() {
+ const [dismissed, setDismissedState] = useState(
+ () => localStorage.getItem(DISMISSED_KEY) === "true",
+ );
+
+ const dismiss = useCallback(() => {
+ localStorage.setItem(DISMISSED_KEY, "true");
+ setDismissedState(true);
+ }, []);
+
+ return { dismissed, dismiss };
+}
+
+export function SecurityCenterBanner() {
+ const tokenFeatures = useSetting("token-features");
+ const plan = getPlan(tokenFeatures);
+ const { data: channelInfo, isLoading: isChannelInfoLoading } =
+ useGetChannelInfoQuery();
+ const { data: advisoriesResponse, isLoading: isAdvisoriesLoading } =
+ useListSecurityAdvisoriesQuery();
+ const { dismissed, dismiss } = useDismissed();
+
+ if (plan !== "pro-self-hosted") {
+ return null;
+ }
+
+ if (isChannelInfoLoading || isAdvisoriesLoading) {
+ return null;
+ }
+
+ const hasEmail = !!channelInfo?.channels?.email?.configured;
+ const hasSlack = !!channelInfo?.channels?.slack?.configured;
+
+ if (hasEmail || hasSlack) {
+ return null;
+ }
+
+ const advisories = advisoriesResponse?.advisories ?? [];
+ const hasActiveAdvisory = advisories.some(isAffected);
+
+ if (dismissed && !hasActiveAdvisory) {
+ return null;
+ }
+
+ const settingsLink = (
+ <Anchor
+ key="link"
+ component={Link}
+ fw="bold"
+ to="/admin/security-center"
+ c="inherit"
+ td="underline"
+ >
+ {t`Set up notifications`}
+ </Anchor>
+ );
+
+ if (hasActiveAdvisory) {
+ return (
+ <Banner
+ contentGroupProps={{ wrap: "nowrap" }}
+ icon="warning_round_filled"
+ bg="error"
+ body={
+ <Text lh="inherit">
+ {jt`Active security advisories require attention, but no notification channels are configured. ${settingsLink}`}
+ </Text>
+ }
+ py="md"
+ />
+ );
+ }
+
+ return (
+ <Banner
+ contentGroupProps={{ wrap: "nowrap" }}
+ icon="warning_round_filled"
+ bg="warning"
+ body={
+ <Text lh="inherit" c="text-primary">
+ {jt`No notification channels are configured for security alerts. ${settingsLink}`}
+ </Text>
+ }
+ closable
+ onClose={dismiss}
+ py="md"
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.unit.spec.tsx
new file mode 100644
index 00000000000..318cee97739
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterBanner/SecurityCenterBanner.unit.spec.tsx
@@ -0,0 +1,151 @@
+import fetchMock from "fetch-mock";
+import { Route } from "react-router";
+
+import { setupNotificationChannelsEndpoints } from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen } from "__support__/ui";
+import type { Advisory } from "metabase-types/api";
+import {
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { createAdvisory } from "metabase-types/api/mocks/security-center";
+import { createMockState } from "metabase-types/store/mocks";
+
+import { SecurityCenterBanner } from "./SecurityCenterBanner";
+
+const DISMISSED_KEY = "security-center-banner-dismissed";
+
+interface SetupOpts {
+ isProSelfHosted?: boolean;
+ emailConfigured?: boolean;
+ slackConfigured?: boolean;
+ advisories?: Advisory[];
+}
+
+function setup({
+ isProSelfHosted = true,
+ emailConfigured = false,
+ slackConfigured = false,
+ advisories = [],
+}: SetupOpts = {}) {
+ const tokenFeatures = createMockTokenFeatures(
+ isProSelfHosted
+ ? { advanced_permissions: true, hosting: false }
+ : { hosting: false },
+ );
+
+ setupNotificationChannelsEndpoints({
+ email: { configured: emailConfigured } as any,
+ slack: { configured: slackConfigured } as any,
+ });
+
+ fetchMock.get("path:/api/ee/security-center", {
+ last_checked_at: null,
+ advisories,
+ });
+
+ const state = createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ settings: mockSettings({
+ "token-features": tokenFeatures,
+ }),
+ });
+
+ renderWithProviders(<Route path="*" component={SecurityCenterBanner} />, {
+ initialRoute: "/",
+ storeInitialState: state,
+ withRouter: true,
+ });
+}
+
+describe("SecurityCenterBanner", () => {
+ afterEach(() => {
+ localStorage.removeItem(DISMISSED_KEY);
+ });
+
+ it("renders warning banner when no channels are configured", async () => {
+ setup();
+
+ expect(
+ await screen.findByText(/No notification channels are configured/),
+ ).toBeInTheDocument();
+ });
+
+ it("does not render when email is configured", async () => {
+ setup({ emailConfigured: true });
+
+ // Wait for API responses to settle, then assert no banner
+ await screen.findByText(() => false).catch(() => {});
+ expect(screen.queryByTestId("app-banner")).not.toBeInTheDocument();
+ });
+
+ it("does not render when slack is configured", async () => {
+ setup({ slackConfigured: true });
+
+ await screen.findByText(() => false).catch(() => {});
+ expect(screen.queryByTestId("app-banner")).not.toBeInTheDocument();
+ });
+
+ it("does not render for non-pro-self-hosted plans", async () => {
+ setup({ isProSelfHosted: false });
+
+ await screen.findByText(() => false).catch(() => {});
+ expect(screen.queryByTestId("app-banner")).not.toBeInTheDocument();
+ });
+
+ it("renders error banner with active advisories", async () => {
+ setup({
+ advisories: [createAdvisory({ match_status: "active" })],
+ });
+
+ expect(
+ await screen.findByText(/Active security advisories require attention/),
+ ).toBeInTheDocument();
+ });
+
+ it("is dismissible when there are no active advisories", async () => {
+ setup();
+
+ await screen.findByTestId("app-banner");
+ expect(screen.getByLabelText("close icon")).toBeInTheDocument();
+ });
+
+ it("is not dismissible when there are active advisories", async () => {
+ setup({
+ advisories: [createAdvisory({ match_status: "active" })],
+ });
+
+ // Wait for the error banner text to confirm advisory data has loaded
+ await screen.findByText(/Active security advisories require attention/);
+ expect(screen.queryByLabelText("close icon")).not.toBeInTheDocument();
+ });
+
+ it("stays hidden after dismissal when there are no active advisories", async () => {
+ localStorage.setItem(DISMISSED_KEY, "true");
+
+ setup();
+
+ await screen.findByText(() => false).catch(() => {});
+ expect(screen.queryByTestId("app-banner")).not.toBeInTheDocument();
+ });
+
+ it("shows banner despite dismissal when there are active advisories", async () => {
+ localStorage.setItem(DISMISSED_KEY, "true");
+
+ setup({
+ advisories: [createAdvisory({ match_status: "active" })],
+ });
+
+ expect(
+ await screen.findByText(/Active security advisories require attention/),
+ ).toBeInTheDocument();
+ });
+
+ it("includes a link to security center settings", async () => {
+ setup();
+
+ const link = await screen.findByText("Set up notifications");
+ expect(link).toHaveAttribute("href", "/admin/security-center");
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterNavItem/SecurityCenterMobileNavItem.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterNavItem/SecurityCenterMobileNavItem.tsx
new file mode 100644
index 00000000000..1655cd81585
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterNavItem/SecurityCenterMobileNavItem.tsx
@@ -0,0 +1,43 @@
+import { t } from "ttag";
+
+import { useListSecurityAdvisoriesQuery } from "metabase/api";
+import { AdminNavLink } from "metabase/nav/components/AdminNavbar/AdminNavItem.styled";
+import { Box, Flex } from "metabase/ui";
+
+import { isAffected } from "../../utils";
+
+const PATH = "/admin/security-center";
+
+interface SecurityCenterMobileNavItemProps {
+ currentPath: string;
+}
+
+export function SecurityCenterMobileNavItem({
+ currentPath,
+}: SecurityCenterMobileNavItemProps) {
+ const { data: advisoriesResponse } = useListSecurityAdvisoriesQuery();
+ const advisories = advisoriesResponse?.advisories ?? [];
+ const hasActive = advisories.some(isAffected);
+
+ return (
+ <AdminNavLink
+ to={PATH}
+ isSelected={currentPath.startsWith(PATH)}
+ isInMobileNav
+ >
+ <Flex align="center" gap="0.375rem">
+ {t`Security`}
+ {hasActive && (
+ <Box
+ w={8}
+ h={8}
+ miw={8}
+ bg="error"
+ style={{ borderRadius: "50%", flexShrink: 0 }}
+ data-testid="security-center-badge"
+ />
+ )}
+ </Flex>
+ </AdminNavLink>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterNavItem/SecurityCenterNavItem.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterNavItem/SecurityCenterNavItem.tsx
new file mode 100644
index 00000000000..63be7835296
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterNavItem/SecurityCenterNavItem.tsx
@@ -0,0 +1,44 @@
+import { t } from "ttag";
+
+import { useListSecurityAdvisoriesQuery } from "metabase/api";
+import {
+ AdminNavLink,
+ AdminNavListItem,
+} from "metabase/nav/components/AdminNavbar/AdminNavItem.styled";
+import { Box, Flex } from "metabase/ui";
+
+import { isAffected } from "../../utils";
+
+const PATH = "/admin/security-center";
+
+interface SecurityCenterNavItemProps {
+ currentPath: string;
+}
+
+export function SecurityCenterNavItem({
+ currentPath,
+}: SecurityCenterNavItemProps) {
+ const { data: advisoriesResponse } = useListSecurityAdvisoriesQuery();
+ const advisories = advisoriesResponse?.advisories ?? [];
+ const hasActive = advisories.some(isAffected);
+
+ return (
+ <AdminNavListItem path={PATH} currentPath={currentPath}>
+ <AdminNavLink to={PATH} isSelected={currentPath.startsWith(PATH)}>
+ <Flex align="center" gap="0.375rem">
+ {t`Security`}
+ {hasActive && (
+ <Box
+ w={8}
+ h={8}
+ miw={8}
+ bg="error"
+ style={{ borderRadius: "50%", flexShrink: 0 }}
+ data-testid="security-center-badge"
+ />
+ )}
+ </Flex>
+ </AdminNavLink>
+ </AdminNavListItem>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.module.css b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.module.css
new file mode 100644
index 00000000000..a3da8d4050e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.module.css
@@ -0,0 +1,53 @@
+.root {
+ display: flex;
+ flex-direction: column;
+ height: calc(100vh - 65px);
+ min-height: 0;
+ padding: 2rem 3rem 0;
+}
+
+.header {
+ flex-shrink: 0;
+ padding-bottom: var(--mantine-spacing-lg);
+}
+
+@media screen and (max-width: 64em) {
+ .root {
+ padding-inline: 2rem;
+ }
+}
+
+@media screen and (max-width: 40em) {
+ .root {
+ padding-inline: 1rem;
+ }
+
+ .content {
+ flex-direction: column;
+ }
+}
+
+.content {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+
+ .filterBar {
+ flex: 0;
+ }
+
+ .list {
+ flex: 1;
+ overflow: auto;
+ }
+
+ .emptyState {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ max-width: 400px;
+ margin-inline: auto;
+ text-align: center;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.tsx
new file mode 100644
index 00000000000..c7fe93d70d8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.tsx
@@ -0,0 +1,201 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { t } from "ttag";
+
+import { useSyncSecurityAdvisoriesMutation } from "metabase/api";
+import { EmptyState } from "metabase/common/components/EmptyState";
+import { useSetting, useToast } from "metabase/common/hooks";
+import { useIsSmallScreen } from "metabase/common/hooks/use-is-small-screen";
+import {
+ Box,
+ Button,
+ Group,
+ Icon,
+ Loader,
+ Stack,
+ Text,
+ Title,
+} from "metabase/ui";
+
+import { trackSecurityCenterPageViewed } from "../../analytics";
+import {
+ NotificationConfigProvider,
+ useNotificationConfigState,
+} from "../../hooks/use-notification-config";
+import { useSecurityAdvisories } from "../../hooks/use-security-advisories";
+import type { AdvisoryFilter } from "../../types";
+import { filterAdvisories, getTargetUpgradeVersion } from "../../utils";
+import { AdvisoryFilterBar } from "../AdvisoryFilterBar/AdvisoryFilterBar";
+import { AdvisoryList } from "../AdvisoryList/AdvisoryList";
+import { NotificationChannelConfigModal } from "../NotificationChannelConfigModal/NotificationChannelConfigModal";
+import { UpgradeBanner } from "../UpgradeBanner/UpgradeBanner";
+
+import S from "./SecurityCenterPage.module.css";
+
+const DEFAULT_FILTER: AdvisoryFilter = {
+ severity: "all",
+ status: "all",
+ showAcknowledged: false,
+};
+
+const MAX_POLL_COUNT = 30;
+
+export function SecurityCenterPage() {
+ const [isPolling, setIsPolling] = useState(false);
+ const {
+ data: advisories,
+ lastCheckedAt,
+ isError,
+ acknowledgeAdvisory,
+ } = useSecurityAdvisories(isPolling);
+ const [syncAdvisories, { isLoading: isSyncing }] =
+ useSyncSecurityAdvisoriesMutation();
+ const [filter, setFilter] = useState<AdvisoryFilter>(DEFAULT_FILTER);
+ const [settingsOpen, setSettingsOpen] = useState(false);
+ const notificationConfig = useNotificationConfigState();
+ const version = useSetting("version");
+ const [sendToast] = useToast();
+ const isSmallScreen = useIsSmallScreen();
+
+ const lastCheckedAtBeforeSync = useRef<string | null>(null);
+ const pollCountRef = useRef(0);
+
+ const handleSync = useCallback(async () => {
+ lastCheckedAtBeforeSync.current = lastCheckedAt;
+ pollCountRef.current = 0;
+
+ try {
+ await syncAdvisories().unwrap();
+ sendToast({
+ icon: "sync",
+ message: t`Checking for security advisories…`,
+ });
+ setIsPolling(true);
+ } catch {
+ sendToast({
+ icon: "warning_triangle_filled",
+ iconColor: "warning",
+ message: t`Failed to check for security advisories`,
+ });
+ }
+ }, [lastCheckedAt, syncAdvisories, sendToast]);
+
+ useEffect(() => {
+ if (!isPolling) {
+ return;
+ }
+
+ pollCountRef.current += 1;
+
+ const syncCompleted =
+ lastCheckedAt !== null &&
+ lastCheckedAt !== lastCheckedAtBeforeSync.current;
+
+ if (syncCompleted) {
+ setIsPolling(false);
+ sendToast({
+ icon: "check_filled",
+ message: t`Security advisories are up to date`,
+ });
+ } else if (pollCountRef.current >= MAX_POLL_COUNT) {
+ setIsPolling(false);
+ sendToast({
+ icon: "warning_triangle_filled",
+ iconColor: "warning",
+ message: t`Security advisory check is taking longer than expected. Results will appear when ready.`,
+ });
+ }
+ }, [isPolling, lastCheckedAt, sendToast]);
+
+ const isSyncInProgress = isSyncing || isPolling;
+
+ useEffect(() => {
+ trackSecurityCenterPageViewed();
+ }, []);
+
+ const currentVersion = version?.tag ?? "";
+ const targetVersion = getTargetUpgradeVersion(advisories);
+ const filtered = filterAdvisories(advisories, filter);
+
+ const nothingToShow = filtered.length === 0 || advisories.length === 0;
+
+ if (isError) {
+ return (
+ <Box className={S.root}>
+ <Stack gap="lg" className={S.header}>
+ <Title order={1}>{t`Security Center`}</Title>
+ </Stack>
+ <Stack gap="xl" className={S.content}>
+ <EmptyState
+ className={S.emptyState}
+ icon="warning_triangle_filled"
+ message={t`Something went wrong loading security advisories.`}
+ />
+ </Stack>
+ </Box>
+ );
+ }
+
+ return (
+ <NotificationConfigProvider value={notificationConfig}>
+ <Box className={S.root} data-testid="security-center-page">
+ <Stack gap="lg" className={S.header}>
+ <Group gap="sm" align="center">
+ <Title order={1}>{t`Security Center`}</Title>
+ <Box style={{ flex: 1 }} />
+ <Button
+ variant="subtle"
+ leftSection={
+ isSyncInProgress ? <Loader size="1rem" /> : <Icon name="sync" />
+ }
+ onClick={handleSync}
+ disabled={isSyncInProgress}
+ data-testid="sync-advisories"
+ >
+ {isSmallScreen ? null : t`Check now`}
+ </Button>
+ <Button
+ variant="subtle"
+ leftSection={isSmallScreen ? undefined : <Icon name="gear" />}
+ onClick={() => setSettingsOpen(true)}
+ data-testid="notification-config-toggle"
+ >
+ {isSmallScreen ? <Icon name="gear" /> : t`Notification settings`}
+ </Button>
+ </Group>
+ <Text c="text-secondary" data-testid="current-version">
+ {t`Current version`}: {currentVersion}
+ </Text>
+ {targetVersion && <UpgradeBanner targetVersion={targetVersion} />}
+ </Stack>
+ <Stack gap="xl" className={S.content}>
+ <AdvisoryFilterBar
+ className={S.filterBar}
+ filter={filter}
+ onChange={setFilter}
+ />
+ {nothingToShow ? (
+ <EmptyState
+ className={S.emptyState}
+ icon="shield_outline"
+ message={
+ advisories.length === 0
+ ? t`Your instance is up to date — no known security issues affect your configuration.`
+ : t`Nothing match your filters.`
+ }
+ />
+ ) : (
+ <AdvisoryList
+ className={S.list}
+ advisories={filtered}
+ onAcknowledge={acknowledgeAdvisory}
+ />
+ )}
+ </Stack>
+ <NotificationChannelConfigModal
+ opened={settingsOpen}
+ onClose={() => setSettingsOpen(false)}
+ />
+ </Box>
+ </NotificationConfigProvider>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.unit.spec.tsx
new file mode 100644
index 00000000000..c1890afb34e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.unit.spec.tsx
@@ -0,0 +1,300 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupRecentViewsAndSelectionsEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen, within } from "__support__/ui";
+import type { Advisory } from "metabase-types/api";
+import { createMockVersion } from "metabase-types/api/mocks";
+import { createAdvisory } from "metabase-types/api/mocks/security-center";
+import { createMockSettingsState } from "metabase-types/store/mocks";
+
+import * as notificationHook from "../../hooks/use-notification-config";
+import * as advisoriesHook from "../../hooks/use-security-advisories";
+
+import { SecurityCenterPage } from "./SecurityCenterPage";
+
+const mockAcknowledge = jest.fn();
+
+function setup(
+ advisories: Advisory[] = [],
+ { lastCheckedAt = null }: { lastCheckedAt?: string | null } = {},
+) {
+ jest.spyOn(advisoriesHook, "useSecurityAdvisories").mockReturnValue({
+ data: advisories,
+ lastCheckedAt,
+ isLoading: false,
+ isError: false,
+ acknowledgeAdvisory: mockAcknowledge,
+ });
+
+ setupRecentViewsAndSelectionsEndpoints([], ["selections"]);
+ jest.spyOn(notificationHook, "useNotificationConfigState").mockReturnValue({
+ config: {
+ email: {
+ sendToAllAdmins: true,
+ handler: { channel_type: "channel/email", recipients: [] },
+ },
+ slack: {
+ enabled: false,
+ handler: { channel_type: "channel/slack", recipients: [] },
+ },
+ },
+ users: [],
+ channels: undefined,
+ updateEmailHandler: jest.fn(),
+ toggleSendToAllAdmins: jest.fn(),
+ updateSlackHandler: jest.fn(),
+ toggleSlack: jest.fn(),
+ save: jest.fn(),
+ resetConfig: jest.fn(),
+ });
+
+ renderWithProviders(<SecurityCenterPage />, {
+ storeInitialState: {
+ settings: createMockSettingsState({
+ version: createMockVersion({ tag: "v0.59.3" }),
+ }),
+ },
+ });
+}
+
+describe("SecurityCenterPage", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ mockAcknowledge.mockClear();
+ });
+
+ it("renders the title and current version", () => {
+ setup();
+
+ expect(screen.getByText("Security Center")).toBeInTheDocument();
+ expect(screen.getByTestId("current-version")).toHaveTextContent("v0.59.3");
+ });
+
+ it("renders the empty state when there are no advisories", () => {
+ setup([]);
+
+ expect(screen.getByText(/Your instance is up to date/)).toBeInTheDocument();
+ });
+
+ it("renders advisory cards in the correct order (affected first, then by severity)", () => {
+ const advisories = [
+ createAdvisory({
+ advisory_id: "1",
+ title: "Low not affected",
+ severity: "low",
+ match_status: "not_affected",
+ }),
+ createAdvisory({
+ advisory_id: "2",
+ title: "Critical affected",
+ severity: "critical",
+ match_status: "active",
+ }),
+ createAdvisory({
+ advisory_id: "3",
+ title: "High affected",
+ severity: "high",
+ match_status: "active",
+ }),
+ ];
+
+ setup(advisories);
+
+ const cards = screen.getAllByTestId("advisory-card");
+ expect(cards).toHaveLength(3);
+
+ expect(within(cards[0]).getByText("Critical affected")).toBeInTheDocument();
+ expect(within(cards[1]).getByText("High affected")).toBeInTheDocument();
+ expect(within(cards[2]).getByText("Low not affected")).toBeInTheDocument();
+ });
+
+ it("shows affected status on cards", () => {
+ const advisories = [
+ createAdvisory({ advisory_id: "1", match_status: "active" }),
+ createAdvisory({ advisory_id: "2", match_status: "not_affected" }),
+ ];
+
+ setup(advisories);
+
+ const statuses = screen.getAllByTestId("affected-status");
+ expect(statuses[0]).toHaveTextContent("Affected");
+ expect(statuses[1]).toHaveTextContent("Not affected");
+ });
+
+ it("renders external links with correct targets", () => {
+ const advisories = [
+ createAdvisory({
+ advisory_id: "1",
+ advisory_url: "https://example.com/advisory/1",
+ }),
+ ];
+
+ setup(advisories);
+
+ const advisoryLink = screen.getByText("View advisory");
+ expect(advisoryLink).toHaveAttribute(
+ "href",
+ "https://example.com/advisory/1",
+ );
+ expect(advisoryLink).toHaveAttribute("target", "_blank");
+ });
+
+ it("calls acknowledgeAdvisory when dismiss button is clicked", async () => {
+ const advisories = [
+ createAdvisory({ advisory_id: "SA-001", acknowledged_at: null }),
+ ];
+
+ setup(advisories);
+
+ await userEvent.click(screen.getByTestId("acknowledge-button"));
+ expect(mockAcknowledge).toHaveBeenCalledWith("SA-001");
+ });
+
+ it("does not show dismiss button for already dismissed advisories", async () => {
+ const advisories = [
+ createAdvisory({
+ advisory_id: "SA-001",
+ acknowledged_at: "2026-03-01T00:00:00Z",
+ }),
+ ];
+
+ setup(advisories);
+
+ // Dismissed advisories are hidden by default — enable the checkbox first
+ await userEvent.click(screen.getByTestId("show-acknowledged-filter"));
+
+ expect(screen.queryByTestId("acknowledge-button")).not.toBeInTheDocument();
+ expect(screen.getByTestId("acknowledged-badge")).toHaveTextContent(
+ "Dismissed",
+ );
+ });
+
+ it("hides dismissed advisories by default", () => {
+ const advisories = [
+ createAdvisory({
+ advisory_id: "1",
+ title: "Visible",
+ acknowledged_at: null,
+ }),
+ createAdvisory({
+ advisory_id: "2",
+ title: "Hidden",
+ acknowledged_at: "2026-03-01T00:00:00Z",
+ }),
+ ];
+
+ setup(advisories);
+
+ expect(screen.getByText("Visible")).toBeInTheDocument();
+ expect(screen.queryByText("Hidden")).not.toBeInTheDocument();
+ });
+
+ it("renders the filter bar", () => {
+ setup([]);
+
+ expect(screen.getByTestId("advisory-filter-bar")).toBeInTheDocument();
+ });
+
+ describe("upgrade banner", () => {
+ it("shows the upgrade banner when there are active advisories", () => {
+ const advisories = [
+ createAdvisory({
+ advisory_id: "1",
+ match_status: "active",
+ affected_versions: [{ min: "0.58.0", fixed: "0.59.4" }],
+ }),
+ ];
+
+ setup(advisories);
+
+ const banner = screen.getByTestId("upgrade-banner");
+ expect(banner).toBeInTheDocument();
+ expect(banner).toHaveTextContent("0.59.4");
+ expect(banner).toHaveTextContent("A security update is available");
+ });
+
+ it("does not show the upgrade banner when there are no active advisories", () => {
+ const advisories = [
+ createAdvisory({
+ advisory_id: "1",
+ match_status: "not_affected",
+ }),
+ ];
+
+ setup(advisories);
+
+ expect(screen.queryByTestId("upgrade-banner")).not.toBeInTheDocument();
+ });
+
+ it("shows the highest fixed version across multiple active advisories", () => {
+ const advisories = [
+ createAdvisory({
+ advisory_id: "1",
+ match_status: "active",
+ affected_versions: [{ min: "0.58.0", fixed: "0.59.2" }],
+ }),
+ createAdvisory({
+ advisory_id: "2",
+ match_status: "active",
+ affected_versions: [{ min: "0.58.0", fixed: "0.59.5" }],
+ }),
+ ];
+
+ setup(advisories);
+
+ const banner = screen.getByTestId("upgrade-banner");
+ expect(banner).toHaveTextContent("0.59.5");
+ });
+
+ it("includes a link to upgrade instructions", () => {
+ const advisories = [
+ createAdvisory({
+ advisory_id: "1",
+ match_status: "active",
+ affected_versions: [{ min: "0.58.0", fixed: "0.59.4" }],
+ }),
+ ];
+
+ setup(advisories);
+
+ const link = screen.getByText("View upgrade instructions");
+ expect(link).toHaveAttribute(
+ "href",
+ "https://www.metabase.com/docs/latest/installation-and-operation/upgrading-metabase",
+ );
+ expect(link).toHaveAttribute("target", "_blank");
+ });
+
+ it("does not show the upgrade banner when there are no advisories", () => {
+ setup([]);
+
+ expect(screen.queryByTestId("upgrade-banner")).not.toBeInTheDocument();
+ });
+ });
+
+ describe("sync polling", () => {
+ it("disables the sync button while syncing", async () => {
+ fetchMock.post("path:/api/ee/security-center/sync", 200);
+ setup();
+
+ await userEvent.click(screen.getByTestId("sync-advisories"));
+
+ expect(screen.getByTestId("sync-advisories")).toBeDisabled();
+ });
+
+ it("passes isPolling to useSecurityAdvisories after sync is triggered", async () => {
+ fetchMock.post("path:/api/ee/security-center/sync", 200);
+ const spy = jest.spyOn(advisoriesHook, "useSecurityAdvisories");
+ setup();
+
+ // Before sync, the hook should be called without polling
+ expect(spy).toHaveBeenCalledWith(false);
+
+ await userEvent.click(screen.getByTestId("sync-advisories"));
+
+ // After sync, the hook should be called with polling enabled
+ expect(spy).toHaveBeenCalledWith(true);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/UpgradeBanner/UpgradeBanner.module.css b/enterprise/frontend/src/metabase-enterprise/security_center/components/UpgradeBanner/UpgradeBanner.module.css
new file mode 100644
index 00000000000..3c91240139a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/UpgradeBanner/UpgradeBanner.module.css
@@ -0,0 +1,20 @@
+.root {
+ padding: var(--mantine-spacing-md) var(--mantine-spacing-lg);
+ background-color: var(--mb-color-background-warning);
+ border-radius: var(--mantine-radius-md);
+ border: 1px solid var(--mb-color-warning);
+}
+
+.icon {
+ flex-shrink: 0;
+ color: var(--mb-color-warning);
+}
+
+.text {
+ flex: 1;
+}
+
+.link {
+ flex-shrink: 0;
+ white-space: nowrap;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/UpgradeBanner/UpgradeBanner.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/UpgradeBanner/UpgradeBanner.tsx
new file mode 100644
index 00000000000..45580f21cbc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/UpgradeBanner/UpgradeBanner.tsx
@@ -0,0 +1,46 @@
+import { c, t } from "ttag";
+
+import { ExternalLink } from "metabase/common/components/ExternalLink";
+import { useIsSmallScreen } from "metabase/common/hooks/use-is-small-screen";
+import { Anchor, Flex, Icon, Text } from "metabase/ui";
+
+import S from "./UpgradeBanner.module.css";
+
+const UPGRADE_DOCS_URL =
+ // eslint-disable-next-line metabase/no-unconditional-metabase-links-render -- This component only renders inside the admin-only Security Center page.
+ "https://www.metabase.com/docs/latest/installation-and-operation/upgrading-metabase";
+
+interface UpgradeBannerProps {
+ targetVersion: string;
+}
+
+export function UpgradeBanner({ targetVersion }: UpgradeBannerProps) {
+ const isSmallScreen = useIsSmallScreen();
+
+ return (
+ <Flex
+ className={S.root}
+ gap="sm"
+ wrap="nowrap"
+ data-testid="upgrade-banner"
+ direction={isSmallScreen ? "column" : "row"}
+ >
+ <Flex gap="md" align="center">
+ <Icon name="warning" className={S.icon} />
+ <Text fw="bold" size="md" className={S.text}>
+ {c("{0} is a version number like v0.59.4")
+ .t`A security update is available. Update to ${targetVersion} or later to resolve known issues.`}
+ </Text>
+ </Flex>
+ <Anchor
+ component={ExternalLink}
+ href={UPGRADE_DOCS_URL}
+ className={S.link}
+ fw="bold"
+ size="md"
+ >
+ {t`View upgrade instructions`}
+ </Anchor>
+ </Flex>
+ );
+}
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.ts
new file mode 100644
index 00000000000..1d6afcbeb77
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/hooks/use-notification-config.ts
@@ -0,0 +1,222 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useState,
+} from "react";
+
+import {
+ useGetChannelInfoQuery,
+ useListUserRecipientsQuery,
+ useUpdateSettingsMutation,
+} from "metabase/api";
+import { useSetting } from "metabase/common/hooks";
+import type {
+ ChannelApiResponse,
+ NotificationHandlerEmail,
+ NotificationHandlerSlack,
+ NotificationRecipient,
+ User,
+} from "metabase-types/api";
+
+const ADMIN_GROUP_ID = 2;
+
+export interface NotificationConfig {
+ email: {
+ sendToAllAdmins: boolean;
+ handler: NotificationHandlerEmail;
+ };
+ slack: {
+ enabled: boolean;
+ handler: NotificationHandlerSlack;
+ };
+}
+
+const DEFAULT_SLACK_HANDLER: NotificationHandlerSlack = {
+ channel_type: "channel/slack",
+ recipients: [],
+};
+
+function buildSlackHandler(
+ channelName: string | null,
+): NotificationHandlerSlack {
+ if (!channelName) {
+ return DEFAULT_SLACK_HANDLER;
+ }
+ return {
+ channel_type: "channel/slack",
+ recipients: [
+ {
+ type: "notification-recipient/raw-value",
+ details: { value: channelName },
+ },
+ ],
+ };
+}
+
+function isAdminGroupRecipient(r: NotificationRecipient): boolean {
+ return (
+ r.type === "notification-recipient/group" &&
+ r.permissions_group_id === ADMIN_GROUP_ID
+ );
+}
+
+function configFromSettings(
+ emailRecipients: NotificationRecipient[] | null,
+ slackChannel: string | null,
+): NotificationConfig {
+ const recipients = emailRecipients ?? [];
+ // null means no setting saved yet — default to sending to all admins
+ const sendToAllAdmins =
+ emailRecipients === null || recipients.some(isAdminGroupRecipient);
+
+ // Filter out the admin group recipient — it's represented by the toggle
+ const extraRecipients = recipients.filter((r) => !isAdminGroupRecipient(r));
+
+ return {
+ email: {
+ sendToAllAdmins,
+ handler: {
+ channel_type: "channel/email",
+ recipients: extraRecipients,
+ },
+ },
+ slack: {
+ enabled: slackChannel !== null,
+ handler: buildSlackHandler(slackChannel),
+ },
+ };
+}
+
+type NotificationConfigValue = {
+ config: NotificationConfig;
+ users: User[];
+ channels: ChannelApiResponse["channels"] | undefined;
+ updateEmailHandler: (handler: NotificationHandlerEmail) => void;
+ toggleSendToAllAdmins: (sendToAllAdmins: boolean) => void;
+ updateSlackHandler: (handler: NotificationHandlerSlack) => void;
+ toggleSlack: (enabled: boolean) => void;
+ save: () => Promise<void>;
+ resetConfig: () => void;
+};
+
+const NotificationConfigContext = createContext<NotificationConfigValue | null>(
+ null,
+);
+
+export const NotificationConfigProvider = NotificationConfigContext.Provider;
+
+/**
+ * Hook for notification channel configuration.
+ * When used inside a NotificationConfigProvider, returns the shared context.
+ * When used as the root (in the modal), creates and owns the state.
+ */
+export function useNotificationConfig(): NotificationConfigValue {
+ const ctx = useContext(NotificationConfigContext);
+ if (ctx) {
+ return ctx;
+ }
+ throw new Error(
+ "useNotificationConfig must be used inside a NotificationConfigProvider",
+ );
+}
+
+/**
+ * Creates the notification config state. Should be called once in the modal
+ * and provided to children via NotificationConfigProvider.
+ */
+export function useNotificationConfigState(): NotificationConfigValue {
+ const savedEmailRecipients = useSetting("security-center-email-recipients");
+ const savedSlackChannel = useSetting("security-center-slack-channel");
+
+ const initialConfig = useMemo(
+ () => configFromSettings(savedEmailRecipients, savedSlackChannel),
+ [savedEmailRecipients, savedSlackChannel],
+ );
+
+ const [config, setConfig] = useState<NotificationConfig>(initialConfig);
+
+ const { data: userRecipients } = useListUserRecipientsQuery();
+ const { data: channelInfo } = useGetChannelInfoQuery();
+ const [updateSettings] = useUpdateSettingsMutation();
+
+ const users: User[] = useMemo(
+ () => userRecipients?.data ?? [],
+ [userRecipients?.data],
+ );
+ const channels: ChannelApiResponse["channels"] | undefined =
+ channelInfo?.channels;
+
+ const updateEmailHandler = useCallback(
+ (handler: NotificationHandlerEmail) => {
+ setConfig((prev) => ({
+ ...prev,
+ email: { ...prev.email, handler },
+ }));
+ },
+ [],
+ );
+
+ const toggleSendToAllAdmins = useCallback((sendToAllAdmins: boolean) => {
+ setConfig((prev) => ({
+ ...prev,
+ email: { ...prev.email, sendToAllAdmins },
+ }));
+ }, []);
+
+ const updateSlackHandler = useCallback(
+ (handler: NotificationHandlerSlack) => {
+ setConfig((prev) => ({
+ ...prev,
+ slack: { ...prev.slack, handler },
+ }));
+ },
+ [],
+ );
+
+ const toggleSlack = useCallback((enabled: boolean) => {
+ setConfig((prev) => ({
+ ...prev,
+ slack: { ...prev.slack, enabled },
+ }));
+ }, []);
+
+ 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;
+
+ await updateSettings({
+ "security-center-email-recipients": emailRecipients,
+ "security-center-slack-channel": slackChannel,
+ }).unwrap();
+ }, [config, updateSettings]);
+
+ const resetConfig = useCallback(() => {
+ setConfig(initialConfig);
+ }, [initialConfig]);
+
+ return {
+ config,
+ users,
+ channels,
+ updateEmailHandler,
+ toggleSendToAllAdmins,
+ updateSlackHandler,
+ toggleSlack,
+ save,
+ resetConfig,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/hooks/use-security-advisories.ts b/enterprise/frontend/src/metabase-enterprise/security_center/hooks/use-security-advisories.ts
new file mode 100644
index 00000000000..c879a7e9032
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/hooks/use-security-advisories.ts
@@ -0,0 +1,34 @@
+import { useMemo } from "react";
+
+import {
+ useAcknowledgeAdvisoryMutation,
+ useListSecurityAdvisoriesQuery,
+} from "metabase/api";
+import type { Advisory } from "metabase-types/api";
+
+const POLLING_INTERVAL = 2000;
+
+export function useSecurityAdvisories(isPolling = false) {
+ const {
+ data: response,
+ isLoading,
+ isError,
+ } = useListSecurityAdvisoriesQuery(undefined, {
+ refetchOnMountOrArgChange: true,
+ pollingInterval: isPolling ? POLLING_INTERVAL : undefined,
+ });
+ const [acknowledgeAdvisory] = useAcknowledgeAdvisoryMutation();
+
+ const advisories: Advisory[] = useMemo(
+ () => response?.advisories ?? [],
+ [response?.advisories],
+ );
+
+ return {
+ data: advisories,
+ lastCheckedAt: response?.last_checked_at ?? null,
+ isLoading,
+ isError,
+ acknowledgeAdvisory,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/index.ts b/enterprise/frontend/src/metabase-enterprise/security_center/index.ts
new file mode 100644
index 00000000000..d96a034ed8c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/index.ts
@@ -0,0 +1,18 @@
+import { PLUGIN_SECURITY_CENTER } from "metabase/plugins";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
+
+import { SecurityCenterBanner } from "./components/SecurityCenterBanner/SecurityCenterBanner";
+import { SecurityCenterMobileNavItem } from "./components/SecurityCenterNavItem/SecurityCenterMobileNavItem";
+import { SecurityCenterNavItem } from "./components/SecurityCenterNavItem/SecurityCenterNavItem";
+import { SecurityCenterPage } from "./components/SecurityCenterPage/SecurityCenterPage";
+
+export function initializePlugin() {
+ if (hasPremiumFeature("admin_security_center")) {
+ PLUGIN_SECURITY_CENTER.isEnabled = true;
+ PLUGIN_SECURITY_CENTER.SecurityCenterPage = SecurityCenterPage;
+ PLUGIN_SECURITY_CENTER.SecurityCenterBanner = SecurityCenterBanner;
+ PLUGIN_SECURITY_CENTER.SecurityCenterNavItem = SecurityCenterNavItem;
+ PLUGIN_SECURITY_CENTER.SecurityCenterMobileNavItem =
+ SecurityCenterMobileNavItem;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/types.ts b/enterprise/frontend/src/metabase-enterprise/security_center/types.ts
new file mode 100644
index 00000000000..adfa496584e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/types.ts
@@ -0,0 +1,7 @@
+import type { AdvisorySeverity } from "metabase-types/api";
+
+export type AdvisoryFilter = {
+ severity: AdvisorySeverity | "all";
+ status: "all" | "affected" | "not-affected";
+ showAcknowledged: boolean;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/utils.ts b/enterprise/frontend/src/metabase-enterprise/security_center/utils.ts
new file mode 100644
index 00000000000..964ebeff9dd
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/utils.ts
@@ -0,0 +1,87 @@
+import { compareVersions } from "metabase/utils/version";
+import type { Advisory, AdvisorySeverity } from "metabase-types/api";
+
+import type { AdvisoryFilter } from "./types";
+
+const SEVERITY_ORDER: Record<AdvisorySeverity, number> = {
+ critical: 0,
+ high: 1,
+ medium: 2,
+ low: 3,
+};
+
+export function isAffected(advisory: Advisory): boolean {
+ return (
+ advisory.match_status === "active" || advisory.match_status === "error"
+ );
+}
+
+export function isAcknowledged(advisory: Advisory): boolean {
+ return advisory.acknowledged_at != null;
+}
+
+export function filterAdvisories(
+ advisories: Advisory[],
+ filter: AdvisoryFilter,
+): Advisory[] {
+ return advisories.filter((a) => {
+ if (filter.severity !== "all" && a.severity !== filter.severity) {
+ return false;
+ }
+ if (filter.status === "affected" && !isAffected(a)) {
+ return false;
+ }
+ if (filter.status === "not-affected" && isAffected(a)) {
+ return false;
+ }
+ if (!filter.showAcknowledged && isAcknowledged(a)) {
+ return false;
+ }
+ return true;
+ });
+}
+
+/**
+ * Returns the highest `fixed` version across all active (unresolved) advisories,
+ * which is the minimum version the instance should upgrade to.
+ */
+export function getTargetUpgradeVersion(advisories: Advisory[]): string | null {
+ let target: string | null = null;
+
+ for (const advisory of advisories) {
+ if (!isAffected(advisory)) {
+ continue;
+ }
+ for (const range of advisory.affected_versions) {
+ if (target === null || compareVersions(range.fixed, target) === 1) {
+ target = range.fixed;
+ }
+ }
+ }
+
+ return target;
+}
+
+export function sortAdvisories(advisories: Advisory[]): Advisory[] {
+ return [...advisories].sort((a, b) => {
+ const aAffected = isAffected(a);
+ const bAffected = isAffected(b);
+
+ // Affected items first
+ if (aAffected !== bAffected) {
+ return aAffected ? -1 : 1;
+ }
+
+ // Then by severity (critical → low)
+ const severityDiff =
+ SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
+ if (severityDiff !== 0) {
+ return severityDiff;
+ }
+
+ // Then by published_at descending (newest first)
+ return (
+ new Date(b.published_at).getTime() - new Date(a.published_at).getTime()
+ );
+ });
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/security_center/utils.unit.spec.ts
new file mode 100644
index 00000000000..c4e1d364b87
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/utils.unit.spec.ts
@@ -0,0 +1,213 @@
+import type { Advisory } from "metabase-types/api";
+
+import type { AdvisoryFilter } from "./types";
+import { filterAdvisories, isAffected, sortAdvisories } from "./utils";
+
+const makeAdvisory = (overrides: Partial<Advisory>): Advisory => ({
+ advisory_id: "SA-001",
+ title: "Test advisory",
+ description: "Test description",
+ severity: "medium",
+ advisory_url: "https://example.com/advisory",
+ remediation: "Upgrade to latest version",
+ published_at: "2026-01-01T00:00:00Z",
+ match_status: "not_affected",
+ last_evaluated_at: null,
+ acknowledged_by: null,
+ acknowledged_at: null,
+ affected_versions: [{ min: "0.45.0", fixed: "0.59.0" }],
+ ...overrides,
+});
+
+const ALL_PASS_FILTER: AdvisoryFilter = {
+ severity: "all",
+ status: "all",
+ showAcknowledged: true,
+};
+
+describe("isAffected", () => {
+ it("should return true for active advisories", () => {
+ expect(isAffected(makeAdvisory({ match_status: "active" }))).toBe(true);
+ });
+
+ it("should return true for error advisories (fail-open)", () => {
+ expect(isAffected(makeAdvisory({ match_status: "error" }))).toBe(true);
+ });
+
+ it.each(["not_affected", "resolved"] as const)(
+ "should return false for %s advisories",
+ (status) => {
+ expect(isAffected(makeAdvisory({ match_status: status }))).toBe(false);
+ },
+ );
+});
+
+describe("sortAdvisories", () => {
+ it("should place affected items before non-affected items", () => {
+ const advisories = [
+ makeAdvisory({
+ advisory_id: "1",
+ match_status: "not_affected",
+ severity: "critical",
+ }),
+ makeAdvisory({
+ advisory_id: "2",
+ match_status: "active",
+ severity: "low",
+ }),
+ ];
+
+ const sorted = sortAdvisories(advisories);
+ expect(sorted[0].advisory_id).toBe("2");
+ expect(sorted[1].advisory_id).toBe("1");
+ });
+
+ it("should sort by severity within the same affected status", () => {
+ const advisories = [
+ makeAdvisory({
+ advisory_id: "low",
+ severity: "low",
+ match_status: "active",
+ }),
+ makeAdvisory({
+ advisory_id: "critical",
+ severity: "critical",
+ match_status: "active",
+ }),
+ makeAdvisory({
+ advisory_id: "medium",
+ severity: "medium",
+ match_status: "active",
+ }),
+ makeAdvisory({
+ advisory_id: "high",
+ severity: "high",
+ match_status: "active",
+ }),
+ ];
+
+ const sorted = sortAdvisories(advisories);
+ expect(sorted.map((a) => a.advisory_id)).toEqual([
+ "critical",
+ "high",
+ "medium",
+ "low",
+ ]);
+ });
+
+ it("should sort by published_at descending within the same severity", () => {
+ const advisories = [
+ makeAdvisory({
+ advisory_id: "older",
+ severity: "high",
+ match_status: "active",
+ published_at: "2026-01-01T00:00:00Z",
+ }),
+ makeAdvisory({
+ advisory_id: "newer",
+ severity: "high",
+ match_status: "active",
+ published_at: "2026-03-01T00:00:00Z",
+ }),
+ ];
+
+ const sorted = sortAdvisories(advisories);
+ expect(sorted[0].advisory_id).toBe("newer");
+ expect(sorted[1].advisory_id).toBe("older");
+ });
+
+ it("should return an empty array when given an empty array", () => {
+ expect(sortAdvisories([])).toEqual([]);
+ });
+
+ it("should not mutate the original array", () => {
+ const advisories = [
+ makeAdvisory({ advisory_id: "2", match_status: "active" }),
+ makeAdvisory({ advisory_id: "1", match_status: "not_affected" }),
+ ];
+ const original = [...advisories];
+
+ sortAdvisories(advisories);
+ expect(advisories).toEqual(original);
+ });
+});
+
+describe("filterAdvisories", () => {
+ const advisories = [
+ makeAdvisory({
+ advisory_id: "1",
+ severity: "critical",
+ match_status: "active",
+ acknowledged_at: null,
+ }),
+ makeAdvisory({
+ advisory_id: "2",
+ severity: "high",
+ match_status: "active",
+ acknowledged_at: "2026-03-01T00:00:00Z",
+ }),
+ makeAdvisory({
+ advisory_id: "3",
+ severity: "medium",
+ match_status: "not_affected",
+ acknowledged_at: null,
+ }),
+ makeAdvisory({
+ advisory_id: "4",
+ severity: "low",
+ match_status: "not_affected",
+ acknowledged_at: "2026-02-01T00:00:00Z",
+ }),
+ ];
+
+ it("should return all advisories when no filters are active", () => {
+ const result = filterAdvisories(advisories, ALL_PASS_FILTER);
+ expect(result).toHaveLength(4);
+ });
+
+ it("should filter by severity", () => {
+ const result = filterAdvisories(advisories, {
+ ...ALL_PASS_FILTER,
+ severity: "critical",
+ });
+ expect(result).toHaveLength(1);
+ expect(result[0].advisory_id).toBe("1");
+ });
+
+ it("should filter by affected status", () => {
+ const result = filterAdvisories(advisories, {
+ ...ALL_PASS_FILTER,
+ status: "affected",
+ });
+ expect(result.every((a) => a.match_status === "active")).toBe(true);
+ expect(result).toHaveLength(2);
+ });
+
+ it("should filter by not-affected status", () => {
+ const result = filterAdvisories(advisories, {
+ ...ALL_PASS_FILTER,
+ status: "not-affected",
+ });
+ expect(result.every((a) => a.match_status !== "active")).toBe(true);
+ expect(result).toHaveLength(2);
+ });
+
+ it("should hide acknowledged advisories when showAcknowledged is false", () => {
+ const result = filterAdvisories(advisories, {
+ ...ALL_PASS_FILTER,
+ showAcknowledged: false,
+ });
+ expect(result.every((a) => a.acknowledged_at == null)).toBe(true);
+ expect(result).toHaveLength(2);
+ });
+
+ it("should combine multiple filters", () => {
+ const result = filterAdvisories(advisories, {
+ severity: "all",
+ status: "affected",
+ showAcknowledged: false,
+ });
+ expect(result).toHaveLength(1);
+ expect(result[0].advisory_id).toBe("1");
+ });
+});
diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.ts
index ab8749aa1b1..f25cdc5eea2 100644
--- a/frontend/src/metabase-types/api/index.ts
+++ b/frontend/src/metabase-types/api/index.ts
@@ -44,6 +44,7 @@ export * from "./remote-sync";
export * from "./revision";
export * from "./schema";
export * from "./search";
+export * from "./security-center";
export * from "./segment";
export * from "./session";
export * from "./settings";
diff --git a/frontend/src/metabase-types/api/mocks/security-center.ts b/frontend/src/metabase-types/api/mocks/security-center.ts
new file mode 100644
index 00000000000..15ca4bd0440
--- /dev/null
+++ b/frontend/src/metabase-types/api/mocks/security-center.ts
@@ -0,0 +1,60 @@
+import type {
+ Advisory,
+ EmailChannelSpec,
+ SlackChannelSpec,
+} from "metabase-types/api";
+
+export function createMockEmailChannelSpec(
+ overrides: Partial<EmailChannelSpec> = {},
+): EmailChannelSpec {
+ return {
+ type: "email",
+ name: "Email",
+ schedules: [],
+ schedule_type: null,
+ allows_recipients: true,
+ configured: true,
+ recipients: ["user", "email"],
+ ...overrides,
+ };
+}
+
+export function createMockSlackChannelSpec(
+ overrides: Partial<SlackChannelSpec> = {},
+): SlackChannelSpec {
+ return {
+ type: "slack",
+ name: "Slack",
+ schedules: [],
+ schedule_type: null,
+ allows_recipients: false,
+ configured: false,
+ fields: [
+ {
+ name: "channel",
+ displayName: "Post to",
+ options: ["#general", "#security"],
+ required: true,
+ },
+ ],
+ ...overrides,
+ };
+}
+
+export function createAdvisory(overrides: Partial<Advisory> = {}): Advisory {
+ return {
+ advisory_id: "SA-001",
+ title: "Test advisory",
+ description: "desc",
+ severity: "medium",
+ advisory_url: null,
+ remediation: "Upgrade",
+ published_at: "2026-01-01T00:00:00Z",
+ match_status: "not_affected",
+ last_evaluated_at: null,
+ acknowledged_by: null,
+ acknowledged_at: null,
+ affected_versions: [{ min: "0.45.0", fixed: "0.59.0" }],
+ ...overrides,
+ };
+}
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index 2fd0de61c5c..7c8ca6af22a 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -148,6 +148,7 @@ export const createMockTokenFeatures = (
tenants: false,
workspaces: false,
writable_connection: false,
+ admin_security_center: false,
ai_controls: false,
...opts,
});
@@ -392,6 +393,8 @@ export const createMockSettings = (
"slack-app-token": null,
"slack-token-valid?": false,
"start-of-week": "sunday",
+ "security-center-email-recipients": null,
+ "security-center-slack-channel": null,
"store-url": "https://store.staging.metabase.com",
"subscription-allowed-domains": null,
"token-features": createMockTokenFeatures(),
diff --git a/frontend/src/metabase-types/api/notification.ts b/frontend/src/metabase-types/api/notification.ts
index e5505338376..3bd1e4c30d9 100644
--- a/frontend/src/metabase-types/api/notification.ts
+++ b/frontend/src/metabase-types/api/notification.ts
@@ -57,9 +57,19 @@ export type NotificationRecipientRawValue = {
updated_at?: string;
};
+export type NotificationRecipientGroup = {
+ type: "notification-recipient/group";
+ permissions_group_id: number;
+
+ id?: number;
+ created_at?: string;
+ updated_at?: string;
+};
+
export type NotificationRecipient =
| NotificationRecipientUser
- | NotificationRecipientRawValue;
+ | NotificationRecipientRawValue
+ | NotificationRecipientGroup;
type NotificationHandlerBase = {
notification_id?: NotificationId;
diff --git a/frontend/src/metabase-types/api/security-center.ts b/frontend/src/metabase-types/api/security-center.ts
new file mode 100644
index 00000000000..ed8b8767b51
--- /dev/null
+++ b/frontend/src/metabase-types/api/security-center.ts
@@ -0,0 +1,41 @@
+export type AdvisoryMatchStatus =
+ | "active"
+ | "resolved"
+ | "not_affected"
+ | "error";
+
+export type AdvisoryVersionRange = {
+ min: string;
+ fixed: string;
+};
+
+export type AdvisorySeverity = "critical" | "high" | "medium" | "low";
+
+export type AdvisoryId = string;
+
+export type Advisory = {
+ advisory_id: AdvisoryId;
+ title: string;
+ severity: AdvisorySeverity;
+ description: string;
+ advisory_url: string | null;
+ remediation: string;
+ published_at: string;
+ match_status: AdvisoryMatchStatus;
+ last_evaluated_at: string | null;
+ acknowledged_by: { id: number; common_name: string; email: string } | null;
+ acknowledged_at: string | null;
+ affected_versions: AdvisoryVersionRange[];
+};
+
+export type ListAdvisoriesResponse = {
+ last_checked_at: string | null;
+ advisories: Advisory[];
+};
+
+export type AcknowledgeAdvisoryResponse = {
+ advisory_id: string;
+ match_status: AdvisoryMatchStatus;
+ acknowledged_by: { id: number; common_name: string; email: string } | null;
+ acknowledged_at: string | null;
+};
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index 98e54c3bc89..a9b7e6ad96f 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -8,6 +8,7 @@ import type { DashboardId } from "./dashboard";
import type { DatabaseId } from "./database";
import type { GroupId } from "./group";
import type { MetabotLimitPeriod, MetabotLimitType } from "./metabot";
+import type { NotificationRecipient } from "./notification";
import type { UserId } from "./user";
export interface OidcAuthProvider {
@@ -367,6 +368,7 @@ export const tokenFeatures = [
"tenants",
"workspaces",
"writable_connection",
+ "admin_security_center",
"ai_controls",
] as const;
@@ -506,6 +508,8 @@ interface AdminSettings {
"embedding-hub-test-embed-snippet-created": boolean;
"embedding-hub-production-embed-snippet-created": boolean;
"embedding-hub-sso-auth-manual-tested": boolean;
+ "security-center-email-recipients": NotificationRecipient[] | null;
+ "security-center-slack-channel": string | null;
"store-url": string;
gsheets: Partial<GdrivePayload>;
"license-token-missing-banner-dismissal-timestamp"?: Array<string>;
diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsx
index 0788eb7dbae..0d3c73b66f1 100644
--- a/frontend/src/metabase/admin/routes.tsx
+++ b/frontend/src/metabase/admin/routes.tsx
@@ -54,6 +54,7 @@ import {
PLUGIN_CACHING,
PLUGIN_DB_ROUTING,
PLUGIN_DEPENDENCIES,
+ PLUGIN_SECURITY_CENTER,
PLUGIN_SUPPORT,
PLUGIN_TENANTS,
PLUGIN_WRITABLE_CONNECTION,
@@ -262,6 +263,13 @@ export const getRoutes = (
{getMetabotAdminRoutes()}
</Route>
+ {PLUGIN_SECURITY_CENTER.isEnabled && (
+ <Route
+ path="security-center"
+ component={PLUGIN_SECURITY_CENTER.SecurityCenterPage}
+ />
+ )}
+
<Route path="tools" component={createAdminRouteGuard("tools")}>
<Route component={ToolsApp}>
<IndexRedirect to="help" />
diff --git a/frontend/src/metabase/api/channel.ts b/frontend/src/metabase/api/channel.ts
index 80f333978be..e5e10e4f9cc 100644
--- a/frontend/src/metabase/api/channel.ts
+++ b/frontend/src/metabase/api/channel.ts
@@ -25,6 +25,16 @@ const channelApi = Api.injectEndpoints({
},
}),
}),
+ testSlackChannel: builder.mutation<Record<string, never>, string>({
+ query: (channel) => ({
+ method: "POST",
+ url: "/api/channel/test",
+ body: {
+ type: "channel/slack",
+ details: { channel },
+ },
+ }),
+ }),
createChannel: builder.mutation<
NotificationChannel[],
Omit<NotificationChannel, "created_at" | "updated_at" | "active" | "id">
@@ -69,5 +79,6 @@ export const {
useCreateChannelMutation,
useDeleteChannelMutation,
useTestChannelMutation,
+ useTestSlackChannelMutation,
endpoints: { listChannels },
} = channelApi;
diff --git a/frontend/src/metabase/api/index.ts b/frontend/src/metabase/api/index.ts
index e9d105c2556..2cde34d0fa7 100644
--- a/frontend/src/metabase/api/index.ts
+++ b/frontend/src/metabase/api/index.ts
@@ -31,6 +31,7 @@ export * from "./permission";
export * from "./persist";
export * from "./premium-features";
export * from "./revision";
+export * from "./security-center";
export * from "./group-table-access-policy";
export * from "./search";
export * from "./segment";
diff --git a/frontend/src/metabase/api/security-center.ts b/frontend/src/metabase/api/security-center.ts
new file mode 100644
index 00000000000..f71a89b9ee9
--- /dev/null
+++ b/frontend/src/metabase/api/security-center.ts
@@ -0,0 +1,45 @@
+import { Api } from "metabase/api";
+import type {
+ AcknowledgeAdvisoryResponse,
+ ListAdvisoriesResponse,
+} from "metabase-types/api";
+
+import { listTag } from "./tags";
+export const securityCenterApi = Api.injectEndpoints({
+ endpoints: (builder) => ({
+ listSecurityAdvisories: builder.query<ListAdvisoriesResponse, void>({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/security-center",
+ }),
+ providesTags: [listTag("security-advisory")],
+ }),
+ acknowledgeAdvisory: builder.mutation<AcknowledgeAdvisoryResponse, string>({
+ query: (advisoryId) => ({
+ method: "POST",
+ url: `/api/ee/security-center/${advisoryId}/acknowledge`,
+ }),
+ invalidatesTags: [listTag("security-advisory")],
+ }),
+ syncSecurityAdvisories: builder.mutation<void, void>({
+ query: () => ({
+ method: "POST",
+ url: "/api/ee/security-center/sync",
+ }),
+ invalidatesTags: [listTag("security-advisory")],
+ }),
+ sendTestNotification: builder.mutation<{ success: boolean }, void>({
+ query: () => ({
+ method: "POST",
+ url: "/api/ee/security-center/test-notification",
+ }),
+ }),
+ }),
+});
+
+export const {
+ useListSecurityAdvisoriesQuery,
+ useAcknowledgeAdvisoryMutation,
+ useSyncSecurityAdvisoriesMutation,
+ useSendTestNotificationMutation,
+} = securityCenterApi;
diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.ts
index 568f28f8096..200ea6b21d6 100644
--- a/frontend/src/metabase/api/tags/constants.ts
+++ b/frontend/src/metabase/api/tags/constants.ts
@@ -67,6 +67,7 @@ export const TAG_TYPES = [
"metabot-entities-list",
"metabot-prompt-suggestions",
"metabot-permissions",
+ "security-advisory",
] as const;
export const TAG_TYPE_MAPPING = {
diff --git a/frontend/src/metabase/common/components/AppBanner/AppBanner.tsx b/frontend/src/metabase/common/components/AppBanner/AppBanner.tsx
index 9cfa7ce1858..9d67d1baef4 100644
--- a/frontend/src/metabase/common/components/AppBanner/AppBanner.tsx
+++ b/frontend/src/metabase/common/components/AppBanner/AppBanner.tsx
@@ -9,6 +9,7 @@ import {
import { PaymentBanner } from "metabase/nav/components/PaymentBanner/PaymentBanner";
import { ReadOnlyBanner } from "metabase/nav/components/ReadOnlyBanner";
import { TrialBanner } from "metabase/nav/components/TrialBanner";
+import { PLUGIN_SECURITY_CENTER } from "metabase/plugins";
import { getUserIsAdmin } from "metabase/selectors/user";
import { getIsHosted } from "metabase/setup/selectors";
import { isWithinIframe } from "metabase/utils/iframe";
@@ -83,6 +84,11 @@ export const AppBanner = () => {
return <PaymentBanner tokenStatus={tokenStatus} />;
}
+ if (PLUGIN_SECURITY_CENTER.isEnabled) {
+ const { SecurityCenterBanner } = PLUGIN_SECURITY_CENTER;
+ return <SecurityCenterBanner />;
+ }
+
if (isDevMode) {
return <DevModeBanner />;
}
diff --git a/frontend/src/metabase/common/components/Banner/Banner.tsx b/frontend/src/metabase/common/components/Banner/Banner.tsx
index d010bcd5406..8ebddd343c9 100644
--- a/frontend/src/metabase/common/components/Banner/Banner.tsx
+++ b/frontend/src/metabase/common/components/Banner/Banner.tsx
@@ -1,7 +1,7 @@
import type { ReactNode } from "react";
import CS from "metabase/css/core/index.css";
-import type { FlexProps, IconName } from "metabase/ui";
+import type { FlexProps, GroupProps, IconName } from "metabase/ui";
import { Flex, Group, Icon } from "metabase/ui";
import type { ColorName } from "metabase/ui/colors/types";
@@ -9,6 +9,7 @@ interface BaseBannerProps extends FlexProps {
icon?: IconName;
iconColor?: ColorName;
body: ReactNode;
+ contentGroupProps?: GroupProps;
}
export type BannerProps =
@@ -22,6 +23,7 @@ export const Banner = ({
closable,
onClose,
bg,
+ contentGroupProps,
...flexProps
}: BannerProps) => {
return (
@@ -35,7 +37,7 @@ export const Banner = ({
pr="md"
{...flexProps}
>
- <Group gap="xs">
+ <Group gap="xs" {...contentGroupProps}>
{icon && <Icon name={icon} w={36} c={iconColor} />}
{body}
</Group>
diff --git a/frontend/src/metabase/nav/components/AdminNavbar/AdminNavbar.tsx b/frontend/src/metabase/nav/components/AdminNavbar/AdminNavbar.tsx
index 0f305333ec8..86a499f82c6 100644
--- a/frontend/src/metabase/nav/components/AdminNavbar/AdminNavbar.tsx
+++ b/frontend/src/metabase/nav/components/AdminNavbar/AdminNavbar.tsx
@@ -5,6 +5,7 @@ import { t } from "ttag";
import { LogoIcon } from "metabase/common/components/LogoIcon";
import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";
+import { PLUGIN_SECURITY_CENTER } from "metabase/plugins";
import { getIsPaidPlan } from "metabase/selectors/settings";
import { getUserIsAdmin } from "metabase/selectors/user";
import { Button, Icon } from "metabase/ui";
@@ -86,6 +87,13 @@ export const AdminNavbar = ({
currentPath={currentPath}
/>
))}
+ {/* Security Center is rendered outside adminPaths because it
+ needs a live query to show an active-advisories badge */}
+ {PLUGIN_SECURITY_CENTER.isEnabled && (
+ <PLUGIN_SECURITY_CENTER.SecurityCenterNavItem
+ currentPath={currentPath}
+ />
+ )}
</AdminNavbarItems>
{!isPaidPlan && isAdmin && <StoreLink />}
@@ -135,6 +143,13 @@ const MobileNavbar = ({ adminPaths, currentPath }: AdminMobileNavbarProps) => {
{name}
</AdminNavLink>
))}
+ {/* Security Center is rendered outside adminPaths because it
+ needs a live query to show an active-advisories badge */}
+ {PLUGIN_SECURITY_CENTER.isEnabled && (
+ <PLUGIN_SECURITY_CENTER.SecurityCenterMobileNavItem
+ currentPath={currentPath}
+ />
+ )}
</AdminMobileNavBarItems>
)}
</AdminMobileNavbar>
diff --git a/frontend/src/metabase/notifications/channels/EmailChannelEdit.tsx b/frontend/src/metabase/notifications/channels/EmailChannelEdit.tsx
index ec47f941de2..ae28a89c426 100644
--- a/frontend/src/metabase/notifications/channels/EmailChannelEdit.tsx
+++ b/frontend/src/metabase/notifications/channels/EmailChannelEdit.tsx
@@ -11,11 +11,13 @@ import { RecipientPicker } from "./RecipientPicker";
export const EmailChannelEdit = ({
channel,
users,
+ autoFocus,
invalidRecipientText,
onChange,
}: {
channel: NotificationHandlerEmail;
users: User[];
+ autoFocus?: boolean;
invalidRecipientText: (domains: string) => string;
onChange: (newConfig: NotificationHandlerEmail) => void;
}) => {
@@ -76,6 +78,7 @@ export const EmailChannelEdit = ({
<RecipientPicker
recipients={mappedUsers}
users={users}
+ autoFocus={autoFocus}
onRecipientsChange={handleRecipientsChange}
invalidRecipientText={invalidRecipientText}
/>
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 3bb5fd2a4a3..e44bd171652 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -146,6 +146,7 @@ export {
PLUGIN_WRITABLE_CONNECTION,
type WritableConnectionInfoSectionProps,
} from "./oss/writable-connection";
+export { PLUGIN_SECURITY_CENTER } from "./oss/security-center";
export { PLUGIN_AI_CONTROLS, type AiControlsPlugin } from "./oss/ai-controls";
export { PLUGIN_SUPPORT } from "./oss/support";
export { PLUGIN_TENANTS } from "./oss/tenants";
@@ -185,6 +186,7 @@ import { reinitialize as reinitializePermissions } from "./oss/permissions";
import { reinitialize as reinitializeRemoteSync } from "./oss/remote-sync";
import { reinitialize as reinitializeReplacement } from "./oss/replacement";
import { reinitialize as reinitializeResourceDownloads } from "./oss/resource-downloads";
+import { reinitialize as reinitializeSecurityCenter } from "./oss/security-center";
import { reinitialize as reinitializeSemanticSearch } from "./oss/semantic-search";
import { reinitialize as reinitializeSettings } from "./oss/settings";
import { reinitialize as reinitializeSmtpOverride } from "./oss/smtp-override";
@@ -226,6 +228,7 @@ export function reinitialize() {
reinitializeRemoteSync();
reinitializeReplacement();
reinitializeResourceDownloads();
+ reinitializeSecurityCenter();
reinitializeSemanticSearch();
reinitializeSettings();
reinitializeSmtpOverride();
diff --git a/frontend/src/metabase/plugins/oss/security-center.ts b/frontend/src/metabase/plugins/oss/security-center.ts
new file mode 100644
index 00000000000..cf3ec9b1fdd
--- /dev/null
+++ b/frontend/src/metabase/plugins/oss/security-center.ts
@@ -0,0 +1,32 @@
+import type { ComponentType } from "react";
+
+import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";
+
+type SecurityCenterNavItemProps = {
+ currentPath: string;
+};
+
+type SecurityCenterPlugin = {
+ isEnabled: boolean;
+ SecurityCenterPage: ComponentType;
+ SecurityCenterBanner: ComponentType;
+ SecurityCenterNavItem: ComponentType<SecurityCenterNavItemProps>;
+ SecurityCenterMobileNavItem: ComponentType<SecurityCenterNavItemProps>;
+};
+
+const getDefaultPlugin = (): SecurityCenterPlugin => ({
+ isEnabled: false,
+ SecurityCenterPage: PluginPlaceholder,
+ SecurityCenterBanner: PluginPlaceholder,
+ SecurityCenterNavItem: PluginPlaceholder,
+ SecurityCenterMobileNavItem: PluginPlaceholder,
+});
+
+export const PLUGIN_SECURITY_CENTER = getDefaultPlugin();
+
+/**
+ * @internal Do not call directly. Use the main reinitialize function from metabase/plugins instead.
+ */
+export function reinitialize() {
+ Object.assign(PLUGIN_SECURITY_CENTER, getDefaultPlugin());
+}
diff --git a/resources/migrations/001_update_migrations.yaml b/resources/migrations/001_update_migrations.yaml
index 12e391950ef..d3affe5fd7d 100644
--- a/resources/migrations/001_update_migrations.yaml
+++ b/resources/migrations/001_update_migrations.yaml
@@ -11594,6 +11594,188 @@ databaseChangeLog:
where: base_type = 'type/Boolean' AND semantic_type = 'type/Category'
rollback: # not necessary
+ - changeSet:
+ id: v55.2026-03-30T00:00:00
+ author: bronsa
+ comment: Create security_advisory table for Security Center
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - tableExists:
+ tableName: security_advisory
+ changes:
+ - createTable:
+ tableName: security_advisory
+ remarks: Stores security advisories fetched from the advisory feed
+ columns:
+ - column:
+ name: id
+ type: int
+ remarks: Auto-incrementing primary key
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: advisory_id
+ type: varchar(255)
+ remarks: Unique advisory identifier (e.g. SC-2026-001)
+ constraints:
+ nullable: false
+ - column:
+ name: severity
+ type: varchar(32)
+ remarks: "Severity level: critical, high, medium, or low"
+ constraints:
+ nullable: false
+ - column:
+ name: title
+ type: varchar(255)
+ remarks: Human-readable advisory title
+ constraints:
+ nullable: false
+ - column:
+ name: description
+ type: ${text.type}
+ remarks: Short summary of the advisory
+ constraints:
+ nullable: false
+ - column:
+ name: advisory_url
+ type: varchar(2048)
+ remarks: Link to the full advisory
+ constraints:
+ nullable: true
+ - column:
+ name: remediation
+ type: ${text.type}
+ remarks: Remediation instructions
+ constraints:
+ nullable: false
+ - column:
+ name: affected_versions
+ type: ${text.type}
+ remarks: "JSON array of {min, fixed} version ranges"
+ constraints:
+ nullable: false
+ - column:
+ name: matching_query
+ type: ${text.type}
+ remarks: JSON HoneySQL query keyed by dialect (null = affects all instances)
+ constraints:
+ nullable: true
+ - column:
+ name: published_at
+ type: ${timestamp_type}
+ remarks: When the advisory was published
+ constraints:
+ nullable: false
+ - column:
+ name: fetched_at
+ type: ${timestamp_type}
+ remarks: When Metabase fetched this advisory
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+ - column:
+ name: match_status
+ type: varchar(32)
+ remarks: "Status: active, resolved, not_affected, or error"
+ constraints:
+ nullable: false
+ - column:
+ name: last_evaluated_at
+ type: ${timestamp_type}
+ remarks: Last time the matching query was evaluated
+ constraints:
+ nullable: true
+ - column:
+ name: acknowledged_by
+ type: int
+ remarks: FK to core_user.id — admin who acknowledged the advisory
+ constraints:
+ nullable: true
+ - column:
+ name: acknowledged_at
+ type: ${timestamp_type}
+ remarks: When the advisory was acknowledged
+ constraints:
+ nullable: true
+ - column:
+ name: last_notified_at
+ type: ${timestamp_type}
+ remarks: When the last notification was sent for this advisory
+ constraints:
+ nullable: true
+ - column:
+ name: updated_at
+ type: ${timestamp_type}
+ remarks: When the advisory was last updated upstream (used as sync cursor)
+ constraints:
+ nullable: false
+
+ - changeSet:
+ id: v55.2026-03-30T00:00:01
+ author: bronsa
+ comment: Add unique constraint on security_advisory.advisory_id
+ changes:
+ - addUniqueConstraint:
+ tableName: security_advisory
+ constraintName: uq_security_advisory_advisory_id
+ columnNames: advisory_id
+
+ - changeSet:
+ id: v55.2026-03-30T00:00:02
+ author: bronsa
+ comment: Add index on security_advisory.acknowledged_by FK
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ indexName: idx_security_advisory_acknowledged_by
+ changes:
+ - createIndex:
+ tableName: security_advisory
+ indexName: idx_security_advisory_acknowledged_by
+ columns:
+ - column:
+ name: acknowledged_by
+
+ - changeSet:
+ id: v55.2026-03-30T00:00:03
+ author: bronsa
+ comment: Add FK on security_advisory.acknowledged_by
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - foreignKeyConstraintExists:
+ foreignKeyName: fk_security_advisory_acknowledged_by
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: security_advisory
+ baseColumnNames: acknowledged_by
+ referencedTableName: core_user
+ referencedColumnNames: id
+ constraintName: fk_security_advisory_acknowledged_by
+ onDelete: SET NULL
+
+ - changeSet:
+ id: v55.2026-03-30T00:00:04
+ author: bronsa
+ comment: Add index on security_advisory.match_status
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ indexName: idx_security_advisory_match_status
+ changes:
+ - createIndex:
+ tableName: security_advisory
+ indexName: idx_security_advisory_match_status
+ columns:
+ - column:
+ name: match_status
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
########################################################################################################################
diff --git a/src/metabase/audit_app/events/audit_log.clj b/src/metabase/audit_app/events/audit_log.clj
index 915b0f8e810..c3b964ac73d 100644
--- a/src/metabase/audit_app/events/audit_log.clj
+++ b/src/metabase/audit_app/events/audit_log.clj
@@ -378,3 +378,11 @@
(methodical/defmethod events/publish-event! ::tenant-event
[topic event]
(audit-log/record-event! topic event))
+
+(derive ::security-advisory-event ::event)
+(derive :event/security-advisory-acknowledge ::security-advisory-event)
+(derive :event/security-advisory-match ::security-advisory-event)
+
+(methodical/defmethod events/publish-event! ::security-advisory-event
+ [topic event]
+ (audit-log/record-event! topic event))
diff --git a/src/metabase/channel/email/messages.clj b/src/metabase/channel/email/messages.clj
index 6bd0656e8ad..69d2102a669 100644
--- a/src/metabase/channel/email/messages.clj
+++ b/src/metabase/channel/email/messages.clj
@@ -107,7 +107,7 @@
;;; ### Public Interface
-(defn- all-admin-recipients
+(defn all-admin-recipients
"Return a sequence of email addresses for all Admin users.
The first recipient will be the site admin (or oldest admin if unset), which is the address that should be used in
diff --git a/src/metabase/channel/email/security_advisory.hbs b/src/metabase/channel/email/security_advisory.hbs
new file mode 100644
index 00000000000..effbacb7f44
--- /dev/null
+++ b/src/metabase/channel/email/security_advisory.hbs
@@ -0,0 +1,21 @@
+{{> metabase/channel/email/_header.hbs }}
+ <div style="padding-bottom: 2em; padding-top: 1em; text-align: center;">
+ <img style="max-height: 40px; max-width: 100%;" src="{{context.application_logo_url}}" alt="{{context.application_name}} logo"/>
+ </div>
+ <div style="text-align: center; margin: 0 auto; max-width: 500px">
+ <div style="text-align: left">
+ <div style="display: inline-block; padding: 4px 12px; border-radius: 4px; font-size: 12px; font-weight: bold; text-transform: uppercase; color: #fff; background-color: {{payload.custom.severity_color}}; margin-bottom: 16px;">
+ {{payload.custom.severity_label}}
+ </div>
+ <h2 style="font-weight: normal; color: #4C545B; line-height: 34px; margin-top: 12px;">Security Advisory: {{payload.event_info.object.title}}</h2>
+ <p style="line-height: 22px; color: #4C545B;">{{payload.event_info.object.description}}</p>
+ <p style="line-height: 22px; color: #4C545B;"><strong>Status:</strong> {{payload.custom.status_label}}</p>
+ <p style="line-height: 22px; color: #4C545B;"><strong>Remediation:</strong> {{payload.event_info.object.remediation}}</p>
+ {{#if payload.event_info.object.advisory_url}}
+ <p style="line-height: 22px;"><a href="{{payload.event_info.object.advisory_url}}" style="color: {{context.application_color}};">Read full advisory</a></p>
+ {{/if}}
+ <p style="line-height: 22px; margin-top: 24px; margin-bottom: 32px; font-size: 13px; color: #696E73;">This notification will repeat until the advisory is acknowledged by an admin.</p>
+ </div>
+ <a style="{{context.style.button}}" href="{{payload.custom.security_center_url}}">Go to Security Center</a>
+ </div>
+{{> metabase/channel/email/_footer.hbs }}
diff --git a/src/metabase/channel/impl/slack.clj b/src/metabase/channel/impl/slack.clj
index d8a11e9d07a..47d9308b367 100644
--- a/src/metabase/channel/impl/slack.clj
+++ b/src/metabase/channel/impl/slack.clj
@@ -138,6 +138,43 @@
(doseq [block-chunk (partition-all 50 blocks)]
(slack/post-chat-message! {:channel channel :blocks block-chunk})))
+;; ------------------------------------------------------------------------------------------------;;
+;; System Event Notifications ;;
+;; ------------------------------------------------------------------------------------------------;;
+
+(mu/defmethod channel/render-notification [:channel/slack :notification/system-event] :- [:sequential SlackMessage]
+ [_channel-type {:keys [payload]} {:keys [recipients]}]
+ (let [{:keys [event_topic event_info custom]} payload
+ blocks (case event_topic
+ :event/security-advisory-match
+ (let [{:keys [title description severity]} (:object event_info)
+ severity-emoji (case severity
+ :critical ":red_circle:"
+ :high ":large_orange_circle:"
+ :medium ":large_yellow_circle:"
+ :low ":large_blue_circle:")]
+ [{:type "header"
+ :text {:type "plain_text"
+ :text (truncate (str severity-emoji " Security Advisory: " title) header-text-limit)
+ :emoji true}}
+ {:type "section"
+ :text {:type "mrkdwn"
+ :text (truncate (escape-mkdwn description) block-text-length-limit)}}
+ {:type "section"
+ :fields [{:type "mrkdwn" :text (str "*Severity:* " (:severity_label custom))}
+ {:type "mrkdwn" :text (str "*Status:* " (:status_label custom))}]}
+ {:type "actions"
+ :elements [{:type "button"
+ :text {:type "plain_text" :text "View in Security Center"}
+ :url (:security_center_url custom)}]}])
+ ;; fallback for other system events: simple text block
+ [{:type "section"
+ :text {:type "mrkdwn"
+ :text (truncate (str "System event: " (name event_topic)) block-text-length-limit)}}])]
+ (doall (for [channel (keep notification-recipient->channel recipients)]
+ {:channel channel
+ :blocks blocks}))))
+
;; ------------------------------------------------------------------------------------------------;;
;; Notification Card ;;
;; ------------------------------------------------------------------------------------------------;;
diff --git a/src/metabase/channel/urls.clj b/src/metabase/channel/urls.clj
index c947199ff40..c8e9a7dd135 100644
--- a/src/metabase/channel/urls.clj
+++ b/src/metabase/channel/urls.clj
@@ -123,3 +123,8 @@
"URL for a transform's run tab."
[transform-id]
(format "%s/data-studio/transforms/%s/run" (site-url) transform-id))
+
+(defn security-center-url
+ "Url for the Security Center"
+ []
+ (format "%s/admin/security-center" (site-url)))
diff --git a/src/metabase/events/schema.clj b/src/metabase/events/schema.clj
index 7e47c6b7a27..43782ac09c9 100644
--- a/src/metabase/events/schema.clj
+++ b/src/metabase/events/schema.clj
@@ -247,3 +247,17 @@
(mr/def :event/field-create ::field)
(mr/def :event/field-update ::field)
(mr/def :event/field-delete ::field)
+
+;; security advisory events
+
+(mr/def :event/security-advisory-match
+ [:map {:closed true}
+ [:object [:map
+ [:advisory_id :string]
+ [:severity [:enum :critical :high :medium :low]]
+ [:title :string]
+ [:description :string]
+ [:match_status [:enum :active :error]]
+ [:advisory_url {:optional true} [:maybe :string]]
+ [:remediation :string]
+ [:affected_versions [:sequential :map]]]]])
diff --git a/src/metabase/models/interface.clj b/src/metabase/models/interface.clj
index 68a48692572..f483a45bbd4 100644
--- a/src/metabase/models/interface.clj
+++ b/src/metabase/models/interface.clj
@@ -9,6 +9,7 @@
(:require
[buddy.core.codecs :as codecs]
[clojure.core.memoize :as memoize]
+ [clojure.edn :as edn]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.string :as str]
@@ -241,6 +242,14 @@
{:in json-in
:out json-out-without-keywordization})
+(def transform-edn
+ "Transform that stores Clojure data as EDN strings. Preserves keywords, sets, and other
+ types that JSON cannot represent. Strings are assumed to already be EDN and passed through."
+ {:in (fn [v] (cond (nil? v) nil
+ (string? v) v
+ :else (pr-str v)))
+ :out (fn [s] (when (string? s) (edn/read-string s)))})
+
(mu/defn assert-enum
"Assert that a value is one of the values in `enum`."
[enum :- [:set :any]
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 6ad0775788c..1dac8950d36 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -100,6 +100,7 @@
:model/Revision metabase.revisions.models.revision
:model/SearchIndexMetadata metabase.search.models.search-index-metadata
:model/Secret metabase.secrets.models.secret
+ :model/SecurityAdvisory metabase-enterprise.security-center.models.security-advisory
:model/Segment metabase.segments.models.segment
:model/SemanticSearchTokenTracking metabase-enterprise.semantic-search.models.token-tracking
:model/Session metabase.session.models.session
diff --git a/src/metabase/notification/payload/impl/system_event.clj b/src/metabase/notification/payload/impl/system_event.clj
index f8ee0ce5dbe..db777e3ccd8 100644
--- a/src/metabase/notification/payload/impl/system_event.clj
+++ b/src/metabase/notification/payload/impl/system_event.clj
@@ -4,6 +4,7 @@
[metabase.appearance.core :as appearance]
[metabase.auth-identity.core :as auth-identity]
[metabase.channel.email.messages :as messages]
+ [metabase.channel.urls :as urls]
[metabase.notification.payload.core :as notification.payload]
[metabase.session.core :as session]
[metabase.sso.core :as sso]
@@ -40,6 +41,22 @@
:event/user-invited
{:user_invited_email_subject (trs "You''re invited to join {0}''s {1}" (appearance/site-name) (messages/app-name-trs))
:user_invited_join_url (join-url user-id (when from-setup "/admin/databases/create"))}
+ :event/security-advisory-match
+ (let [{:keys [severity match_status]} (:object event-info)]
+ {:severity_label (case severity
+ :critical (trs "Critical")
+ :high (trs "High")
+ :medium (trs "Medium")
+ :low (trs "Low"))
+ :severity_color (case severity
+ :critical "#E65050"
+ :high "#F0830E"
+ :medium "#F0C431"
+ :low "#509EE3")
+ :status_label (case match_status
+ :active (trs "Active")
+ :error (trs "Error"))
+ :security_center_url (urls/security-center-url)})
{})))
(mu/defmethod notification.payload/payload :notification/system-event
diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.clj
index ba77e268b42..b2583195418 100644
--- a/src/metabase/premium_features/core.clj
+++ b/src/metabase/premium_features/core.clj
@@ -24,6 +24,7 @@
assert-has-feature
assert-has-any-features
ee-feature-error
+ is-trial?
has-any-features?
has-feature?
log-enabled?
@@ -33,6 +34,7 @@
quotas
TokenStatus
clear-cache!
+ token-check-url
transform-stats]
(metabase.premium-features.settings
@@ -87,6 +89,7 @@
hide-embed-branding?
is-hosted?
premium-embedding-token
+ security-center-enabled?
site-uuid-for-premium-features-token-checks
table-data-editing?
token-features
diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.clj
index 43b8b205db3..cff6a6178cf 100644
--- a/src/metabase/premium_features/settings.clj
+++ b/src/metabase/premium_features/settings.clj
@@ -1,6 +1,7 @@
(ns metabase.premium-features.settings
"Impls for settings that need to fetch token status live in [[metabase.premium-features.token-check]]."
(:require
+ [metabase.app-db.core :as mdb]
[metabase.config.core :as config]
[metabase.settings.core :as setting :refer [defsetting]]
[metabase.util.i18n :refer [deferred-tru]]))
@@ -292,6 +293,18 @@
"Should we enable the Library?"
:library)
+(define-premium-feature security-center-enabled?
+ "True if the current instance has Security Center access.
+ Requires the `:admin-security-center` feature flag, a non-trial subscription,
+ and a self-hosted instance."
+ :admin-security-center
+ :getter (fn []
+ (and (has-feature? :admin-security-center)
+ (not (is-hosted?))
+ (not ((requiring-resolve 'metabase.premium-features.token-check/is-trial?)))
+ (or config/is-test? config/is-e2e?
+ (not= (mdb/db-type) :h2)))))
+
(define-premium-feature ^{:added "0.58.0"} enable-tenants?
"Should the multi-tenant feature be enabled?"
:tenants)
@@ -317,7 +330,8 @@
:ai-controls)
(defn- -token-features []
- {:advanced_permissions (enable-advanced-permissions?)
+ {:admin_security_center (security-center-enabled?)
+ :advanced_permissions (enable-advanced-permissions?)
:attached_dwh (has-attached-dwh?)
:audit_app (enable-audit-app?)
:cache_granular_controls (enable-cache-granular-controls?)
diff --git a/src/metabase/premium_features/token_check.clj b/src/metabase/premium_features/token_check.clj
index 58669aded71..33a3c2d58bb 100644
--- a/src/metabase/premium_features/token_check.clj
+++ b/src/metabase/premium_features/token_check.clj
@@ -667,6 +667,12 @@
(when-not (some has-feature? feature-flag)
(throw (ee-feature-error feature-name))))
+(defn is-trial?
+ "True if the current premium token is a trial subscription.
+ Returns false if there is no token or the status cannot be fetched."
+ []
+ (-> (-token-status) :trial boolean))
+
(defn log-enabled?
"Returns true when we should record audit data into the audit log."
[]
diff --git a/src/metabase/testing_api/api.clj b/src/metabase/testing_api/api.clj
index 282a70d3a4d..c3cc41c7b96 100644
--- a/src/metabase/testing_api/api.clj
+++ b/src/metabase/testing_api/api.clj
@@ -263,6 +263,31 @@
(-> (lib-be/application-database-metadata-provider database)
(lib/test-query query-spec)))
+(def ^:private TestAdvisory
+ "Schema for a single advisory in the testing seed endpoint."
+ [:map
+ [:advisory_id ms/NonBlankString]
+ [:title ms/NonBlankString]
+ [:severity [:enum "critical" "high" "medium" "low"]]
+ [:description ms/NonBlankString]
+ [:advisory_url {:optional true} [:maybe ms/NonBlankString]]
+ [:remediation ms/NonBlankString]
+ [:affected_versions [:sequential [:map [:min :string] [:fixed :string]]]]
+ [:matching_query {:optional true} [:maybe [:map-of :keyword :string]]]
+ [:match_status [:enum "unknown" "active" "resolved" "not_affected" "error"]]
+ [:published_at :any]
+ [:updated_at :any]])
+
+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
+(api.macros/defendpoint :post "/security-advisories"
+ "Nuke all existing security advisories and insert the provided ones."
+ [_route-params
+ _query-params
+ {:keys [advisories]} :- [:map
+ [:advisories [:sequential TestAdvisory]]]]
+ (t2/delete! :model/SecurityAdvisory)
+ (t2/insert-returning-instances! :model/SecurityAdvisory advisories))
+
(api.macros/defendpoint :post "/native-query" :- ::lib.schema/query
"Creates a native query from a test query spec."
[_route-params
diff --git a/test/metabase/analytics/stats_test.clj b/test/metabase/analytics/stats_test.clj
index d1612aea300..2618800cfc1 100644
--- a/test/metabase/analytics/stats_test.clj
+++ b/test/metabase/analytics/stats_test.clj
@@ -572,7 +572,8 @@
:metabase-ai-managed
:cloud-custom-smtp
:session-timeout-config
- :sso-oidc})
+ :sso-oidc
+ :admin-security-center})
(deftest every-feature-is-accounted-for-test
(testing "Is every premium feature either tracked under the :features key, or intentionally excluded?"
diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.clj
index a29cc946ec4..ac9a9b43cd2 100644
--- a/test/metabase/cmd/copy_test.clj
+++ b/test/metabase/cmd/copy_test.clj
@@ -50,6 +50,7 @@
:model/RemoteSyncTask
:model/ReplacementRun
:model/SearchIndexMetadata
+ :model/SecurityAdvisory
:model/SemanticSearchTokenTracking
:model/SupportAccessGrantLog
:model/TaskHistory