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
Block official collections in shared collections and its subcollections (#67537)
Phoomparin Manofd6740eee7cd
diff --git a/e2e/test/scenarios/collections/collection-picker-tenants.cy.spec.ts b/e2e/test/scenarios/collections/collection-picker-tenants.cy.spec.tsnew file mode 100644index 00000000000..4f5f6c8b0ca--- /dev/null+++ b/e2e/test/scenarios/collections/collection-picker-tenants.cy.spec.ts@@ -0,0 +1,215 @@+const { H } = cy;++const TENANT_NAMESPACE = "shared-tenant-collection";++/**+ * Create a collection in the shared-tenant-collection namespace.+ * Collections with this namespace are shared collections.+ */+function createSharedCollection(name: string, parentId?: number) {+ return cy.request("POST", "/api/collection", {+ name,+ namespace: TENANT_NAMESPACE,+ parent_id: parentId ?? null,+ });+}++describe("scenarios > collections > collection picker with tenants", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ H.updateSetting("use-tenants", true);+ });++ it("should not allow marking collections as official in shared collections and its sub-collections", () => {+ createSharedCollection("Test Shared Collection").then((response) => {+ const sharedCollectionId = response.body.id;++ cy.log("Navigate to the shared collection");+ H.visitCollection(sharedCollectionId);++ cy.log("Verify collection loaded");+ cy.findByTestId("collection-name-heading").should(+ "have.text",+ "Test Shared Collection",+ );++ cy.log("Click on the three dots menu and verify cannot mark as official");+ H.openCollectionMenu();++ H.popover().within(() => {+ cy.log("Should not have 'Make collection official' option");+ cy.findByText("Make collection official").should("not.exist");+ cy.findByText("Remove Official badge").should("not.exist");+ });++ // Close the popover+ cy.findByTestId("app-bar").click();++ cy.log("Click 'Create a new collection' button");+ cy.findByTestId("collection-menu")+ .findByLabelText("Create a new collection")+ .click();++ cy.findByTestId("new-collection-modal").within(() => {+ cy.log("Should not see 'Collection type' picker");+ cy.findByText(/Collection type/i).should("not.exist");+ cy.findByText("Regular").should("not.exist");+ cy.findByText("Official").should("not.exist");++ cy.log("Verify we're creating inside the shared collection");+ cy.findByTestId("collection-picker-button").should(+ "contain",+ "Test Shared Collection",+ );++ cy.log("Edge case: Change target collection to a normal collection");+ cy.findByTestId("collection-picker-button").click();+ });++ H.entityPickerModal().within(() => {+ cy.log("Select 'Our analytics' (a normal collection)");+ H.entityPickerModalTab("Collections").click();+ cy.findByText("Our analytics").click();+ cy.button("Select").click();+ });++ cy.findByTestId("new-collection-modal").within(() => {+ cy.log("Wait for collection picker to update to 'Our analytics'");+ cy.findByTestId("collection-picker-button").should(+ "contain",+ "Our analytics",+ );++ cy.log("Should now see 'Collection type' picker");+ cy.findByText(/Collection type/i).should("exist");+ cy.findByText("Regular").should("exist");+ cy.findByText("Official").should("exist");++ cy.log("Close modal without creating");+ cy.findByLabelText("Close").click();+ });+ });+ });++ it("should block official collections in sub-collections of shared collections", () => {+ createSharedCollection("Shared Parent Collection").then((response) => {+ const sharedParentId = response.body.id;++ createSharedCollection("Shared Sub Collection", sharedParentId).then(+ (subResponse) => {+ const sharedSubCollectionId = subResponse.body.id;++ cy.log("Navigate to the sub-collection");+ H.visitCollection(sharedSubCollectionId);++ cy.log("Verify sub-collection loaded");+ cy.findByTestId("collection-name-heading").should(+ "have.text",+ "Shared Sub Collection",+ );++ cy.log("Open collection menu");+ H.openCollectionMenu();++ H.popover().within(() => {+ cy.log("Should not have 'Make collection official' option");+ cy.findByText("Make collection official").should("not.exist");+ cy.findByText("Remove Official badge").should("not.exist");+ });++ // Close the popover+ cy.findByTestId("app-bar").click();++ cy.log("Create a new sub-sub-collection");+ cy.findByTestId("collection-menu")+ .findByLabelText("Create a new collection")+ .click();++ cy.findByTestId("new-collection-modal").within(() => {+ cy.log("Should not see 'Collection type' picker");+ cy.findByText(/Collection type/i).should("not.exist");+ cy.findByText("Regular").should("not.exist");+ cy.findByText("Official").should("not.exist");+ });+ },+ );+ });+ });++ it("should hide collection type picker when switching from normal to shared collection in create modal", () => {+ createSharedCollection("Target Shared Collection");++ cy.log("Start creating a new collection from root");+ cy.visit("/collection/root");+ H.startNewCollectionFromSidebar();++ cy.findByTestId("new-collection-modal").within(() => {+ cy.log("Initially should see collection type picker");+ cy.findByText(/Collection type/i).should("exist");++ cy.log("Click collection picker to change target");+ cy.findByTestId("collection-picker-button").click();+ });++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Collections").click();+ cy.log("Navigate to Shared collections");+ cy.findByText("Shared collections").click();+ cy.findByText("Target Shared Collection").click();+ cy.button("Select").click();+ });++ cy.findByTestId("new-collection-modal").within(() => {+ cy.log("Should no longer see collection type picker");+ cy.findByText(/Collection type/i).should("not.exist");+ cy.findByText("Regular").should("not.exist");+ cy.findByText("Official").should("not.exist");+ });+ });++ it("should show collection type picker when switching from shared to normal collection in create modal", () => {+ createSharedCollection("Shared Collection for Switching").then(+ (response) => {+ const sharedCollectionId = response.body.id;++ cy.log("Navigate inside shared collection");+ H.visitCollection(sharedCollectionId);++ cy.log("Start creating a sub-collection");+ cy.findByTestId("collection-menu")+ .findByLabelText("Create a new collection")+ .click();++ cy.findByTestId("new-collection-modal").within(() => {+ cy.log("Should not see collection type picker initially");+ cy.findByText(/Collection type/i).should("not.exist");++ cy.log("Click collection picker to change target");+ cy.findByTestId("collection-picker-button").click();+ });++ H.entityPickerModal().within(() => {+ H.entityPickerModalTab("Collections").click();+ cy.log("Select 'Our analytics' (normal collection)");+ cy.findByText("Our analytics").click();+ cy.button("Select").click();+ });++ cy.findByTestId("new-collection-modal").within(() => {+ cy.log("Wait for collection picker to update to 'Our analytics'");+ cy.findByTestId("collection-picker-button").should(+ "contain",+ "Our analytics",+ );++ cy.log("Should now see collection type picker");+ cy.findByText(/Collection type/i).should("exist");+ cy.findByText("Regular").should("exist");+ cy.findByText("Official").should("exist");+ });+ },+ );+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/collections/index.tsx b/enterprise/frontend/src/metabase-enterprise/collections/index.tsxindex 0c05b276159..b6a2cc1de05 100644--- a/enterprise/frontend/src/metabase-enterprise/collections/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/collections/index.tsx@@ -8,6 +8,8 @@ import { Icon, Menu } from "metabase/ui";import { hasPremiumFeature } from "metabase-enterprise/settings";import type { Collection } from "metabase-types/api";+import { isTenantCollection } from "../tenants/utils/utils";+import { CollectionAuthorityLevelDisplay } from "./components/CollectionAuthorityLevelDisplay";import { CollectionAuthorityLevelIcon } from "./components/CollectionAuthorityLevelIcon";import { CollectionInstanceAnalyticsIcon } from "./components/CollectionInstanceAnalyticsIcon";@@ -45,6 +47,11 @@ export function initializePlugin() {collection: Collection,onUpdate: (collection: Collection, values: Partial<Collection>) => void,) => {+ // Shared tenant collections cannot be marked as official+ if (isTenantCollection(collection)) {+ return [];+ }+if (isRegularCollection(collection)) {return [<Menu.Itemdiff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsxindex 6b47329160d..12f95069ec5 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx@@ -74,6 +74,9 @@ describe("MainNavSharedCollections > new shared collection modal", () => {setup({ isAdmin: true, canWriteToSharedCollectionRoot: true });await screen.findByText("External collections");+ // Mock the initial collection fetch that CreateCollectionForm makes+ fetchMock.get("path:/api/collection/1", MOCK_TENANT_COLLECTIONS[0]);+const addButton = screen.getByRole("button", { name: /add/i });addButton.click();diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.ts b/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.tsindex 7d0dc45f9f1..e773ac8a836 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/tenants/utils/utils.ts@@ -14,5 +14,6 @@ export const isExternalUser = (user?: Pick<User, "tenant_id">): boolean => {return Boolean(user && user.tenant_id !== null);};-export const isTenantCollection = (collection: Collection) =>- collection.namespace === "shared-tenant-collection";+export const isTenantCollection = (+ collection: Partial<Pick<Collection, "namespace">>,+) => collection.namespace === "shared-tenant-collection";diff --git a/frontend/src/metabase/collections/components/CollectionMenu/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionMenu/tests/enterprise.unit.spec.tsxindex 29d6870cf8f..ca79811d79d 100644--- a/frontend/src/metabase/collections/components/CollectionMenu/tests/enterprise.unit.spec.tsx+++ b/frontend/src/metabase/collections/components/CollectionMenu/tests/enterprise.unit.spec.tsx@@ -44,4 +44,43 @@ describe("CollectionMenu", () => {await userEvent.click(getIcon("ellipsis"));expect(screen.queryByText("Edit permissions")).not.toBeInTheDocument();});++ it("should not be able to make shared tenant collections official", async () => {+ setupEnterprise({+ collection: createMockCollection({+ can_write: true,+ namespace: "shared-tenant-collection",+ }),+ isAdmin: true,+ tokenFeatures: createMockTokenFeatures({+ tenants: true,+ official_collections: true,+ }),+ });++ await userEvent.click(getIcon("ellipsis"));++ expect(+ screen.queryByText("Make collection official"),+ ).not.toBeInTheDocument();+ });++ it("should not be able to remove official badge from shared tenant collections", async () => {+ setupEnterprise({+ collection: createMockCollection({+ can_write: true,+ namespace: "shared-tenant-collection",+ authority_level: "official",+ }),+ isAdmin: true,+ tokenFeatures: createMockTokenFeatures({+ tenants: true,+ official_collections: true,+ }),+ });++ await userEvent.click(getIcon("ellipsis"));++ expect(screen.queryByText("Remove Official badge")).not.toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx b/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsxindex 73ed6dfb15c..8597d3528c3 100644--- a/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx+++ b/frontend/src/metabase/collections/components/CreateCollectionForm/CreateCollectionForm.tsx@@ -1,9 +1,10 @@-import { useMemo } from "react";+import { useMemo, useState } from "react";import { withRouter } from "react-router";import { t } from "ttag";import _ from "underscore";import * as Yup from "yup";+import { skipToken, useGetCollectionQuery } from "metabase/api";import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker";import Button from "metabase/common/components/Button";import type { FilterItemsInPersonalCollection } from "metabase/common/components/EntityPicker";@@ -12,10 +13,12 @@ import { FormFooter } from "metabase/common/components/FormFooter";import FormInput from "metabase/common/components/FormInput";import FormSubmitButton from "metabase/common/components/FormSubmitButton";import FormTextArea from "metabase/common/components/FormTextArea";+import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";import { Collections } from "metabase/entities/collections";import { Form, FormProvider } from "metabase/forms";import * as Errors from "metabase/lib/errors";import { connect } from "metabase/lib/redux";+import { PLUGIN_TENANTS } from "metabase/plugins";import type { Collection } from "metabase-types/api";import type { State } from "metabase-types/store";@@ -30,7 +33,6 @@ const COLLECTION_SCHEMA = Yup.object({authority_level: Yup.mixed().oneOf(["official", null]).default(null),parent_id: Yup.number().nullable(),- namespace: Yup.string().nullable().default(null),});export interface CreateCollectionProperties {@@ -94,49 +96,65 @@ function CreateCollectionForm({[initialCollectionId],);+ const { data: initialCollection } = useGetCollectionQuery(+ initialCollectionId != null ? { id: initialCollectionId } : skipToken,+ );++ const [selectedParentCollection, setSelectedParentCollection] =+ useState<CollectionPickerItem | null>(null);+return (<FormProviderinitialValues={initialValues}validationSchema={COLLECTION_SCHEMA}onSubmit={onSubmit}>- {({ dirty, setFieldValue }) => (- <Form>- <FormInput- name="name"- title={t`Name`}- placeholder={t`My new fantastic collection`}- data-autofocus- />- <FormTextArea- name="description"- title={t`Description`}- placeholder={t`It's optional but oh, so helpful`}- nullable- optional- />- {showCollectionPicker && (- <FormCollectionPicker- name="parent_id"- setNamespace={(namespace) =>- setFieldValue("namespace", namespace)- }- title={t`Collection it's saved in`}- filterPersonalCollections={filterPersonalCollections}- entityType="collection"- savingModel="collection"+ {({ dirty }) => {+ const parentCollection = selectedParentCollection ?? initialCollection;++ // Hide the authority level picker if the parent is a tenant collection.+ const isParentTenantCollection = parentCollection+ ? PLUGIN_TENANTS.isTenantCollection(parentCollection)+ : false;++ return (+ <Form>+ <FormInput+ name="name"+ title={t`Name`}+ placeholder={t`My new fantastic collection`}+ data-autofocus+ />+ <FormTextArea+ name="description"+ title={t`Description`}+ placeholder={t`It's optional but oh, so helpful`}+ nullable+ optional/>- )}- {showAuthorityLevelPicker && <FormAuthorityLevelField />}- <FormFooter>- <FormErrorMessage inline />- {!!onCancel && (- <Button type="button" onClick={onCancel}>{t`Cancel`}</Button>+ {showCollectionPicker && (+ <FormCollectionPicker+ name="parent_id"+ title={t`Collection it's saved in`}+ filterPersonalCollections={filterPersonalCollections}+ entityType="collection"+ savingModel="collection"+ onCollectionSelect={setSelectedParentCollection}+ />+ )}+ {showAuthorityLevelPicker && !isParentTenantCollection && (+ <FormAuthorityLevelField />)}- <FormSubmitButton title={t`Create`} disabled={!dirty} primary />- </FormFooter>- </Form>- )}+ <FormFooter>+ <FormErrorMessage inline />+ {!!onCancel && (+ <Button type="button" onClick={onCancel}>{t`Cancel`}</Button>+ )}+ <FormSubmitButton title={t`Create`} disabled={!dirty} primary />+ </FormFooter>+ </Form>+ );+ }}</FormProvider>);}diff --git a/frontend/src/metabase/collections/components/CreateCollectionForm/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/collections/components/CreateCollectionForm/tests/enterprise.unit.spec.tsxindex e2451d7661c..ea0e06fec8a 100644--- a/frontend/src/metabase/collections/components/CreateCollectionForm/tests/enterprise.unit.spec.tsx+++ b/frontend/src/metabase/collections/components/CreateCollectionForm/tests/enterprise.unit.spec.tsx@@ -1,4 +1,5 @@-import { screen } from "__support__/ui";+import { screen, waitFor } from "__support__/ui";+import { createMockTokenFeatures } from "metabase-types/api/mocks";import { setup } from "./setup";@@ -7,4 +8,36 @@ describe("CreateCollectionForm", () => {setup();expect(screen.queryByText("Collection type")).not.toBeInTheDocument();});++ it("hides authority level picker when initial parent is a shared tenant collection", async () => {+ setup({+ showAuthorityLevelPicker: true,+ tokenFeatures: createMockTokenFeatures({+ tenants: true,+ official_collections: true,+ }),+ enterprisePlugins: ["collections", "tenants"],+ parentCollectionNamespace: "shared-tenant-collection",+ });++ // Wait for the authority level picker to disappear after collection data loads+ await waitFor(() => {+ expect(screen.queryByText("Collection type")).not.toBeInTheDocument();+ });+ });++ it("shows authority level picker when initial parent is a regular collection", () => {+ setup({+ showAuthorityLevelPicker: true,+ tokenFeatures: createMockTokenFeatures({+ tenants: true,+ official_collections: true,+ }),+ enterprisePlugins: ["collections", "tenants"],+ parentCollectionNamespace: null,+ });++ // The authority level picker should be visible+ expect(screen.getByText("Collection type")).toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/collections/components/CreateCollectionForm/tests/setup.tsx b/frontend/src/metabase/collections/components/CreateCollectionForm/tests/setup.tsxindex 1e3d4587064..3068bf98a0d 100644--- a/frontend/src/metabase/collections/components/CreateCollectionForm/tests/setup.tsx+++ b/frontend/src/metabase/collections/components/CreateCollectionForm/tests/setup.tsx@@ -1,10 +1,17 @@/* istanbul ignore file */import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";-import { setupCollectionsEndpoints } from "__support__/server-mocks";+import {+ setupCollectionByIdEndpoint,+ setupCollectionsEndpoints,+} from "__support__/server-mocks";import { mockSettings } from "__support__/settings";import { createMockEntitiesState } from "__support__/store";import { renderWithProviders } from "__support__/ui";-import type { TokenFeatures, User } from "metabase-types/api";+import type {+ CollectionNamespace,+ TokenFeatures,+ User,+} from "metabase-types/api";import {createMockCollection,createMockTokenFeatures,@@ -25,6 +32,7 @@ export interface SetupOpts {tokenFeatures?: TokenFeatures;showAuthorityLevelPicker?: boolean;enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];+ parentCollectionNamespace?: CollectionNamespace | null;}export const setup = ({@@ -32,28 +40,52 @@ export const setup = ({tokenFeatures = createMockTokenFeatures(),showAuthorityLevelPicker,enterprisePlugins,+ parentCollectionNamespace,}: SetupOpts = {}) => {const settings = mockSettings({ "token-features": tokenFeatures });const onCancel = jest.fn();+ // Create a parent collection with the specified namespace if provided+ const parentCollection = parentCollectionNamespace+ ? createMockCollection({+ id: 1,+ name: "Parent Collection",+ namespace: parentCollectionNamespace,+ can_write: true,+ })+ : ROOT_COLLECTION;++ const collections =+ parentCollectionNamespace !== undefined+ ? [ROOT_COLLECTION, parentCollection]+ : [ROOT_COLLECTION];+if (enterprisePlugins) {enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);}setupCollectionsEndpoints({- collections: [],+ collections:+ parentCollectionNamespace !== undefined ? [parentCollection] : [],rootCollection: ROOT_COLLECTION,});++ // Mock individual collection fetches+ setupCollectionByIdEndpoint({+ collections,+ });+renderWithProviders(<CreateCollectionFormonCancel={onCancel}showAuthorityLevelPicker={showAuthorityLevelPicker}+ collectionId={parentCollectionNamespace !== undefined ? 1 : undefined}/>,{storeInitialState: createMockState({currentUser: user,settings,entities: createMockEntitiesState({- collections: [ROOT_COLLECTION],+ collections,}),}),},diff --git a/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx b/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsxindex b664691364d..cfc3eb6f122 100644--- a/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx+++ b/frontend/src/metabase/collections/containers/FormCollectionPicker/FormCollectionPicker.tsx@@ -42,7 +42,7 @@ interface FormCollectionPickerProps extends HTMLAttributes<HTMLDivElement> {filterPersonalCollections?: FilterItemsInPersonalCollection;entityType?: EntityType;collectionPickerModalProps?: Partial<CollectionPickerModalProps>;- setNamespace?: (namespace: string | undefined) => void;+ onCollectionSelect?: (collection: CollectionPickerItem) => void;/*** When set to "collection", allows saving to namespace root collections* (like tenant root). When null/undefined, namespace roots are disabled.@@ -84,7 +84,6 @@ function FormCollectionPicker({className,style,name,- setNamespace,title,placeholder = t`Select a collection`,type = "collections",@@ -92,6 +91,7 @@ function FormCollectionPicker({entityType,collectionPickerModalProps,savingModel,+ onCollectionSelect,}: FormCollectionPickerProps) {const id = useUniqueId();@@ -155,16 +155,13 @@ function FormCollectionPicker({);const handleChange = useCallback(- ({ id, namespace }: CollectionPickerItem) => {- if (namespace) {- setNamespace?.(namespace);- setCollectionNamespace(namespace);- }- setCollectionNamespace(namespace ?? null);- setValue(canonicalCollectionId(id));+ (collection: CollectionPickerItem) => {+ onCollectionSelect?.(collection);+ setCollectionNamespace(collection.namespace ?? null);+ setValue(canonicalCollectionId(collection.id));setIsPickerOpen(false);},- [setValue, setNamespace, setCollectionNamespace],+ [onCollectionSelect, setValue],);return (diff --git a/frontend/src/metabase/plugins/oss/tenants.ts b/frontend/src/metabase/plugins/oss/tenants.tsindex 3c0db4f0600..d67bcc14b01 100644--- a/frontend/src/metabase/plugins/oss/tenants.ts+++ b/frontend/src/metabase/plugins/oss/tenants.ts@@ -32,7 +32,8 @@ const getDefaultPluginTenants = () => ({isExternalUsersGroup: (_group: Pick<Group, "magic_group_type">) => false,isTenantGroup: (_group: Pick<Group, "is_tenant_group">) => false,isExternalUser: (_user?: Pick<User, "tenant_id">) => false,- isTenantCollection: (_collection: Collection) => false,+ isTenantCollection: (_collection: Partial<Pick<Collection, "namespace">>) =>+ false,PeopleNav: null as React.ReactElement | null,ReactivateExternalUserButton: ({ user: _user }: { user: User }) =>null as React.ReactElement | null,@@ -92,7 +93,9 @@ export const PLUGIN_TENANTS: {isExternalUsersGroup: (group: Pick<Group, "magic_group_type">) => boolean;isTenantGroup: (group: Pick<Group, "is_tenant_group">) => boolean;isExternalUser: (user?: Pick<User, "tenant_id">) => boolean;- isTenantCollection: (collection: Collection) => boolean;+ isTenantCollection: (+ collection: Partial<Pick<Collection, "namespace">>,+ ) => boolean;PeopleNav: React.ReactElement | null;ReactivateExternalUserButton: (props: {user: User;