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
Make action writes admin-only (#85285)
Alexander Polyankin79c61b5222b8
diff --git a/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js b/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.jsindex b6d6ea557cf..311383d6941 100644--- a/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js+++ b/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js@@ -1005,8 +1005,6 @@ describe(cy.icon("pencil").click();});- cy.wait("@getModel");-cy.findAllByRole("dialog").filter(":visible").within(() => {@@ -1069,8 +1067,6 @@ function createDashboardWithActionButton({if (hideField) {cy.findByRole("dialog").within(() => {cy.icon("pencil").click();-- cy.wait("@getModel");});cy.findAllByRole("dialog")diff --git a/e2e/test/scenarios/actions/model-actions.cy.spec.js b/e2e/test/scenarios/actions/model-actions.cy.spec.jsindex 5544dc7896b..23420dd0eee 100644--- a/e2e/test/scenarios/actions/model-actions.cy.spec.js+++ b/e2e/test/scenarios/actions/model-actions.cy.spec.js@@ -151,11 +151,11 @@ describe(.should("be.visible");openActionMenuFor("Delete Order");- H.popover().findByText("Archive").click();+ H.popover().findByText("Delete").click();H.modal().within(() => {- cy.findByText("Archive Delete Order?").should("be.visible");- cy.findByRole("button", { name: "Archive" }).click();+ cy.findByText("Delete Delete Order?").should("be.visible");+ cy.findByRole("button", { name: "Delete" }).click();});cy.findByRole("listitem", { name: "Delete Order" }).should("not.exist");@@ -212,7 +212,7 @@ describe(openActionMenuFor(SAMPLE_QUERY_ACTION.name);H.popover().within(() => {cy.findByText("View").should("be.visible");- cy.findByText("Archive").should("not.exist");+ cy.findByText("Delete").should("not.exist");cy.findByText("View").click();});@@ -237,7 +237,7 @@ describe(cy.findByLabelText("Success message").should("be.disabled");});- cy.signIn("normal");+ cy.signInAsAdmin();cy.reload();// Check can pick between all databases@@ -250,9 +250,7 @@ describe(cy.findByText("QA Postgres12").should("be.visible");});- cy.signInAsAdmin();H.setActionsEnabledForDB(SAMPLE_DB_ID, false);- cy.signIn("normal");cy.reload();// Check can only see the action databasediff --git a/e2e/test/scenarios/dashboard/dashcard-fetching.cy.spec.js b/e2e/test/scenarios/dashboard/dashcard-fetching.cy.spec.jsindex 5e44663bcfc..5843e9e45be 100644--- a/e2e/test/scenarios/dashboard/dashcard-fetching.cy.spec.js+++ b/e2e/test/scenarios/dashboard/dashcard-fetching.cy.spec.js@@ -68,7 +68,6 @@ describe("issue 48878", () => {cy.signInAsAdmin();H.setActionsEnabledForDB(SAMPLE_DB_ID);- cy.signInAsNormalUser();cy.intercept("POST", "/api/dataset").as("dataset");cy.intercept("POST", "/api/card").as("saveQuestion");cy.intercept("POST", "/api/action").as("createAction");@@ -82,7 +81,6 @@ describe("issue 48878", () => {// I could only reproduce this issue in Cypress when I didn't use any helpers like createQuestion, etc.it("does not crash the action button viz (metabase#48878)", () => {cy.reload();- cy.wait("@fetchCard");H.getDashboardCard(0).findByText("Click Me").should("be.visible");});@@ -141,7 +139,6 @@ describe("issue 48878", () => {});cy.button("Save").click();cy.wait("@updateDashboard");- cy.wait("@fetchCard");}function createModel({ name, query }) {diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.cljindex e9b084d4a0f..b380ea26e65 100644--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj@@ -194,3 +194,19 @@(data-perms/set-table-permission! group-id table :perms/view-data :unrestricted)(is (= ["table"] (:available_models (fetch))))(is (pos? (:total_items (fetch))))))))))))++(deftest collection-items-table-can-write-test+ (mt/with-premium-features #{:library :advanced-permissions}+ (testing "GET /api/collection/:id/items - table items have `can_write` from the table metadata permission"+ (mt/with-temp [:model/Collection collection {:type "library-data"}+ :model/Table {table-id :id} {:collection_id (u/the-id collection)+ :is_published true}]+ (let [table-item (fn [user]+ (->> (mt/user-http-request user :get 200 (str "collection/" (u/the-id collection) "/items"))+ :data+ (filter #(= "table" (:model %)))))]+ (is (=? [{:id table-id :can_write true}] (table-item :crowberto)))+ (is (=? [{:id table-id :can_write false}] (table-item :rasta)))+ (mt/with-restored-data-perms-for-group! (u/the-id (perms/all-users-group))+ (data-perms/set-table-permission! (perms/all-users-group) table-id :perms/manage-table-metadata :yes)+ (is (=? [{:id table-id :can_write true}] (table-item :rasta)))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/search_test.cljindex 5407b91e2ba..e757d1514ec 100644--- a/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj@@ -276,3 +276,26 @@(is (contains? result-ids visible-metric)))(testing "metric in no-access subcollection is hidden"(is (not (contains? result-ids hidden-metric)))))))))))))++(deftest published-table-can-write-test+ (mt/with-premium-features #{:library :advanced-permissions}+ (testing "Table results have `can_write` from the table metadata permission"+ (let [search-term (random-name)]+ (mt/with-temp [:model/Collection {coll-id :id} {:type "library-data"}+ :model/Table {table-id :id} {:name (str search-term " published")+ :is_published true+ :collection_id coll-id}]+ (perms/grant-collection-read-permissions! (perms/all-users-group) coll-id)+ (doseq [engine (test-engines)]+ (search/reindex! {:async? false :in-place? true})+ (let [table-result (fn [user]+ (->> (mt/user-http-request user :get 200 "search"+ :q search-term :models "table" :search_engine engine)+ :data+ (filter #(= table-id (:id %)))))]+ (testing engine+ (is (=? [{:can_write true}] (table-result :crowberto)))+ (is (=? [{:can_write false}] (table-result :rasta)))+ (mt/with-restored-data-perms-for-group! (:id (perms/all-users-group))+ (data-perms/set-table-permission! (perms/all-users-group) table-id :perms/manage-table-metadata :yes)+ (is (=? [{:can_write true}] (table-result :rasta))))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.cljindex 7113f031291..2aaca9cf0d2 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj@@ -1040,17 +1040,15 @@(is (false? (remote-sync.object/dirty?)))(is (not (t2/exists? :model/RemoteSyncObject :model_type "Action")))))))-(deftest push-tracks-archiving-an-action-test- (testing "GHY-4722: archiving an action removes its file on the next push, and unarchiving it writes the file back"+(deftest push-tracks-deleting-an-action-test+ (testing "deleting a model's action removes its file on the next push"(do-with-pushed-model-actions!(fn [{:keys [model push! repo-file]}](let [action-id (t2/select-one-pk :model/Action :model_id (:id model) :name "Rename Venue")]- (mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived true})+ (is (some? (repo-file "collections/main/synced/rename_venue.yaml")))+ (mt/user-http-request :crowberto :delete 204 (str "action/" action-id))(is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "collections/main/synced/rename_venue.yaml")))- (mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived false})- (is (remote-sync.task/successful? (push!)))- (is (some? (repo-file "collections/main/synced/rename_venue.yaml"))))))))+ (is (nil? (repo-file "collections/main/synced/rename_venue.yaml"))))))))(deftest push-tracks-moving-an-action-between-models-test(testing "GHY-4722: moving an action to a model outside the synced collections removes its file on the next push, and moving it back writes the file again"@@ -2406,11 +2404,11 @@"no NEW RemoteSyncTask row should be created when the guard fires")))))))(deftest archiving-a-synced-model-with-actions-test- (testing "a model in a synced collection can be archived although it has actions, which are archived with it"+ (testing "a model in a synced collection can be archived although it has actions, which are deleted with it"(mt/with-temporary-setting-values [remote-sync-type :read-write](mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :is_remote_synced true :location "/"}:model/Card {model-id :id} {:type :model :collection_id synced-id:dataset_query (mt/mbql-query venues)}:model/Action {action-id :id} {:type :query :name "Rename" :model_id model-id}](mt/user-http-request :crowberto :put 200 (str "card/" model-id) {:archived true})- (is (true? (t2/select-one-fn :archived :model/Action :id action-id)))))))+ (is (not (t2/exists? :model/Action :id action-id)))))))diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/actions_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/actions_test.cljnew file mode 100644index 00000000000..ae16032c98e--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/sandbox/actions_test.clj@@ -0,0 +1,42 @@+(ns metabase-enterprise.sandbox.actions-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.test :as met]+ [metabase.actions.test-util :as actions.tu]+ [metabase.test :as mt]))++(def ^:private sandboxed-message+ "You can't run actions on this database because row and column security applies to your data access.")++(defn- execute! [user expected-status action-id]+ (mt/user-http-request user :post expected-status (format "action/%s/execute" action-id)+ {:parameters {:id 1 :name "European"}}))++(defn- do-with-query-and-implicit-actions! [f]+ (mt/with-actions-enabled+ (mt/with-actions [{query-action-id :action-id} {}+ {implicit-action-id :action-id} {:type :implicit :kind "row/update"}]+ (f query-action-id implicit-action-id))))++(deftest unsandboxed-users-run-actions-test+ (testing "Without a sandbox a non-admin runs query and implicit actions"+ (mt/with-actions-test-data+ (do-with-query-and-implicit-actions!+ (fn [query-action-id implicit-action-id]+ (is (=? {:rows-affected 1} (execute! :rasta 200 query-action-id)))+ (is (=? {:rows-updated 1} (execute! :rasta 200 implicit-action-id))))))))++(deftest sandboxed-users-cannot-run-actions-test+ (testing "A user with a sandbox on another table of a database can't run any action on it"+ (actions.tu/with-actions-test-data-tables #{"categories" "venues"}+ (mt/with-actions-test-data+ (met/with-gtaps-for-all-users! {:gtaps {:venues {}}}+ (do-with-query-and-implicit-actions!+ (fn [query-action-id implicit-action-id]+ (testing "a query action, whose endpoint reports a permission error with a generic message"+ (is (=? {:message "You don't have permissions to do that."}+ (execute! :rasta 403 query-action-id))))+ (testing "an implicit action"+ (is (= sandboxed-message (execute! :rasta 403 implicit-action-id))))+ (testing "an admin in a sandboxed group"+ (is (=? {:rows-affected 1} (execute! :crowberto 200 query-action-id)))))))))))diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/use-library-search-results.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/use-library-search-results.tsindex 090e1ecde36..0bee4a59865 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/use-library-search-results.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/hooks/use-library-search-results/use-library-search-results.ts@@ -86,6 +86,7 @@ function createSearchResultItem(archived: result.archived ?? false,collection_position: result.collection_position,"last-edit-info": result["last-edit-info"],+ can_write: result.can_write ?? false,},};}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.unit.spec.tsxindex 8d6d5790336..a2ae324dc80 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/pages/LibraryPage/LibraryPage.unit.spec.tsx@@ -95,6 +95,7 @@ const createTableItem = (model: "table",database_id: 1,collection_id: collectionId,+ can_write: true,});const ORDERS = createTableItem(10, "Orders");diff --git a/frontend/src/metabase-lib/v1/actions/utils.ts b/frontend/src/metabase-lib/v1/actions/utils.tsindex 31db168da15..d2b0f68da68 100644--- a/frontend/src/metabase-lib/v1/actions/utils.ts+++ b/frontend/src/metabase-lib/v1/actions/utils.ts@@ -9,15 +9,10 @@ export const canRunAction = (return Boolean(database?.settings?.["database-enable-actions"]);};-export const canEditAction = (action: WritebackAction, model: Question) => {- if (action.model_id !== model.id()) {- return false;- }-- return model.canWriteActions();-};+export const canEditAction = (action: WritebackAction, model: Question) =>+ action.model_id === model.id() && action.can_write === true;-export const canArchiveAction = (action: WritebackAction, model: Question) => {+export const canDeleteAction = (action: WritebackAction, model: Question) => {if (action.model_id !== model.id()) {return false;}diff --git a/frontend/src/metabase-types/api/snippets.ts b/frontend/src/metabase-types/api/snippets.tsindex 64efc5f2696..28fbd6725d2 100644--- a/frontend/src/metabase-types/api/snippets.ts+++ b/frontend/src/metabase-types/api/snippets.ts@@ -20,6 +20,7 @@ export interface NativeQuerySnippet {creator?: UserInfo;collection?: Collection;+ can_write?: boolean;}export type ListSnippetsParams = {diff --git a/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx b/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsxindex b2431d48d0d..199be47a7d5 100644--- a/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx+++ b/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx@@ -19,8 +19,8 @@ import type { DataReferenceSlot } from "./types";export interface ActionCreatorProps {modelId?: CardId;- /** Whether the model accepts new actions, i.e. `Question.canWriteActions`. */- canWriteModelActions?: boolean;+ canCreateActions?: boolean;+ canWriteAction?: boolean;/*** Whether the creator is mounted as its own route. A routed creator guards* leaving with `LeaveRouteConfirmModal`; an inline one only has `beforeunload`.@@ -34,7 +34,8 @@ export interface ActionCreatorProps {export function ActionCreator({modelId,- canWriteModelActions = false,+ canCreateActions = false,+ canWriteAction = false,isRouted,dataReference,onSubmit,@@ -62,7 +63,7 @@ export function ActionCreator({const [isCallbackScheduled, scheduleCallback] = useCallbackEffect();const [isSaveModalShown, setShowSaveModal] = useState(false);- const isEditable = isNew || canWriteModelActions;+ const isEditable = isSavedAction(action) ? canWriteAction : canCreateActions;const showUnsavedChangesWarning =isEditable && isDirty && !isCallbackScheduled;diff --git a/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.tsx b/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.tsxindex 1906abd11a9..59e76196991 100644--- a/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.tsx+++ b/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.tsx@@ -41,7 +41,8 @@ export function CollectionRowMenu({const showPermissionsOption =isAdmin &&(PLUGIN_LIBRARY.isEnabled || PLUGIN_SNIPPET_FOLDERS.isEnabled) &&- collection.namespace !== "transforms";+ collection.namespace !== "transforms" &&+ collection.namespace !== "data-actions";const isRoot = isRootCollection(collection);diff --git a/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx b/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsxindex 5c06cca11ad..65b3bbaa082 100644--- a/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx+++ b/frontend/src/metabase/common/collections/components/CollectionRowMenu/CollectionRowMenu.unit.spec.tsx@@ -148,6 +148,17 @@ describe("CollectionRowMenu", () => {expect(queryMenuItem(/Change permissions/)).not.toBeInTheDocument();});+ it("does not render permissions option for data actions folders", async () => {+ setup({ collection: { namespace: "data-actions" } });++ await userEvent.click(+ screen.getByRole("button", { name: "Folder options" }),+ );++ expect(getMenuItem(/Edit folder details/)).toBeInTheDocument();+ expect(queryMenuItem(/Change permissions/)).not.toBeInTheDocument();+ });+it("archives a collection after confirmation", async () => {const collection = createMockCollection({ id: 1, name: "Archived soon" });setupUpdateCollectionEndpoint(collection);diff --git a/frontend/src/metabase/dashboard/components/ActionSidebar/ActionSidebar.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ActionSidebar/ActionSidebar.unit.spec.tsxindex 4164c7880e5..10a69b19742 100644--- a/frontend/src/metabase/dashboard/components/ActionSidebar/ActionSidebar.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/ActionSidebar/ActionSidebar.unit.spec.tsx@@ -6,6 +6,7 @@ import {setupDatabasesEndpoints,setupSearchEndpoints,} from "__support__/server-mocks";+import { createMockState } from "__support__/state";import {renderWithProviders,screen,@@ -22,6 +23,7 @@ import {createMockDashboardCard,createMockDatabase,createMockQueryAction,+ createMockUser,} from "metabase-types/api/mocks";import { ActionSidebar } from "./ActionSidebar";@@ -71,6 +73,11 @@ const setup = ({><ActionSidebar /></MockDashboardContext>,+ {+ storeInitialState: createMockState({+ currentUser: createMockUser({ is_superuser: true }),+ }),+ },);return { vizUpdateSpy, closeSpy };diff --git a/frontend/src/metabase/dashboard/components/ActionViz/Action.tsx b/frontend/src/metabase/dashboard/components/ActionViz/Action.tsxindex 45c3a60eefc..1648d0364f5 100644--- a/frontend/src/metabase/dashboard/components/ActionViz/Action.tsx+++ b/frontend/src/metabase/dashboard/components/ActionViz/Action.tsx@@ -2,7 +2,6 @@ import { useCallback, useMemo } from "react";import { t } from "ttag";import { getActionDisplayType } from "metabase/actions/utils";-import { skipToken, useGetCardQuery } from "metabase/api";import {executeRowAction,reloadDashboardCards,@@ -12,7 +11,6 @@ import {getParameterValues,} from "metabase/dashboard/selectors";import { getActionIsEnabledInDatabase } from "metabase/dashboard/utils";-import { useQuestionFromCard } from "metabase/metadata-store";import { connect } from "metabase/redux";import type { Dispatch, State } from "metabase/redux/store";import { Box, Tooltip } from "metabase/ui";@@ -59,11 +57,6 @@ const ActionComponent = ({parameterValues,isEditingDashcard,}: ActionProps) => {- const { data: card } = useGetCardQuery(- dashcard.action?.model_id ? { id: dashcard.action.model_id } : skipToken,- );- const model = useQuestionFromCard(card);-const actionDisplayType = getActionDisplayType(settings?.actionDisplayType,dashcard.action,@@ -102,8 +95,6 @@ const ActionComponent = ({shouldConfirm);- const canWrite = Boolean(model?.canWriteActions());-const onSubmit = useCallback(async (parameters: ParametersForActionExecution) => {const result = await executeRowAction({@@ -136,7 +127,7 @@ const ActionComponent = ({isSettings={isSettings}shouldDisplayButton={shouldDisplayButton}isEditingDashcard={isEditingDashcard}- canEditAction={canWrite}+ canEditAction={dashcard.action?.can_write === true}onSubmit={onSubmit}/>);@@ -156,11 +147,13 @@ function ActionFn(props: ActionProps) {const { action } = dashcard;const hasActionsEnabled = getActionIsEnabledInDatabase(dashcard);+ const isArchived = action?.archived === true;- if (!action || !hasActionsEnabled) {+ if (!action || !hasActionsEnabled || isArchived) {const tooltip = getErrorTooltip({hasActionAssigned: !!action,hasActionsEnabled,+ isArchived,});return (@@ -185,14 +178,20 @@ function ActionFn(props: ActionProps) {function getErrorTooltip({hasActionAssigned,hasActionsEnabled,+ isArchived,}: {hasActionAssigned: boolean;hasActionsEnabled: boolean;+ isArchived: boolean;}) {if (!hasActionAssigned) {return t`No action assigned`;}+ if (isArchived) {+ return t`This action is archived`;+ }+if (!hasActionsEnabled) {return t`Actions are not enabled for this database`;}diff --git a/frontend/src/metabase/dashboard/components/ActionViz/Action.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ActionViz/Action.unit.spec.tsxindex f036d2a1506..a86acbe6d46 100644--- a/frontend/src/metabase/dashboard/components/ActionViz/Action.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/ActionViz/Action.unit.spec.tsx@@ -50,6 +50,7 @@ const ACTION = createMockQueryAction({name: "My Awesome Action",database_id: DATABASE_ID,model_id: ACTION_MODEL_ID,+ can_write: true,parameters: [createMockActionParameter({id: "parameter_1",@@ -195,6 +196,18 @@ describe("Actions > ActionViz > Action", () => {).toBeInTheDocument();});+ it("should render a disabled state for a button with an archived action", async () => {+ await setup({+ dashcard: createMockActionDashboardCard({+ action: { ...ACTION, archived: true },+ }),+ });+ expect(screen.getByRole("button")).toBeDisabled();+ expect(+ screen.getByLabelText(/this action is archived/i),+ ).toBeInTheDocument();+ });+it("should render an enabled state when the action is valid", async () => {await setup();expect(screen.getByRole("button")).toBeEnabled();@@ -316,13 +329,10 @@ describe("Actions > ActionViz > Action", () => {});});- it("should NOT allow to edit underlying action if a user does not has edit permissions for this model", async () => {+ it("should NOT allow to edit underlying action if a user can't write it", async () => {await setup({dashcard: createMockActionDashboardCard({- card: {- ...CARD,- can_write: false,- },+ action: { ...ACTION, can_write: false },}),});@@ -331,19 +341,6 @@ describe("Actions > ActionViz > Action", () => {expect(queryIcon("pencil")).not.toBeInTheDocument();});- it("should NOT allow to edit underlying action if a user does not has edit permissions for this database", async () => {- const readOnlyDB: Database = {- ...DATABASE,- native_permissions: "none",- };-- await setup({ database: readOnlyDB });-- await userEvent.click(screen.getByText("Click me"));-- expect(queryIcon("pencil")).not.toBeInTheDocument();- });-it("should allow to edit underlying action if a user has edit permissions", async () => {await setup();diff --git a/frontend/src/metabase/dashboard/components/ActionViz/ActionDashcardSettings.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ActionViz/ActionDashcardSettings.unit.spec.tsxindex 446faa3417a..e611050b79c 100644--- a/frontend/src/metabase/dashboard/components/ActionViz/ActionDashcardSettings.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/components/ActionViz/ActionDashcardSettings.unit.spec.tsx@@ -5,6 +5,7 @@ import {setupCardsEndpoints,setupSearchEndpoints,} from "__support__/server-mocks";+import { createMockState } from "__support__/state";import {renderWithProviders,screen,@@ -24,6 +25,7 @@ import {createMockImplicitCUDActions,createMockParameter,createMockQueryAction,+ createMockUser,} from "metabase-types/api/mocks";import { ActionDashcardSettings } from "./ActionDashcardSettings";@@ -80,9 +82,18 @@ const dashboard = createMockDashboard({const DEFAULT_VALUE = "default value";-const setup = (- options?: Partial<React.ComponentProps<typeof ActionDashcardSettings>>,-) => {+type SetupOpts = Partial<+ React.ComponentProps<typeof ActionDashcardSettings>+> & {+ isAdmin?: boolean;+ canWriteActions?: boolean;+};++const setup = ({+ isAdmin = true,+ canWriteActions = true,+ ...options+}: SetupOpts = {}) => {const searchItems = models.map((model) =>createMockCollectionItem({ ...model, model: "dataset" }),);@@ -90,7 +101,12 @@ const setup = (setupSearchEndpoints(searchItems);setupCardsEndpoints(models);- setupActionsEndpoints([...actions1, ...actions2, ...implicitActions]);+ setupActionsEndpoints(+ [...actions1, ...actions2, ...implicitActions].map((action) => ({+ ...action,+ can_write: canWriteActions,+ })),+ );renderWithProviders(<ActionDashcardSettings@@ -99,6 +115,11 @@ const setup = (dashcard={actionDashcard}{...options}/>,+ {+ storeInitialState: createMockState({+ currentUser: createMockUser({ is_superuser: isAdmin }),+ }),+ },);return { closeSpy };@@ -510,6 +531,24 @@ describe("ActionViz > ActionDashcardSettings", () => {).toBeInTheDocument();});+ it("doesn't offer creating or editing actions to non-admins", async () => {+ setup({+ dashcard: actionDashcardWithAction,+ isAdmin: false,+ canWriteActions: false,+ });++ await waitForLoaderToBeRemoved();+ const queryAction = await screen.findByTestId(+ `action-item-${actions2[0].name}`,+ );++ expect(+ within(queryAction).queryByRole("button", { name: "pencil icon" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("Create new action")).not.toBeInTheDocument();+ });+it("can close the modal with the done button", async () => {const { closeSpy } = setup();diff --git a/frontend/src/metabase/dashboard/components/ActionViz/ActionPicker/ActionPicker.tsx b/frontend/src/metabase/dashboard/components/ActionViz/ActionPicker/ActionPicker.tsxindex f6eac708aa9..7b3f80c9454 100644--- a/frontend/src/metabase/dashboard/components/ActionViz/ActionPicker/ActionPicker.tsx+++ b/frontend/src/metabase/dashboard/components/ActionViz/ActionPicker/ActionPicker.tsx@@ -9,7 +9,9 @@ import { EmptyState } from "metabase/common/components/EmptyState";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { useToggle } from "metabase/common/hooks/use-toggle";import CS from "metabase/css/core/index.css";+import { getUserIsAdmin } from "metabase/current-user";import { ActionCreator } from "metabase/querying/action-creator";+import { useSelector } from "metabase/redux";import {ActionIcon,Box,@@ -79,6 +81,7 @@ function ModelActionPicker({actions: WritebackAction[];currentAction?: WritebackAction;}) {+ const isAdmin = useSelector(getUserIsAdmin);const [editingActionId, setEditingActionId] = useState<number | undefined>(undefined,);@@ -99,7 +102,7 @@ function ModelActionPicker({onClick(updatedAction);};- const newActionButton = (+ const newActionButton = isAdmin && (<Buttonvariant="subtle"m="0.25rem 0.75rem"@@ -139,18 +142,20 @@ function ModelActionPicker({data-testid={`action-item-${action.name}`}><span>{action.name}</span>- <ActionIcon- variant="subtle"- onClick={(event: MouseEvent<HTMLButtonElement>) => {- // we have a click listener on the parent- event.stopPropagation();-- setEditingActionId(action.id);- toggleIsActionCreatorVisible();- }}- >- <Icon name="pencil" />- </ActionIcon>+ {action.can_write && (+ <ActionIcon+ variant="subtle"+ onClick={(event: MouseEvent<HTMLButtonElement>) => {+ // we have a click listener on the parent+ event.stopPropagation();++ setEditingActionId(action.id);+ toggleIsActionCreatorVisible();+ }}+ >+ <Icon name="pencil" />+ </ActionIcon>+ )}</Flex>))}{newActionButton}diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsxindex e84449fec25..19632ef8253 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.tsx@@ -7,6 +7,7 @@ import {type CollectionRowModalState,} from "metabase/common/collections/components/CollectionRowModal";import { ForwardRefLink } from "metabase/common/components/Link";+import { getUserIsAdmin } from "metabase/current-user";import { LibraryTreePage } from "metabase/data-studio/common/components/LibraryTreePage";import { useErrorHandling } from "metabase/data-studio/common/hooks/use-error-handling";import type { TreeItem } from "metabase/data-studio/common/types";@@ -15,7 +16,7 @@ import {isCollectionData,openNewCollectionModal,} from "metabase/data-studio/common/utils";-import { PLUGIN_LIBRARY, PLUGIN_REMOTE_SYNC } from "metabase/plugins";+import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";import { useDispatch, useSelector } from "metabase/redux";import { Button, FixedSizeIcon, Icon, Menu } from "metabase/ui";import * as Urls from "metabase/urls";@@ -40,10 +41,10 @@ export function ActionListPage() {isLoading: isLoadingDatabases,error: databasesError,} = useActionDatabases();- const canCreate = canCreateActions(databases);+ const isAdmin = useSelector(getUserIsAdmin);+ const canCreate = isAdmin && canCreateActions(databases);const {tree,- rootCollection,isLoading: isLoadingActions,error: actionsError,} = useBuildActionTree({@@ -81,9 +82,6 @@ export function ActionListPage() {to: Urls.dataStudioArchivedActions(),},],- permissionsCollection: PLUGIN_LIBRARY.isEnabled- ? rootCollection- : undefined,onOpenModal: setCollectionModal,}}renderRowMenu={renderRowMenu}diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.unit.spec.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.unit.spec.tsxindex 2fe948e3ade..d307a29b2ef 100644--- a/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ActionListPage/ActionListPage.unit.spec.tsx@@ -1,10 +1,12 @@import userEvent from "@testing-library/user-event";+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";import {setupActionsEndpoints,setupCollectionsEndpoints,setupDatabasesEndpoints,} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state";import {mockGetBoundingClientRect,@@ -18,6 +20,7 @@ import {createMockCollection,createMockDatabase,createMockQueryAction,+ createMockTokenFeatures,createMockUser,} from "metabase-types/api/mocks";@@ -26,6 +29,8 @@ import { ActionListPage } from "./ActionListPage";type SetupOpts = {databases?: Database[];actions?: WritebackAction[];+ isAdmin?: boolean;+ hasLibrary?: boolean;};const ACTIONS_DATABASE = createMockDatabase({@@ -33,7 +38,12 @@ const ACTIONS_DATABASE = createMockDatabase({settings: { "database-enable-actions": true },});-function setup({ databases = [ACTIONS_DATABASE], actions = [] }: SetupOpts) {+function setup({+ databases = [ACTIONS_DATABASE],+ actions = [],+ isAdmin = true,+ hasLibrary = false,+}: SetupOpts) {setupDatabasesEndpoints(databases);setupActionsEndpoints(actions);setupCollectionsEndpoints({@@ -46,10 +56,17 @@ function setup({ databases = [ACTIONS_DATABASE], actions = [] }: SetupOpts) {],});+ if (hasLibrary) {+ setupEnterpriseOnlyPlugin("library");+ }+renderWithProviders(<Route path="/" element={<ActionListPage />} />, {withRouter: true,storeInitialState: createMockState({- currentUser: createMockUser({ is_superuser: true }),+ currentUser: createMockUser({ is_superuser: isAdmin }),+ settings: mockSettings({+ "token-features": createMockTokenFeatures({ library: hasLibrary }),+ }),}),});}@@ -86,6 +103,17 @@ describe("ActionListPage", () => {).toEqual(["Action", "Collection"]);});+ it("does not offer non-admins to create anything", async () => {+ setup({ isAdmin: false });++ expect(+ await screen.findByText("Queries that change data"),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /New/ }),+ ).not.toBeInTheDocument();+ });+it("does not offer to create anything without an actions-enabled database, but still links to the archive", async () => {setup({databases: [@@ -113,4 +141,19 @@ describe("ActionListPage", () => {screen.getByRole("menuitem", { name: /View archived actions/ }),).toBeInTheDocument();});++ it("does not offer changing the permissions of data actions", async () => {+ setup({ hasLibrary: true });++ await userEvent.click(+ await screen.findByRole("button", { name: "Data action options" }),+ );++ expect(+ screen.getByRole("menuitem", { name: /View archived actions/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("menuitem", { name: /Change permissions/ }),+ ).not.toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.tsxindex 1a46114b00b..93ef7d06762 100644--- a/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.tsx+++ b/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.tsx@@ -168,7 +168,7 @@ function ArchivedItemMenu({}: ArchivedItemMenuProps) {const { data } = treeItem;- if (readOnly || isEmptyStateData(data)) {+ if (readOnly || isEmptyStateData(data) || !data.can_write) {return null;}diff --git a/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.unit.spec.tsx b/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.unit.spec.tsxnew file mode 100644index 00000000000..e04110abecb--- /dev/null+++ b/frontend/src/metabase/data-studio/actions/pages/ArchivedActionListPage/ArchivedActionListPage.unit.spec.tsx@@ -0,0 +1,87 @@+import {+ setupActionsEndpoints,+ setupCollectionsEndpoints,+} from "__support__/server-mocks";+import { createMockState } from "__support__/state";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+} from "__support__/ui";+import { Route } from "metabase/router";+import type { WritebackAction } from "metabase-types/api";+import {+ createMockCollection,+ createMockQueryAction,+ createMockUser,+} from "metabase-types/api/mocks";++import { ArchivedActionListPage } from "./ArchivedActionListPage";++type SetupOpts = {+ actions: WritebackAction[];+};++function setup({ actions }: SetupOpts) {+ setupActionsEndpoints(actions);+ setupCollectionsEndpoints({+ collections: [+ createMockCollection({+ id: "root",+ name: "Root",+ namespace: "data-actions",+ }),+ ],+ });++ renderWithProviders(<Route path="/" element={<ArchivedActionListPage />} />, {+ withRouter: true,+ storeInitialState: createMockState({+ currentUser: createMockUser({ is_superuser: false }),+ }),+ });+}++describe("ArchivedActionListPage", () => {+ beforeEach(() => {+ mockGetBoundingClientRect({ width: 1000, height: 1000 });+ });++ it("offers unarchiving an archived action the user can write", async () => {+ setup({+ actions: [+ createMockQueryAction({+ id: 1,+ name: "Refund order",+ collection_id: null,+ archived: true,+ can_write: true,+ }),+ ],+ });++ expect(await screen.findByText("Refund order")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Unarchive action" }),+ ).toBeInTheDocument();+ });++ it("doesn't offer unarchiving an archived action the user can't write", async () => {+ setup({+ actions: [+ createMockQueryAction({+ id: 1,+ name: "Refund order",+ collection_id: null,+ archived: true,+ can_write: false,+ }),+ ],+ });++ expect(await screen.findByText("Refund order")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Unarchive action" }),+ ).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/data-studio/actions/routes.tsx b/frontend/src/metabase/data-studio/actions/routes.tsxindex 82e7c2cbc21..3a02e078229 100644--- a/frontend/src/metabase/data-studio/actions/routes.tsx+++ b/frontend/src/metabase/data-studio/actions/routes.tsx@@ -1,3 +1,5 @@+import type { ComponentType } from "react";+import { ActionsSectionLayout } from "metabase/data-studio/app/pages/ActionsSectionLayout";import { PLUGIN_DEPENDENCIES } from "metabase/plugins";import { Route } from "metabase/router";@@ -49,11 +51,13 @@ const actionDependenciesPage = () =>Component: ActionDependenciesPage,}));-export function getDataStudioActionRoutes() {+export function getDataStudioActionRoutes(IsAdmin: ComponentType) {return (<Route path="actions" element={<ActionsSectionLayout />}><Route index lazy={actionsPage} />- <Route path="new" lazy={newActionPage} />+ <Route path="new" element={<IsAdmin />}>+ <Route index lazy={newActionPage} />+ </Route><Route path="archived" lazy={archivedActionListPage} /><Route path=":actionId" lazy={actionQueryPage} /><Route path=":actionId/edit" lazy={actionQueryPage} />diff --git a/frontend/src/metabase/data-studio/actions/routes.unit.spec.tsx b/frontend/src/metabase/data-studio/actions/routes.unit.spec.tsxindex a0c0b02596c..4d43d8fb388 100644--- a/frontend/src/metabase/data-studio/actions/routes.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/actions/routes.unit.spec.tsx@@ -1,10 +1,15 @@import { lazyLoaders } from "__support__/lazy-routes";+import { renderWithProviders, screen } from "__support__/ui";import { getDataStudioActionRoutes } from "./routes";+function AdminGuard() {+ return <div data-testid="admin-guard" />;+}+describe("data studio action routes", () => {it("resolves every page", async () => {- const loaders = lazyLoaders(getDataStudioActionRoutes());+ const loaders = lazyLoaders(getDataStudioActionRoutes(() => null));expect(loaders).toHaveLength(9);@@ -12,4 +17,13 @@ describe("data studio action routes", () => {expect((await load()).Component).toBeDefined();}});++ it("guards the new action page with the admin guard", async () => {+ renderWithProviders(getDataStudioActionRoutes(AdminGuard), {+ withRouter: true,+ initialRoute: "/actions/new",+ });++ expect(await screen.findByTestId("admin-guard")).toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.tsx b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.tsxindex e1733af96a0..65e55132a93 100644--- a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.tsx+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.tsx@@ -65,6 +65,7 @@ export function LibraryBulkActions({);const hasTables = selectedItems.some((item) => item.model === "table");+ const canWriteAll = selectedItems.every((item) => item.canWrite);// A collection can't be moved into itself or one of its descendants.const movingCollectionIds = useMemo(@@ -139,10 +140,12 @@ export function LibraryBulkActions({return (<><BulkActionBar opened={count > 0} message={message}>- <BulkActionButton onClick={() => setAction("move")}>- {t`Move`}- </BulkActionButton>- {!hasTables && (+ {canWriteAll && (+ <BulkActionButton onClick={() => setAction("move")}>+ {t`Move`}+ </BulkActionButton>+ )}+ {canWriteAll && !hasTables && (<BulkActionButton onClick={confirmTrash}>{t`Move to trash`}</BulkActionButton>diff --git a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.unit.spec.tsx b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.unit.spec.tsxindex 40bf2db690d..29ac1bf395d 100644--- a/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/common/components/LibraryTreePage/LibraryBulkActions/LibraryBulkActions.unit.spec.tsx@@ -1,6 +1,72 @@+import { renderWithProviders, screen } from "__support__/ui";+import type { SelectedItem } from "metabase/data-studio/common/hooks/use-library-bulk-selection";import { createMockCollectionItem } from "metabase-types/api/mocks";-import { isMoveDestinationDisabled } from "./LibraryBulkActions";+import {+ LibraryBulkActions,+ isMoveDestinationDisabled,+} from "./LibraryBulkActions";++type SetupOpts = {+ selectedItems: SelectedItem[];+};++function setup({ selectedItems }: SetupOpts) {+ renderWithProviders(+ <LibraryBulkActions+ selectedItems={selectedItems}+ selectionSection="actions"+ isAllTables={false}+ defaultCollectionId={undefined}+ onClear={jest.fn()}+ />,+ );+}++function createSelectedAction(+ opts: Pick<SelectedItem, "entityId" | "canWrite">,+): SelectedItem {+ return {+ key: `action-${opts.entityId}`,+ model: "action",+ section: "actions",+ sourceCollectionId: null,+ ...opts,+ };+}++describe("LibraryBulkActions", () => {+ it("offers moving and trashing when every selected item is writable", () => {+ setup({+ selectedItems: [+ createSelectedAction({ entityId: 1, canWrite: true }),+ createSelectedAction({ entityId: 2, canWrite: true }),+ ],+ });++ expect(screen.getByRole("button", { name: "Move" })).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Move to trash" }),+ ).toBeInTheDocument();+ });++ it("doesn't offer moving or trashing when a selected item isn't writable", () => {+ setup({+ selectedItems: [+ createSelectedAction({ entityId: 1, canWrite: true }),+ createSelectedAction({ entityId: 2, canWrite: false }),+ ],+ });++ expect(+ screen.queryByRole("button", { name: "Move" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Move to trash" }),+ ).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Clear" })).toBeInTheDocument();+ });+});describe("isMoveDestinationDisabled", () => {const moving = ["5"]; // collection 5 is being moveddiff --git a/frontend/src/metabase/data-studio/routes.tsx b/frontend/src/metabase/data-studio/routes.tsxindex e7f2ac70208..6a43fffa780 100644--- a/frontend/src/metabase/data-studio/routes.tsx+++ b/frontend/src/metabase/data-studio/routes.tsx@@ -112,7 +112,7 @@ export function getDataStudioRoutes(IsAdmin: RouteComponent) {</Route>{getDataStudioGlossaryRoutes()}{getDataStudioSnippetRoutes()}- {getDataStudioActionRoutes()}+ {getDataStudioActionRoutes(IsAdmin)}{PLUGIN_DATA_APPS.isEnabled &&PLUGIN_DATA_APPS.getDataStudioRoutes(IsAdmin)}{getDataStudioSettingsRoutes()}diff --git a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.tsx b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.tsxindex 87a3a19439f..a68e0b8610d 100644--- a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.tsx+++ b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.tsx@@ -7,9 +7,10 @@ import {useListActionsQuery,useListDatabasesQuery,} from "metabase/api";-import { useSetArchive } from "metabase/archive/hooks";import { Link } from "metabase/common/components/Link";import { useConfirmation } from "metabase/common/hooks/use-confirmation";+import { getUserIsAdmin } from "metabase/current-user";+import { useSelector } from "metabase/redux";import {ActionIcon,Alert,@@ -26,7 +27,7 @@ import * as Urls from "metabase/urls";import { parseTimestamp } from "metabase/utils/time-dayjs";import type Question from "metabase-lib/v1/Question";import {- canArchiveAction,+ canDeleteAction,canEditAction,canRunAction,} from "metabase-lib/v1/actions/utils";@@ -53,18 +54,13 @@ export function ModelActionDetails({ model }: ModelActionDetailsProps) {(action: WritebackAction) => deleteAction(action.id),[deleteAction],);- const archive = useSetArchive();- const onArchiveAction = useCallback(- (action: WritebackAction) =>- archive({ id: action.id, model: "action" }, true),- [archive],- );const { show: askConfirmation, modalContent: confirmationModal } =useConfirmation();const database = model.database();const hasActionsEnabled = database != null && database.hasActionsEnabled();- const canWrite = model.canWriteActions();+ const isAdmin = useSelector(getUserIsAdmin);+ const canWrite = isAdmin && model.canWriteActions();const supportsImplicitActions = model.supportsImplicitActions();const actionsSorted = useMemo(@@ -104,13 +100,13 @@ export function ModelActionDetails({ model }: ModelActionDetailsProps) {actionUrl={actionUrl}canRun={canRunAction(action, databases)}canEdit={canEditAction(action, model)}- canArchive={canArchiveAction(action, model)}- onArchive={onArchiveAction}+ canDelete={canDeleteAction(action, model)}+ onDelete={onDeleteAction}/></li>);},- [model, databases, onArchiveAction],+ [model, databases, onDeleteAction],);const newActionUrl = Urls.newAction(model.card());diff --git a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.unit.spec.tsx b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.unit.spec.tsxindex 45ef622e83e..a418fe1024d 100644--- a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.unit.spec.tsx+++ b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.unit.spec.tsx@@ -12,6 +12,7 @@ import {waitForLoaderToBeRemoved,} from "__support__/ui";import { getRoutes as getModelRoutes } from "metabase/models/routes";+import { Outlet } from "metabase/router";import type {Card,Database,@@ -54,7 +55,7 @@ async function setup({);setupModelActionsEndpoints(actions, model.id);- renderWithProviders(getModelRoutes(), {+ renderWithProviders(getModelRoutes(Outlet), {withRouter: true,initialRoute,});diff --git a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionListItem.tsx b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionListItem.tsxindex 97aee15be62..b2c4598b34a 100644--- a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionListItem.tsx+++ b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionListItem.tsx@@ -68,8 +68,8 @@ interface ModelActionListItemProps {actionUrl: string;canRun: boolean;canEdit: boolean;- canArchive: boolean;- onArchive: (action: WritebackAction) => void;+ canDelete: boolean;+ onDelete: (action: WritebackAction) => void;}export function ModelActionListItem({@@ -77,8 +77,8 @@ export function ModelActionListItem({actionUrl,canRun,canEdit,- canArchive,- onArchive,+ canDelete,+ onDelete,}: ModelActionListItemProps) {const { show: askConfirmation, modalContent: confirmationModal } =useConfirmation();@@ -87,13 +87,14 @@ export function ModelActionListItem({{ open: openExecuteModal, close: closeExecuteModal },] = useDisclosure(false);- const handleArchive = useCallback(() => {+ const handleDelete = useCallback(() => {askConfirmation({- title: t`Archive ${action.name}?`,- confirmButtonText: t`Archive`,- onConfirm: () => onArchive(action),+ title: t`Delete ${action.name}?`,+ message: t`Dashboard buttons and public forms that use this action will be removed.`,+ confirmButtonText: t`Delete`,+ onConfirm: () => onDelete(action),});- }, [action, askConfirmation, onArchive]);+ }, [action, askConfirmation, onDelete]);return (<>@@ -139,12 +140,12 @@ export function ModelActionListItem({>{canEdit ? t`Edit` : t`View`}</Menu.Item>- {canArchive && (+ {canDelete && (<Menu.Item- leftSection={<Icon name="archive" aria-hidden />}- onClick={handleArchive}+ leftSection={<Icon name="trash" aria-hidden />}+ onClick={handleDelete}>- {t`Archive`}+ {t`Delete`}</Menu.Item>)}</Menu.Dropdown>diff --git a/frontend/src/metabase/models/containers/ActionCreatorModal/ActionCreatorModal.unit.spec.tsx b/frontend/src/metabase/models/containers/ActionCreatorModal/ActionCreatorModal.unit.spec.tsxindex 8769dceccd8..cb45ff2a045 100644--- a/frontend/src/metabase/models/containers/ActionCreatorModal/ActionCreatorModal.unit.spec.tsx+++ b/frontend/src/metabase/models/containers/ActionCreatorModal/ActionCreatorModal.unit.spec.tsx@@ -6,6 +6,7 @@ import {setupDatabasesEndpoints,setupModelActionsEndpoints,} from "__support__/server-mocks";+import { createMockState } from "__support__/state";import {act,renderWithProviders,@@ -20,6 +21,7 @@ import type { Card, WritebackAction } from "metabase-types/api";import {createMockCard,createMockQueryAction,+ createMockUser,} from "metabase-types/api/mocks";import { createSampleDatabase } from "metabase-types/api/mocks/presets";@@ -36,7 +38,7 @@ function RoutedActionCreatorModal({ onClose }: { onClose: () => void }) {const MODEL = createMockCard({ id: 1, type: "model" });const MODEL_SLUG = `${MODEL.id}-${MODEL.name.toLowerCase()}`;-const ACTION = createMockQueryAction({ model_id: MODEL.id });+const ACTION = createMockQueryAction({ model_id: MODEL.id, can_write: true });const ACTION_NOT_FOUND_ID = 999;const DATABASE = createSampleDatabase({settings: { "database-enable-actions": true },@@ -87,6 +89,9 @@ async function setup({{withRouter: true,initialRoute,+ storeInitialState: createMockState({+ currentUser: createMockUser({ is_superuser: true }),+ }),},);diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsxindex f3832868b26..368e0c6dffc 100644--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx@@ -47,6 +47,7 @@ import {createMockStructuredDatasetQuery,createMockStructuredQuery,createMockTable,+ createMockUser,} from "metabase-types/api/mocks";import {createNativeModelCard as _createNativeModelCard,@@ -162,6 +163,7 @@ function createMockQueryAction(opts?: Partial<WritebackQueryAction>,): WritebackQueryAction {return _createMockQueryAction({+ can_write: true,...opts,dataset_query: createMockNativeDatasetQuery({native: createMockNativeQuery({ query: TEST_QUERY }),@@ -178,6 +180,7 @@ type SetupOpts = {usedBy?: Card[];settings?: Partial<Settings>;deferDatabaseList?: boolean;+ isAdmin?: boolean;};async function setup({@@ -188,8 +191,10 @@ async function setup({usedBy = [],settings = {},deferDatabaseList = false,+ isAdmin = true,}: SetupOpts) {const storeInitialState = createMockState({+ currentUser: createMockUser({ is_superuser: isAdmin }),settings: createMockSettingsState(settings),});const metadata = createMockMetadata({@@ -445,19 +450,19 @@ describe("ModelActions", () => {expect(await screen.findByTestId("mock-action-editor")).toBeVisible();});- it("allows to archive a query action", async () => {+ it("allows to delete a query action", async () => {const model = getModel();const action = createMockQueryAction({ model_id: model.id });await setupActions({ model, actions: [action] });const listItem = screen.getByRole("listitem", { name: action.name });await userEvent.click(within(listItem).getByLabelText("ellipsis icon"));- await userEvent.click(await screen.findByText("Archive"));+ await userEvent.click(await screen.findByText("Delete"));expect(- screen.getByRole("heading", { name: /Archive/ }),+ screen.getByRole("heading", { name: /Delete/ }),).toBeInTheDocument();- await userEvent.click(screen.getByRole("button", { name: "Archive" }));+ await userEvent.click(screen.getByRole("button", { name: "Delete" }));await waitFor(() =>expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),@@ -465,22 +470,17 @@ describe("ModelActions", () => {expect(fetchMock.callHistory.calls(`path:/api/action/${action.id}`, {- method: "PUT",+ method: "DELETE",}),).toHaveLength(1);- const call = fetchMock.callHistory.lastCall(- `path:/api/action/${action.id}`,- {+ expect(+ fetchMock.callHistory.calls(`path:/api/action/${action.id}`, {method: "PUT",- },- );- expect(await call?.request?.json()).toEqual({- id: action.id,- archived: true,- });+ }),+ ).toHaveLength(0);});- it("doesn't allow to archive an implicit action", async () => {+ it("doesn't allow to delete an implicit action", async () => {const model = getModel();const action = createMockImplicitQueryAction({model_id: model.id,@@ -489,7 +489,7 @@ describe("ModelActions", () => {await openActionMenu(action);- expect(screen.queryByText("Archive")).not.toBeInTheDocument();+ expect(screen.queryByText("Delete")).not.toBeInTheDocument();});it("allows to disable implicit actions", async () => {@@ -524,7 +524,10 @@ describe("ModelActions", () => {});it("doesn't allow to edit actions", async () => {- const action = createMockQueryAction({ model_id: modelCard.id });+ const action = createMockQueryAction({+ model_id: modelCard.id,+ can_write: false,+ });await setupActions({ model: modelCard, actions: [action] });await openActionMenu(action);@@ -532,13 +535,46 @@ describe("ModelActions", () => {expect(await screen.findByText("View")).toBeInTheDocument();});- it("doesn't allow to archive actions", async () => {- const action = createMockQueryAction({ model_id: modelCard.id });+ it("doesn't allow to delete actions", async () => {+ const action = createMockQueryAction({+ model_id: modelCard.id,+ can_write: false,+ });await setupActions({ model: modelCard, actions: [action] });await openActionMenu(action);- expect(screen.queryByText("Archive")).not.toBeInTheDocument();+ expect(screen.queryByText("Delete")).not.toBeInTheDocument();+ });+ });++ describe("non-admin with write permissions on the model", () => {+ const modelCard = getModel();++ it("doesn't allow to create actions", async () => {+ await setupActions({ model: modelCard, actions: [], isAdmin: false });+ expect(screen.queryByText("New action")).not.toBeInTheDocument();+ expect(+ screen.queryByText("Create basic actions"),+ ).not.toBeInTheDocument();+ expect(screen.queryByTestId("actions-menu")).not.toBeInTheDocument();+ });++ it("doesn't allow to edit or delete actions", async () => {+ const action = createMockQueryAction({+ model_id: modelCard.id,+ can_write: false,+ });+ await setupActions({+ model: modelCard,+ actions: [action],+ isAdmin: false,+ });++ await openActionMenu(action);++ expect(await screen.findByText("View")).toBeInTheDocument();+ expect(screen.queryByText("Delete")).not.toBeInTheDocument();});});diff --git a/frontend/src/metabase/models/routes.tsx b/frontend/src/metabase/models/routes.tsxindex 696dd576603..274d6e936d2 100644--- a/frontend/src/metabase/models/routes.tsx+++ b/frontend/src/metabase/models/routes.tsx@@ -1,3 +1,5 @@+import type { ComponentType } from "react";+import { lazyModalRouteElement } from "metabase/common/components/ModalRoute";import ModelActions from "metabase/models/containers/ModelActions/ModelActions";import { loadActionCreator } from "metabase/querying/action-creator";@@ -22,7 +24,7 @@ const modelDetailPage = () =>/* webpackChunkName: "model-detail" */ "metabase/detail-view/pages/ModelDetailPage/ModelDetailPage").then(({ ModelDetailPage }) => ({ Component: ModelDetailPage }));-export const getRoutes = () => {+export const getRoutes = (IsAdmin: ComponentType) => {const modalProps: Partial<ModalProps> = {...PREVENT_AUTOCOMPLETE_CLIPPING_MODAL_PROPS,size: "95%",@@ -30,7 +32,9 @@ export const getRoutes = () => {return (<Route path="/model/:slug/detail"><Route path="actions" element={<ModelActions />}>- {lazyModalRouteElement("new", actionCreatorModal, { modalProps })}+ <Route element={<IsAdmin />}>+ {lazyModalRouteElement("new", actionCreatorModal, { modalProps })}+ </Route>{lazyModalRouteElement(":actionId", actionCreatorModal, { modalProps })}</Route><Route path=":rowId" lazy={modelDetailPage} />diff --git a/frontend/src/metabase/models/routes.unit.spec.tsx b/frontend/src/metabase/models/routes.unit.spec.tsxindex 78284e16802..20ccf5aaac8 100644--- a/frontend/src/metabase/models/routes.unit.spec.tsx+++ b/frontend/src/metabase/models/routes.unit.spec.tsx@@ -1,10 +1,21 @@import { lazyLoaders } from "__support__/lazy-routes";+import { renderWithProviders, screen } from "__support__/ui";+import { Outlet } from "metabase/router";import { getRoutes } from "./routes";+jest.mock("metabase/models/containers/ModelActions/ModelActions", () => ({+ __esModule: true,+ default: () => <Outlet />,+}));++function AdminGuard() {+ return <div data-testid="admin-guard" />;+}+describe("model routes", () => {it("resolves every page", async () => {- const loaders = lazyLoaders(getRoutes());+ const loaders = lazyLoaders(getRoutes(() => null));expect(loaders).toHaveLength(3);@@ -12,4 +23,13 @@ describe("model routes", () => {expect((await load()).Component).toBeDefined();}});++ it("guards the new action page with the admin guard", async () => {+ renderWithProviders(getRoutes(AdminGuard), {+ withRouter: true,+ initialRoute: "/model/1/detail/actions/new",+ });++ expect(await screen.findByTestId("admin-guard")).toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/new/components/NewModals/NewModals.unit.spec.tsx b/frontend/src/metabase/new/components/NewModals/NewModals.unit.spec.tsxindex 1f368cf1837..9229251c518 100644--- a/frontend/src/metabase/new/components/NewModals/NewModals.unit.spec.tsx+++ b/frontend/src/metabase/new/components/NewModals/NewModals.unit.spec.tsx@@ -6,6 +6,7 @@ import {setupCollectionsEndpoints,setupDatabasesEndpoints,} from "__support__/server-mocks";+import { createMockState } from "__support__/state";import {act,renderWithProviders,@@ -16,7 +17,7 @@ import {import { loadActionCreator } from "metabase/querying/action-creator";import { setOpenModal } from "metabase/redux/ui";import { Route } from "metabase/router";-import { createMockDatabase } from "metabase-types/api/mocks";+import { createMockDatabase, createMockUser } from "metabase-types/api/mocks";import { NewModals } from "./NewModals";@@ -31,7 +32,12 @@ async function setup() {const { store } = renderWithProviders(<Route path="/" element={<NewModals />} />,- { withRouter: true },+ {+ withRouter: true,+ storeInitialState: createMockState({+ currentUser: createMockUser({ is_superuser: true }),+ }),+ },);act(() => {diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsxindex 597cc4bdb5d..d5de290ac0c 100644--- a/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx+++ b/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx@@ -4,6 +4,7 @@ import fetchMock from "fetch-mock";import { screen, waitFor, within } from "__support__/ui";import * as Analytics from "metabase/analytics";import {+ createMockDatabase,createMockRecentCollectionItem,createMockRecentTableItem,} from "metabase-types/api/mocks";@@ -31,6 +32,10 @@ const withRealSearchDebounce = () => {});};+const ACTIONS_DATABASE = createMockDatabase({+ settings: { "database-enable-actions": true },+});+const setup = (props: CommonSetupProps = {}) =>commonSetup({ ...props, isEE: false });@@ -261,6 +266,27 @@ describe("PaletteResults", () => {expect(screen.queryByText("New embed")).not.toBeInTheDocument();});+ it("should offer the New action action to admins", async () => {+ setup({+ query: "new action",+ isAdmin: true,+ databases: [ACTIONS_DATABASE],+ });+ expect(await screen.findByText("New action")).toBeInTheDocument();+ });++ it("should not offer the New action action to non-admins", async () => {+ setup({+ query: "new action",+ isAdmin: false,+ databases: [ACTIONS_DATABASE],+ });+ expect(+ await screen.findByText(`Search Metabase's docs for "new action"`),+ ).toBeInTheDocument();+ expect(screen.queryByText("New action")).not.toBeInTheDocument();+ });+it("should start a new metric", async () => {const { router } = setup({ query: "new met" });diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsxindex 20fa5f765ac..e5d2ef21c85 100644--- a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx+++ b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx@@ -20,7 +20,12 @@ import { useCommandPalette } from "metabase/palette/hooks/useCommandPalette";import { useCommandPaletteBasicActions } from "metabase/palette/hooks/useCommandPaletteBasicActions";import { Route, useLocation, useParams } from "metabase/router";import { parseSearchQuery } from "metabase/utils/browser";-import type { CollectionItem, RecentItem, Settings } from "metabase-types/api";+import type {+ CollectionItem,+ Database,+ RecentItem,+ Settings,+} from "metabase-types/api";import {createMockCollection,createMockCollectionItem,@@ -134,6 +139,7 @@ export interface CommonSetupProps {searchItems?: CollectionItem[];isEE?: boolean;isAdmin?: boolean;+ databases?: Database[];}export const commonSetup = ({@@ -143,8 +149,9 @@ export const commonSetup = ({searchItems = [model_1, model_2, dashboard],isEE,isAdmin = false,+ databases = [DATABASE],}: CommonSetupProps = {}) => {- setupDatabasesEndpoints([DATABASE]);+ setupDatabasesEndpoints(databases);setupSearchEndpoints(searchItems);setupRecentViewsEndpoints(recents);setupCollectionByIdEndpoint({diff --git a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsxindex 89e9666c8a2..40bbfd8563a 100644--- a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx+++ b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx@@ -348,7 +348,7 @@ export const useCommandPaletteBasicActions = ({const openActionModal = [];- if (hasDatabaseWithActionsEnabled && hasNativeWrite && hasModels) {+ if (isAdmin && hasDatabaseWithActionsEnabled && hasNativeWrite && hasModels) {openActionModal.push({id: "create-action",name: t`New action`,@@ -361,6 +361,7 @@ export const useCommandPaletteBasicActions = ({});}useRegisterActions(openActionModal, [+ isAdmin,hasDatabaseWithActionsEnabled,hasNativeWrite,hasModels,diff --git a/frontend/src/metabase/querying/action-creator/ActionCreator.tsx b/frontend/src/metabase/querying/action-creator/ActionCreator.tsxindex 2e6c157eef8..4b2a2a9a4b2 100644--- a/frontend/src/metabase/querying/action-creator/ActionCreator.tsx+++ b/frontend/src/metabase/querying/action-creator/ActionCreator.tsx@@ -3,13 +3,12 @@ import type { DataReferenceSlot } from "metabase/actions/containers/ActionCreatoimport {skipToken,useGetActionQuery,- useGetCardQuery,useListDatabasesQuery,} from "metabase/api";+import { getUserIsAdmin } from "metabase/current-user";+import { useSelector } from "metabase/redux";import type {- Card,CardId,- Database,DatabaseId,WritebackAction,WritebackActionId,@@ -51,20 +50,20 @@ export function ActionCreator({onSubmit,onClose,}: ActionCreatorProps) {+ const isAdmin = useSelector(getUserIsAdmin);const { data: databases } = useListDatabasesQuery();- const { data: model } = useGetCardQuery(- modelId != null ? { id: modelId } : skipToken,- );- // `dataset_query.database` and not `database_id`: the v1 wrapper this- // replaced read the database off the query, and the two can differ.- const modelDatabase = databases?.data.find(- (database) => database.id === model?.dataset_query.database,- );const { data: initialAction } = useGetActionQuery(actionId != null ? { id: actionId } : skipToken,);// This is needed in case we already have an action and pass it from the outsideconst contextAction = action || initialAction;+ const savedAction = initialAction ?? action;+ const actionDatabase = databases?.data.find(+ (database) => database.id === savedAction?.database_id,+ );+ const canWriteAction =+ savedAction?.can_write === true &&+ Boolean(actionDatabase?.settings?.["database-enable-actions"]);return (<ActionContextProvider@@ -73,7 +72,8 @@ export function ActionCreator({><ActionCreatorContentmodelId={modelId}- canWriteModelActions={canWriteActions(model, modelDatabase)}+ canCreateActions={isAdmin}+ canWriteAction={canWriteAction}isRouted={isRouted}dataReference={DATA_REFERENCE}onSubmit={onSubmit}@@ -82,14 +82,3 @@ export function ActionCreator({</ActionContextProvider>);}--function canWriteActions(- model: Card | undefined,- database: Database | undefined,-): boolean {- return (- model?.can_write === true &&- database?.native_permissions === "write" &&- Boolean(database.settings?.["database-enable-actions"])- );-}diff --git a/frontend/src/metabase/querying/action-creator/tests/ActionCreator-QueryActions.unit.spec.ts b/frontend/src/metabase/querying/action-creator/tests/ActionCreator-QueryActions.unit.spec.tsindex 9fdec67dc6b..20178fcc5f7 100644--- a/frontend/src/metabase/querying/action-creator/tests/ActionCreator-QueryActions.unit.spec.ts+++ b/frontend/src/metabase/querying/action-creator/tests/ActionCreator-QueryActions.unit.spec.ts@@ -27,6 +27,15 @@ describe("ActionCreator > Query Actions", () => {).toBeInTheDocument();});+ it("doesn't let non-admins create an action", async () => {+ await setup({ isAdmin: false });++ expect(screen.getByText(/New action/i)).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Save" }),+ ).not.toBeInTheDocument();+ });+it("should disable submit by default", async () => {await setup();expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();diff --git a/frontend/src/metabase/querying/action-creator/tests/ActionCreator-Sharing.unit.spec.tsx b/frontend/src/metabase/querying/action-creator/tests/ActionCreator-Sharing.unit.spec.tsxindex 692a57f5d1c..65b887fd771 100644--- a/frontend/src/metabase/querying/action-creator/tests/ActionCreator-Sharing.unit.spec.tsx+++ b/frontend/src/metabase/querying/action-creator/tests/ActionCreator-Sharing.unit.spec.tsx@@ -162,6 +162,7 @@ describe("ActionCreator > Sharing", () => {it("should not show sharing settings when user is not admin but public sharing is enabled", async () => {await setup({action: getAction(),+ isAdmin: false,isPublicSharingEnabled: true,});diff --git a/frontend/src/metabase/querying/action-creator/tests/common.tsx b/frontend/src/metabase/querying/action-creator/tests/common.tsxindex a9e6f5a7e04..0c678972c30 100644--- a/frontend/src/metabase/querying/action-creator/tests/common.tsx+++ b/frontend/src/metabase/querying/action-creator/tests/common.tsx@@ -35,7 +35,7 @@ export async function setup({action,canWrite = true,hasActionsEnabled = true,- isAdmin = false,+ isAdmin = true,isPublicSharingEnabled = false,model,}: SetupOpts = {}) {@@ -54,9 +54,13 @@ export async function setup({setupCardsEndpoints(model ? [model] : []);if (action) {- fetchMock.get(`path:/api/action/${action.id}`, action, {- name: `action-${action.id}-get`,- });+ fetchMock.get(+ `path:/api/action/${action.id}`,+ { ...action, can_write: canWrite },+ {+ name: `action-${action.id}-get`,+ },+ );fetchMock.delete(`path:/api/action/${action.id}/public_link`, 204, {name: `public-link-${action.id}-delete`,});diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsxindex a0bf8869d92..7ba36ba02f8 100644--- a/frontend/src/metabase/routes.tsx+++ b/frontend/src/metabase/routes.tsx@@ -459,7 +459,7 @@ export const getRoutes = (store: AppStore): RouteObject[] => [},// MODELS- ...toRouteObjects(getModelRoutes()),+ ...toRouteObjects(getModelRoutes(IsAdmin)),{path: "/model",diff --git a/resources/migrations/065/20261022_delete_actions_of_non_models.yaml b/resources/migrations/065/20261022_delete_actions_of_non_models.yamlnew file mode 100644index 00000000000..e67b89df6af--- /dev/null+++ b/resources/migrations/065/20261022_delete_actions_of_non_models.yaml@@ -0,0 +1,20 @@+## A model's actions are never kept around: archiving a model or turning it into a question deletes its actions, and a+## model's action can't be archived, only deleted. This deletes the ones left behind: actions of cards that are no longer+## models, of archived models, and archived actions of models. Their dashboard cards and query_action/implicit_action+## rows cascade. Actions without a model are left alone.++databaseChangeLog:+ - changeSet:+ id: v65.2026-10-22T02:00:00+ author: ranquild+ comment: Delete the actions of non-models and archived models, and the archived actions of models+ changes:+ - sql:+ sql: >-+ DELETE FROM action+ WHERE EXISTS (SELECT 1 FROM report_card+ WHERE report_card.id = action.model_id+ AND (report_card.type <> 'model'+ OR report_card.archived = TRUE+ OR action.archived = TRUE));+ rollback: # nothing to do; the deleted actions cannot be restoreddiff --git a/src/metabase/actions/execution.clj b/src/metabase/actions/execution.cljindex a8dc83df587..eb1c678fab3 100644--- a/src/metabase/actions/execution.clj+++ b/src/metabase/actions/execution.clj@@ -266,7 +266,7 @@request-parameters :- RequestParametersopts :- [:maybe ExecuteActionOpts]](let [dashcard (api/check-404 (actions.db/dashcard-in-dashboard dashcard-id dashboard-id))- action (api/check-404 (action/select-action :id (:action_id dashcard)))]+ action (api/check-404 (action/select-action :id (:action_id dashcard) :archived false))](analytics/track-event! :snowplow/action{:event :action-executed:source :dashboarddiff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.cljindex 764af8ca04f..5bd936f4778 100644--- a/src/metabase/actions/models.clj+++ b/src/metabase/actions/models.clj@@ -253,14 +253,6 @@:when database-id](actions/check-actions-enabled-for-database (actions.db/database database-id))))-(defn- native-query-permitted?- "Whether the current user may author the query of `action`: a native one needs native query permission."- [{query :dataset_query, :keys [database_id]}]- (or (not (and (seq query) (lib/native? query)))- (= :query-builder-and-native- (perms/full-database-permission-for-user api/*current-user-id* :perms/create-queries- (or (:database query) database_id)))))-(defn- effective-collection-id"The id of the Collection `action` goes in, its model's when it has one; throws a 404 when either does not exist."[{model-id :model_id, collection-id :collection_id}]@@ -294,16 +286,23 @@((get-method mi/can-create? :perms/use-parent-collection-perms) :model/Action action)(mi/current-user-has-full-permissions? ((get-method mi/perms-objects-set :model/Action) action :write)))))+(defmethod mi/can-write? :model/Action+ ([action]+ (and (mi/superuser?)+ (mi/current-user-has-full-permissions? :write action)))+ ([model pk]+ (and (mi/superuser?)+ (mi/current-user-has-full-permissions? :write model pk))))+(defmethod mi/can-create? :model/Action[_model action]- (and (collection-writable? action)- (native-query-permitted? action)))+ (and (mi/superuser?)+ (collection-writable? action)))(defmethod mi/can-update? :model/Action[action changes](and (mi/can-write? action)- (collection-writable? (merge action changes))- (native-query-permitted? changes)))+ (collection-writable? (merge action changes))))(def ^:private action-columns"The columns that are common to all Action types."@@ -619,24 +618,24 @@actions)))(methodical/defmethod t2.hydrate/batched-hydrate [:model/DashboardCard :dashcard/action]- "Hydrates actions from DashboardCards. Adds a boolean field `:database-enabled-actions` to each action according to- the\n `database-enable-actions` setting for the action's database."+ "Hydrates DashboardCard actions, with `:can_write` and `:database_enabled_actions` from the action's database."[_model _k dashcards](let [actions-by-id(when-let [action-ids (seq (keep :action_id dashcards))]- (->> (select-actions-for-ids nil action-ids)- map-assoc-database-enable-actions- (m/index-by :id)))]+ (as-> (select-actions-for-ids nil action-ids) actions+ (map-assoc-database-enable-actions actions)+ (t2/hydrate actions :can_write)+ (m/index-by :id actions)))](for [dashcard dashcards:let [action-id (:action_id dashcard)action (get actions-by-id action-id)]](m/assoc-some dashcard :action action))))(defn dashcard->action- "Get the action associated with a dashcard if exists, return `nil` otherwise."+ "Get the unarchived action associated with a dashcard if exists, return `nil` otherwise."[dashcard-or-dashcard-id]- (some->> (actions.db/dashcard-action-id (u/the-id dashcard-or-dashcard-id))- (select-action :id)))+ (when-let [action-id (actions.db/dashcard-action-id (u/the-id dashcard-or-dashcard-id))]+ (select-action :id action-id :archived false)));;; ------------------------------------------------ Serialization ---------------------------------------------------diff --git a/src/metabase/actions_rest/api.clj b/src/metabase/actions_rest/api.cljindex 44527df0c60..93220d5312a 100644--- a/src/metabase/actions_rest/api.clj+++ b/src/metabase/actions_rest/api.clj@@ -110,6 +110,8 @@(let [existing-action (api/write-check :model/Action id)action (api/updates-with-archived-directly existing-action action)](api/update-check existing-action action)+ (api/check-400 (not (and (:archived action) (get action :model_id (:model_id existing-action))))+ (tru "A model''s action can''t be archived. Delete it instead."))(when (some #(contains? action %) [:dataset_query :database_id :type :kind :model_id])(actions/check-action-databases-enabled (merge (actions/select-action :id id) action)))(actions/update! (assoc action :id id) existing-action))diff --git a/src/metabase/collections/children.clj b/src/metabase/collections/children.cljindex c1e1c54c479..aa08caf5119 100644--- a/src/metabase/collections/children.clj+++ b/src/metabase/collections/children.clj@@ -894,8 +894,11 @@(defmethod post-process-collection-children :table[_ {:keys [models]} _collection rows]- (let [tables (map #(-> (t2/instance :model/Table %)- (update :archived api/bit->boolean)) rows)]+ (let [tables (->> (t2/hydrate (map #(-> (t2/instance :model/Table (assoc % :db_id (:database_id %) :is_published true))+ (update :archived api/bit->boolean))+ rows)+ :can_write)+ (map #(dissoc % :db_id :is_published)))](if (contains? models :measure)(t2/hydrate tables :measures)tables)))diff --git a/src/metabase/native_query_snippets/api.clj b/src/metabase/native_query_snippets/api.cljindex ea544bf54c3..6f792f3aeb4 100644--- a/src/metabase/native_query_snippets/api.clj+++ b/src/metabase/native_query_snippets/api.clj@@ -23,7 +23,7 @@(list-native-query-snippets false))([archived :- ms/BooleanValue](let [snippets (native-query-snippets.db/snippets-by-archived archived)]- (t2/hydrate (filter mi/can-read? snippets) :creator :is_remote_synced))))+ (t2/hydrate (filter mi/can-read? snippets) :can_write :creator :is_remote_synced))));; 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 happendiff --git a/src/metabase/permissions/models/collection/graph.clj b/src/metabase/permissions/models/collection/graph.cljindex cb9c8d4b411..c1586c81799 100644--- a/src/metabase/permissions/models/collection/graph.clj+++ b/src/metabase/permissions/models/collection/graph.clj@@ -14,6 +14,7 @@[metabase.permissions.util :as perms.u][metabase.premium-features.core :refer [defenterprise]][metabase.util :as u]+ [metabase.util.i18n :refer [tru]][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -227,6 +228,18 @@"' group."){:status-code 400})))))))+(def ^:private admin-only-write-namespaces+ "The Collection namespaces only admins can write, so no group can be granted write on them."+ #{"data-actions" "data-apps"})++(defn- check-no-admin-only-namespace-write+ "Throws a 400 when `changes` to the Collections of `collection-namespace` grant write in an admin-only namespace."+ [collection-namespace changes]+ (when (and (contains? admin-only-write-namespaces (some-> collection-namespace name))+ (some #{:write} (mapcat vals (vals changes))))+ (throw (ex-info (tru "You cannot grant write permissions on collections only admins can write.")+ {:status-code 400}))))+(mu/defn update-graph!"Update the Collections permissions graph for Collections of `collection-namespace` (default `nil`, the 'default'namespace). This works just like [[metabase.models.permission/update-data-perms-graph!]], but for Collections;@@ -273,6 +286,7 @@(filter (comp seq second))(into {})))](check-data-analyst-library-permissions changes)+ (check-no-admin-only-namespace-write collection-namespace changes)(when-not force? (perms.u/check-revision-numbers old-graph filtered-new-graph))(when (seq changes)(let [revision-id (t2/with-transaction [_conn]diff --git a/src/metabase/queries/db.clj b/src/metabase/queries/db.cljindex bd2c65a7f2a..0b301d827df 100644--- a/src/metabase/queries/db.clj+++ b/src/metabase/queries/db.clj@@ -367,14 +367,10 @@collection-id :- [:maybe ::lib.schema.id/collection]](t2/update! :model/Action :model_id [:in model-ids] {:collection_id collection-id}))-(mu/defn set-actions-of-model-archived!- "Archive the unarchived Actions of the Card with `model-id` along with it, or unarchive the ones archived along with- it, returning the number updated."- [model-id :- ms/PositiveInt- archived? :- :boolean]- (if archived?- (t2/update! :model/Action {:model_id model-id, :archived false} {:archived true, :archived_directly false})- (t2/update! :model/Action {:model_id model-id, :archived true, :archived_directly false} {:archived false})))+(mu/defn delete-actions-of-model!+ "Delete the Actions of the Card with `model-id`, returning the number deleted."+ [model-id :- ms/PositiveInt]+ (t2/delete! :model/Action :model_id model-id))(mu/defn actions-for-model"The Actions of the model Card with `model-id`."@@ -386,25 +382,6 @@[action-ids :- [:set ::lib.schema.id/action]](t2/delete! :model/Action :id [:in action-ids]))-(mu/defn delete-dashcards-for-model-actions!- "Delete the DashboardCards of the Actions of the model Card with `model-id`, returning the number deleted."- [model-id :- ms/PositiveInt]- (if-let [action-ids (not-empty (t2/select-pks-set :model/Action :model_id model-id))]- (t2/delete! :model/DashboardCard :action_id [:in action-ids])- 0))--(mu/defn archive-explicit-actions-for-model!- "Archive the unarchived non-implicit Actions of the model Card with `model-id` directly, returning the number- updated."- [model-id :- ms/PositiveInt]- (t2/update! :model/Action {:model_id model-id, :type [:not= :implicit], :archived false}- {:archived true, :archived_directly true}))--(mu/defn delete-implicit-actions-for-model!- "Delete the implicit Actions of the model Card with `model-id`, returning the number deleted."- [model-id :- ms/PositiveInt]- (t2/delete! :model/Action :model_id model-id :type :implicit))-(mu/defn delete-card-moderation-reviews!"Delete the ModerationReviews of the Card with `card-id`, returning the number deleted."[card-id :- ::lib.schema.id/card]diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex d29be54592d..98e8cc42184 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -586,14 +586,10 @@(= (:type old-card-info) :model)(not (query/supports-implicit-actions? (:dataset_query changes))))(disable-implicit-action-for-model! id))- ;; Changing from a Model to a Question: archive associated actions- (when (and (= (:type changes) :question)- (= (:type old-card-info) :model))- (queries.db/delete-dashcards-for-model-actions! id)- (queries.db/archive-explicit-actions-for-model! id)- (queries.db/delete-implicit-actions-for-model! id))- (when (contains? changes :archived)- (queries.db/set-actions-of-model-archived! id (boolean (:archived changes))))+ (when (or (:archived changes)+ (and (= (:type changes) :question)+ (= (:type old-card-info) :model)))+ (queries.db/delete-actions-of-model! id));; Make sure any native query template tags match the DB in the query.(check-field-filter-fields-are-from-correct-database changes);; Make sure the Collection is in the default Collection namespace (e.g. as opposed to the Snippets Collectiondiff --git a/src/metabase/query_processor/middleware/permissions.clj b/src/metabase/query_processor/middleware/permissions.cljindex b67bb0e261a..fd9cc4cd3cf 100644--- a/src/metabase/query_processor/middleware/permissions.clj+++ b/src/metabase/query_processor/middleware/permissions.clj@@ -9,6 +9,7 @@[metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]][metabase.query-permissions.core :as query-perms]+ [metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.schema :as qp.schema];; the legacy QP pipeline still conveys the metadata provider via the ambient store; no MBQL 5 path yet^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store]@@ -147,11 +148,20 @@;;; | Writeback fns |;;; +----------------------------------------------------------------------------------------------------------------++(defn- check-no-sandboxed-action-access+ "Throws a 403 when the current user has a sandbox on any table of the Database with `database-id`, since actions+ write around sandboxes."+ [database-id]+ (when (and *current-user-id* (perms/sandboxed-user-for-db? database-id))+ (throw (ex-info (tru "You can''t run actions on this database because row and column security applies to your data access.")+ {:type qp.error-type/missing-required-permissions+ :status-code 403}))))+(mu/defn check-query-action-permissions*- "Check that User with `user-id` has permissions to run query action `query`, or throw an exception. Takes- as [[metabase.actions.args/action-arg-map-schema]]."+ "Throws unless the current user can run an action with the already preprocessed `query`."[{database-id :database, :as query} :- ::lib.schema/query](log/tracef "Checking query permissions. Current user perms set = %s" (pr-str @*current-user-permissions-set*))+ (check-no-sandboxed-action-access database-id)(when *card-id*(query-perms/check-card-read-perms database-id *card-id*))(when-not (query-perms/check-data-permsdiff --git a/src/metabase/search/impl.clj b/src/metabase/search/impl.cljindex eec314021f5..45bd7c91eb2 100644--- a/src/metabase/search/impl.clj+++ b/src/metabase/search/impl.clj@@ -443,8 +443,14 @@(check-permissions-for-model search-ctx (normalize-result result)))(defn- add-can-write [search-ctx row]- (if (some #(mi/instance-of? % row) [:model/Dashboard :model/Card :model/Collection])+ (cond+ (some #(mi/instance-of? % row) [:model/Dashboard :model/Card :model/Collection])(assoc row :can_write (can-write? search-ctx row))++ (mi/instance-of? :model/Table row)+ (assoc row :can_write (can-write? search-ctx (assoc row :db_id (:database_id row))))++ :elserow))(defn- normalize-result-morediff --git a/test/metabase/actions/models_test.clj b/test/metabase/actions/models_test.cljindex cf97e8569a2..6370f4ab989 100644--- a/test/metabase/actions/models_test.clj+++ b/test/metabase/actions/models_test.clj@@ -313,13 +313,13 @@(deftest model-to-saved-question-test(mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)(mt/with-actions-enabled- (testing "Non-implicit actions are archived directly, and their dashboard buttons deleted, if their model is converted to a saved question"+ (testing "Non-implicit actions and their dashboard buttons are deleted if their model is converted to a saved question"(mt/with-actions [{:keys [action-id model-id]} {:type :query}](mt/with-temp [:model/Dashboard {dashboard-id :id} {}:model/DashboardCard {dashcard-id :id} {:action_id action-id :dashboard_id dashboard-id}](is (false? (t2/select-one-fn :archived :model/Action action-id)))(t2/update! :model/Card model-id {:type :question})- (is (= [true true] ((juxt :archived :archived_directly) (t2/select-one :model/Action :id action-id))))+ (is (not (t2/exists? :model/Action :id action-id)))(is (not (t2/exists? :model/DashboardCard :id dashcard-id))))))(testing "Implicit actions are deleted if their model is converted to a saved question"(mt/with-actions [{:keys [action-id model-id]} {:type :implicit}]diff --git a/test/metabase/actions_rest/api_test.clj b/test/metabase/actions_rest/api_test.cljindex 0259ba1a39a..e8f74659319 100644--- a/test/metabase/actions_rest/api_test.clj+++ b/test/metabase/actions_rest/api_test.clj@@ -15,7 +15,6 @@[metabase.search.core :as search][metabase.test :as mt][metabase.test.fixtures :as fixtures]- [metabase.util :as u][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -191,7 +190,7 @@(mt/with-temp [:model/Card model {:type :model:dataset_query (mt/native-query {:query "select * from checkins limit 1"})}](let [action (cross-db-action (:id model) test-data-id)- response (mt/user-http-request :rasta :post 400 "action" action)]+ response (mt/user-http-request :crowberto :post 400 "action" action)](testing "Checks both databases for actions enabled"(is (= "Actions are not enabled."response))))))))))@@ -402,14 +401,7 @@:dataset_query (update (mt/native-query {:query "update venues set name = 'foo' where id = {{x}}"}):type name):parameters [{:id "x" :type "number"}]}- created-action (mt/user-http-request :crowberto :post 200 "action" initial-action)- action-id (u/the-id created-action)- action-path (str "action/" action-id)]- (testing "Archiving"- (mt/user-http-request :crowberto :put 200 action-path {:archived true})- (is (true? (t2/select-one-fn :archived :model/Action :id action-id)))- (mt/user-http-request :crowberto :put 200 action-path {:archived false})- (is (false? (t2/select-one-fn :archived :model/Action :id action-id))))+ _ (mt/user-http-request :crowberto :post 200 "action" initial-action)](testing "Validate POST"(testing "Required fields"(is (=? {:errors {:name "string"},@@ -418,55 +410,51 @@(is (=? {:specific-errors {:model_id ["missing required key, received: nil"]}}(mt/user-http-request :crowberto :post 400 "action" {:type "implicit" :name "test"}))))))))))-(deftest native-query-action-requires-native-permission-test- (testing "creating or updating a native query action requires native query permission on the database"+(deftest model-actions-cannot-be-archived-test+ (testing "a model's action can't be archived, only deleted"+ (mt/with-actions-enabled+ (mt/with-actions-test-data-tables #{"users"}+ (mt/with-actions [{:keys [action-id]} {:type :query}]+ (let [path (str "action/" action-id)]+ (is (= "A model's action can't be archived. Delete it instead."+ (mt/user-http-request :crowberto :put 400 path {:archived true})))+ (is (false? (t2/select-one-fn :archived :model/Action :id action-id)))+ (mt/user-http-request :crowberto :delete 204 path)+ (is (not (t2/exists? :model/Action :id action-id)))))))))++(deftest only-admins-write-model-actions-test+ (testing "only admins can create, update, or delete an action of a model, whatever their permissions on the model"(mt/with-actions-enabled(mt/with-actions-test-data-tables #{"users"}(mt/with-model-cleanup [:model/Action]- (perms.test-util/with-restored-data-perms!- (mt/with-temp [:model/Card {model-id :id}- {:type :model- :dataset_query (mt/mbql-query users)- ;; personal collection so a non-admin has write permission on the model- :collection_id (:id (collection/user->personal-collection (mt/user->id :rasta)))}]- (let [native-action {:name "native example"- :type "query"- :model_id model-id- :database_id (mt/id)- :dataset_query (lib/native-query (mt/metadata-provider)- "update users set name = 'foo' where id = {{x}}")- :parameters [{:id "x" :type "number"}]}- implicit-action {:name "implicit example"- :type "implicit"- :model_id model-id- :kind "row/create"- :parameters [{:id "id" :type "number"}]}- set-native! (fn [level]- (perms/set-database-permission! (perms/all-users-group) (mt/id)- :perms/create-queries level))]- (testing "without native permission, creating a native query action is rejected"- (set-native! :query-builder)- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :post 403 "action" native-action))))- (testing "an implicit (non-native) action is unaffected by native permission"- (is (=? {:type "implicit"}- (mt/user-http-request :rasta :post 200 "action" implicit-action))))- (testing "with native permission, creating a native query action succeeds"- (set-native! :query-builder-and-native)- (let [created (mt/user-http-request :rasta :post 200 "action" native-action)]- (is (=? {:type "query"} created))- (testing "without native permission, updating to a native query is rejected"- (set-native! :query-builder)- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :put 403 (str "action/" (:id created))- {:dataset_query (lib/native-query (mt/metadata-provider)- "update users set name = 'bar' where id = {{x}}")}))))- (testing "with native permission, updating to a native query succeeds"- (set-native! :query-builder-and-native)- (is (=? {:type "query"}- (mt/user-http-request :rasta :put 200 (str "action/" (:id created))- {:dataset_query (lib/native-query (mt/metadata-provider)- "update users set name = 'baz' where id = {{x}}")}))))))))))))))+ (mt/with-temp [:model/Card {model-id :id}+ {:type :model+ :dataset_query (mt/mbql-query users)+ :collection_id (:id (collection/user->personal-collection (mt/user->id :rasta)))}]+ (let [native-action {:name "native example"+ :type "query"+ :model_id model-id+ :database_id (mt/id)+ :dataset_query (lib/native-query (mt/metadata-provider)+ "update users set name = 'foo' where id = {{x}}")+ :parameters [{:id "x" :type "number"}]}+ implicit-action {:name "implicit example"+ :type "implicit"+ :model_id model-id+ :kind "row/create"+ :parameters [{:id "id" :type "number"}]}]+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "action" native-action)))+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "action" implicit-action)))+ (let [path (str "action/" (:id (mt/user-http-request :crowberto :post 200 "action" native-action)))]+ (is (=? {:can_write false} (mt/user-http-request :rasta :get 200 path)))+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :put 403 path {:name "Renamed"})))+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :delete 403 path)))+ (is (=? {:name "Renamed"} (mt/user-http-request :crowberto :put 200 path {:name "Renamed"})))+ (mt/user-http-request :crowberto :delete 204 path)))))))))(defn- model-less-query-action"A POST body for a query action on the categories table with no model, in the Collection with `collection-id`."@@ -509,27 +497,22 @@mt/rowsffirst)))))))))-(deftest action-without-model-collection-perms-test- (testing "creating or moving an action without a model requires write permission on its data actions collection"+(deftest only-admins-write-actions-without-model-test+ (testing "only admins can create or update an action without a model, whatever their permissions on its collection"(mt/with-actions-test-data-and-actions-enabled(perms.test-util/with-restored-perms!(mt/with-model-cleanup [:model/Action]- (mt/with-temp [:model/Collection {locked-id :id} {:namespace "data-actions"}- :model/Collection {writable-id :id} {:namespace "data-actions"}]- (perms/grant-collection-readwrite-permissions! (perms/all-users-group) writable-id)+ (mt/with-temp [:model/Collection {coll-id :id} {:namespace "data-actions"}]+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) coll-id)+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) (data-actions-root))(is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :post 403 "action" (model-less-query-action locked-id))))- (testing "the data actions root needs its own permission"- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :post 403 "action" (model-less-query-action nil))))- (perms/grant-collection-readwrite-permissions! (perms/all-users-group) (data-actions-root))- (is (=? {:collection_id nil}- (mt/user-http-request :rasta :post 200 "action" (model-less-query-action nil)))))- (let [created (mt/user-http-request :rasta :post 200 "action" (model-less-query-action writable-id))]- (is (=? {:collection_id writable-id} created))+ (mt/user-http-request :rasta :post 403 "action" (model-less-query-action coll-id))))+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "action" (model-less-query-action nil))))+ (let [path (str "action/" (:id (mt/user-http-request :crowberto :post 200 "action" (model-less-query-action coll-id))))](is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :put 403 (str "action/" (:id created)) {:collection_id locked-id})))- (is (= writable-id (t2/select-one-fn :collection_id :model/Action :id (:id created)))))))))))+ (mt/user-http-request :rasta :put 403 path {:collection_id nil})))+ (is (=? {:collection_id coll-id} (mt/user-http-request :rasta :get 200 path))))))))))(deftest list-actions-without-model-test(testing "the action list includes actions without a model, filtered by data actions collection permissions"@@ -675,16 +658,16 @@(mt/with-model-cleanup [:model/Action](mt/with-temp [:model/Collection {coll-id :id} {:namespace "data-actions"}](perms/grant-collection-readwrite-permissions! (perms/all-users-group) coll-id)- (let [spoofed {:creator_id (mt/user->id :crowberto)- :made_public_by_id (mt/user->id :crowberto)+ (let [spoofed {:creator_id (mt/user->id :rasta)+ :made_public_by_id (mt/user->id :rasta):public_uuid (str (random-uuid))}stored #(t2/select-one [:model/Action :creator_id :made_public_by_id :public_uuid] :id %)- created (mt/user-http-request :rasta :post 200 "action"+ created (mt/user-http-request :crowberto :post 200 "action"(merge (model-less-query-action coll-id) spoofed))]- (is (= {:creator_id (mt/user->id :rasta) :made_public_by_id nil :public_uuid nil}+ (is (= {:creator_id (mt/user->id :crowberto) :made_public_by_id nil :public_uuid nil}(into {} (stored (:id created)))))- (mt/user-http-request :rasta :put 200 (str "action/" (:id created)) (assoc spoofed :name "Renamed"))- (is (= {:creator_id (mt/user->id :rasta) :made_public_by_id nil :public_uuid nil}+ (mt/user-http-request :crowberto :put 200 (str "action/" (:id created)) (assoc spoofed :name "Renamed"))+ (is (= {:creator_id (mt/user->id :crowberto) :made_public_by_id nil :public_uuid nil}(into {} (stored (:id created)))))))))))(deftest update-checks-actions-enabled-testdiff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.cljindex 87566e889e7..187ea7d7910 100644--- a/test/metabase/app_db/schema_migrations_test.clj+++ b/test/metabase/app_db/schema_migrations_test.clj@@ -3702,6 +3702,77 @@(is (= #{implicit-id} (t2/select-pks-set :action)))(is (= #{other-button} (t2/select-pks-set :report_dashboardcard :id [:in [http-button other-button]])))))))+(deftest delete-actions-of-non-models-test+ (testing "v65.2026-10-22T02:00:00: the actions of non-models and archived models, and the archived actions of models, are deleted+ with their dashboard buttons"+ (impl/test-migrations ["v65.2026-10-22T02:00:00"] [migrate!]+ (let [user-id (t2/insert-returning-pk! :core_user {:first_name "Action"+ :last_name "Owner"+ :email "[email protected]"+ :password "superstrong"+ :entity_id (u/generate-nano-id)+ :date_joined :%now})+ db-id (t2/insert-returning-pk! :metabase_database {:name "Actions DB"+ :engine "h2"+ :details "{}"+ :created_at :%now+ :updated_at :%now})+ dash-id (t2/insert-returning-pk! :report_dashboard {:name "Buttons"+ :creator_id user-id+ :parameters "[]"+ :entity_id (u/generate-nano-id)+ :created_at :%now+ :updated_at :%now})+ insert-card! (fn [card-type & {:keys [archived]}]+ (t2/insert-returning-pk! :report_card {:name "Card"+ :entity_id (u/generate-nano-id)+ :type card-type+ :archived (boolean archived)+ :display "table"+ :dataset_query "{}"+ :visualization_settings "{}"+ :creator_id user-id+ :database_id db-id+ :created_at :%now+ :updated_at :%now}))+ insert-action! (fn [model-id & {:keys [archived archived-directly]}]+ (t2/insert-returning-pk! :action {:name "Action"+ :entity_id (u/generate-nano-id)+ :type "query"+ :model_id model-id+ :archived (boolean archived)+ :archived_directly (boolean archived-directly)+ :created_at :%now+ :updated_at :%now}))+ insert-button! (fn [action-id]+ (t2/insert-returning-pk! :report_dashboardcard {:dashboard_id dash-id+ :action_id action-id+ :parameter_mappings "[]"+ :visualization_settings "{}"+ :entity_id (u/generate-nano-id)+ :size_x 4+ :size_y 4+ :row 0+ :col 0+ :created_at :%now+ :updated_at :%now}))+ model-id (insert-card! "model")+ model-action (insert-action! model-id)+ archived-alone (insert-action! model-id :archived true :archived-directly true)+ archived-along (insert-action! model-id :archived true)+ no-model (insert-action! nil :archived true)+ archived-model (insert-action! (insert-card! "model" :archived true))+ question (insert-action! (insert-card! "question"))+ metric (insert-action! (insert-card! "metric"))+ kept-button (insert-button! model-action)+ deleted-button (insert-button! question)+ action-ids [model-action archived-alone archived-along no-model archived-model question metric]]+ (t2/insert! :query_action {:action_id question :database_id db-id :dataset_query "{}"})+ (migrate!)+ (is (= #{model-action no-model} (t2/select-pks-set :action :id [:in action-ids])))+ (is (= #{kept-button} (t2/select-pks-set :report_dashboardcard :id [:in [kept-button deleted-button]])))+ (is (not (t2/exists? :query_action :action_id question)))))))+(deftest timeline-event-entity-ids-test(testing "v65.h1c4r5 thru v65.lpm4z3: existing timeline events get distinct portable IDs, other data unchanged"(impl/test-migrations ["v65.h1c4r5" "v65.lpm4z3"] [migrate!]diff --git a/test/metabase/collections/models/collection_test.clj b/test/metabase/collections/models/collection_test.cljindex c50e2094631..70b128c1d8d 100644--- a/test/metabase/collections/models/collection_test.clj+++ b/test/metabase/collections/models/collection_test.clj@@ -203,15 +203,27 @@(unarchive-collection! (t2/select-one :model/Collection :id (u/the-id collection)))(is (false? (t2/select-one-fn :archived :model/Card :id (u/the-id card)))))))-(deftest archive-actions-test- (testing "archiving a Collection archives its Actions and keeps their dashboard buttons, and unarchiving restores- only the Actions archived along with it"+(deftest archive-default-collection-deletes-actions-test+ (testing "archiving a Collection in the default namespace deletes the Actions of its models and their dashboard buttons"(mt/with-temp [:model/Collection collection {}:model/Card model {:type :model :collection_id (u/the-id collection)}:model/Action action {:type :query :name "Rename" :model_id (u/the-id model)}- :model/Action old-action {:type :query :name "Old" :model_id (u/the-id model)+ :model/Dashboard dashboard {}+ :model/DashboardCard dashcard {:dashboard_id (u/the-id dashboard) :action_id (u/the-id action)}]+ (archive-collection! collection)+ (is (not (t2/exists? :model/Action :id (u/the-id action))))+ (is (not (t2/exists? :model/DashboardCard :id (u/the-id dashcard)))))))++(deftest archive-data-actions-collection-archives-actions-test+ (testing "archiving a data actions Collection archives its Actions and keeps their dashboard buttons, and unarchiving+ restores only the Actions archived along with it"+ (mt/with-temp [:model/Collection collection {:namespace "data-actions"}+ :model/Action action {:type :query :name "Rename" :model_id nil+ :collection_id (u/the-id collection)}+ :model/Action old-action {:type :query :name "Old" :model_id nil+ :collection_id (u/the-id collection):archived true :archived_directly true}- :model/Dashboard dashboard {:collection_id (u/the-id collection)}+ :model/Dashboard dashboard {}:model/DashboardCard dashcard {:dashboard_id (u/the-id dashboard) :action_id (u/the-id action)}](archive-collection! collection)(is (true? (t2/select-one-fn :archived :model/Action :id (u/the-id action))))@@ -220,17 +232,6 @@(is (false? (t2/select-one-fn :archived :model/Action :id (u/the-id action))))(is (true? (t2/select-one-fn :archived :model/Action :id (u/the-id old-action)))))))-(deftest unarchive-collection-keeps-actions-of-archived-models-test- (testing "restoring a Collection does not restore the Actions of a model that is still in the trash"- (mt/with-temp [:model/Collection collection {}- :model/Card model {:type :model :collection_id (u/the-id collection)}- :model/Action action {:type :query :name "Rename" :model_id (u/the-id model)}]- (t2/update! :model/Card (u/the-id model) {:archived true :archived_directly true})- (archive-collection! collection)- (unarchive-collection! (t2/select-one :model/Collection :id (u/the-id collection)))- (is (true? (t2/select-one-fn :archived :model/Card :id (u/the-id model))))- (is (true? (t2/select-one-fn :archived :model/Action :id (u/the-id action)))))))-(deftest delete-collection-deletes-actions-test(testing "deleting a Collection deletes the Actions in it, including the ones without a model"(mt/with-temp [:model/Collection collection {:namespace "data-actions"}diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex d2919121520..6357e881718 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -1253,6 +1253,16 @@(is (= ["table"] (:available_models response)))(is (= ["table"] (mapv :model (:data response)))))))))))+(deftest collection-items-tables-can-write-test+ (testing "GET /api/collection/:id/items includes whether the current user can write each published table"+ (mt/with-premium-features #{:library}+ (mt/with-temp [:model/Collection collection {:type "library-data"}+ :model/Table {table-id :id} {:collection_id (u/the-id collection)+ :is_published true}]+ (is (=? [{:id table-id, :model "table", :can_write true}]+ (:data (mt/user-http-request :crowberto :get 200+ (str "collection/" (u/the-id collection) "/items")))))))))+(deftest collection-items-available-models-permissions-test(testing "GET /api/collection/:id/items"(mt/with-non-admin-groups-no-root-collection-permsdiff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.cljindex ccecf01116f..da75cbeff45 100644--- a/test/metabase/dashboards_rest/api_test.clj+++ b/test/metabase/dashboards_rest/api_test.clj@@ -2653,6 +2653,18 @@(is (partial= {:dashcards [{:action {:database_enabled_actions enable-actions?}}]}(mt/user-http-request :crowberto :get 200 (format "dashboard/%s" dashboard-id)))))))))))))+(deftest dashcard-action-can-write-test+ (testing "Dashcard actions hydrate can_write, which only admins have"+ (mt/test-driver :h2+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-actions [{:keys [action-id model-id]} {}]+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}+ :model/DashboardCard _ {:action_id action-id :card_id model-id :dashboard_id dashboard-id}]+ (doseq [[user can-write?] [[:crowberto true] [:rasta false]]]+ (testing user+ (is (partial= {:dashcards [{:action {:id action-id :can_write can-write?}}]}+ (mt/user-http-request user :get 200 (format "dashboard/%s" dashboard-id))))))))))))+(deftest add-card-parameter-mapping-permissions-test(testing "PUT /api/dashboard/:id"(testing "Should check current user's data permissions for the `parameter_mapping`"@@ -4290,6 +4302,23 @@(defn- has-valid-action-execution-error-message? [response](string? (:message response)))+(deftest dashcard-archived-action-execution-test+ (testing "A dashcard can't run an archived action until an admin unarchives it"+ (mt/test-driver :h2+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-actions [{:keys [action-id model-id]} {}]+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}+ :model/DashboardCard {dashcard-id :id} {:dashboard_id dashboard-id+ :action_id action-id+ :card_id model-id}]+ (let [execute-path (format "dashboard/%s/dashcard/%s/execute" dashboard-id dashcard-id)]+ (t2/update! :model/Action action-id {:archived true :archived_directly true})+ (is (= "Not found."+ (mt/user-http-request :crowberto :post 404 execute-path {:parameters {"id" 1}})))+ (mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived false})+ (is (partial= {:rows-affected 1}+ (mt/user-http-request :crowberto :post 200 execute-path {:parameters {"id" 1}}))))))))))+(deftest dashcard-query-action-execution-test(mt/test-drivers (mt/normal-drivers-with-feature :actions)(mt/with-actions-test-data-and-actions-enableddiff --git a/test/metabase/native_query_snippets/api_test.clj b/test/metabase/native_query_snippets/api_test.cljindex 902ab6dfe2c..c7ed16c7c5e 100644--- a/test/metabase/native_query_snippets/api_test.clj+++ b/test/metabase/native_query_snippets/api_test.clj@@ -38,6 +38,13 @@(is (contains? snippets-from-api (select-keys snippet-1 test-snippet-fields)))(is (contains? snippets-from-api (select-keys snippet-2 test-snippet-fields)))))))))))+(deftest list-snippets-can-write-test+ (testing "GET /api/native-query-snippet includes whether the current user can write each snippet"+ (mt/with-temp [:model/NativeQuerySnippet {snippet-id :id} {:content "1" :name "snippet_can_write"}]+ (is (=? {:can_write true}+ (some #(when (= snippet-id (:id %)) %)+ (mt/user-http-request :crowberto :get 200 (snippet-url))))))))+(deftest list-snippets-call-count-test(testing "GET /api/native-query-snippet app-DB call count should not scale with the number of snippets"(mt/with-model-cleanup [:model/NativeQuerySnippet]diff --git a/test/metabase/permissions/models/collection/graph_test.clj b/test/metabase/permissions/models/collection/graph_test.cljindex 2ec3034fa3f..a667cb12464 100644--- a/test/metabase/permissions/models/collection/graph_test.clj+++ b/test/metabase/permissions/models/collection/graph_test.clj@@ -448,6 +448,28 @@[:created_at (ms/InstanceOfClass java.time.temporal.Temporal)]](t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]}))))))))))+(deftest admin-only-namespaces-reject-write-test+ (testing "The data actions and data apps namespaces reject write permissions and accept read permissions"+ (doseq [collection-namespace [:data-actions :data-apps]]+ (testing collection-namespace+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {collection-id :id} {:namespace (name collection-namespace) :location "/"}+ :model/PermissionsGroup {group-id :id} {}]+ (mt/with-test-user :crowberto+ (doseq [target-id [collection-id :root]]+ (testing target-id+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"You cannot grant write permissions on collections only admins can write"+ (graph/update-graph! collection-namespace+ (assoc (graph/graph collection-namespace) :groups {group-id {target-id :write}})+ false)))))+ (is (= :none (get-in (graph/graph collection-namespace) [:groups group-id collection-id] :none)))+ @(graph/update-graph! collection-namespace+ (assoc (graph/graph collection-namespace) :groups {group-id {collection-id :read}})+ false)+ (is (= :read (get-in (graph/graph collection-namespace) [:groups group-id collection-id]))))))))))+(deftest collection-namespace-update-root-default-test(testing "Should be able to update permissions for the Root Collection in the default namespace"(mt/with-non-admin-groups-no-root-collection-permsdiff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex de6b097643c..f66a211f4fc 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -820,11 +820,12 @@(lib/filter (lib/> (lib.metadata/field mp (mt/id :venues :price)) 1)))))(deftest model-becoming-question-publishes-action-events-test- (testing "update-card! announces the actions it archives and deletes when a model becomes a question"+ (testing "update-card! announces the actions it deletes when a model becomes a question"(do-with-model-actions!- (fn [{:keys [model-id implicit query]}]- (is (= #{[:event/action-update query true]- [:event/action-delete implicit false]}+ (fn [{:keys [model-id implicit query archived]}]+ (is (= #{[:event/action-delete implicit false]+ [:event/action-delete query false]+ [:event/action-delete archived true]}(action-events-during! #(update-model! model-id {:type :question}))))))))(deftest model-query-without-implicit-support-publishes-action-events-test@@ -851,19 +852,17 @@(is (= #{[:event/action-update action-id false]}(action-events-during! #(update-model! question-id {:collection_id coll-id})))))))-(deftest model-archive-cascades-to-actions-test- (testing "archiving a model archives its actions, and unarchiving it restores only those"+(deftest model-archive-deletes-actions-test+ (testing "archiving a model deletes its actions, and unarchiving it brings none back"(do-with-model-actions!(fn [{:keys [model-id implicit query archived]}]- (let [archived-state #(t2/select-pk->fn (juxt :archived :archived_directly) :model/Action :model_id model-id)]- (is (= #{[:event/action-update implicit true]- [:event/action-update query true]}- (action-events-during! #(update-model! model-id {:archived true}))))- (is (= {implicit [true false], query [true false], archived [true true]} (archived-state)))- (is (= #{[:event/action-update implicit false]- [:event/action-update query false]}- (action-events-during! #(update-model! model-id {:archived false}))))- (is (= {implicit [false false], query [false false], archived [true true]} (archived-state))))))))+ (is (= #{[:event/action-delete implicit false]+ [:event/action-delete query false]+ [:event/action-delete archived true]}+ (action-events-during! #(update-model! model-id {:archived true}))))+ (is (not (t2/exists? :model/Action :model_id model-id)))+ (update-model! model-id {:archived false})+ (is (not (t2/exists? :model/Action :model_id model-id)))))))(deftest model-actions-follow-model-collection-test(testing "the actions of a model are kept in the model's collection"diff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.cljindex 6aad925f23c..e865d039825 100644--- a/test/metabase/search/api_test.clj+++ b/test/metabase/search/api_test.clj@@ -1076,7 +1076,7 @@(testing "You should see Tables in the search results!\n"(mt/with-temp [:model/Table _ {:name "RoundTable"}](do-test-users [user [:crowberto :rasta]]- (is (= [(default-table-search-row "RoundTable")]+ (is (= [(assoc (default-table-search-row "RoundTable") :can_write (= user :crowberto))](search-request-data user :q "RoundTable" :models "table")))))))(deftest table-test-2@@ -1084,7 +1084,7 @@(mt/with-temp [:model/Table _normal {:name "Foo Visible"}:model/Table _hidden {:name "Foo Hidden", :visibility_type "hidden"}](do-test-users [user [:crowberto :rasta]]- (is (= [(default-table-search-row "Foo Visible")]+ (is (= [(assoc (default-table-search-row "Foo Visible") :can_write (= user :crowberto))](search-request-data user :q "Foo")))))))(deftest table-test-3@@ -1092,7 +1092,7 @@(let [lancelot "Lancelot's Favorite Furniture"](mt/with-temp [:model/Table _ {:name "RoundTable" :display_name lancelot}](do-test-users [user [:crowberto :rasta]]- (is (= [(assoc (default-table-search-row "RoundTable") :name lancelot)]+ (is (= [(assoc (default-table-search-row "RoundTable") :name lancelot :can_write (= user :crowberto))](search-request-data user :q "Lancelot"))))))))(deftest table-test-4@@ -1100,7 +1100,8 @@(let [lancelot "Lancelot's Favorite Furniture"](mt/with-temp [:model/Table _ {:name "RoundTable" :description lancelot}](do-test-users [user [:crowberto :rasta]]- (is (= [(assoc (default-table-search-row "RoundTable") :description lancelot :table_description lancelot)]+ (is (= [(assoc (default-table-search-row "RoundTable")+ :description lancelot :table_description lancelot :can_write (= user :crowberto))](search-request-data user :q "Lancelot"))))))))(deftest table-test-5@@ -1148,7 +1149,7 @@(perms/set-database-permission! group-id db-id :perms/view-data :unrestricted)(perms/set-table-permission! group-id table :perms/create-queries :query-builder)(do-test-users [user [:crowberto :rasta]]- (is (= [(default-table-search-row "RoundTable")]+ (is (= [(assoc (default-table-search-row "RoundTable") :can_write (= user :crowberto))](binding [*search-request-results-database-id* db-id](search-request-data user :q "RoundTable")))))))))