The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
fix: allow dashboard caching in read-only mode (#70511)
Edward Paget6d84d80c06e9
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex bda3cb4caf5..d26456b5404 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -276,6 +276,7 @@configeventsmodels+ permissionspremium-featuresrequestsettingsdiff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/cache_api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/cache_api_test.cljnew file mode 100644index 00000000000..b188b4a9022--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/cache_api_test.clj@@ -0,0 +1,40 @@+(ns metabase-enterprise.remote-sync.cache-api-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.remote-sync.settings :as rs-settings]+ [metabase.test :as mt]))++(deftest cache-policy-on-read-only-remote-synced-dashboard-test+ (testing "Setting a cache policy on a dashboard in a remote-synced collection should succeed even when remote-sync-type is read-only"+ (mt/with-model-cleanup [:model/CacheConfig]+ (mt/with-premium-features #{:cache-granular-controls}+ (mt/with-temporary-setting-values [rs-settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Remote-Synced Collection"+ :is_remote_synced true}+ :model/Dashboard {dash-id :id} {:name "Synced Dashboard"+ :collection_id coll-id}]+ (is (=? {:id pos-int?}+ (mt/user-http-request :crowberto :put 200 "cache/"+ {:model "dashboard"+ :model_id dash-id+ :strategy {:type "nocache"}})))))))))++(deftest can-set-cache-policy-hydrated-on-dashboard-test+ (testing "GET /api/dashboard/:id includes can_set_cache_policy in the response"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}+ :model/Dashboard {dash-id :id} {:name "Test Dashboard"+ :collection_id coll-id}]+ (let [response (mt/user-http-request :crowberto :get 200 (format "dashboard/%d" dash-id))]+ (is (contains? response :can_set_cache_policy))+ (is (true? (:can_set_cache_policy response))))))+ (testing "can_set_cache_policy is true even when can_write is false (remote-synced, read-only)"+ (mt/with-temporary-setting-values [rs-settings/remote-sync-type :read-only]+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Remote-Synced Collection"+ :is_remote_synced true}+ :model/Dashboard {dash-id :id} {:name "Synced Dashboard"+ :collection_id coll-id}]+ (let [response (mt/user-http-request :crowberto :get 200 (format "dashboard/%d" dash-id))]+ (is (false? (:can_write response))+ "can_write should be false for remote-synced dashboards in read-only mode")+ (is (true? (:can_set_cache_policy response))+ "can_set_cache_policy should be true even when can_write is false"))))))diff --git a/frontend/src/metabase-types/api/dashboard.ts b/frontend/src/metabase-types/api/dashboard.tsindex d70c1dbe23c..de9272cb850 100644--- a/frontend/src/metabase-types/api/dashboard.ts+++ b/frontend/src/metabase-types/api/dashboard.ts@@ -65,6 +65,7 @@ export interface Dashboard {can_write: boolean;can_restore: boolean;can_delete: boolean;+ can_set_cache_policy?: boolean;cache_ttl: number | null;"last-edit-info": {id: number;diff --git a/frontend/src/metabase-types/api/mocks/dashboard.ts b/frontend/src/metabase-types/api/mocks/dashboard.tsindex 7fe393174c9..5b7435482c2 100644--- a/frontend/src/metabase-types/api/mocks/dashboard.ts+++ b/frontend/src/metabase-types/api/mocks/dashboard.ts@@ -24,6 +24,7 @@ export const createMockDashboard = (opts?: Partial<Dashboard>): Dashboard => ({can_write: true,can_restore: false,can_delete: false,+ can_set_cache_policy: true,description: "",cache_ttl: null,"last-edit-info": {diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsxindex 9b6595f192f..8b15331fa65 100644--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx@@ -11,7 +11,7 @@ import { getIsSharing as getIsDashboardSubscriptionSidebarOpen } from "metabase/import { useDispatch, useSelector } from "metabase/lib/redux";import { DashboardSubscriptionMenuItem } from "metabase/notifications/NotificationsActionsMenu/DashboardSubscriptionMenuItem";import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";-import { PLUGIN_MODERATION } from "metabase/plugins";+import { PLUGIN_CACHING, PLUGIN_MODERATION } from "metabase/plugins";import { Icon, Menu } from "metabase/ui";type DashboardActionMenuProps = {@@ -82,6 +82,9 @@ const DashboardActionMenuInner = ({return null;}+ const canConfigureCaching =+ dashboard.can_set_cache_policy && PLUGIN_CACHING.isGranularCachingEnabled();+return (<Menu position="bottom-end" opened={opened} onChange={setOpened}><Menu.Target>@@ -117,19 +120,17 @@ const DashboardActionMenuInner = ({{t`Enter fullscreen`}</Menu.Item>- {canEdit && (- <>- <Menu.Item- leftSection={<Icon name="gear" />}- onClick={openSettingsSidebar}- >- {t`Edit settings`}- </Menu.Item>-- {moderationItems}- </>+ {(canEdit || canConfigureCaching) && (+ <Menu.Item+ leftSection={<Icon name="gear" />}+ onClick={openSettingsSidebar}+ >+ {t`Edit settings`}+ </Menu.Item>)}+ {canEdit && moderationItems}+{canEdit && (<><Menu.Divider />diff --git a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsxindex 55008e3b3a2..da5e35cce8b 100644--- a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx@@ -82,7 +82,9 @@ const DashboardSidesheetBody = ({const canWrite = dashboard.can_write && !dashboard.archived;const isCacheable = isDashboardCacheable(dashboard);- const showCaching = canWrite && PLUGIN_CACHING.isGranularCachingEnabled();+ const showCaching =+ (dashboard.can_set_cache_policy ?? canWrite) &&+ PLUGIN_CACHING.isGranularCachingEnabled();if (dashboard.archived) {return null;diff --git a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/premium.unit.spec.ts b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/premium.unit.spec.tsindex db76566d439..b09407b5c26 100644--- a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/premium.unit.spec.ts+++ b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/premium.unit.spec.ts@@ -55,6 +55,36 @@ describe("DashboardSettingsSidebar > premium enterprise", () => {expect(await screen.findByText("Caching settings")).toBeInTheDocument();});+ it("should render caching section when can_set_cache_policy is true but can_write is false", async () => {+ await setup({+ dashboard: createMockDashboard({+ can_write: false,+ can_set_cache_policy: true,+ }),+ settings: createMockSettings({+ "token-features": createMockTokenFeatures(tokenFeatures),+ }),+ enterprisePlugins: ["audit_app", "caching"],+ });++ expect(await screen.findByText("Caching")).toBeInTheDocument();+ });++ it("should not render caching section when can_set_cache_policy is false", async () => {+ await setup({+ dashboard: createMockDashboard({+ can_write: true,+ can_set_cache_policy: false,+ }),+ settings: createMockSettings({+ "token-features": createMockTokenFeatures(tokenFeatures),+ }),+ enterprisePlugins: ["audit_app", "caching"],+ });++ expect(screen.queryByText("Caching")).not.toBeInTheDocument();+ });+it("should hide history for instance analytics dashboard", async () => {await setup({dashboard: createMockDashboard({diff --git a/src/metabase/cache/api.clj b/src/metabase/cache/api.cljindex bf0c78918af..78b2da4a1e8 100644--- a/src/metabase/cache/api.clj+++ b/src/metabase/cache/api.clj@@ -4,6 +4,7 @@[metabase.api.macros :as api.macros][metabase.cache.models.cache-config :as cache-config][metabase.config.core :as config]+ [metabase.models.interface :as mi][metabase.premium-features.core :as premium-features][metabase.request.core :as request][metabase.util.cron :as u.cron]@@ -97,6 +98,35 @@"question" :model/Card):id [:in ids]))))+(mr/def ::cache-config-item+ [:map+ [:model cache-config/CachingModel]+ [:model_id ms/IntGreaterThanOrEqualToZero]+ [:strategy [:map [:type :keyword]]]+ [:name {:optional true} [:maybe :string]]+ [:collection {:optional true} [:maybe [:map+ [:id ms/PositiveInt]+ [:name [:maybe :string]]+ [:authority_level {:optional true} [:maybe :string]]+ [:type {:optional true} [:maybe :string]]]]]])++(mr/def ::cache-config-list-response+ [:map+ [:data [:sequential ::cache-config-item]]+ [:total {:optional true} ms/IntGreaterThanOrEqualToZero]+ [:limit {:optional true} [:maybe ms/PositiveInt]]+ [:offset {:optional true} [:maybe ms/IntGreaterThanOrEqualToZero]]])++(mr/def ::cache-config-store-response+ [:map [:id ms/PositiveInt]])++(mr/def ::cache-invalidate-response+ [:map+ [:status [:enum 200 404]]+ [:body [:map+ [:count :int]+ [:message :string]]]])+(defn- check-cache-access [model id](if (or (nil? id);; sometimes its a sequence and we're going to check for settings access anyway@@ -104,17 +134,11 @@(zero? id));; if you're not accessing a concrete entity, you have to be an admin(api/check-superuser)- (api/write-check (case model- "database" :model/Database- "dashboard" :model/Dashboard- "question" :model/Card)- id)))--;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to-;; use our API + we will need it when we make auto-TypeScript-signature generation happen-;;-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}-(api.macros/defendpoint :get "/"+ ;; Use CacheConfig's can-write? which checks collection permissions directly,+ ;; bypassing the remote-sync content lock on Dashboards/Cards.+ (api/check-403 (mi/can-write? (t2/instance :model/CacheConfig {:model model :model_id id})))))++(api.macros/defendpoint :get "/" :- ::cache-config-list-response"Return cache configuration. Supports pagination via `limit` and `offset` query parameters,and sorting via `sort_column` and `sort_direction`."[_route-params@@ -143,11 +167,7 @@:offset offset}{:data data})))-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to-;; use our API + we will need it when we make auto-TypeScript-signature generation happen-;;-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}-(api.macros/defendpoint :put "/"+(api.macros/defendpoint :put "/" :- ::cache-config-store-response"Store cache configuration."[_route-params_query-params@@ -159,11 +179,7 @@(check-cache-access model model_id){:id (cache-config/store! api/*current-user-id* config)})-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to-;; use our API + we will need it when we make auto-TypeScript-signature generation happen-;;-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}-(api.macros/defendpoint :delete "/"+(api.macros/defendpoint :delete "/" :- :nil"Delete cache configurations."[_route-params_query-params@@ -175,11 +191,7 @@(cache-config/delete! api/*current-user-id* model model_id)nil)-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to-;; use our API + we will need it when we make auto-TypeScript-signature generation happen-;;-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}-(api.macros/defendpoint :post "/invalidate"+(api.macros/defendpoint :post "/invalidate" :- ::cache-invalidate-response"Invalidate cache entries.Use it like `/api/cache/invalidate?database=1&dashboard=15` (any number of database/dashboard/question can bediff --git a/src/metabase/cache/models/cache_config.clj b/src/metabase/cache/models/cache_config.cljindex 6945513cdbf..c1160ec09b0 100644--- a/src/metabase/cache/models/cache_config.clj+++ b/src/metabase/cache/models/cache_config.clj@@ -6,6 +6,7 @@[metabase.app-db.core :as app-db][metabase.events.core :as events][metabase.models.interface :as mi]+ [metabase.permissions.core :as perms][metabase.util :as u][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]@@ -36,6 +37,56 @@:config mi/transform-json:state mi/transform-json})+(defn- target-collection-id+ "Get the collection_id for the target entity of a CacheConfig."+ [{:keys [model model_id]}]+ (case model+ "dashboard" (:collection_id (t2/select-one [:model/Dashboard :collection_id] :id model_id))+ "question" (:collection_id (t2/select-one [:model/Card :collection_id] :id model_id))+ nil))++(defmethod mi/can-write? :model/CacheConfig+ ([instance]+ (case (:model instance)+ "root" (mi/superuser?)+ "database" (mi/can-write? :model/Database (:model_id instance))+ ("dashboard" "question")+ (mi/current-user-has-full-permissions?+ (perms/perms-objects-set-for-parent-collection+ {:collection_id (target-collection-id instance)}+ :write))))+ ([_model pk]+ (mi/can-write? (t2/select-one :model/CacheConfig pk))))++(defmethod mi/can-read? :model/CacheConfig+ ([instance]+ (case (:model instance)+ "root" (mi/superuser?)+ "database" (mi/can-read? :model/Database (:model_id instance))+ "dashboard" (mi/can-read? :model/Dashboard (:model_id instance))+ "question" (mi/can-read? :model/Card (:model_id instance))))+ ([_model pk]+ (mi/can-read? (t2/select-one :model/CacheConfig pk))))++(defn- can-set-cache-policy?+ "Check if the current user can set a cache policy for an entity.+ Uses collection permissions directly, bypassing remote-sync content lock."+ [{model-id :id :as instance}]+ (mi/can-write? (t2/instance :model/CacheConfig {:model (-> (t2/model instance)+ name+ u/lower-case-en)+ :model_id model-id})))++(methodical/defmethod t2/batched-hydrate [:perms/use-parent-collection-perms :can_set_cache_policy]+ [_model k models]+ (mi/instances-with-hydrated-data+ models k+ #(into {}+ (map (juxt :id can-set-cache-policy?))+ (t2/hydrate (remove nil? models) :collection))+ :id+ {:default false}))+(defn- audit-caching-change! [user-id id prev new](events/publish-event!:event/cache-config-updatediff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.cljindex 6c30b3db568..0866864a50b 100644--- a/src/metabase/dashboards_rest/api.clj+++ b/src/metabase/dashboards_rest/api.clj@@ -113,6 +113,7 @@:tabs:collection_authority_level:can_write+ :can_set_cache_policy:param_fields:is_remote_synced[:moderation_reviews :moderator_details]